Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion tests/TUnit.Mocks.SourceGenerator.Tests/Issue6505Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
3 changes: 3 additions & 0 deletions tests/TUnit.Mocks.SourceGenerator.Tests/MockGeneratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ void M()
}
""";

AssertGeneratedCodeHasNoNullableWarnings(source);
return VerifyGeneratorOutput(source);
}

Expand Down Expand Up @@ -271,6 +272,7 @@ void M()
}
""";

AssertGeneratedCodeHasNoNullableWarnings(source);
return VerifyGeneratorOutput(source);
}

Expand Down Expand Up @@ -298,6 +300,7 @@ void M()
}
""";

AssertGeneratedCodeHasNoNullableWarnings(source);
return VerifyGeneratorOutput(source);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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<string?>? Changed;
}

public class Usage
{
void M() => _ = Mock.Of<IService>();
}
""";

AssertGeneratedCodeHasNoNullableWarnings(source);
var exception = Assert.Throws<InvalidOperationException>(() =>
AssertGeneratedCodeHasNoNullableWarnings(source, transformGeneratedSource: generated =>
generated.Replace(
"event global::System.EventHandler<string?>? global::IService.Changed",
"event global::System.EventHandler<string> global::IService.Changed",
StringComparison.Ordinal)));

await Assert.That(exception.Message).Contains("CS8615");
}
}
40 changes: 36 additions & 4 deletions tests/TUnit.Mocks.SourceGenerator.Tests/SnapshotTestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -212,7 +214,7 @@ protected static IReadOnlyList<Diagnostic> GetGeneratedCompilationErrors(

/// <summary>
/// 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
Expand All @@ -221,9 +223,11 @@ protected static IReadOnlyList<Diagnostic> GetGeneratedCompilationErrors(
protected static void AssertGeneratedCodeHasNoNullableWarnings(
string source,
IEnumerable<MetadataReference>? additionalReferences = null,
CSharpParseOptions? parseOptions = null)
CSharpParseOptions? parseOptions = null,
Func<string, string>? 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();
Expand Down Expand Up @@ -265,7 +269,9 @@ protected static void AssertGeneratedCodeHasNoObsoleteWarnings(
private static (Compilation Compilation, IReadOnlyList<Diagnostic> Diagnostics) RunGeneratorWithCompilationDiagnostics(
string source,
IEnumerable<MetadataReference>? additionalReferences,
CSharpParseOptions? parseOptions)
CSharpParseOptions? parseOptions,
bool restoreNullableWarnings = false,
Func<string, string>? transformGeneratedSource = null)
{
parseOptions ??= GeneratorTestInput.ParseOptions;
var syntaxTree = CSharpSyntaxTree.ParseText(source, parseOptions);
Expand Down Expand Up @@ -294,6 +300,32 @@ private static (Compilation Compilation, IReadOnlyList<Diagnostic> 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<PragmaWarningDirectiveTriviaSyntax>()
.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());
}

Expand Down
Loading