Skip to content

Latest commit

 

History

History
162 lines (128 loc) · 13.6 KB

mutation-testing.md

File metadata and controls

162 lines (128 loc) · 13.6 KB

Mutation testing (Stryker.NET)

Mutation testing asks a different question than code coverage. Coverage says a line ran; mutation testing says the tests would notice if that line changed. Stryker.NET rewrites the compiled library one small change at a time (>= → >, a string literal → "", a statement deleted) and reruns the suite: a mutant that makes a test fail is killed, one that survives is a hole in the suite.

This repository runs mutation testing explicitly, like the benchmarks — never inside dotnet test and never in CI.

Tooling

Stryker.NET is pinned as a local tool so the version travels with the repository:

dotnet tool restore          # once per clone, and after a pull that changes .config/dotnet-tools.json
dotnet stryker --version     # 5.1.0

Running a suite

Stryker must run from the test project directory: a stryker-config.json lives there and is picked up automatically.

cd tests/SafeWebCore.Tests
dotnet stryker -O ../../artifacts/stryker/safewebcore
Test project Mutates Config file
tests/SafeWebCore.Tests src/SafeWebCore tests/SafeWebCore.Tests/stryker-config.json
tests/SafeWebCore.FraudDetection.Tests src/SafeWebCore.FraudDetection tests/SafeWebCore.FraudDetection.Tests/stryker-config.json
tests/SafeWebCore.JwtBearer.Tests src/SafeWebCore.JwtBearer tests/SafeWebCore.JwtBearer.Tests/stryker-config.json
tests/SafeWebCore.Analyzers.Tests src/SafeWebCore.Analyzers tests/SafeWebCore.Analyzers.Tests/stryker-config.json
tests/SafeWebCore.Testing.Tests src/SafeWebCore.Testing tests/SafeWebCore.Testing.Tests/stryker-config.json

Only the benchmarks have no mutation suite.

Reports land in artifacts/stryker/<name>/<timestamp>/reports/ (git-ignored): mutation-report.json for tooling, mutation-report.html to browse a file's mutants, plus the console table.

Why the configuration looks the way it does

Setting Value Reason
project e.g. SafeWebCore.csproj Names the project under test explicitly, even though each test project has one project reference.
target-framework net10.0 (analyzers: netstandard2.0) The libraries multi-target net10.0;net11.0 and Stryker mutates one build at a time. Both targets compile the same sources, so one target covers the code. The analyzer assembly is single-targeted netstandard2.0 (a compiler-host constraint), so that is what Stryker builds.
test-runner mtp xUnit v3 runs on the Microsoft.Testing.Platform (global.json), not vstest. Without this, Stryker finds zero tests.
mutation-level Standard The default mutator set. Advanced costs several times the runtime for little extra signal on this code.
thresholds high 80, low 60, break 0 Reported so a score is readable, but a run never fails: today's scores are a backlog, not a gate.
-O on the command line artifacts/stryker/<name> output is command-line-only in 5.1.0; it is rejected inside stryker-config.json.

Two practical constraints:

  • Run from the test project folder. From the repository root Stryker picks up SafeWebCore.slnx and then rejects --test-project with "Test projects cannot be specified when running Stryker in solution context". One config file per test project avoids solution mode entirely.
  • test-runner: mtp is not optional. The xUnit v3 projects have no vstest adapter configured, so the default runner reports no tests; the config sets the runner for you.

Baseline results — 2026-11-15 (all three packages re-baselined)

Package Mutation score Killed Survived No coverage Compile error Wall time
SafeWebCore 89.18 % 750 68 23 49 ~40 s
SafeWebCore.JwtBearer 93.57 % 232 + 1 timeout 14 2 51 ~30 s
SafeWebCore.FraudDetection 93.00 % 596 + 2 timeouts 39 6 21 ~40 s
SafeWebCore.Analyzers 90.67 % 202 + 2 timeouts 20 1 83 ~35 s
SafeWebCore.Testing 96.62 % 143 5 0 0 ~35 s

The score is (killed + timeout) / (killed + timeout + survived + no coverage); a Compile error mutant is excluded. Compile errors come from mutations Stryker cannot compile — Append() → Prepend() (no such member on IHeaderDictionary), Count() → Sum() on a non-numeric type — and say nothing about the tests.

The SafeWebCore.FraudDetection row was re-baselined after a large fraud test-hardening pass in this working tree: the new score-weight, defaults, scanner-signal, detector, validator, metrics, dispatcher, webhook and DI tests pin every observable behaviour, moving the score from 20.68 % (killed 131, survived 354, no coverage 156) to 93.00 % (killed 596 + 2 timeouts, survived 39, no coverage 6). The remaining survivors are equivalent mutants (see below).

The SafeWebCore row was re-baselined in the same pass: exact-value tests pin every preset header/CSP value, every NetSecureHeadersOptions default, the CspOptions.Build() output, every PermissionsFeature token, every validation rule, the middleware's full header set/events and the diagnostics snapshot. Direct unit tests then covered CspReportMiddleware (payload parsing, directive validation, event mapping, metrics), NetSecureHeadersDiagnosticsService (every header, the NEL/Reporting-Endpoints gates, the warnings and path normalisation), CspOptions/CspBuilder, the typed ReferrerPolicyBuilder/CrossOriginPolicyBuilder, the validator short-circuits and NonceService.TryWriteNonce, moving the score from 53.53 % (killed 440, survived 255, no coverage 127) to 89.18 % (killed 750, survived 68, no coverage 23). The 1.10.0 additions — sixteen new PermissionsPolicyBuilder tokens and the opt-in EmitHstsOnlyOverHttps switch — are pinned by PermissionsFeatureTokenTests and NetSecureHeadersHstsOverHttpsTests.

The SafeWebCore.JwtBearer row was re-baselined in the same pass: defaults tests pin both options classes, direct tests cover JwtBearerHardeningApplication (Apply wiring, the clock-skew clamp and every claim constraint), the configuration-validator branches, JwtBearerLoggingConfigurationPostConfigure, LoggingConfigurationManager (guards and address resolution) and the DI registration surface, moving the score from 57.43 % (killed 142 + 1 timeout, survived 66, no coverage 40) to 93.57 % (killed 232 + 1 timeout, survived 14, no coverage 2).

The SafeWebCore.Analyzers suite is new in the same pass and starts at 48.23 % (killed 67 + 1 timeout, survived 65, no coverage 8). DiagnosticDescriptorsTests pins every property of all six descriptors, a theory covers all twelve registration method names, and the pattern-analyzer edge tests cover interpolated strings, bare https:, the HSTS max-age parsing variants (missing/whitespace/no-digit/zero) and whitespace-only object-src, moving the score to 91.49 % (killed 127 + 2 timeouts, survived 11, no coverage 1).

Analyzers need one testability detail: static readonly field initializers are reported by Stryker as static mutants, which are always run against the whole suite and are not attributed to a test (and, for this netstandard2.0 project-reference setup, were never actually applied — they all showed coveredBy: []). Both descriptor groups are therefore created in an expression-bodied property / on the analyzer instance instead, which turns those literals into ordinary mutants that the tests kill.

SWC007 (HstsValue with a max-age but no includeSubDomains) and SWC008 (Cross-Origin-Opener-Policy: unsafe-none, via CoopValue or the fluent CoopUnsafeNone()) were added afterwards with their own positive/negative tests and four new descriptor strings, followed by SWC009 (an empty or whitespace PermissionsPolicyValue, which still emits the header while denying nothing) and SWC010 (COEP require-corp while CORP is explicitly disabled). Every behavioural mutant of the four rules is killed; the score reads 90.67 % only because each new analyzer adds two more equivalent ConfigureGeneratedCodeAnalysis / EnableConcurrentExecution statements to the denominator.

The SafeWebCore.Testing suite is also new: HeaderAssertionsTests (the aggregate header assert plus a missing-header fact for each of the nine headers, content-header lookup, AssertHeaderValue — including the found-value list in the failure message — AssertHasNoHeader, and both CSP mode helpers), CspNonceAssertionsTests (both header names, the enforce-before-report-only precedence, the missing-header and no-nonce paths, and that a nonce token is not assembled across separate header values), CspDirectiveAssertionsTests (AssertCspDirective / AssertHasNoCspDirective, boolean directives, case-insensitive names, the enforce-header precedence and the space join) and TestHostBootstrapExtensionsTests (both overloads against a real TestServer, headers, body and the custom-option path) take it from a first measured 88.61 % to 96.62 % (killed 70 → 143; the Array.Exists refactor that satisfied Sonar's S3267 also removed the loop's mutants).

What the survivors say

Area Surviving mutations Reading
SecurePresets, NetSecureHeadersOptions, PermissionsPolicyBuilder, NetSecureHeadersOptionsValidator ✅ resolved Exact-value tests pin every preset, default, permission token and validation rule.
NetSecureHeadersDiagnosticsService ✅ resolved The preview snapshot, NEL/Reporting-Endpoints gates, warnings and path normalisation are pinned per scenario.
ServiceCollectionExtensions, CspReportMiddleware 25 + 11 / 6 + 2 survived Equivalent: a deleted registration guard still throws from the inner AddNetSecureHeaders, and the remaining report-middleware mutants are the empty-catch null return and the non-object payload path that ends in the same 400.
NetSecureHeadersMiddleware, CspOptions, CspBuilder ✅ resolved Header branches, Build() directives and every fluent method are pinned.
JwtBearerHardeningApplication, JwtBearerLoggingConfigurationPostConfigure, both options classes ✅ resolved Every hardening rule, the claim constraints and the decorator paths are pinned.
JwtAuthorityValidationGuard, LoggingConfigurationManager 6 + 2 / 3 survived Stop/Dispose statements that only release resources and the rate-limit booleans, whose observable output is identical in every tested path.
JwtBearer DI guards, JwtBearerConfigurationValidator string edges 3 + 2 survived Equivalent: a deleted registration guard still throws from the inner Configure/AddOptions, and the two validator mutants only differ for whitespace-only values that never resolve an issuer.
SafeWebCore.Analyzers 20 + 1 survived Equivalent: the ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None) / EnableConcurrentExecution() statements of all nine analyzers (dropping them changes no diagnostic), the string.Empty default arm of the two syntax-name switches, the start <= value.Length bound that the harness swallows as an analyzer exception, and SWC010's `!string.Equals(...)
SafeWebCore.Testing 5 survived Equivalent: the delegated ThrowIfNull(response) in AssertHasSecurityHeaders (the first AssertHeaderExists call re-guards with the same exception), the separator < 0 bound in FindDirectiveValue (a zero index cannot survive Trim(), counted twice) and the two MapGet("/") path literals (an empty pattern maps to the root route too).
FraudDetectionServiceCollectionExtensions 16 survived AddOptions / TryAdd registration-shape mutants; the behaviour is equivalent to the tests' pre-configured options.
PenTestSignalAnalyzer, SuspicionScorer 6 + 1 / 6 + 1 survived Equivalent mutants only: out-parameter sentinels, source-key fallback literals and defensive null-coalescing defaults that never run.
LoggingPenTestAuthorizationNotificationSender 3 survived A redundant IsEnabled guard (the [LoggerMessage] generator also guards) plus two join-separator mutations.
Rest of the fraud package (metrics, validator, detectors, webhook, RiskScore, defaults) ✅ resolved Every behavioural mutant in these files is covered by a test.

Every survivor maps to a test somebody could add, which is why the score is recorded per package instead of as one number.

Reading a report

  • Killed — the suite noticed the change; the good case.
  • Survived — the change is invisible to the tests: add an assertion, or accept it here with a reason.
  • No coverage — no test reaches the code: a missing scenario, or dead code.
  • Timeout — counts as detected: the mutant made the suite hang, which is a failure too.
  • Compile error — neither killed nor survived; ignore it when reading a score.

Improve one file at a time and re-run that suite (about 30 seconds each). Chasing the percentage without naming the survivor wastes time: the score only moves when a specific mutant dies.

Why this is not in CI

A run is fast today (~30 s per suite) but grows with the test count, and a mutation score is a trend, not a gate. The configs carry break: 0 so a run can never fail a build by itself. If this ever becomes a nightly check, add a separate workflow_dispatch workflow that runs dotnet tool restore plus the three commands above and uploads artifacts/stryker/** — do not add it to .github/workflows/ci.yml, which every pull request waits for.