-
Notifications
You must be signed in to change notification settings - Fork 262
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
Implement analyzer and codefix to switch to Assert.ThrowsExactly[Async] #4459
Open
Youssef1313
wants to merge
5
commits into
microsoft:main
Choose a base branch
from
Youssef1313:assert-throwsex-analyzer
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
5 commits
Select commit
Hold shift + click to select a range
6e4454b
Implement analyzer and codefix to switch to Assert.ThrowsExactly[Async]
Youssef1313 763c14e
More complex scenarios
Youssef1313 6b5a967
Merge branch 'main' into assert-throwsex-analyzer
Evangelink 87279f7
Merge branch 'main' into assert-throwsex-analyzer
Evangelink 1d16c93
Address review comments
Youssef1313 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
9 changes: 9 additions & 0 deletions
9
src/Analyzers/MSTest.Analyzers.CodeFixes/CodeFixResources.Designer.cs
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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
156 changes: 156 additions & 0 deletions
156
src/Analyzers/MSTest.Analyzers.CodeFixes/UseNewerAssertThrowsFixer.cs
This file contains 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,156 @@ | ||
// 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 Microsoft.CodeAnalysis.Simplification; | ||
|
||
using MSTest.Analyzers.Helpers; | ||
|
||
namespace MSTest.Analyzers; | ||
|
||
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(UseNewerAssertThrowsFixer))] | ||
[Shared] | ||
public sealed class UseNewerAssertThrowsFixer : CodeFixProvider | ||
{ | ||
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } | ||
= ImmutableArray.Create(DiagnosticIds.UseNewerAssertThrowsRuleId); | ||
|
||
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; | ||
|
||
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); | ||
if (diagnosticNode is not InvocationExpressionSyntax invocation) | ||
{ | ||
Debug.Fail($"Is this an interesting scenario where IInvocationOperation for Assert call isn't associated with InvocationExpressionSyntax? SyntaxNode type: '{diagnosticNode.GetType()}', Text: '{diagnosticNode.GetText()}'"); | ||
return; | ||
} | ||
|
||
SyntaxNode methodNameIdentifier = invocation.Expression; | ||
if (methodNameIdentifier is MemberAccessExpressionSyntax memberAccess) | ||
{ | ||
methodNameIdentifier = memberAccess.Name; | ||
} | ||
|
||
if (methodNameIdentifier is not GenericNameSyntax genericNameSyntax) | ||
{ | ||
Debug.Fail($"Is this an interesting scenario where we are unable to retrieve GenericNameSyntax corresponding to the assert method? SyntaxNode type: '{methodNameIdentifier}', Text: '{methodNameIdentifier.GetText()}'."); | ||
return; | ||
} | ||
|
||
string updatedMethodName = genericNameSyntax.Identifier.Text switch | ||
{ | ||
"ThrowsException" => "ThrowsExactly", | ||
"ThrowsExceptionAsync" => "ThrowsExactlyAsync", | ||
// The analyzer should report a diagnostic only for ThrowsException and ThrowsExceptionAsync | ||
_ => throw ApplicationStateGuard.Unreachable(), | ||
}; | ||
|
||
context.RegisterCodeFix( | ||
CodeAction.Create( | ||
title: string.Format(CultureInfo.InvariantCulture, CodeFixResources.UseNewerAssertThrows, updatedMethodName), | ||
ct => Task.FromResult(context.Document.WithSyntaxRoot(UpdateMethodName(new SyntaxEditor(root, context.Document.Project.Solution.Workspace), invocation, genericNameSyntax, updatedMethodName, diagnostic.AdditionalLocations))), | ||
equivalenceKey: nameof(UseProperAssertMethodsFixer)), | ||
diagnostic); | ||
} | ||
|
||
private static SyntaxNode UpdateMethodName(SyntaxEditor editor, InvocationExpressionSyntax invocation, GenericNameSyntax genericNameSyntax, string updatedMethodName, IReadOnlyList<Location> additionalLocations) | ||
{ | ||
editor.ReplaceNode(genericNameSyntax, genericNameSyntax.WithIdentifier(SyntaxFactory.Identifier(updatedMethodName).WithTriviaFrom(genericNameSyntax.Identifier))); | ||
|
||
// The object[] parameter to format the message is named parameters in the old ThrowsException[Async] methods, but is named messageArgs in the new ThrowsExactly[Async] methods. | ||
if (invocation.ArgumentList.Arguments.FirstOrDefault(arg => arg.NameColon is { Name.Identifier.Text: "parameters" }) is { } arg) | ||
{ | ||
editor.ReplaceNode(arg.NameColon!.Name, arg.NameColon!.Name.WithIdentifier(SyntaxFactory.Identifier("messageArgs").WithTriviaFrom(arg.NameColon.Name.Identifier))); | ||
} | ||
|
||
if (additionalLocations.Count != 1) | ||
{ | ||
return editor.GetChangedRoot(); | ||
} | ||
|
||
// The existing ThrowsException call is using the Func<object> overload. The new ThrowsExactly method does not have this overload, so we need to adjust. | ||
// This is a best effort handling. | ||
SyntaxNode actionArgument = editor.OriginalRoot.FindNode(additionalLocations[0].SourceSpan, getInnermostNodeForTie: true); | ||
|
||
if (actionArgument is ParenthesizedLambdaExpressionSyntax lambdaSyntax) | ||
{ | ||
if (lambdaSyntax.ExpressionBody is not null) | ||
{ | ||
editor.ReplaceNode( | ||
lambdaSyntax.ExpressionBody, | ||
AssignToDiscard(lambdaSyntax.ExpressionBody)); | ||
} | ||
else if (lambdaSyntax.Block is not null) | ||
{ | ||
// This is more complex. We need to iterate through all descendants of type ReturnStatementSyntax, and split it into two statements. | ||
// The first statement will be an assignment expression to a discard, and the second statement will be 'return;'. | ||
// We may even need to add extra braces in case the return statement (for example) is originally inside an if statement without braces. | ||
// For example: | ||
// if (condition) | ||
// return Whatever; | ||
// should be converted to: | ||
// if (condition) | ||
// { | ||
// _ = Whatever; | ||
// return; | ||
// } | ||
// Keep in mind: When descending into descendant nodes, we shouldn't descend into potential other lambda expressions or local functions. | ||
IEnumerable<ReturnStatementSyntax> returnStatements = lambdaSyntax.Block.DescendantNodes(descendIntoChildren: node => node is not (LocalFunctionStatementSyntax or AnonymousFunctionExpressionSyntax)).OfType<ReturnStatementSyntax>(); | ||
foreach (ReturnStatementSyntax returnStatement in returnStatements) | ||
{ | ||
if (returnStatement.Expression is not { } returnExpression) | ||
{ | ||
// This should be an error in user code. | ||
continue; | ||
} | ||
|
||
ExpressionStatementSyntax returnReplacement = SyntaxFactory.ExpressionStatement(AssignToDiscard(returnStatement.Expression)); | ||
|
||
if (returnStatement.Parent is BlockSyntax blockSyntax) | ||
{ | ||
editor.InsertAfter(returnStatement, SyntaxFactory.ReturnStatement()); | ||
editor.ReplaceNode(returnStatement, returnReplacement); | ||
} | ||
else | ||
{ | ||
editor.ReplaceNode( | ||
returnStatement, | ||
SyntaxFactory.Block( | ||
returnReplacement, | ||
SyntaxFactory.ReturnStatement())); | ||
} | ||
} | ||
} | ||
} | ||
else if (actionArgument is ExpressionSyntax expressionSyntax) | ||
{ | ||
editor.ReplaceNode( | ||
expressionSyntax, | ||
SyntaxFactory.ParenthesizedLambdaExpression( | ||
SyntaxFactory.ParameterList(), | ||
block: null, | ||
expressionBody: AssignToDiscard(SyntaxFactory.InvocationExpression(SyntaxFactory.ParenthesizedExpression(expressionSyntax).WithAdditionalAnnotations(Simplifier.Annotation))))); | ||
} | ||
|
||
return editor.GetChangedRoot(); | ||
} | ||
|
||
private static AssignmentExpressionSyntax AssignToDiscard(ExpressionSyntax expression) | ||
=> SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, SyntaxFactory.IdentifierName("_"), expression); | ||
} |
This file contains 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 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 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 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 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 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 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 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 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 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 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 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 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 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,7 @@ | ||
; 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 | ||
--------|----------|----------|------- | ||
MSTEST0038 | Usage | Info | UseNewerAssertThrowsAnalyzer, [Documentation](https://learn.microsoft.com/dotnet/core/testing/mstest-analyzers/mstest0038) |
This file contains 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 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't recall, do we see title on the menu or message?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think the message. Not sure of all places that show the title, but Solution Explorer is one that shows the title (when you expand Dependencies -> Analyzers)