diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bd75df..4ac96ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,13 @@ All notable changes to BenchmarkGate are documented here. `compare` pipeline. Deterministic output ordering via a new `Core.Identity.BenchmarkIdentityComparer`. Policy-free — no threshold or pass/fail vocabulary. +- `Reporting.ConsoleComparisonReporter`, `Reporting.JsonComparisonReporter`, + `Reporting.MarkdownComparisonReporter` — console, JSON (`schemaVersion=1`, + independently versioned, full precision preserved), and Markdown output + for `ComparisonResult`. No JUnit — no test verdict exists for a + policy-free comparison. No pass/fail vocabulary in any of the three. +- `Reporting.MarkdownBuilder.CodeSpan` — CommonMark-safe backtick-delimited + code spans. ### Changed - `Core.Comparison.MetricValue.Unit` is now `string?` rather than `string`. diff --git a/src/BenchmarkGate.Reporting/ComparisonValueFormatter.cs b/src/BenchmarkGate.Reporting/ComparisonValueFormatter.cs new file mode 100644 index 0000000..e2a2cd2 --- /dev/null +++ b/src/BenchmarkGate.Reporting/ComparisonValueFormatter.cs @@ -0,0 +1,74 @@ +using Bijecta.BenchmarkGate.Core.Comparison; +using Bijecta.BenchmarkGate.Core.Evaluation; +using System.Globalization; + +namespace Bijecta.BenchmarkGate.Reporting; + +/// +/// Shared formatting for human-readable comparison reporters (Console, +/// Markdown). Policy-free — this is reporting-layer sharing, not a Core +/// dependency. +/// +internal static class ComparisonValueFormatter +{ + /// + /// Formats a raw metric value. Uses as + /// the source of truth for whether a known-unit formatter applies — + /// when unit is null (unknown metric), falls back to a raw + /// round-trippable numeric representation rather than reconstructing + /// unit semantics from the metric name alone. + /// + public static string FormatMetricValue(string metricName, MetricValue? value) + { + if (value is not { } metricValue) + { + return "-"; + } + + return metricValue.Unit is null + ? metricValue.Value.ToString("G17", CultureInfo.InvariantCulture) + : MetricFormatters.For(metricName).Format(metricValue.Value); + } + + /// + /// Formats an absolute delta with an explicit "+" for positive values + /// (formatter output already carries "-" naturally for negative ones). + /// Meaningful even when is + /// null (a zero-reference change) — callers must not skip this column + /// just because the percent column shows "n/a". + /// + /// + /// The metric's name, used to select a display formatter when + /// is known. + /// + /// + /// The comparison's known unit for this metric (from either side's + /// — safe to use either today, since + /// genuine unit-mismatch detection isn't producible yet and a + /// Comparable metric receives the same catalog-derived unit on both + /// sides). Null means unknown, same as 's + /// contract — the delta then gets a raw round-trippable representation + /// rather than assuming a formatter derived from the metric name alone + /// knows the right unit. + /// + /// + /// The raw delta from , or + /// null when no delta was computed (any non-Comparable metric status). + /// + public static string FormatAbsoluteDelta(string metricName, string? unit, double? absoluteDelta) + { + if (absoluteDelta is not { } delta) + { + return "-"; + } + + var formatted = unit is null + ? delta.ToString("G17", CultureInfo.InvariantCulture) + : MetricFormatters.For(metricName).Format(delta); + + return delta > 0d ? $"+{formatted}" : formatted; + } + + public static string FormatPercentDelta(double? percentDelta) => + percentDelta is { } percent ? MarkdownBuilder.FormatDeltaPercent(percent) : "n/a"; +} \ No newline at end of file diff --git a/src/BenchmarkGate.Reporting/ConsoleComparisonReporter.cs b/src/BenchmarkGate.Reporting/ConsoleComparisonReporter.cs new file mode 100644 index 0000000..8f5c6b4 --- /dev/null +++ b/src/BenchmarkGate.Reporting/ConsoleComparisonReporter.cs @@ -0,0 +1,129 @@ +using System.Globalization; +using Bijecta.BenchmarkGate.Core.Comparison; + +namespace Bijecta.BenchmarkGate.Reporting; + +/// +/// Renders a as a compact console table. One +/// printed row per (benchmark, metric) pair for Comparable benchmarks; +/// Added/Removed benchmarks are listed separately by name, not folded into +/// the metric table, since they have no meaningful reference-vs-candidate +/// row. Reporting only consumes the comparison result — it never +/// re-compares anything, and never prints SuiteDecision's pass/fail +/// vocabulary (Passed/Warning/Regressed/Unstable). +/// +/// +/// Preserves ' given order rather +/// than re-sorting — per ADR-0004, canonical ordering is +/// BenchmarkComparisonEngine's responsibility alone; a reporter +/// re-sorting by CanonicalString would duplicate that responsibility +/// with a different (string, not structured) comparator. +/// +public static class ConsoleComparisonReporter +{ + public static void Write(TextWriter output, ComparisonResult comparison) + { + ArgumentNullException.ThrowIfNull(output); + ArgumentNullException.ThrowIfNull(comparison); + + output.WriteLine(string.Create(CultureInfo.InvariantCulture, + $"Suite: {comparison.Suite} " + + $"Comparable: {comparison.ComparableCount} " + + $"Added: {comparison.AddedCount} " + + $"Removed: {comparison.RemovedCount}")); + output.WriteLine(); + + var comparableBenchmarks = comparison.Benchmarks + .Where(b => b.Status == BenchmarkComparisonStatus.Comparable) + .ToList(); + + if (comparableBenchmarks.Count == 0 && comparison.AddedCount == 0 && comparison.RemovedCount == 0) + { + output.WriteLine("No benchmarks compared."); + return; + } + + if (comparableBenchmarks.Count > 0) + { + WriteMetricTable(output, comparableBenchmarks); + } + + WriteNameList(output, "Added benchmarks:", comparison.Benchmarks, BenchmarkComparisonStatus.Added); + WriteNameList(output, "Removed benchmarks:", comparison.Benchmarks, BenchmarkComparisonStatus.Removed); + } + + private static void WriteMetricTable(TextWriter output, IReadOnlyList benchmarks) + { + const int nameWidth = 40; + const int metricWidth = 20; + const int valueWidth = 12; + const int absoluteWidth = 14; + const int percentWidth = 10; + const int directionWidth = 14; + + output.WriteLine( + $"{"Benchmark".PadRight(nameWidth)} {"Metric".PadRight(metricWidth)} {"Reference".PadRight(valueWidth)} " + + $"{"Candidate".PadRight(valueWidth)} {"Abs Delta".PadRight(absoluteWidth)} {"% Delta".PadRight(percentWidth)} " + + $"{"Direction".PadRight(directionWidth)} Status"); + + foreach (var benchmark in benchmarks) + { + var name = Truncate(benchmark.Identity.CanonicalString, nameWidth); + + if (benchmark.Metrics.Count == 0) + { + // The benchmark itself IS Comparable — "No metrics" says + // why the row has no values, rather than "-" which could + // read as an unknown/missing status. + output.WriteLine( + $"{name.PadRight(nameWidth)} {"-".PadRight(metricWidth)} {"-".PadRight(valueWidth)} " + + $"{"-".PadRight(valueWidth)} {"-".PadRight(absoluteWidth)} {"-".PadRight(percentWidth)} " + + $"{"-".PadRight(directionWidth)} No metrics"); + continue; + } + + foreach (var metric in benchmark.Metrics) + { + var metricName = Truncate(metric.MetricName, metricWidth); + var unit = metric.Reference?.Unit ?? metric.Candidate?.Unit; + var referenceText = Truncate(ComparisonValueFormatter.FormatMetricValue(metric.MetricName, metric.Reference), valueWidth); + var candidateText = Truncate(ComparisonValueFormatter.FormatMetricValue(metric.MetricName, metric.Candidate), valueWidth); + var absoluteText = Truncate(ComparisonValueFormatter.FormatAbsoluteDelta(metric.MetricName, unit, metric.AbsoluteDelta), absoluteWidth); + var percentText = Truncate(ComparisonValueFormatter.FormatPercentDelta(metric.PercentDelta), percentWidth); + var directionText = Truncate(metric.Direction?.ToString() ?? "-", directionWidth); + + output.WriteLine( + $"{name.PadRight(nameWidth)} {metricName.PadRight(metricWidth)} {referenceText.PadRight(valueWidth)} " + + $"{candidateText.PadRight(valueWidth)} {absoluteText.PadRight(absoluteWidth)} {percentText.PadRight(percentWidth)} " + + $"{directionText.PadRight(directionWidth)} {metric.Status}"); + + // Only print the benchmark name on the first metric row to + // avoid visual repetition on multi-metric benchmarks. + name = ""; + } + } + + output.WriteLine(); + } + + private static void WriteNameList( + TextWriter output, string heading, IReadOnlyList benchmarks, BenchmarkComparisonStatus status) + { + var matching = benchmarks.Where(b => b.Status == status).ToList(); + if (matching.Count == 0) + { + return; + } + + output.WriteLine(heading); + foreach (var benchmark in matching) + { + output.WriteLine($" {benchmark.Identity.CanonicalString}"); + } + + output.WriteLine(); + } + + private static string Truncate(string value, int maxLength) => + value.Length <= maxLength ? value : value[..(maxLength - 1)] + "\u2026"; +} \ No newline at end of file diff --git a/src/BenchmarkGate.Reporting/JsonComparisonReporter.cs b/src/BenchmarkGate.Reporting/JsonComparisonReporter.cs new file mode 100644 index 0000000..a2c3bb0 --- /dev/null +++ b/src/BenchmarkGate.Reporting/JsonComparisonReporter.cs @@ -0,0 +1,201 @@ +using System.Diagnostics; +using System.Text.Json; +using System.Text.Json.Serialization; +using Bijecta.BenchmarkGate.Core.Comparison; +using Bijecta.BenchmarkGate.Storage.FileSystem; + +namespace Bijecta.BenchmarkGate.Reporting; + +/// +/// Writes the machine-readable comparison document. Independently +/// versioned from , JsonValidationReporter, +/// and the baseline/policy document schemas — this schema tracks +/// 's shape only, and changing it does not +/// imply anything about those other documents' compatibility. +/// +/// +/// +/// Full numeric precision is preserved: no value here is rounded before +/// serialization. Display rounding is a console/Markdown-only concern — +/// see /. +/// +/// +/// Non-finite IEEE-754 values (NaN, Infinity, -Infinity — preserved raw by +/// for / +/// metrics) are +/// serialized using System.Text.Json's named floating-point representation +/// and therefore appear as JSON strings — "NaN", +/// "Infinity", "-Infinity" — not JSON numbers, at a given +/// value's position. Consumers must handle either a JSON number or a named +/// floating-point string for floating-point fields that preserve raw +/// benchmark values (reference.value, candidate.value, +/// absoluteDelta, percentDelta, standardDeviationNanoseconds); +/// integer/count fields (schemaVersion, comparable, added, +/// removed, measurementCount) cannot contain named +/// floating-point strings. +/// +/// +/// status and direction strings use BenchmarkGate's +/// established PascalCase JSON convention (matching +/// ), via an explicit switch mapper +/// rather than raw enum ToString() — a future enum member rename +/// fails this build instead of silently changing the shipped contract. +/// +/// +/// /.Candidate are nested +/// value+unit objects rather than flattened fields, since (unlike +/// 's baseline/current fields) a unit is +/// meaningful metadata here, not something to drop or duplicate into a +/// second flat field. +/// +/// +public static class JsonComparisonReporter +{ + private const int SchemaVersion = 1; + + private static readonly JsonSerializerOptions SerializerOptions = new() + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + // ComparisonResult deliberately preserves raw NaN/Infinity values + // (InvalidReferenceValue/InvalidCandidateValue metrics) rather than + // omitting them — System.Text.Json throws on those by default, so + // this is required, not optional, for real compare output. + NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals, + }; + + public static void Write(string path, ComparisonResult comparison) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentNullException.ThrowIfNull(comparison); + + var dto = new ComparisonDocumentDto + { + SchemaVersion = SchemaVersion, + Suite = comparison.Suite, + Comparable = comparison.ComparableCount, + Added = comparison.AddedCount, + Removed = comparison.RemovedCount, + // Preserves comparison.Benchmarks' given order rather than + // re-sorting — see ConsoleComparisonReporter's remarks (ADR-0004). + Benchmarks = comparison.Benchmarks + .Select(b => new ComparisonBenchmarkDto + { + Identity = b.Identity.CanonicalString, + Status = FormatBenchmarkStatus(b.Status), + CandidateStability = b.CandidateStability is { } stability + ? new ComparisonStabilityDto + { + MeasurementCount = stability.MeasurementCount, + StandardDeviationNanoseconds = stability.StandardDeviationNanoseconds, + } + : null, + Metrics = b.Metrics + .Select(m => new ComparisonMetricDto + { + MetricName = m.MetricName, + Status = FormatMetricStatus(m.Status), + Reference = ToValueDto(m.Reference), + Candidate = ToValueDto(m.Candidate), + AbsoluteDelta = m.AbsoluteDelta, + PercentDelta = m.PercentDelta, + Direction = m.Direction is { } direction ? FormatDirection(direction) : null, + }) + .ToList(), + }) + .ToList(), + }; + + try + { + AtomicFileWriter.WriteJson(path, dto, SerializerOptions); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new ReportWriteException(path, "Failed to write JSON comparison report.", ex); + } + } + + private static ComparisonValueDto? ToValueDto(MetricValue? value) => + value is { } metricValue + ? new ComparisonValueDto { Value = metricValue.Value, Unit = metricValue.Unit } + : null; + + /// + /// Explicit switch rather than status.ToString(): a future enum + /// member rename fails this build instead of silently changing the + /// shipped JSON contract. PascalCase, matching 's + /// existing enum-string convention — kept consistent across the two + /// JSON schemas deliberately, since casing is a project-wide JSON + /// style question, not something schema-version independence should + /// decide per-schema. + /// + private static string FormatBenchmarkStatus(BenchmarkComparisonStatus status) => status switch + { + BenchmarkComparisonStatus.Comparable => "Comparable", + BenchmarkComparisonStatus.Added => "Added", + BenchmarkComparisonStatus.Removed => "Removed", + _ => throw new UnreachableException($"Unhandled {nameof(BenchmarkComparisonStatus)}: {status}"), + }; + + private static string FormatMetricStatus(MetricComparisonStatus status) => status switch + { + MetricComparisonStatus.Comparable => "Comparable", + MetricComparisonStatus.MissingReferenceMetric => "MissingReferenceMetric", + MetricComparisonStatus.MissingCandidateMetric => "MissingCandidateMetric", + MetricComparisonStatus.UnitMismatch => "UnitMismatch", + MetricComparisonStatus.InvalidReferenceValue => "InvalidReferenceValue", + MetricComparisonStatus.InvalidCandidateValue => "InvalidCandidateValue", + _ => throw new UnreachableException($"Unhandled {nameof(MetricComparisonStatus)}: {status}"), + }; + + private static string FormatDirection(ChangeDirection direction) => direction switch + { + ChangeDirection.Improvement => "Improvement", + ChangeDirection.Unchanged => "Unchanged", + ChangeDirection.Degradation => "Degradation", + ChangeDirection.Indeterminate => "Indeterminate", + _ => throw new UnreachableException($"Unhandled {nameof(ChangeDirection)}: {direction}"), + }; + + private sealed class ComparisonDocumentDto + { + [JsonPropertyName("schemaVersion")] public required int SchemaVersion { get; init; } + [JsonPropertyName("suite")] public required string Suite { get; init; } + [JsonPropertyName("comparable")] public required int Comparable { get; init; } + [JsonPropertyName("added")] public required int Added { get; init; } + [JsonPropertyName("removed")] public required int Removed { get; init; } + [JsonPropertyName("benchmarks")] public required List Benchmarks { get; init; } + } + + private sealed class ComparisonBenchmarkDto + { + [JsonPropertyName("identity")] public required string Identity { get; init; } + [JsonPropertyName("status")] public required string Status { get; init; } + [JsonPropertyName("candidateStability")] public ComparisonStabilityDto? CandidateStability { get; init; } + [JsonPropertyName("metrics")] public required List Metrics { get; init; } + } + + private sealed class ComparisonStabilityDto + { + [JsonPropertyName("measurementCount")] public required int MeasurementCount { get; init; } + [JsonPropertyName("standardDeviationNanoseconds")] public required double StandardDeviationNanoseconds { get; init; } + } + + private sealed class ComparisonMetricDto + { + [JsonPropertyName("metricName")] public required string MetricName { get; init; } + [JsonPropertyName("status")] public required string Status { get; init; } + [JsonPropertyName("reference")] public ComparisonValueDto? Reference { get; init; } + [JsonPropertyName("candidate")] public ComparisonValueDto? Candidate { get; init; } + [JsonPropertyName("absoluteDelta")] public double? AbsoluteDelta { get; init; } + [JsonPropertyName("percentDelta")] public double? PercentDelta { get; init; } + [JsonPropertyName("direction")] public string? Direction { get; init; } + } + + private sealed class ComparisonValueDto + { + [JsonPropertyName("value")] public required double Value { get; init; } + [JsonPropertyName("unit")] public string? Unit { get; init; } + } +} \ No newline at end of file diff --git a/src/BenchmarkGate.Reporting/MarkdownBuilder.cs b/src/BenchmarkGate.Reporting/MarkdownBuilder.cs index 30a2b1c..fe4d333 100644 --- a/src/BenchmarkGate.Reporting/MarkdownBuilder.cs +++ b/src/BenchmarkGate.Reporting/MarkdownBuilder.cs @@ -83,4 +83,41 @@ public static string FormatDeltaPercent(double? deltaPercent) => deltaPercent is { } delta ? string.Create(CultureInfo.InvariantCulture, $"{(delta >= 0 ? "+" : "")}{delta:F2}%") : "-"; + + /// + /// Wraps in a CommonMark-safe inline code span: + /// the backtick delimiter is chosen one character longer than the + /// longest run of consecutive backticks in , so + /// content containing backticks can never prematurely close the span. + /// (.NET reflection names generic types with a literal backtick — e.g. + /// List`1 — so this is a real case for benchmark type names, not + /// a hypothetical one.) Per CommonMark, a single leading or trailing + /// space is added when the content itself starts or ends with a + /// backtick, so the delimiter and the content's own backtick don't + /// visually run together. + /// + public static string CodeSpan(string text) + { + ArgumentNullException.ThrowIfNull(text); + + var longestBacktickRun = 0; + var currentRun = 0; + foreach (var ch in text) + { + if (ch == '`') + { + currentRun++; + longestBacktickRun = Math.Max(longestBacktickRun, currentRun); + } + else + { + currentRun = 0; + } + } + + var delimiter = new string('`', longestBacktickRun + 1); + var needsPadding = text.StartsWith('`') || text.EndsWith('`'); + + return needsPadding ? $"{delimiter} {text} {delimiter}" : $"{delimiter}{text}{delimiter}"; + } } \ No newline at end of file diff --git a/src/BenchmarkGate.Reporting/MarkdownComparisonReporter.cs b/src/BenchmarkGate.Reporting/MarkdownComparisonReporter.cs new file mode 100644 index 0000000..afd56f8 --- /dev/null +++ b/src/BenchmarkGate.Reporting/MarkdownComparisonReporter.cs @@ -0,0 +1,113 @@ +using Bijecta.BenchmarkGate.Core.Comparison; +using Bijecta.BenchmarkGate.Storage.FileSystem; +using System.Globalization; + +namespace Bijecta.BenchmarkGate.Reporting; + +/// +/// Writes a GitHub-friendly Markdown summary of a +/// using . Describes change — useful for PR +/// comments and build summaries — and deliberately does not imitate a +/// check report with the verdict column removed: there is no +/// verdict here to remove a column for. +/// +/// +/// Preserves ' given order rather +/// than re-sorting — see 's remarks +/// for why (ADR-0004: canonical ordering is the engine's responsibility +/// alone). +/// +public static class MarkdownComparisonReporter +{ + public static void Write(string path, ComparisonResult comparison) + { + ArgumentException.ThrowIfNullOrWhiteSpace(path); + ArgumentNullException.ThrowIfNull(comparison); + + var md = new MarkdownBuilder() + .Heading(1, $"Benchmark Compare — {comparison.Suite}") + .Table( + ["Comparable", "Added", "Removed"], + [[ + comparison.ComparableCount.ToString(CultureInfo.InvariantCulture), + comparison.AddedCount.ToString(CultureInfo.InvariantCulture), + comparison.RemovedCount.ToString(CultureInfo.InvariantCulture), + ]]); + + var comparableBenchmarks = comparison.Benchmarks + .Where(b => b.Status == BenchmarkComparisonStatus.Comparable) + .ToList(); + + if (comparableBenchmarks.Count > 0) + { + md.Table( + ["Benchmark", "Metric", "Reference", "Candidate", "Absolute delta", "Percent delta", "Direction", "Status"], + comparableBenchmarks.SelectMany(BuildRows)); + } + + WriteNameSection(md, "Added benchmarks", comparison.Benchmarks, BenchmarkComparisonStatus.Added); + WriteNameSection(md, "Removed benchmarks", comparison.Benchmarks, BenchmarkComparisonStatus.Removed); + + try + { + AtomicFileWriter.Write(path, md.ToString()); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + throw new ReportWriteException(path, "Failed to write Markdown comparison report.", ex); + } + } + + private static void WriteNameSection( + MarkdownBuilder md, string heading, IReadOnlyList benchmarks, BenchmarkComparisonStatus status) + { + var matching = benchmarks.Where(b => b.Status == status).ToList(); + if (matching.Count == 0) + { + return; + } + + md.Heading(2, heading); + foreach (var benchmark in matching) + { + // CodeSpan chooses a safe delimiter even if the identity + // contains a backtick (real case: .NET names generic types + // like List`1, and BenchmarkIdentity.TypeName can be one). + md.Bullet(MarkdownBuilder.CodeSpan(benchmark.Identity.CanonicalString)); + } + } + + private static IEnumerable> BuildRows(BenchmarkComparison benchmark) + { + // A benchmark with no metric comparisons still gets one row, so it + // isn't silently dropped from the table. The benchmark itself IS + // Comparable here — "No metrics" says why the row is empty, rather + // than "-" which could read as an unknown status. + if (benchmark.Metrics.Count == 0) + { + yield return + [ + benchmark.Identity.CanonicalString, + "-", "-", "-", "-", "-", + "No metrics", + ]; + yield break; + } + + foreach (var metric in benchmark.Metrics) + { + var unit = metric.Reference?.Unit ?? metric.Candidate?.Unit; + yield return + [ + benchmark.Identity.CanonicalString, + metric.MetricName, + ComparisonValueFormatter.FormatMetricValue(metric.MetricName, metric.Reference), + ComparisonValueFormatter.FormatMetricValue(metric.MetricName, metric.Candidate), + ComparisonValueFormatter.FormatAbsoluteDelta(metric.MetricName, unit, metric.AbsoluteDelta), + ComparisonValueFormatter.FormatPercentDelta(metric.PercentDelta), + metric.Direction?.ToString() ?? "-", + metric.Status.ToString(), + ]; + } + } +} \ No newline at end of file diff --git a/tests/BenchmarkGate.Reporting.Tests/ComparisonReportingFixtures.cs b/tests/BenchmarkGate.Reporting.Tests/ComparisonReportingFixtures.cs new file mode 100644 index 0000000..d8d897f --- /dev/null +++ b/tests/BenchmarkGate.Reporting.Tests/ComparisonReportingFixtures.cs @@ -0,0 +1,99 @@ +using Bijecta.BenchmarkGate.Core.Comparison; +using Bijecta.BenchmarkGate.Core.Identity; + +namespace Bijecta.BenchmarkGate.Reporting.Tests; + +/// +/// Hand-built fixtures for reporter tests. +/// Built directly rather than via BenchmarkComparisonEngine, since these +/// tests exercise reporting in isolation from the engine that produces +/// real comparisons. +/// +internal static class ComparisonReportingFixtures +{ + private static BenchmarkIdentity Identity(string method) => new("Ns.Type", method, "Ci"); + + /// + /// A representative comparison: one Comparable benchmark with a known + /// metric (normal delta) and an unknown metric (Indeterminate + /// direction), one Comparable benchmark with a zero-reference metric + /// (null PercentDelta), one Added benchmark, one Removed benchmark. + /// + public static ComparisonResult Sample() => new( + "nightly", + [ + new BenchmarkComparison( + Identity("Sort"), + BenchmarkComparisonStatus.Comparable, + new BenchmarkStabilityMeasurement(MeasurementCount: 20, StandardDeviationNanoseconds: 5.0), + [ + new MetricComparison( + "meanNanoseconds", MetricComparisonStatus.Comparable, + new MetricDescriptor("meanNanoseconds", OptimizationDirection.LowerIsBetter, "ns"), + Reference: new MetricValue(1000d, "ns"), Candidate: new MetricValue(1100d, "ns"), + AbsoluteDelta: 100d, PercentDelta: 10d, Direction: ChangeDirection.Degradation), + new MetricComparison( + "gen0Collections", MetricComparisonStatus.Comparable, + Descriptor: null, + Reference: new MetricValue(4d, null), Candidate: new MetricValue(4d, null), + AbsoluteDelta: 0d, PercentDelta: 0d, Direction: ChangeDirection.Unchanged), + ]), + new BenchmarkComparison( + Identity("Zeroed"), + BenchmarkComparisonStatus.Comparable, + new BenchmarkStabilityMeasurement(MeasurementCount: 20, StandardDeviationNanoseconds: 1.0), + [ + new MetricComparison( + "allocatedBytesPerOperation", MetricComparisonStatus.Comparable, + new MetricDescriptor("allocatedBytesPerOperation", OptimizationDirection.LowerIsBetter, "bytes"), + Reference: new MetricValue(0d, "bytes"), Candidate: new MetricValue(64d, "bytes"), + AbsoluteDelta: 64d, PercentDelta: null, Direction: ChangeDirection.Degradation), + ]), + new BenchmarkComparison( + Identity("New"), + BenchmarkComparisonStatus.Added, + new BenchmarkStabilityMeasurement(MeasurementCount: 20, StandardDeviationNanoseconds: 2.0), + [ + new MetricComparison( + "meanNanoseconds", MetricComparisonStatus.MissingReferenceMetric, + new MetricDescriptor("meanNanoseconds", OptimizationDirection.LowerIsBetter, "ns"), + Reference: null, Candidate: new MetricValue(500d, "ns"), + AbsoluteDelta: null, PercentDelta: null, Direction: null), + ]), + new BenchmarkComparison( + Identity("Old"), + BenchmarkComparisonStatus.Removed, + CandidateStability: null, + [ + new MetricComparison( + "meanNanoseconds", MetricComparisonStatus.MissingCandidateMetric, + new MetricDescriptor("meanNanoseconds", OptimizationDirection.LowerIsBetter, "ns"), + Reference: new MetricValue(800d, "ns"), Candidate: null, + AbsoluteDelta: null, PercentDelta: null, Direction: null), + ]), + ]); + + /// + /// A single Comparable benchmark with an InvalidCandidateValue metric + /// carrying a raw NaN value — for JSON serialization tests, since + /// System.Text.Json throws on NaN/Infinity by default. + /// + public static ComparisonResult WithNonFiniteValue() => new( + "nightly", + [ + new BenchmarkComparison( + Identity("Flaky"), + BenchmarkComparisonStatus.Comparable, + new BenchmarkStabilityMeasurement(MeasurementCount: 20, StandardDeviationNanoseconds: 1.0), + [ + new MetricComparison( + "meanNanoseconds", MetricComparisonStatus.InvalidCandidateValue, + new MetricDescriptor("meanNanoseconds", OptimizationDirection.LowerIsBetter, "ns"), + Reference: new MetricValue(1000d, "ns"), Candidate: new MetricValue(double.NaN, "ns"), + AbsoluteDelta: null, PercentDelta: null, Direction: null), + ]), + ]); + + /// A comparison with no benchmarks at all. + public static ComparisonResult Empty() => new("nightly", []); +} \ No newline at end of file diff --git a/tests/BenchmarkGate.Reporting.Tests/ConsoleComparisonReporterTests.cs b/tests/BenchmarkGate.Reporting.Tests/ConsoleComparisonReporterTests.cs new file mode 100644 index 0000000..809cdd1 --- /dev/null +++ b/tests/BenchmarkGate.Reporting.Tests/ConsoleComparisonReporterTests.cs @@ -0,0 +1,161 @@ +using Bijecta.BenchmarkGate.Reporting; +using FluentAssertions; +using Xunit; + +namespace Bijecta.BenchmarkGate.Reporting.Tests; + +public class ConsoleComparisonReporterTests +{ + private static string Render(Core.Comparison.ComparisonResult comparison) + { + using var writer = new StringWriter(); + ConsoleComparisonReporter.Write(writer, comparison); + return writer.ToString(); + } + + [Fact] + public void output_includes_suite_name_and_comparable_added_removed_counts() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Suite: nightly"); + output.Should().Contain("Comparable: 2"); + output.Should().Contain("Added: 1"); + output.Should().Contain("Removed: 1"); + } + + [Fact] + public void output_lists_a_comparable_metric_row_with_its_direction() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("meanNanoseconds"); + output.Should().Contain(nameof(Core.Comparison.ChangeDirection.Degradation)); + } + + [Fact] + public void output_lists_an_unknown_metric_with_indeterminate_or_unchanged_direction_not_dropped() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("gen0Collections"); + output.Should().Contain(nameof(Core.Comparison.ChangeDirection.Unchanged)); + } + + [Fact] + public void output_shows_na_for_a_zero_reference_metrics_percent_delta() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("n/a"); + } + + [Fact] + public void output_lists_added_benchmarks_by_name_in_their_own_section() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Added benchmarks:"); + output.Should().Contain("Ns.Type.New"); + } + + [Fact] + public void output_lists_removed_benchmarks_by_name_in_their_own_section() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Removed benchmarks:"); + output.Should().Contain("Ns.Type.Old"); + } + + [Fact] + public void empty_comparison_reports_no_benchmarks_compared() + { + var output = Render(ComparisonReportingFixtures.Empty()); + + output.Should().Contain("No benchmarks compared."); + } + + [Fact] + public void absolute_delta_is_shown_even_when_percent_delta_is_unavailable() + { + // Zero-reference metric: PercentDelta is null ("n/a") but + // AbsoluteDelta (64) is still meaningful and must not be hidden. + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("+64"); + } + + [Fact] + public void a_comparable_benchmark_with_no_metrics_shows_no_metrics_not_a_dash() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Empty", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), + []), + ]); + + var output = Render(comparison); + + output.Should().Contain("No metrics"); + } + + [Fact] + public void write_throws_when_output_is_null() + { + var act = () => ConsoleComparisonReporter.Write(null!, ComparisonReportingFixtures.Sample()); + + act.Should().Throw(); + } + + [Fact] + public void write_throws_when_comparison_is_null() + { + using var writer = new StringWriter(); + var act = () => ConsoleComparisonReporter.Write(writer, null!); + + act.Should().Throw(); + } + + [Fact] + public void benchmarks_are_rendered_in_the_order_supplied_not_re_sorted() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Zoo", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Alpha", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + ]); + + var output = Render(comparison); + + output.IndexOf("Ns.Type.Zoo", StringComparison.Ordinal) + .Should().BeLessThan(output.IndexOf("Ns.Type.Alpha", StringComparison.Ordinal)); + } + + [Fact] + public void console_output_matches_the_verified_golden_capture() + { + // Captured from a real local run against ComparisonReportingFixtures.Sample() + // and verified by hand. Line endings normalized on both sides + // (TextWriter.WriteLine emits the OS's Environment.NewLine, which + // differs between the machine this was captured on and CI) — + // spacing/alignment is NOT normalized, since alignment is the + // behavior this test exists to verify. + const string golden = "Suite: nightly Comparable: 2 Added: 1 Removed: 1\n\nBenchmark Metric Reference Candidate Abs Delta % Delta Direction Status\nNs.Type.Sort|job=Ci meanNanoseconds 1.000 µs 1.100 µs +100.000 ns +10.00% Degradation Comparable\n gen0Collections 4 4 0 +0.00% Unchanged Comparable\nNs.Type.Zeroed|job=Ci allocatedBytesPerOp… 0 B 64 B +64 B n/a Degradation Comparable\n\nAdded benchmarks:\n Ns.Type.New|job=Ci\n\nRemoved benchmarks:\n Ns.Type.Old|job=Ci\n\n"; + + var output = Render(ComparisonReportingFixtures.Sample()); + + output.ReplaceLineEndings("\n").Should().Be(golden.ReplaceLineEndings("\n")); + } +} \ No newline at end of file diff --git a/tests/BenchmarkGate.Reporting.Tests/JsonComparisonReporterTests.cs b/tests/BenchmarkGate.Reporting.Tests/JsonComparisonReporterTests.cs new file mode 100644 index 0000000..5001408 --- /dev/null +++ b/tests/BenchmarkGate.Reporting.Tests/JsonComparisonReporterTests.cs @@ -0,0 +1,228 @@ +using System.Text.Json; +using Bijecta.BenchmarkGate.Reporting; +using FluentAssertions; +using Xunit; + +namespace Bijecta.BenchmarkGate.Reporting.Tests; + +public class JsonComparisonReporterTests +{ + private static JsonDocument RenderAsDocument(Core.Comparison.ComparisonResult comparison) + { + var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.json"); + try + { + JsonComparisonReporter.Write(path, comparison); + return JsonDocument.Parse(File.ReadAllText(path)); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void schema_version_is_one_and_independent_of_the_decision_reports_schema_version() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.Sample()); + + document.RootElement.GetProperty("schemaVersion").GetInt32().Should().Be(1); + } + + [Fact] + public void full_numeric_precision_is_preserved_without_rounding() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Precise", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), + [ + new Core.Comparison.MetricComparison( + "meanNanoseconds", Core.Comparison.MetricComparisonStatus.Comparable, + new Core.Comparison.MetricDescriptor( + "meanNanoseconds", Core.Comparison.OptimizationDirection.LowerIsBetter, "ns"), + Reference: new Core.Comparison.MetricValue(1000.123456789012, "ns"), + Candidate: new Core.Comparison.MetricValue(1000.987654321098, "ns"), + AbsoluteDelta: 0.864197532086, PercentDelta: 0.0864066d, + Direction: Core.Comparison.ChangeDirection.Degradation), + ]), + ]); + + using var document = RenderAsDocument(comparison); + + var reference = document.RootElement + .GetProperty("benchmarks")[0].GetProperty("metrics")[0].GetProperty("reference").GetProperty("value"); + reference.GetDouble().Should().Be(1000.123456789012); + } + + [Fact] + public void non_finite_values_serialize_without_throwing() + { + var act = () => RenderAsDocument(ComparisonReportingFixtures.WithNonFiniteValue()); + + act.Should().NotThrow(); + } + + [Fact] + public void non_finite_candidate_value_serializes_as_the_exact_named_literal_string() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.WithNonFiniteValue()); + + var metric = document.RootElement.GetProperty("benchmarks")[0].GetProperty("metrics")[0]; + var candidateValueElement = metric.GetProperty("candidate").GetProperty("value"); + + candidateValueElement.ValueKind.Should().Be(JsonValueKind.String); + candidateValueElement.GetString().Should().Be("NaN"); + } + + [Fact] + public void non_finite_metric_still_identifies_which_side_is_invalid_via_status() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.WithNonFiniteValue()); + + var metric = document.RootElement.GetProperty("benchmarks")[0].GetProperty("metrics")[0]; + + metric.GetProperty("status").GetString().Should().Be("InvalidCandidateValue"); + } + + [Fact] + public void positive_infinity_serializes_as_the_exact_named_literal_string() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Infinite", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), + [ + new Core.Comparison.MetricComparison( + "meanNanoseconds", Core.Comparison.MetricComparisonStatus.InvalidCandidateValue, + new Core.Comparison.MetricDescriptor( + "meanNanoseconds", Core.Comparison.OptimizationDirection.LowerIsBetter, "ns"), + Reference: new Core.Comparison.MetricValue(1000d, "ns"), + Candidate: new Core.Comparison.MetricValue(double.PositiveInfinity, "ns"), + AbsoluteDelta: null, PercentDelta: null, Direction: null), + ]), + ]); + + using var document = RenderAsDocument(comparison); + + var candidateValueElement = document.RootElement + .GetProperty("benchmarks")[0].GetProperty("metrics")[0].GetProperty("candidate").GetProperty("value"); + candidateValueElement.GetString().Should().Be("Infinity"); + } + + [Fact] + public void reference_and_candidate_are_nested_objects_with_value_and_unit() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.Sample()); + + var reference = document.RootElement + .GetProperty("benchmarks")[0].GetProperty("metrics")[0].GetProperty("reference"); + reference.GetProperty("value").GetDouble().Should().Be(1000d); + reference.GetProperty("unit").GetString().Should().Be("ns"); + } + + [Fact] + public void unknown_metric_has_null_unit_not_an_empty_string() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.Sample()); + + var metrics = document.RootElement.GetProperty("benchmarks")[0].GetProperty("metrics"); + var unknownMetric = metrics.EnumerateArray().Single(m => m.GetProperty("metricName").GetString() == "gen0Collections"); + + unknownMetric.GetProperty("reference").TryGetProperty("unit", out _).Should().BeFalse(); + } + + [Fact] + public void removed_benchmark_omits_null_candidate_stability_rather_than_writing_null() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.Sample()); + + var removedBenchmark = document.RootElement.GetProperty("benchmarks") + .EnumerateArray().Single(b => b.GetProperty("status").GetString() == "Removed"); + + removedBenchmark.TryGetProperty("candidateStability", out _).Should().BeFalse(); + } + + [Fact] + public void write_throws_when_path_is_null_or_whitespace() + { + var act = () => JsonComparisonReporter.Write(" ", ComparisonReportingFixtures.Sample()); + + act.Should().Throw(); + } + + [Fact] + public void write_throws_when_comparison_is_null() + { + var act = () => JsonComparisonReporter.Write(Path.GetTempFileName(), null!); + + act.Should().Throw(); + } + + [Fact] + public void non_finite_standard_deviation_serializes_as_the_exact_named_literal_string() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "NoisyStddev", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, double.NaN), + []), + ]); + + using var document = RenderAsDocument(comparison); + + var stddevElement = document.RootElement + .GetProperty("benchmarks")[0].GetProperty("candidateStability").GetProperty("standardDeviationNanoseconds"); + stddevElement.ValueKind.Should().Be(JsonValueKind.String); + stddevElement.GetString().Should().Be("NaN"); + } + + [Fact] + public void benchmarks_are_serialized_in_the_order_supplied_not_re_sorted() + { + // Deliberately non-alphabetical order (Zoo before Alpha) — proves + // the reporter preserves ComparisonResult.Benchmarks' given order + // rather than re-sorting by CanonicalString. + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Zoo", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Alpha", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + ]); + + using var document = RenderAsDocument(comparison); + + var identities = document.RootElement.GetProperty("benchmarks") + .EnumerateArray().Select(b => b.GetProperty("identity").GetString()).ToArray(); + identities.Should().Equal("Ns.Type.Zoo|job=Ci", "Ns.Type.Alpha|job=Ci"); + } + + [Fact] + public void a_metric_with_no_computed_delta_omits_those_fields_rather_than_writing_null() + { + using var document = RenderAsDocument(ComparisonReportingFixtures.Sample()); + + var addedBenchmarkMetric = document.RootElement.GetProperty("benchmarks") + .EnumerateArray().Single(b => b.GetProperty("status").GetString() == "Added") + .GetProperty("metrics")[0]; + + addedBenchmarkMetric.TryGetProperty("absoluteDelta", out _).Should().BeFalse(); + addedBenchmarkMetric.TryGetProperty("percentDelta", out _).Should().BeFalse(); + addedBenchmarkMetric.TryGetProperty("direction", out _).Should().BeFalse(); + } +} \ No newline at end of file diff --git a/tests/BenchmarkGate.Reporting.Tests/MarkdownBuilderCodeSpanTests.cs b/tests/BenchmarkGate.Reporting.Tests/MarkdownBuilderCodeSpanTests.cs new file mode 100644 index 0000000..1cc28e3 --- /dev/null +++ b/tests/BenchmarkGate.Reporting.Tests/MarkdownBuilderCodeSpanTests.cs @@ -0,0 +1,52 @@ +using Bijecta.BenchmarkGate.Reporting; +using FluentAssertions; +using Xunit; + +namespace Bijecta.BenchmarkGate.Reporting.Tests; + +public class MarkdownBuilderCodeSpanTests +{ + [Fact] + public void content_with_no_backticks_uses_a_single_backtick_delimiter() + { + MarkdownBuilder.CodeSpan("plain-text").Should().Be("`plain-text`"); + } + + [Fact] + public void content_with_one_backtick_uses_a_double_backtick_delimiter() + { + MarkdownBuilder.CodeSpan("List`1").Should().Be("``List`1``"); + } + + [Fact] + public void content_with_a_run_of_two_backticks_uses_a_triple_backtick_delimiter() + { + MarkdownBuilder.CodeSpan("a``b").Should().Be("```a``b```"); + } + + [Fact] + public void content_starting_with_a_backtick_gets_a_leading_and_trailing_space() + { + MarkdownBuilder.CodeSpan("`leading").Should().Be("`` `leading ``"); + } + + [Fact] + public void content_ending_with_a_backtick_gets_a_leading_and_trailing_space() + { + MarkdownBuilder.CodeSpan("trailing`").Should().Be("`` trailing` ``"); + } + + [Fact] + public void empty_content_uses_a_single_backtick_delimiter_with_no_padding() + { + MarkdownBuilder.CodeSpan(string.Empty).Should().Be("``"); + } + + [Fact] + public void throws_when_text_is_null() + { + var act = () => MarkdownBuilder.CodeSpan(null!); + + act.Should().Throw(); + } +} \ No newline at end of file diff --git a/tests/BenchmarkGate.Reporting.Tests/MarkdownComparisonReporterTests.cs b/tests/BenchmarkGate.Reporting.Tests/MarkdownComparisonReporterTests.cs new file mode 100644 index 0000000..8a6248e --- /dev/null +++ b/tests/BenchmarkGate.Reporting.Tests/MarkdownComparisonReporterTests.cs @@ -0,0 +1,167 @@ +using Bijecta.BenchmarkGate.Reporting; +using FluentAssertions; +using Xunit; + +namespace Bijecta.BenchmarkGate.Reporting.Tests; + +public class MarkdownComparisonReporterTests +{ + private static string Render(Core.Comparison.ComparisonResult comparison) + { + var path = Path.Combine(Path.GetTempPath(), $"{Guid.NewGuid()}.md"); + try + { + MarkdownComparisonReporter.Write(path, comparison); + return File.ReadAllText(path); + } + finally + { + File.Delete(path); + } + } + + [Fact] + public void output_has_a_heading_with_the_suite_name() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("# Benchmark Compare — nightly"); + } + + [Fact] + public void output_includes_a_comparable_added_removed_counts_table() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Comparable"); + output.Should().Contain("Added"); + output.Should().Contain("Removed"); + } + + [Fact] + public void output_lists_metric_rows_with_direction_and_status_columns() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("meanNanoseconds"); + output.Should().Contain(nameof(Core.Comparison.ChangeDirection.Degradation)); + output.Should().Contain(nameof(Core.Comparison.MetricComparisonStatus.Comparable)); + } + + [Fact] + public void output_has_an_added_benchmarks_section() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Added benchmarks"); + output.Should().Contain("Ns.Type.New"); + } + + [Fact] + public void output_has_a_removed_benchmarks_section() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Removed benchmarks"); + output.Should().Contain("Ns.Type.Old"); + } + + [Fact] + public void zero_reference_metric_row_shows_na_delta() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("n/a"); + } + + [Fact] + public void absolute_delta_is_shown_even_when_percent_delta_is_unavailable() + { + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("+64"); + } + + [Fact] + public void write_throws_when_path_is_null_or_whitespace() + { + var act = () => MarkdownComparisonReporter.Write(" ", ComparisonReportingFixtures.Sample()); + + act.Should().Throw(); + } + + [Fact] + public void write_throws_when_comparison_is_null() + { + var act = () => MarkdownComparisonReporter.Write(Path.GetTempFileName(), null!); + + act.Should().Throw(); + } + + [Fact] + public void benchmarks_are_rendered_in_the_order_supplied_not_re_sorted() + { + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Zoo", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.Type", "Alpha", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Comparable, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + ]); + + var output = Render(comparison); + + output.IndexOf("Ns.Type.Zoo", StringComparison.Ordinal) + .Should().BeLessThan(output.IndexOf("Ns.Type.Alpha", StringComparison.Ordinal)); + } + + [Fact] + public void a_pipe_character_in_the_identity_is_escaped_in_the_table_cell() + { + // Every canonical identity legitimately contains '|' as its own + // field separator (e.g. "Ns.Type.Sort|job=Ci") — this is not a + // contrived case, every row in the Sample fixture already + // exercises it. MarkdownBuilder.Table escapes '|' to '\|'. + var output = Render(ComparisonReportingFixtures.Sample()); + + output.Should().Contain("Ns.Type.Sort\\|job=Ci"); + } + + [Fact] + public void a_backtick_in_an_identity_produces_a_safely_delimited_code_span() + { + // .NET reflection names generic types with a literal backtick + // (e.g. "List`1"), so BenchmarkIdentity.TypeName can contain one — + // a naive `{identity}` wrap would prematurely close the span. + var comparison = new Core.Comparison.ComparisonResult( + "nightly", + [ + new Core.Comparison.BenchmarkComparison( + new Core.Identity.BenchmarkIdentity("Ns.List`1", "Sort", "Ci"), + Core.Comparison.BenchmarkComparisonStatus.Added, + new Core.Comparison.BenchmarkStabilityMeasurement(20, 1.0), []), + ]); + + var output = Render(comparison); + + output.Should().Contain("``Ns.List`1.Sort|job=Ci``"); + } + + [Fact] + public void markdown_output_matches_the_verified_golden_capture() + { + // Captured from a real local run against ComparisonReportingFixtures.Sample() + // and verified by hand. Line endings normalized on both sides for + // the same reason as the console reporter's equivalent test. + const string golden = "# Benchmark Compare — nightly\n\n| Comparable | Added | Removed |\n|---|---|---|\n| 2 | 1 | 1 |\n\n| Benchmark | Metric | Reference | Candidate | Absolute delta | Percent delta | Direction | Status |\n|---|---|---|---|---|---|---|---|\n| Ns.Type.Sort\\|job=Ci | meanNanoseconds | 1.000 µs | 1.100 µs | +100.000 ns | +10.00% | Degradation | Comparable |\n| Ns.Type.Sort\\|job=Ci | gen0Collections | 4 | 4 | 0 | +0.00% | Unchanged | Comparable |\n| Ns.Type.Zeroed\\|job=Ci | allocatedBytesPerOperation | 0 B | 64 B | +64 B | n/a | Degradation | Comparable |\n\n## Added benchmarks\n\n- `Ns.Type.New|job=Ci`\n## Removed benchmarks\n\n- `Ns.Type.Old|job=Ci`\n"; + + var output = Render(ComparisonReportingFixtures.Sample()); + + output.ReplaceLineEndings("\n").Should().Be(golden.ReplaceLineEndings("\n")); + } +} \ No newline at end of file