From 027cf78e197e6bf5f0eaf1a3c34b144f7bbbf8ee Mon Sep 17 00:00:00 2001 From: AamiriYouness Date: Mon, 17 Aug 2026 12:46:37 +0100 Subject: [PATCH 1/2] Preserve malformed BenchmarkDotNet parameter fragments, add BGV306 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BdnParameterStringParser previously discarded any parameter fragment without an '=' with a bare `continue`, so a malformed fragment was indistinguishable from one that never existed by the time validation ran. Parse now returns a ParameterParseResult(Parameters, Issues) instead of a bare dictionary, classifying each malformed fragment as either MissingSeparator (no '=' at all) or EmptyKey ('=' present, key empty) via the new ParameterParseIssueKind enum. IdentityFactory.TryCreate is renamed to Create and widened to return IdentityCreationResult(Identity, ParameterIssues), since it's the single call site for parameter parsing shared by ObservationValidator, ObservationSetValidator, and BenchmarkDotNetResultParser — this keeps parsing happening exactly once rather than letting ObservationValidator reparse independently just to read issues. ObservationValidator now emits BGV306 (Error) per issue at /Benchmarks/{index}/Parameters. Fixture testing confirmed a malformed fragment can drop a parameter entirely and collapse two distinct benchmarks onto the same canonical identity, so BGV306 blocks compilation via the existing ValidationResult.IsValid path rather than being a cosmetic warning. Resolves #16. --- CHANGELOG.md | 20 ++ .../Parsing/BdnParameterStringParser.cs | 102 +++++++-- .../Parsing/BenchmarkDotNetResultParser.cs | 9 +- .../Validation/IdentityFactory.cs | 36 ++- .../Validation/ObservationSetValidator.cs | 2 +- .../Validation/ObservationValidator.cs | 28 ++- .../ObservationValidatorDiagnostics.cs | 3 + .../Fixtures/malformed-parameter.json | 37 ++++ .../Fixtures/parameter-collision.json | 61 ++++++ .../Parsing/BdnParameterStringParserTests.cs | 207 ++++++++++++++++++ .../BenchmarkDotNetResultParserTests.cs | 27 ++- 11 files changed, 497 insertions(+), 35 deletions(-) create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/malformed-parameter.json create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/parameter-collision.json create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BdnParameterStringParserTests.cs rename tests/BenchmarkGate.BenchmarkDotNet.Tests/{ => Parsing}/BenchmarkDotNetResultParserTests.cs (80%) diff --git a/CHANGELOG.md b/CHANGELOG.md index c3be4a7..9210c0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ All notable changes to BenchmarkGate are documented here. ## [Unreleased] +### Fixed +- `BdnParameterStringParser` no longer silently discards malformed BenchmarkDotNet + parameter fragments (e.g. `N1000000` missing its `=`, or `=1000000` with an empty + key). Parsing now returns both successfully parsed parameters and structured + parse issues via the new `ParameterParseResult`/`ParameterParseIssue` types. +- Added diagnostic `BGV306` (Error) — malformed BenchmarkDotNet parameter fragment, + reported at `/Benchmarks/{index}/Parameters`. A malformed fragment can silently + drop from a benchmark's identity, which was confirmed (via fixture testing) able + to collapse two otherwise-distinct benchmarks into the same canonical identity — + so this blocks observation compilation rather than being a cosmetic warning. + +### Changed +- `IdentityFactory.TryCreate` renamed to `IdentityFactory.Create` and now returns + `IdentityCreationResult(BenchmarkIdentity? Identity, IReadOnlyList ParameterIssues)` + instead of a bare `BenchmarkIdentity?`, so parameter-string interpretation happens + in exactly one place and both `ObservationValidator` and + `BenchmarkDotNetResultParser` consume the same result. All call sites + (`ObservationValidator`, `ObservationSetValidator`, `BenchmarkDotNetResultParser`) + updated accordingly. Pre-1.0 breaking change, no external consumers. + ## [0.4.0-alpha.1] - 06/08/2026 ### Added diff --git a/src/BenchmarkGate.BenchmarkDotNet/Parsing/BdnParameterStringParser.cs b/src/BenchmarkGate.BenchmarkDotNet/Parsing/BdnParameterStringParser.cs index aaca73a..22d8ca2 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Parsing/BdnParameterStringParser.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Parsing/BdnParameterStringParser.cs @@ -1,37 +1,103 @@ namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Parsing; +/// +/// The categories of malformed parameter fragment that +/// can encounter. Each corresponds +/// to a distinct malformed input shape — see . +/// No broader taxonomy is introduced until a concrete BenchmarkDotNet +/// output shape requires it (see Issue #16). +/// +internal enum ParameterParseIssueKind +{ + /// The fragment contains no '=' separator at all, e.g. "N1000000". + MissingSeparator, + + /// + /// The fragment contains a '=' separator, but the key portion before it + /// is empty, e.g. "=1000000". + /// + EmptyKey +} + +/// +/// One malformed fragment encountered while parsing a BenchmarkDotNet +/// parameter display string. Preserved rather than discarded so callers +/// can report a precise diagnostic instead of silently losing the +/// fragment. +/// +/// +/// The position of this fragment among the non-empty, comma-separated +/// fragments of the display string (empty fragments, e.g. from a trailing +/// comma, are skipped before indexing — matching this parser's prior +/// behavior — so this is not a raw character offset). +/// +/// +/// The raw, untrimmed fragment text exactly as it appeared in the display +/// string. +/// +/// The specific way this fragment is malformed. +internal sealed record ParameterParseIssue( + int FragmentIndex, + string Fragment, + ParameterParseIssueKind Kind); + +/// +/// The outcome of parsing a BenchmarkDotNet parameter display string: +/// every successfully parsed key/value pair, plus every malformed +/// fragment encountered along the way. Both are preserved in full so +/// downstream diagnostics never need to reparse or guess — see Issue #16. +/// +/// Successfully parsed key/value pairs, keyed by parameter name. +/// +/// Malformed fragments encountered during parsing, in the order they were +/// found. Empty when every fragment parsed successfully. +/// +internal sealed record ParameterParseResult( + IReadOnlyDictionary Parameters, + IReadOnlyList Issues); + /// /// Parses BenchmarkDotNet's single-string parameter display format -/// ("N=1000000,Distribution=Canonical") into a key/value dictionary. -/// Key ordering and invariant-culture value normalization are handled by -/// itself; this class only -/// splits the display string. +/// ("N=1000000,Distribution=Canonical") into a key/value dictionary, +/// preserving any malformed fragments encountered rather than discarding +/// them. Key ordering and invariant-culture value normalization are +/// handled by itself; this +/// class only splits the display string. /// internal static class BdnParameterStringParser { - public static Dictionary Parse(string? parametersDisplayString) + public static ParameterParseResult Parse(string? parametersDisplayString) { - var result = new Dictionary(StringComparer.Ordinal); + var parameters = new Dictionary(StringComparer.Ordinal); + var issues = new List(); if (string.IsNullOrWhiteSpace(parametersDisplayString)) - return result; + return new ParameterParseResult(parameters, issues); + + var fragments = parametersDisplayString.Split(',', StringSplitOptions.RemoveEmptyEntries); - foreach (var pair in parametersDisplayString.Split(',', StringSplitOptions.RemoveEmptyEntries)) + for (var fragmentIndex = 0; fragmentIndex < fragments.Length; fragmentIndex++) { - var separatorIndex = pair.IndexOf('='); - if (separatorIndex <= 0) + var fragment = fragments[fragmentIndex]; + var separatorIndex = fragment.IndexOf('='); + + if (separatorIndex < 0) { - // Malformed pair without '=' — skip rather than throw here; - // the identity will simply not include this fragment. - // A future version could surface this as a diagnostic. + issues.Add(new ParameterParseIssue(fragmentIndex, fragment, ParameterParseIssueKind.MissingSeparator)); continue; } - var key = pair[..separatorIndex].Trim(); - var value = pair[(separatorIndex + 1)..].Trim(); - result[key] = value; + if (separatorIndex == 0) + { + issues.Add(new ParameterParseIssue(fragmentIndex, fragment, ParameterParseIssueKind.EmptyKey)); + continue; + } + + var key = fragment[..separatorIndex].Trim(); + var value = fragment[(separatorIndex + 1)..].Trim(); + parameters[key] = value; } - return result; + return new ParameterParseResult(parameters, issues); } -} +} \ No newline at end of file diff --git a/src/BenchmarkGate.BenchmarkDotNet/Parsing/BenchmarkDotNetResultParser.cs b/src/BenchmarkGate.BenchmarkDotNet/Parsing/BenchmarkDotNetResultParser.cs index a41fd45..64c832a 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Parsing/BenchmarkDotNetResultParser.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Parsing/BenchmarkDotNetResultParser.cs @@ -79,10 +79,11 @@ private static List CompileObservations(BdnReportRootDto d private static BenchmarkObservation CompileObservation(BdnBenchmarkDto benchmark) { // Trusts ObservationValidator has already confirmed Type, Method, - // and Statistics.Mean are present — this method does not re-check - // them, matching PolicyCompiler/BaselineCompiler's CompileValidated - // pattern (one implementation of each rule, not two). - var identity = IdentityFactory.TryCreate(benchmark) + // Statistics.Mean, and parameter-fragment well-formedness (BGV306) + // — this method does not re-check them, matching + // PolicyCompiler/BaselineCompiler's CompileValidated pattern (one + // implementation of each rule, not two). + var identity = IdentityFactory.Create(benchmark).Identity ?? throw new InvalidOperationException( "CompileObservation called with an entry that did not pass ObservationValidator."); diff --git a/src/BenchmarkGate.BenchmarkDotNet/Validation/IdentityFactory.cs b/src/BenchmarkGate.BenchmarkDotNet/Validation/IdentityFactory.cs index b20b1fd..9fb1018 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Validation/IdentityFactory.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Validation/IdentityFactory.cs @@ -3,13 +3,31 @@ namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Validation; +/// +/// The outcome of interpreting one BdnBenchmarkDto as a BenchmarkIdentity: +/// the identity itself, plus any malformed parameter fragments +/// encountered while parsing. Identity is absent only when Type or Method +/// is missing — the caller is responsible for having already reported +/// that via BGV301/BGV302. +/// +/// The constructed identity, or null if Type or Method was missing. +/// +/// Malformed parameter fragments encountered while parsing, in the order +/// they were found. Empty when parsing succeeded cleanly or was not +/// attempted (Identity is null). +/// +internal sealed record IdentityCreationResult( + BenchmarkIdentity? Identity, + IReadOnlyList ParameterIssues); + /// /// Builds a BenchmarkIdentity from a raw BdnBenchmarkDto, shared by /// ObservationValidator (duplicate detection) and -/// BenchmarkDotNetResultParser (final BenchmarkObservation compilation) -/// so identity composition exists in exactly one place. Returns null only -/// when Type or Method is missing — the caller is responsible for having -/// already reported that via BGV301/BGV302. +/// BenchmarkDotNetResultParser (final BenchmarkObservation compilation) so +/// identity composition — and parameter-string parsing — exists in +/// exactly one place. ObservationValidator must never call +/// BdnParameterStringParser directly; all interpretation of a benchmark's +/// raw parameter string goes through this class (see Issue #16). /// internal static class IdentityFactory { @@ -18,14 +36,16 @@ internal static class IdentityFactory private static readonly System.Text.RegularExpressions.Regex JobTokenPattern = new(@": (?[^\s(]+)", System.Text.RegularExpressions.RegexOptions.Compiled); - internal static BenchmarkIdentity? TryCreate(BdnBenchmarkDto benchmark) + internal static IdentityCreationResult Create(BdnBenchmarkDto benchmark) { if (string.IsNullOrWhiteSpace(benchmark.Type) || string.IsNullOrWhiteSpace(benchmark.Method)) - return null; + return new IdentityCreationResult(Identity: null, ParameterIssues: []); var job = ExtractJob(benchmark.DisplayInfo); - var parameters = BdnParameterStringParser.Parse(benchmark.Parameters); - return new BenchmarkIdentity(benchmark.Type, benchmark.Method, job, parameters); + var parameterResult = BdnParameterStringParser.Parse(benchmark.Parameters); + var identity = new BenchmarkIdentity(benchmark.Type, benchmark.Method, job, parameterResult.Parameters); + + return new IdentityCreationResult(identity, parameterResult.Issues); } private static string ExtractJob(string? displayInfo) diff --git a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationSetValidator.cs b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationSetValidator.cs index ed10128..09ae86c 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationSetValidator.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationSetValidator.cs @@ -24,7 +24,7 @@ internal static IReadOnlyList ValidateWithSources( foreach (var benchmark in parsed.Document.Benchmarks ?? []) { - var identity = IdentityFactory.TryCreate(benchmark); + var identity = IdentityFactory.Create(benchmark).Identity; if (identity is null || !identitiesInThisFile.Add(identity)) continue; diff --git a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidator.cs b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidator.cs index 4b17173..9f90614 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidator.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidator.cs @@ -8,7 +8,9 @@ namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Validation; /// Validates one deserialized BenchmarkDotNet report document, collecting /// every finding in one pass rather than failing fast. Adapter-owned per /// ADR-0003 — Core has no knowledge of BenchmarkDotNet's document shape or -/// these BGV3xx codes. +/// these BGV3xx codes. Parameter-string parsing is never performed here +/// directly — all identity/parameter interpretation goes through +/// IdentityFactory (see Issue #16). /// internal static class ObservationValidator { @@ -61,8 +63,17 @@ internal static ValidationResult Validate(BdnReportRootDto document) // constructible identity — an entry already missing Type/Method // has no trustworthy identity to compare, and would otherwise // produce a spurious duplicate alongside its real BGV301/302. - var identity = IdentityFactory.TryCreate(benchmark); - if (identity is not null && !seenIdentities.Add(identity)) + var identityResult = IdentityFactory.Create(benchmark); + + foreach (var issue in identityResult.ParameterIssues) + { + diagnostics.Add(new ValidationDiagnostic( + ObservationValidatorDiagnostics.MalformedParameterFragment, + $"{path}/Parameters", + DescribeParameterIssue(issue))); + } + + if (identityResult.Identity is { } identity && !seenIdentities.Add(identity)) { diagnostics.Add(new ValidationDiagnostic( ObservationValidatorDiagnostics.DuplicateIdentityWithinFile, path, @@ -72,4 +83,15 @@ internal static ValidationResult Validate(BdnReportRootDto document) return new ValidationResult(diagnostics); } + + private static string DescribeParameterIssue(ParameterParseIssue issue) => issue.Kind switch + { + ParameterParseIssueKind.MissingSeparator => + $"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: " + + $"'{issue.Fragment}' does not contain a '=' separator.", + ParameterParseIssueKind.EmptyKey => + $"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: " + + $"'{issue.Fragment}' has an empty parameter name.", + _ => $"Malformed BenchmarkDotNet parameter fragment at position {issue.FragmentIndex}: '{issue.Fragment}'.", + }; } \ No newline at end of file diff --git a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidatorDiagnostics.cs b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidatorDiagnostics.cs index 6107a5f..6d05ab0 100644 --- a/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidatorDiagnostics.cs +++ b/src/BenchmarkGate.BenchmarkDotNet/Validation/ObservationValidatorDiagnostics.cs @@ -14,10 +14,13 @@ internal static class ObservationValidatorDiagnostics new("BGV304", "Duplicate benchmark identity within one file", Core.Validation.DiagnosticSeverity.Error); internal static readonly Core.Validation.DiagnosticDescriptor DuplicateIdentityAcrossFiles = new("BGV305", "Duplicate benchmark identity across result files", Core.Validation.DiagnosticSeverity.Error); + internal static readonly Core.Validation.DiagnosticDescriptor MalformedParameterFragment = + new("BGV306", "Malformed BenchmarkDotNet parameter fragment", Core.Validation.DiagnosticSeverity.Error); internal static IReadOnlyList All { get; } = [ MissingBenchmarks, MissingType, MissingMethod, MissingMean, DuplicateIdentityWithinFile, DuplicateIdentityAcrossFiles, + MalformedParameterFragment, ]; } \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/malformed-parameter.json b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/malformed-parameter.json new file mode 100644 index 0000000..a97b309 --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/malformed-parameter.json @@ -0,0 +1,37 @@ +{ + "Title": "MalformedParameter-report-full", + "HostEnvironmentInfo": { + "BenchmarkDotNetCaption": "BenchmarkDotNet", + "BenchmarkDotNetVersion": "0.14.0", + "OsVersion": "Linux", + "ProcessorName": "Unknown", + "RuntimeVersion": ".NET 10.0.0" + }, + "Benchmarks": [ + { + "DisplayInfo": "MalformedParam: DefaultJob [N1000000]", + "Namespace": "Recon.Benchmarks", + "Type": "Recon.Benchmarks.ClassificationBenchmarks", + "Method": "MalformedParam", + "MethodTitle": "MalformedParam", + "Parameters": "N1000000", + "FullName": "Recon.Benchmarks.ClassificationBenchmarks.MalformedParam(N1000000)", + "Statistics": { + "N": 15, + "Min": 4400000.0, + "Mean": 4540000.0, + "Median": 4510000.0, + "Max": 4700000.0, + "StandardDeviation": 85000.0, + "StandardError": 22000.0 + }, + "Memory": { + "Gen0Collections": 0, + "Gen1Collections": 0, + "Gen2Collections": 0, + "TotalOperations": 15, + "BytesAllocatedPerOperation": 0 + } + } + ] +} \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/parameter-collision.json b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/parameter-collision.json new file mode 100644 index 0000000..86fb804 --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/parameter-collision.json @@ -0,0 +1,61 @@ +{ + "Title": "ParameterCollision-report-full", + "HostEnvironmentInfo": { + "BenchmarkDotNetCaption": "BenchmarkDotNet", + "BenchmarkDotNetVersion": "0.14.0", + "OsVersion": "Linux", + "ProcessorName": "Unknown", + "RuntimeVersion": ".NET 10.0.0" + }, + "Benchmarks": [ + { + "DisplayInfo": "CollisionCase: DefaultJob [N1000000]", + "Namespace": "Recon.Benchmarks", + "Type": "Recon.Benchmarks.ClassificationBenchmarks", + "Method": "CollisionCase", + "MethodTitle": "CollisionCase", + "Parameters": "N1000000", + "FullName": "Recon.Benchmarks.ClassificationBenchmarks.CollisionCase(N1000000)", + "Statistics": { + "N": 15, + "Min": 4400000.0, + "Mean": 4540000.0, + "Median": 4510000.0, + "Max": 4700000.0, + "StandardDeviation": 85000.0, + "StandardError": 22000.0 + }, + "Memory": { + "Gen0Collections": 0, + "Gen1Collections": 0, + "Gen2Collections": 0, + "TotalOperations": 15, + "BytesAllocatedPerOperation": 0 + } + }, + { + "DisplayInfo": "CollisionCase: DefaultJob", + "Namespace": "Recon.Benchmarks", + "Type": "Recon.Benchmarks.ClassificationBenchmarks", + "Method": "CollisionCase", + "MethodTitle": "CollisionCase", + "FullName": "Recon.Benchmarks.ClassificationBenchmarks.CollisionCase()", + "Statistics": { + "N": 15, + "Min": 4400000.0, + "Mean": 4540000.0, + "Median": 4510000.0, + "Max": 4700000.0, + "StandardDeviation": 85000.0, + "StandardError": 22000.0 + }, + "Memory": { + "Gen0Collections": 0, + "Gen1Collections": 0, + "Gen2Collections": 0, + "TotalOperations": 15, + "BytesAllocatedPerOperation": 0 + } + } + ] +} \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BdnParameterStringParserTests.cs b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BdnParameterStringParserTests.cs new file mode 100644 index 0000000..51dd7aa --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BdnParameterStringParserTests.cs @@ -0,0 +1,207 @@ +using Bijecta.BenchmarkGate.BenchmarkDotNet.Parsing; +using FluentAssertions; +using Xunit; + +namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Tests; + +public class BdnParameterStringParserTests +{ + // --- Null / empty / whitespace input --- + + [Fact] + public void Returns_empty_result_when_input_is_null() + { + var result = BdnParameterStringParser.Parse(null); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Returns_empty_result_when_input_is_an_empty_string() + { + var result = BdnParameterStringParser.Parse(string.Empty); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Returns_empty_result_when_input_is_whitespace_only() + { + var result = BdnParameterStringParser.Parse(" "); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().BeEmpty(); + } + + // --- Valid parsing (existing behavior, must remain unchanged) --- + + [Fact] + public void Parses_single_valid_fragment_into_one_parameter() + { + var result = BdnParameterStringParser.Parse("N=1000000"); + + result.Parameters.Should().ContainSingle() + .Which.Should().Be(new KeyValuePair("N", "1000000")); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Parses_multiple_valid_fragments_into_all_parameters() + { + var result = BdnParameterStringParser.Parse("N=1000000,Distribution=Canonical"); + + result.Parameters.Should().HaveCount(2); + result.Parameters.Should().ContainKey("N").WhoseValue.Should().Be("1000000"); + result.Parameters.Should().ContainKey("Distribution").WhoseValue.Should().Be("Canonical"); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Trims_whitespace_around_keys_and_values() + { + var result = BdnParameterStringParser.Parse(" N = 1000000 , Distribution = Canonical "); + + result.Parameters.Should().ContainKey("N").WhoseValue.Should().Be("1000000"); + result.Parameters.Should().ContainKey("Distribution").WhoseValue.Should().Be("Canonical"); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Splits_on_first_equals_sign_when_value_itself_contains_equals() + { + var result = BdnParameterStringParser.Parse("Expr=a=b"); + + result.Parameters.Should().ContainKey("Expr").WhoseValue.Should().Be("a=b"); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Last_value_wins_for_duplicate_keys() + { + var result = BdnParameterStringParser.Parse("N=1,N=2"); + + result.Parameters.Should().ContainSingle(); + result.Parameters.Should().ContainKey("N").WhoseValue.Should().Be("2"); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Ignores_empty_fragment_after_a_trailing_comma() + { + var result = BdnParameterStringParser.Parse("N=1000000,"); + + result.Parameters.Should().ContainSingle(); + result.Issues.Should().BeEmpty(); + } + + [Fact] + public void Ignores_empty_fragments_between_consecutive_commas() + { + var result = BdnParameterStringParser.Parse("N=1000000,,Distribution=Canonical"); + + result.Parameters.Should().HaveCount(2); + result.Issues.Should().BeEmpty(); + } + + // --- MissingSeparator --- + + [Fact] + public void Records_missing_separator_issue_for_fragment_without_an_equals_sign() + { + var result = BdnParameterStringParser.Parse("N1000000"); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().ContainSingle().Which.Should().BeEquivalentTo(new + { + FragmentIndex = 0, + Fragment = "N1000000", + Kind = ParameterParseIssueKind.MissingSeparator, + }); + } + + [Fact] + public void Records_one_missing_separator_issue_per_fragment_when_several_lack_a_separator() + { + var result = BdnParameterStringParser.Parse("N1000000,Distribution"); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().SatisfyRespectively( + first => + { + first.Kind.Should().Be(ParameterParseIssueKind.MissingSeparator); + first.Fragment.Should().Be("N1000000"); + first.FragmentIndex.Should().Be(0); + }, + second => + { + second.Kind.Should().Be(ParameterParseIssueKind.MissingSeparator); + second.Fragment.Should().Be("Distribution"); + second.FragmentIndex.Should().Be(1); + }); + } + + // --- EmptyKey --- + + [Fact] + public void Records_empty_key_issue_for_fragment_starting_with_equals() + { + var result = BdnParameterStringParser.Parse("=1000000"); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().ContainSingle().Which.Should().BeEquivalentTo(new + { + FragmentIndex = 0, + Fragment = "=1000000", + Kind = ParameterParseIssueKind.EmptyKey, + }); + } + + [Fact] + public void Records_empty_key_issue_when_fragment_is_only_an_equals_sign() + { + // separatorIndex == 0 either way; the key being empty is what's + // classified, not the (also-empty) value. + var result = BdnParameterStringParser.Parse("="); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().ContainSingle() + .Which.Kind.Should().Be(ParameterParseIssueKind.EmptyKey); + } + + // --- Mixed valid + malformed --- + + [Fact] + public void Preserves_both_valid_parameters_and_malformed_fragments_in_order() + { + var result = BdnParameterStringParser.Parse("N=1000000,Junk,Distribution=Canonical,=5"); + + result.Parameters.Should().HaveCount(2); + result.Parameters.Should().ContainKey("N").WhoseValue.Should().Be("1000000"); + result.Parameters.Should().ContainKey("Distribution").WhoseValue.Should().Be("Canonical"); + + result.Issues.Should().SatisfyRespectively( + first => + { + first.Kind.Should().Be(ParameterParseIssueKind.MissingSeparator); + first.Fragment.Should().Be("Junk"); + first.FragmentIndex.Should().Be(1); // 2nd non-empty fragment + }, + second => + { + second.Kind.Should().Be(ParameterParseIssueKind.EmptyKey); + second.Fragment.Should().Be("=5"); + second.FragmentIndex.Should().Be(3); // 4th non-empty fragment + }); + } + + [Fact] + public void Returns_empty_parameters_when_every_fragment_is_malformed() + { + var result = BdnParameterStringParser.Parse("Junk,=5,MoreJunk"); + + result.Parameters.Should().BeEmpty(); + result.Issues.Should().HaveCount(3); + } +} \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/BenchmarkDotNetResultParserTests.cs b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs similarity index 80% rename from tests/BenchmarkGate.BenchmarkDotNet.Tests/BenchmarkDotNetResultParserTests.cs rename to tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs index 1a53cd4..f03b409 100644 --- a/tests/BenchmarkGate.BenchmarkDotNet.Tests/BenchmarkDotNetResultParserTests.cs +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs @@ -3,7 +3,7 @@ using FluentAssertions; using Xunit; -namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Tests; +namespace Bijecta.BenchmarkGate.BenchmarkDotNet.Tests.Parsing; public class BenchmarkDotNetResultParserTests { @@ -143,4 +143,29 @@ public void Cross_file_duplicate_identity_throws_with_BGV305() exception.ValidationResult.Should().NotBeNull(); exception.ValidationResult!.Diagnostics.Should().ContainSingle(d => d.Descriptor.Id == "BGV305"); } + + [Fact] + public void Malformed_parameter_fragment_throws_with_BGV306() + { + var act = () => BenchmarkDotNetResultParser.ParseFile(FixturePath("malformed-parameter.json")); + + var exception = act.Should().Throw().Which; + exception.ValidationResult.Should().NotBeNull(); + exception.ValidationResult!.Diagnostics.Should().ContainSingle(d => d.Descriptor.Id == "BGV306"); + } + + [Fact] + public void Malformed_fragment_that_drops_the_only_parameter_can_collide_with_a_parameterless_benchmark() + { + // parameter-collision.json: two entries, same Type/Method/DisplayInfo — + // one has Parameters "N1000000" (malformed, parses to {}), the other + // has no Parameters at all — both resolve to the same canonical + // identity once the malformed fragment is dropped. + var act = () => BenchmarkDotNetResultParser.ParseFile(FixturePath("parameter-collision.json")); + + var exception = act.Should().Throw().Which; + exception.ValidationResult.Should().NotBeNull(); + exception.ValidationResult!.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV306"); + exception.ValidationResult!.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV304"); + } } \ No newline at end of file From e061b0dededace9b99f019f2115b1cad5fb78085 Mon Sep 17 00:00:00 2001 From: AamiriYouness Date: Mon, 17 Aug 2026 14:50:34 +0100 Subject: [PATCH 2/2] Add missing test coverage for BenchmarkDotNetResultParser --- .../Fixtures/ValidMultiFile/file-a.json | 11 +++ .../Fixtures/ValidMultiFile/file-b.json | 11 +++ .../Fixtures/null-document.json | 1 + .../BenchmarkDotNetResultParserTests.cs | 44 +++++++++ .../Validation/ObservationValidatorTests.cs | 96 +++++++++++++++++++ 5 files changed, 163 insertions(+) create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-a.json create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-b.json create mode 100644 tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/null-document.json diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-a.json b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-a.json new file mode 100644 index 0000000..d416f55 --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-a.json @@ -0,0 +1,11 @@ +{ + "Title": "ValidMultiFile-a", + "Benchmarks": [ + { + "Type": "Ns.MultiFile", + "Method": "MethodA", + "Parameters": "N=1", + "Statistics": { "Mean": 100.0 } + } + ] +} \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-b.json b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-b.json new file mode 100644 index 0000000..e8004cd --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/ValidMultiFile/file-b.json @@ -0,0 +1,11 @@ +{ + "Title": "ValidMultiFile-b", + "Benchmarks": [ + { + "Type": "Ns.MultiFile", + "Method": "MethodB", + "Parameters": "N=1", + "Statistics": { "Mean": 200.0 } + } + ] +} \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/null-document.json b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/null-document.json new file mode 100644 index 0000000..ec747fa --- /dev/null +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Fixtures/null-document.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs index f03b409..dfcc121 100644 --- a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Parsing/BenchmarkDotNetResultParserTests.cs @@ -168,4 +168,48 @@ public void Malformed_fragment_that_drops_the_only_parameter_can_collide_with_a_ exception.ValidationResult!.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV306"); exception.ValidationResult!.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV304"); } + + [Fact] + public void ParsePath_on_a_directory_with_no_json_files_throws_typed_exception() + { + var emptyDirectory = Path.Combine(AppContext.BaseDirectory, "Fixtures", "EmptyDirectory"); + Directory.CreateDirectory(emptyDirectory); + + var act = () => BenchmarkDotNetResultParser.ParsePath(emptyDirectory); + + act.Should().Throw() + .WithMessage("*No *.json result files found*"); + } + + [Fact] + public void ParsePath_on_a_nonexistent_path_throws_typed_exception() + { + var path = Path.Combine(AppContext.BaseDirectory, "Fixtures", "does-not-exist-at-all"); + + var act = () => BenchmarkDotNetResultParser.ParsePath(path); + + act.Should().Throw() + .WithMessage("*Results path does not exist*"); + } + + [Fact] + public void Document_that_deserializes_to_null_throws_typed_exception() + { + // null-document.json contains the literal JSON token `null`. + var act = () => BenchmarkDotNetResultParser.ParseFile(FixturePath("null-document.json")); + + act.Should().Throw() + .WithMessage("*deserialized to null*"); + } + + [Fact] + public void ParsePath_on_a_directory_with_valid_files_returns_merged_observations() + { + var directory = Path.Combine(AppContext.BaseDirectory, "Fixtures", "ValidMultiFile"); + + var observations = BenchmarkDotNetResultParser.ParsePath(directory); + + observations.Should().HaveCount(2); + observations.Select(o => o.Identity.MethodName).Should().BeEquivalentTo(["MethodA", "MethodB"]); + } } \ No newline at end of file diff --git a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Validation/ObservationValidatorTests.cs b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Validation/ObservationValidatorTests.cs index b2b4d49..0de394b 100644 --- a/tests/BenchmarkGate.BenchmarkDotNet.Tests/Validation/ObservationValidatorTests.cs +++ b/tests/BenchmarkGate.BenchmarkDotNet.Tests/Validation/ObservationValidatorTests.cs @@ -147,6 +147,102 @@ public void All_observation_diagnostic_ids_match_the_BGV3_convention(Core.Valida descriptor.Id.Should().MatchRegex("^BGV3\\d{2}$"); } + [Fact] + public void Missing_separator_fragment_reports_BGV306() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "N1000000"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Should().ContainSingle(d => d.Descriptor.Id == "BGV306"); + } + + [Fact] + public void Empty_key_fragment_reports_BGV306() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "=1000000"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Should().ContainSingle(d => d.Descriptor.Id == "BGV306"); + } + + [Fact] + public void BGV306_diagnostic_path_targets_the_parameters_field() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "N1000000"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Should().ContainSingle(d => d.Path == "/Benchmarks/0/Parameters"); + } + + [Fact] + public void BGV306_message_identifies_a_missing_separator_fragment() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "N1000000"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Single(d => d.Descriptor.Id == "BGV306").Message + .Should().Contain("N1000000").And.Contain("does not contain a '=' separator"); + } + + [Fact] + public void BGV306_message_identifies_an_empty_key_fragment() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "=1000000"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Single(d => d.Descriptor.Id == "BGV306").Message + .Should().Contain("=1000000").And.Contain("empty parameter name"); + } + + [Fact] + public void Multiple_malformed_fragments_in_one_benchmark_each_report_their_own_BGV306() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "Junk,=5"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Where(d => d.Descriptor.Id == "BGV306").Should().HaveCount(2); + } + + [Fact] + public void Well_formed_parameters_do_not_report_BGV306() + { + var benchmark = ValidBenchmark(); + benchmark.Parameters = "N=1,M=2"; + + var result = ObservationValidator.Validate(ValidDocument([benchmark])); + + result.Diagnostics.Should().NotContain(d => d.Descriptor.Id == "BGV306"); + } + + [Fact] + public void Missing_separator_fragment_that_drops_the_only_parameter_causes_a_collision_reported_as_BGV304_and_BGV306() + { + // Two benchmarks, same Type/Method/Job — one has a malformed + // parameter that parses to {}, the other has none at all. Once the + // fragment is dropped, both resolve to the same canonical identity. + var malformed = ValidBenchmark(); + malformed.Parameters = "N1000000"; + var parameterless = ValidBenchmark(); + parameterless.Parameters = null; + + var result = ObservationValidator.Validate(ValidDocument([malformed, parameterless])); + + result.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV306"); + result.Diagnostics.Should().Contain(d => d.Descriptor.Id == "BGV304"); + } + public static IEnumerable AllObservationDescriptors() => ObservationValidatorDiagnostics.All.Select(d => new object[] { d }); } \ No newline at end of file