Skip to content

Commit

Permalink
Fix bug in xUnit1051 to account for arbitrary parameter order (#187)
Browse files Browse the repository at this point in the history
  • Loading branch information
campersau authored Aug 25, 2024
1 parent bc0dbe4 commit 3932a3e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 9 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,13 @@ public async Task WithAnyCancellationToken_DoesNotTrigger(string token)
class TestClass {{
[Fact]
public async Task TestMethod() {{
await Task.Delay(1, {0});
public void TestMethod() {{
FunctionWithDefaults(42, {0});
FunctionWithDefaults(42, cancellationToken: {0});
FunctionWithDefaults(cancellationToken: {0});
}}
void FunctionWithDefaults(int _1 = 2112, CancellationToken cancellationToken = default(CancellationToken)) {{ }}
}}
""", token);

Expand Down
15 changes: 8 additions & 7 deletions src/xunit.analyzers/X1000/UseCancellationToken.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,17 @@ public override void AnalyzeCompilation(
var invokedMethod = invocationOperation.TargetMethod;
var parameters = invokedMethod.Parameters;

var parameterIdx = 0;
for (; parameterIdx < parameters.Length; ++parameterIdx)
if (SymbolEqualityComparer.Default.Equals(parameters[parameterIdx].Type, cancellationTokenType))
IArgumentOperation? argument = null;
foreach (var parameter in parameters)
if (SymbolEqualityComparer.Default.Equals(parameter.Type, cancellationTokenType))
{
argument = invocationOperation.Arguments.FirstOrDefault(arg => SymbolEqualityComparer.Default.Equals(arg.Parameter, parameter));
break;
}

// The invoked method has the parameter we're looking for
if (parameterIdx != parameters.Length)
if (argument is not null)
{
var argument = invocationOperation.Arguments[parameterIdx];

// Default parameter value
if (argument.ArgumentKind == ArgumentKind.DefaultValue)
Report(context, invocationOperation.Syntax.GetLocation());
Expand All @@ -61,7 +62,7 @@ public override void AnalyzeCompilation(
// Look for an overload with the exact same parameter types + a CancellationToken
else
{
var targetParameterTypes = invokedMethod.Parameters.Select(p => p.Type).Concat([cancellationTokenType]).ToArray();
var targetParameterTypes = parameters.Select(p => p.Type).Concat([cancellationTokenType]).ToArray();
foreach (var member in invokedMethod.ContainingType.GetMembers(invokedMethod.Name))
if (member is IMethodSymbol method)
{
Expand Down

0 comments on commit 3932a3e

Please sign in to comment.