From 4bb7210e90b94fcf84a141b2bf39e0436fcd6a4a Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Thu, 5 Nov 2026 16:27:20 +0000 Subject: [PATCH] Enforce generated nullable diagnostics in mock regression guards (#7436) --- .../Issue6505Tests.cs | 2 +- .../MockGeneratorTests.cs | 3 ++ .../NullableWarningGuardTests.cs | 34 ++++++++++++++++ .../SnapshotTestBase.cs | 40 +++++++++++++++++-- 4 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 tests/TUnit.Mocks.SourceGenerator.Tests/NullableWarningGuardTests.cs diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6505Tests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6505Tests.cs index 5960eb31a1f..8cc26475a1e 100644 --- a/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6505Tests.cs +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/Issue6505Tests.cs @@ -94,7 +94,7 @@ public void Run() var (sources, diagnostics) = RunGeneratorForDiagnostics(source); var collisions = diagnostics.Where(d => d.Id == "TM008").ToList(); - await Assert.That(collisions).HasCount(2); + await Assert.That(collisions).Count().IsEqualTo(2); await Assert.That(collisions[0].GetMessage()).Contains("A___B_IFoo"); // Both culprits are named, so the message says what to rename. await Assert.That(collisions.Select(d => d.GetMessage()).Any(m => m.Contains("A_.B.IFoo"))).IsTrue(); diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/MockGeneratorTests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/MockGeneratorTests.cs index d76699a8c06..9b400d23bf7 100644 --- a/tests/TUnit.Mocks.SourceGenerator.Tests/MockGeneratorTests.cs +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/MockGeneratorTests.cs @@ -243,6 +243,7 @@ void M() } """; + AssertGeneratedCodeHasNoNullableWarnings(source); return VerifyGeneratorOutput(source); } @@ -271,6 +272,7 @@ void M() } """; + AssertGeneratedCodeHasNoNullableWarnings(source); return VerifyGeneratorOutput(source); } @@ -298,6 +300,7 @@ void M() } """; + AssertGeneratedCodeHasNoNullableWarnings(source); return VerifyGeneratorOutput(source); } diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/NullableWarningGuardTests.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/NullableWarningGuardTests.cs new file mode 100644 index 00000000000..aedfde2ca73 --- /dev/null +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/NullableWarningGuardTests.cs @@ -0,0 +1,34 @@ +namespace TUnit.Mocks.SourceGenerator.Tests; + +public class NullableWarningGuardTests : SnapshotTestBase +{ + [Test] + public async Task Rejects_Nullable_Mismatch_In_Generated_Event() + { + const string source = """ + #nullable enable + using System; + using TUnit.Mocks; + + public interface IService + { + event EventHandler? Changed; + } + + public class Usage + { + void M() => _ = Mock.Of(); + } + """; + + AssertGeneratedCodeHasNoNullableWarnings(source); + var exception = Assert.Throws(() => + AssertGeneratedCodeHasNoNullableWarnings(source, transformGeneratedSource: generated => + generated.Replace( + "event global::System.EventHandler? global::IService.Changed", + "event global::System.EventHandler global::IService.Changed", + StringComparison.Ordinal))); + + await Assert.That(exception.Message).Contains("CS8615"); + } +} diff --git a/tests/TUnit.Mocks.SourceGenerator.Tests/SnapshotTestBase.cs b/tests/TUnit.Mocks.SourceGenerator.Tests/SnapshotTestBase.cs index a461c4c4538..51738efb549 100644 --- a/tests/TUnit.Mocks.SourceGenerator.Tests/SnapshotTestBase.cs +++ b/tests/TUnit.Mocks.SourceGenerator.Tests/SnapshotTestBase.cs @@ -2,6 +2,8 @@ using System.Text; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; using TUnit.Tests.Shared; namespace TUnit.Mocks.SourceGenerator.Tests; @@ -212,7 +214,7 @@ protected static IReadOnlyList GetGeneratedCompilationErrors( /// /// Compiles the generator output under nullable-enabled context and asserts that no - /// CS86xx-family nullable warnings (CS8600, CS8602, CS8603, CS8604, CS8618, CS8625) + /// CS86xx-family nullable warnings (including CS8604 and CS8612–CS8615) /// are emitted. Used as a regression guard for #5626 and #5424/#5425/#5251. /// Other compiler diagnostics (e.g. CS1520 from C# 14 extension() blocks not parseable /// by the test-pinned Roslyn) are intentionally not asserted because they're @@ -221,9 +223,11 @@ protected static IReadOnlyList GetGeneratedCompilationErrors( protected static void AssertGeneratedCodeHasNoNullableWarnings( string source, IEnumerable? additionalReferences = null, - CSharpParseOptions? parseOptions = null) + CSharpParseOptions? parseOptions = null, + Func? transformGeneratedSource = null) { - var (_, diagnostics) = RunGeneratorWithCompilationDiagnostics(source, additionalReferences, parseOptions); + var (_, diagnostics) = RunGeneratorWithCompilationDiagnostics( + source, additionalReferences, parseOptions, restoreNullableWarnings: true, transformGeneratedSource); var nullableWarnings = diagnostics .Where(d => d.Severity >= DiagnosticSeverity.Warning && d.Id.StartsWith("CS86", StringComparison.Ordinal)) .ToList(); @@ -265,7 +269,9 @@ protected static void AssertGeneratedCodeHasNoObsoleteWarnings( private static (Compilation Compilation, IReadOnlyList Diagnostics) RunGeneratorWithCompilationDiagnostics( string source, IEnumerable? additionalReferences, - CSharpParseOptions? parseOptions) + CSharpParseOptions? parseOptions, + bool restoreNullableWarnings = false, + Func? transformGeneratedSource = null) { parseOptions ??= GeneratorTestInput.ParseOptions; var syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions); @@ -294,6 +300,32 @@ private static (Compilation Compilation, IReadOnlyList Diagnostics) throw new InvalidOperationException($"Generator produced errors:{Environment.NewLine}{errorMessages}"); } + if (restoreNullableWarnings) + { + // Compilation options cannot override a generated #pragma warning disable. + // Restore the whole family checked by the guard after each suppression, in + // test-only trees. Keep production output and snapshot text untouched. + var restoreDirective = "#pragma warning restore " + string.Join(", ", + Enumerable.Range(8600, 100).Select(id => $"CS{id}")) + "\n"; + foreach (var tree in driver.GetRunResult().GeneratedTrees) + { + var text = tree.GetText(); + if (transformGeneratedSource is not null) + { + text = SourceText.From(transformGeneratedSource(text.ToString()), text.Encoding); + } + + var testTree = CSharpSyntaxTree.ParseText(text, parseOptions, tree.FilePath); + var restorations = testTree.GetRoot().DescendantTrivia() + .Select(trivia => trivia.GetStructure()) + .OfType() + .Where(directive => directive.DisableOrRestoreKeyword.IsKind(SyntaxKind.DisableKeyword)) + .Select(directive => new TextChange(new TextSpan(directive.FullSpan.End, 0), restoreDirective)); + var restoredTree = CSharpSyntaxTree.ParseText(text.WithChanges(restorations), parseOptions, tree.FilePath); + outputCompilation = outputCompilation.ReplaceSyntaxTree(tree, restoredTree); + } + } + return (outputCompilation, outputCompilation.GetDiagnostics()); }