-
Notifications
You must be signed in to change notification settings - Fork 293
Add MSTEST0064 to prefer async assertions #8256
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Copilot
wants to merge
12
commits into
main
Choose a base branch
from
copilot/add-analyzer-favorizing-async-assertions
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
4bd6683
Initial plan
Copilot 0da8df4
Add async assertion analyzer
Copilot dd56bd5
Address async assertion review feedback
Copilot 1dd5492
Share async blocking method name constants
Copilot 96e9fc5
Fix PreferAsyncAssertion review issues
Evangelink 8debda3
Merge remote-tracking branch 'origin/main' into copilot/add-analyzer-…
Evangelink 4c1fe75
Plan review feedback fixes
Copilot b71536c
Address async assertion review feedback
Copilot 190da15
Distinguish VB synthetic implicit returns from C# expression-body ret…
4bf3ff6
Merge branch 'main' into copilot/add-analyzer-favorizing-async-assert…
Evangelink 687b203
Address async assertion review feedback
Copilot ec68da1
Handle converted async assertion arguments
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
364 changes: 364 additions & 0 deletions
364
src/Analyzers/MSTest.Analyzers.CodeFixes/PreferAsyncAssertionFixer.cs
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,8 @@ | ||
| ; Unshipped analyzer release | ||
| ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md | ||
|
|
||
| ### New Rules | ||
|
|
||
| Rule ID | Category | Severity | Notes | ||
| --------|----------|----------|------- | ||
| MSTEST0064 | Usage | Info | PreferAsyncAssertionAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0064) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
203 changes: 203 additions & 0 deletions
203
src/Analyzers/MSTest.Analyzers/PreferAsyncAssertionAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,203 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using System.Collections.Immutable; | ||
|
|
||
| using Analyzer.Utilities.Extensions; | ||
|
|
||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.Diagnostics; | ||
| using Microsoft.CodeAnalysis.Operations; | ||
|
|
||
| using MSTest.Analyzers.Helpers; | ||
| using MSTest.Analyzers.RoslynAnalyzerHelpers; | ||
|
|
||
| namespace MSTest.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// MSTEST0064: <inheritdoc cref="Resources.PreferAsyncAssertionTitle"/>. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
| public sealed class PreferAsyncAssertionAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| internal const string GetAwaiterMethodName = "GetAwaiter"; | ||
| internal const string GetResultMethodName = "GetResult"; | ||
|
|
||
| private static readonly LocalizableResourceString Title = new(nameof(Resources.PreferAsyncAssertionTitle), Resources.ResourceManager, typeof(Resources)); | ||
| private static readonly LocalizableResourceString Description = new(nameof(Resources.PreferAsyncAssertionDescription), Resources.ResourceManager, typeof(Resources)); | ||
| private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.PreferAsyncAssertionMessageFormat), Resources.ResourceManager, typeof(Resources)); | ||
|
|
||
| internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( | ||
| DiagnosticIds.PreferAsyncAssertionRuleId, | ||
| Title, | ||
| MessageFormat, | ||
| Description, | ||
| Category.Usage, | ||
| DiagnosticSeverity.Info, | ||
| isEnabledByDefault: true); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } | ||
| = ImmutableArray.Create(Rule); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override void Initialize(AnalysisContext context) | ||
| { | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
| context.EnableConcurrentExecution(); | ||
|
|
||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| if (!context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert, out INamedTypeSymbol? assertSymbol) || | ||
| !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute, out INamedTypeSymbol? testMethodAttributeSymbol) || | ||
| !context.Compilation.TryGetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask, out INamedTypeSymbol? taskSymbol)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.RegisterOperationAction( | ||
| context => AnalyzeInvocation(context, assertSymbol, testMethodAttributeSymbol, taskSymbol), | ||
| OperationKind.Invocation); | ||
| }); | ||
| } | ||
|
|
||
| private static void AnalyzeInvocation(OperationAnalysisContext context, INamedTypeSymbol assertSymbol, INamedTypeSymbol testMethodAttributeSymbol, INamedTypeSymbol taskSymbol) | ||
| { | ||
| var operation = (IInvocationOperation)context.Operation; | ||
| IMethodSymbol targetMethod = operation.TargetMethod; | ||
| if ( | ||
| !SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, assertSymbol) || | ||
| targetMethod.Name is not ("Throws" or "ThrowsExactly") || | ||
| context.ContainingSymbol is not IMethodSymbol containingMethod || | ||
| !containingMethod.GetAttributes().Any(attr => attr.AttributeClass.Inherits(testMethodAttributeSymbol)) || | ||
| IsInsideUnsupportedAwaitContext(operation) || | ||
| !TryGetActionArgument(operation, out IArgumentOperation? actionArgument) || | ||
| !TryGetBlockedTaskOperationFromArgument(actionArgument.Value, out IOperation? asyncOperation)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| ITypeSymbol? asyncExpressionType = asyncOperation.Type; | ||
| if (asyncExpressionType is null || !context.Compilation.ClassifyCommonConversion(asyncExpressionType, taskSymbol).IsImplicit) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.ReportDiagnostic(operation.CreateDiagnostic(Rule, targetMethod.Name + "Async", targetMethod.Name)); | ||
| } | ||
|
|
||
| private static bool TryGetActionArgument(IInvocationOperation operation, [NotNullWhen(true)] out IArgumentOperation? actionArgument) | ||
| { | ||
| foreach (IArgumentOperation argument in operation.Arguments) | ||
| { | ||
| if (argument.Parameter?.Name == "action") | ||
| { | ||
| actionArgument = argument; | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| actionArgument = null; | ||
| return false; | ||
| } | ||
|
|
||
| private static bool IsInsideUnsupportedAwaitContext(IOperation operation) | ||
| { | ||
| for (IOperation? current = operation.Parent; current is not null; current = current.Parent) | ||
| { | ||
| if (current is IAnonymousFunctionOperation or ILocalFunctionOperation || | ||
| current.Kind == OperationKind.Lock || | ||
| (current.Parent is ICatchClauseOperation catchClauseOperation && ReferenceEquals(catchClauseOperation.Filter, current))) | ||
|
Comment on lines
+108
to
+110
|
||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static bool TryGetBlockedTaskOperationFromArgument(IOperation argumentValueOperation, [NotNullWhen(true)] out IOperation? asyncOperation) | ||
| { | ||
| if (argumentValueOperation.WalkDownConversion() is not IDelegateCreationOperation delegateCreationOperation || | ||
| delegateCreationOperation.Target is not IAnonymousFunctionOperation anonymousFunctionOperation || | ||
| !TryGetSingleOperation(anonymousFunctionOperation.Body, out IOperation? lambdaOperation)) | ||
| { | ||
| asyncOperation = null; | ||
| return false; | ||
| } | ||
|
|
||
| return TryGetBlockedTaskOperation(lambdaOperation, out asyncOperation); | ||
| } | ||
|
|
||
| private static bool TryGetSingleOperation(IBlockOperation blockOperation, [NotNullWhen(true)] out IOperation? operation) | ||
| { | ||
| operation = null; | ||
|
|
||
| foreach (IOperation childOperation in blockOperation.Operations) | ||
| { | ||
| IOperation? candidateOperation = childOperation switch | ||
| { | ||
| IExpressionStatementOperation expressionStatementOperation => expressionStatementOperation.Operation, | ||
|
|
||
| // For any return-with-value, treat the returned value as the candidate, except for the | ||
| // synthetic implicit return that VB 'Function' lambdas emit: it returns an implicit | ||
| // ILocalReferenceOperation to the function-name local. Treating that as a candidate | ||
| // would cause single-statement VB Function lambdas to look as if they contain | ||
| // multiple operations, and the diagnostic would be missed. | ||
| IReturnOperation { ReturnedValue: { } returnedValue } | ||
| => GetExplicitReturnedValue(returnedValue), | ||
|
|
||
| // Implicit return with no value contributes no candidate (e.g. end of void lambda). | ||
| IReturnOperation => null, | ||
|
|
||
| // Skip any other compiler-synthesized operation (e.g. VB exit-function labels). | ||
| _ when childOperation.IsImplicit => null, | ||
|
|
||
| _ => childOperation, | ||
| }; | ||
|
|
||
| if (candidateOperation is null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (operation is not null) | ||
| { | ||
| operation = null; | ||
| return false; | ||
| } | ||
|
|
||
| operation = candidateOperation; | ||
| } | ||
|
|
||
| return operation is not null; | ||
| } | ||
|
|
||
| private static IOperation? GetExplicitReturnedValue(IOperation returnedValue) | ||
| { | ||
| // The synthetic implicit return that VB Function lambdas emit returns the (also implicit) | ||
| // function-name local. Detect that case via the unwrapped operation. | ||
| IOperation unwrapped = returnedValue.WalkDownConversion(); | ||
| return unwrapped is ILocalReferenceOperation { IsImplicit: true } | ||
| ? null | ||
| : returnedValue; | ||
| } | ||
|
|
||
| private static bool TryGetBlockedTaskOperation(IOperation operation, [NotNullWhen(true)] out IOperation? asyncOperation) | ||
| { | ||
| if (operation.WalkDownConversion() is IInvocationOperation getResultInvocation && | ||
| getResultInvocation.Arguments.Length == 0 && | ||
| getResultInvocation.TargetMethod.Name == GetResultMethodName && | ||
| getResultInvocation.Instance?.WalkDownConversion() is IInvocationOperation getAwaiterInvocation && | ||
| getAwaiterInvocation.Arguments.Length == 0 && | ||
| getAwaiterInvocation.TargetMethod.Name == GetAwaiterMethodName && | ||
| getAwaiterInvocation.Instance is { } instance) | ||
| { | ||
| asyncOperation = instance.WalkDownConversion(); | ||
| return true; | ||
| } | ||
|
|
||
| asyncOperation = null; | ||
| return false; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.