-
Notifications
You must be signed in to change notification settings - Fork 293
Add code fix for MSTEST0040 — AvoidUsingAssertsInAsyncVoidContext #7892
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/fix-asserts-in-async-void-context
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 4 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0d18f9d
Initial plan
Copilot 9dfec9e
feat: Add code fix for MSTEST0040 (AvoidUsingAssertsInAsyncVoidContext)
Copilot a04fed9
fix: ensure System.Threading.Tasks is imported when changing void to …
Copilot 523a6ba
refactor: simplify insertion logic and use ElasticCarriageReturnLineFeed
Copilot d780534
fix: address code review feedback on AvoidUsingAssertsInAsyncVoidCont…
Copilot e83ec4a
Merge main into copilot/fix-asserts-in-async-void-context
Evangelink 53c7127
Address review comments: override guard, alphabetical using insertion…
Evangelink 44e8a77
fix: address correctness issues in AvoidUsingAssertsInAsyncVoidContex…
Copilot f6c0efc
refactor: simplify namespace usings iteration and extract IsSystemNam…
Copilot 0de07bb
Merge branch 'main' into copilot/fix-asserts-in-async-void-context
Evangelink 0488837
Address review comments: multi-namespace import scoping & net8 test c…
8fb991f
Fix line-ending mismatch in async-void-context code fix on Linux/macOS
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
150 changes: 150 additions & 0 deletions
150
src/Analyzers/MSTest.Analyzers.CodeFixes/AvoidUsingAssertsInAsyncVoidContextFixer.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,150 @@ | ||
| // 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 System.Composition; | ||
|
|
||
| using Analyzer.Utilities; | ||
|
|
||
| using Microsoft.CodeAnalysis; | ||
| using Microsoft.CodeAnalysis.CodeActions; | ||
| using Microsoft.CodeAnalysis.CodeFixes; | ||
| using Microsoft.CodeAnalysis.CSharp; | ||
| using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
| using Microsoft.CodeAnalysis.Editing; | ||
|
|
||
| using MSTest.Analyzers.Helpers; | ||
|
|
||
| namespace MSTest.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// Code fixer for <see cref="AvoidUsingAssertsInAsyncVoidContextAnalyzer"/>. | ||
| /// </summary> | ||
| [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(AvoidUsingAssertsInAsyncVoidContextFixer))] | ||
| [Shared] | ||
| public sealed class AvoidUsingAssertsInAsyncVoidContextFixer : CodeFixProvider | ||
| { | ||
| /// <inheritdoc /> | ||
| public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } | ||
| = ImmutableArray.Create(DiagnosticIds.AvoidUsingAssertsInAsyncVoidContextRuleId); | ||
|
|
||
| /// <inheritdoc /> | ||
| public override FixAllProvider GetFixAllProvider() | ||
| // See https://github.com/dotnet/roslyn/blob/main/docs/analyzers/FixAllProvider.md for more information on Fix All Providers | ||
| => WellKnownFixAllProviders.BatchFixer; | ||
|
|
||
| /// <inheritdoc /> | ||
| public override async Task RegisterCodeFixesAsync(CodeFixContext context) | ||
| { | ||
| SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); | ||
|
|
||
| Diagnostic diagnostic = context.Diagnostics[0]; | ||
| SyntaxNode diagnosticNode = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); | ||
|
|
||
| // Walk up the ancestors to find the nearest async void method or local function. | ||
| foreach (SyntaxNode ancestor in diagnosticNode.AncestorsAndSelf()) | ||
| { | ||
| if (ancestor is MethodDeclarationSyntax methodDeclaration) | ||
| { | ||
| if (methodDeclaration.Modifiers.Any(SyntaxKind.AsyncKeyword) && | ||
| methodDeclaration.ReturnType.IsVoid()) | ||
| { | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: CodeFixResources.AvoidUsingAssertsInAsyncVoidContextFix, | ||
| createChangedDocument: ct => ChangeReturnTypeToTaskAsync(context.Document, methodDeclaration, ct), | ||
| equivalenceKey: nameof(AvoidUsingAssertsInAsyncVoidContextFixer)), | ||
| diagnostic); | ||
| } | ||
|
|
||
| break; | ||
| } | ||
|
|
||
| if (ancestor is LocalFunctionStatementSyntax localFunction) | ||
| { | ||
| if (localFunction.Modifiers.Any(SyntaxKind.AsyncKeyword) && | ||
| localFunction.ReturnType.IsVoid()) | ||
| { | ||
| context.RegisterCodeFix( | ||
| CodeAction.Create( | ||
| title: CodeFixResources.AvoidUsingAssertsInAsyncVoidContextFix, | ||
| createChangedDocument: ct => ChangeReturnTypeToTaskAsync(context.Document, localFunction, ct), | ||
| equivalenceKey: nameof(AvoidUsingAssertsInAsyncVoidContextFixer)), | ||
| diagnostic); | ||
| } | ||
|
|
||
| break; | ||
| } | ||
|
|
||
| if (ancestor is AnonymousFunctionExpressionSyntax) | ||
| { | ||
| // For lambdas/anonymous functions, we don't provide a fix since changing to Task | ||
| // would require changing the delegate type as well. | ||
| break; | ||
| } | ||
|
Evangelink marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
|
|
||
| private static async Task<Document> ChangeReturnTypeToTaskAsync( | ||
| Document document, | ||
| MethodDeclarationSyntax methodDeclaration, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
| MethodDeclarationSyntax newMethodDeclaration = methodDeclaration.WithReturnType( | ||
| SyntaxFactory.IdentifierName("Task").WithTriviaFrom(methodDeclaration.ReturnType)); | ||
| editor.ReplaceNode(methodDeclaration, newMethodDeclaration); | ||
| Document updatedDocument = editor.GetChangedDocument(); | ||
|
|
||
| return await EnsureSystemThreadingTasksImportAsync(updatedDocument, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static async Task<Document> ChangeReturnTypeToTaskAsync( | ||
| Document document, | ||
| LocalFunctionStatementSyntax localFunction, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); | ||
| LocalFunctionStatementSyntax newLocalFunction = localFunction.WithReturnType( | ||
| SyntaxFactory.IdentifierName("Task").WithTriviaFrom(localFunction.ReturnType)); | ||
| editor.ReplaceNode(localFunction, newLocalFunction); | ||
| Document updatedDocument = editor.GetChangedDocument(); | ||
|
|
||
| return await EnsureSystemThreadingTasksImportAsync(updatedDocument, cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static async Task<Document> EnsureSystemThreadingTasksImportAsync(Document document, CancellationToken cancellationToken) | ||
| { | ||
| SyntaxNode root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); | ||
| if (root is not CompilationUnitSyntax compilationUnit) | ||
| { | ||
| return document; | ||
| } | ||
|
|
||
| bool hasUsing = compilationUnit.Usings.Any( | ||
|
Evangelink marked this conversation as resolved.
Outdated
|
||
| u => string.Equals(u.Name?.ToString(), "System.Threading.Tasks", StringComparison.Ordinal)); | ||
|
Evangelink marked this conversation as resolved.
Outdated
|
||
| if (hasUsing) | ||
| { | ||
| return document; | ||
| } | ||
|
Evangelink marked this conversation as resolved.
Outdated
|
||
|
|
||
| UsingDirectiveSyntax usingDirective = SyntaxFactory | ||
| .UsingDirective(SyntaxFactory.ParseName("System.Threading.Tasks").WithLeadingTrivia(SyntaxFactory.Space)) | ||
| .WithTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed); | ||
|
|
||
| // Insert after all existing System.* usings but before any non-System usings to maintain conventional ordering. | ||
| int insertionIndex = compilationUnit.Usings.Count; // default: append after all usings | ||
| for (int i = 0; i < compilationUnit.Usings.Count; i++) | ||
| { | ||
| string? nameText = compilationUnit.Usings[i].Name?.ToString(); | ||
|
Evangelink marked this conversation as resolved.
Outdated
|
||
| if (nameText is not null && !nameText.StartsWith("System", StringComparison.Ordinal)) | ||
| { | ||
| insertionIndex = i; | ||
| break; | ||
| } | ||
| } | ||
|
|
||
| SyntaxList<UsingDirectiveSyntax> newUsings = compilationUnit.Usings.Insert(insertionIndex, usingDirective); | ||
| return document.WithSyntaxRoot(compilationUnit.WithUsings(newUsings)); | ||
| } | ||
| } | ||
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
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.