Skip to content

Commit

Permalink
Add fixer for xUnit1029
Browse files Browse the repository at this point in the history
  • Loading branch information
bradwilson committed Aug 2, 2023
1 parent ada1d2f commit e366e1e
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;

namespace Xunit.Analyzers.Fixes;

[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public class LocalFunctionsCannotBeTestFunctionsFixer : BatchedCodeFixProvider
{
public const string Key_RemoveAttribute = "xUnit1029_RemoveAttribute";

public LocalFunctionsCannotBeTestFunctionsFixer() :
base(Descriptors.X1029_LocalFunctionsCannotBeTestFunctions.Id)
{ }

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
if (root is null)
return;

var localFunctionDeclaration = root.FindNode(context.Span).FirstAncestorOrSelf<LocalFunctionStatementSyntax>();
if (localFunctionDeclaration is null)
return;

context.RegisterCodeFix(
new RemoveAttributesOfTypeCodeAction(
"Remove attribute",
Key_RemoveAttribute,
context.Document,
localFunctionDeclaration.AttributeLists,
Constants.Types.Xunit.FactAttribute
),
context.Diagnostics
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using Microsoft.CodeAnalysis.CSharp;
using Xunit;
using Xunit.Analyzers.Fixes;
using Verify = CSharpVerifier<Xunit.Analyzers.LocalFunctionsCannotBeTestFunctions>;

public class LocalFunctionsCannotBeTestFunctionsFixerTests
{
[Theory]
[InlineData("Fact")]
[InlineData("Theory")]
public async void LocalFunctionsCannotHaveTestAttributes(string attribute)
{
var before = $@"
using Xunit;
public class TestClass {{
public void Method() {{
[[|{attribute}|]]
void LocalFunction() {{
}}
}}
}}";
var after = @"
using Xunit;
public class TestClass {
public void Method() {
void LocalFunction() {
}
}
}";

await Verify.VerifyCodeFix(LanguageVersion.CSharp9, before, after, LocalFunctionsCannotBeTestFunctionsFixer.Key_RemoveAttribute);
}
}

0 comments on commit e366e1e

Please sign in to comment.