Skip to content

Commit

Permalink
Add xUnit1051 to detect v3 tests which should use the test context ca…
Browse files Browse the repository at this point in the history
…ncellation token
  • Loading branch information
bradwilson committed Jul 14, 2024
1 parent 7f99c6a commit 2188a2d
Show file tree
Hide file tree
Showing 4 changed files with 229 additions and 1 deletion.
119 changes: 119 additions & 0 deletions src/xunit.analyzers.tests/Analyzers/X1000/UseCancellationTokenTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
using Verify = CSharpVerifier<Xunit.Analyzers.UseCancellationToken>;

public class UseCancellationTokenTests
{
[Fact]
public async Task NoCancellationToken_DoesNotTrigger()
{
var source = @"
using System.Threading;
using Xunit;
class TestClass {
[Fact]
public void TestMethod() {
Thread.Sleep(1);
}
}";

await Verify.VerifyAnalyzerV3(source);
}

[Theory]
[InlineData("TestContext.Current.CancellationToken")]
[InlineData("new CancellationTokenSource().Token")]
public async Task WithAnyCancellationToken_DoesNotTrigger(string token)
{
var source = @$"
using System.Threading;
using System.Threading.Tasks;
using Xunit;
class TestClass {{
[Fact]
public async Task TestMethod() {{
await Task.Delay(1, {token});
}}
}}";

await Verify.VerifyAnalyzerV3(source);
}

[Fact]
public async Task WithoutCancellationToken_V2_DoesNotTrigger()
{
var source = @$"
using System.Threading;
using System.Threading.Tasks;
using Xunit;
class TestClass {{
[Fact]
public async Task TestMethod() {{
await Task.Delay(1);
}}
}}";

await Verify.VerifyAnalyzerV2(source);
}

[Fact]
public async Task WithoutCancellationToken_WithoutDirectUpgrade_DoesNotTrigger()
{
var source = @"
using System.Threading;
using System.Threading.Tasks;
using Xunit;
class TestClass {
[Fact]
public void TestMethod() {
FunctionWithOverload(42);
}
void FunctionWithOverload(int _) { }
void FunctionWithOverload(CancellationToken _) { }
}";

await Verify.VerifyAnalyzerV3(source);
}

[Theory]
[InlineData("FunctionWithDefaults()")]
[InlineData("FunctionWithDefaults(42)")]
[InlineData("FunctionWithDefaults(42, default)")]
[InlineData("FunctionWithDefaults(42, default(CancellationToken))")]
[InlineData("FunctionWithDefaults(cancellationToken: default)")]
[InlineData("FunctionWithDefaults(cancellationToken: default(CancellationToken))")]
[InlineData("FunctionWithOverload(42)")]
[InlineData("FunctionWithOverload(42, default)")]
[InlineData("FunctionWithOverload(42, default(CancellationToken))")]
public async Task WithoutCancellationToken_V3_Triggers(string invocation)
{
var source = @$"
using System.Threading;
using System.Threading.Tasks;
using Xunit;
class TestClass {{
[Fact]
public void TestMethod() {{
{invocation};
}}
void FunctionWithDefaults(int _1 = 2112, CancellationToken cancellationToken = default) {{ }}
void FunctionWithOverload(int _) {{ }}
void FunctionWithOverload(int _1, CancellationToken _2) {{ }}
}}";
var expected =
Verify
.Diagnostic()
.WithSpan(9, 9, 9, 9 + invocation.Length);

await Verify.VerifyAnalyzerV3(LanguageVersion.CSharp7_1, source, expected);
}
}
9 changes: 8 additions & 1 deletion src/xunit.analyzers/Utility/Descriptors.xUnit1xxx.cs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,14 @@ public static partial class Descriptors
"The class referenced by the ClassData attribute returns untyped data rows, such as object[] or ITheoryDataRow. Consider using generic TheoryDataRow<> as the row type to provide better type safety."
);

// Placeholder for rule X1051
public static DiagnosticDescriptor X1051_UseCancellationToken { get; } =
Diagnostic(
"xUnit1051",
"Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken",
Usage,
Warning,
"Calls to methods which accept CancellationToken should use TestContext.Current.CancellationToken to allow test cancellation to be more responsive."
);

// Placeholder for rule X1052

Expand Down
3 changes: 3 additions & 0 deletions src/xunit.analyzers/Utility/TypeSymbolFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ public static class TypeSymbolFactory
public static INamedTypeSymbol? BigInteger(Compilation compilation) =>
Guard.ArgumentNotNull(compilation).GetTypeByMetadataName("System.Numerics.BigInteger");

public static INamedTypeSymbol? CancellationToken(Compilation compilation) =>
Guard.ArgumentNotNull(compilation).GetTypeByMetadataName("System.Threading.CancellationToken");

public static INamedTypeSymbol? ClassDataAttribute(Compilation compilation) =>
Guard.ArgumentNotNull(compilation).GetTypeByMetadataName(Constants.Types.Xunit.ClassDataAttribute);

Expand Down
99 changes: 99 additions & 0 deletions src/xunit.analyzers/X1000/UseCancellationToken.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;

namespace Xunit.Analyzers;

[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UseCancellationToken : XunitDiagnosticAnalyzer
{
public UseCancellationToken() :
base(Descriptors.X1051_UseCancellationToken)
{ }

public override void AnalyzeCompilation(
CompilationStartAnalysisContext context,
XunitContext xunitContext)
{
Guard.ArgumentNotNull(context);
Guard.ArgumentNotNull(xunitContext);

var cancellationTokenType = TypeSymbolFactory.CancellationToken(context.Compilation);
if (cancellationTokenType is null)
return;

context.RegisterOperationAction(context =>
{
if (context.Operation is not IInvocationOperation invocationOperation)
return;
var invokedMethod = invocationOperation.TargetMethod;
var parameters = invokedMethod.Parameters;
var parameterIdx = 0;
for (; parameterIdx < parameters.Length; ++parameterIdx)
if (SymbolEqualityComparer.Default.Equals(parameters[parameterIdx].Type, cancellationTokenType))
break;
// The invoked method has the parameter we're looking for
if (parameterIdx != parameters.Length)
{
var argument = invocationOperation.Arguments[parameterIdx];
// Default parameter value
if (argument.ArgumentKind == ArgumentKind.DefaultValue)
Report(context, invocationOperation.Syntax.GetLocation());
// Explicit parameter value
else if (argument.Syntax is ArgumentSyntax argumentSyntax)
{
var kind = argumentSyntax.Expression.Kind();
if (kind == SyntaxKind.DefaultExpression || kind == SyntaxKind.DefaultLiteralExpression)
Report(context, invocationOperation.Syntax.GetLocation());
}
}
// Look for an overload with the exact same parameter types + a CancellationToken
else
{
var targetParameterTypes = invokedMethod.Parameters.Select(p => p.Type).Concat([cancellationTokenType]).ToArray();
foreach (var member in invokedMethod.ContainingType.GetMembers(invokedMethod.Name))
if (member is IMethodSymbol method)
{
var methodParameterTypes = method.Parameters.Select(p => p.Type).ToArray();
if (methodParameterTypes.Length != targetParameterTypes.Length)
continue;
var match = true;
for (var idx = 0; idx < targetParameterTypes.Length; ++idx)
if (!SymbolEqualityComparer.Default.Equals(targetParameterTypes[idx], methodParameterTypes[idx]))
{
match = false;
break;
}
if (match)
{
Report(context, invocationOperation.Syntax.GetLocation());
return;
}
}
}
}, OperationKind.Invocation);

static void Report(
OperationAnalysisContext context,
Location location) =>
context.ReportDiagnostic(
Diagnostic.Create(
Descriptors.X1051_UseCancellationToken,
location
)
);
}

protected override bool ShouldAnalyze(XunitContext xunitContext) =>
Guard.ArgumentNotNull(xunitContext).HasV3References;
}

0 comments on commit 2188a2d

Please sign in to comment.