Skip to content

Commit

Permalink
Fix Disposable Analyzer with Primary Constructor (#1398)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomhurst authored Dec 12, 2024
1 parent 31060e5 commit 2e48379
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 4 deletions.
36 changes: 35 additions & 1 deletion TUnit.Analyzers.Tests/DisposableFieldPropertyAnalyzerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,41 @@ public void Test1()
"""
);
}


[Test]
public async Task New_Disposable_No_Issue_When_Cleaned_Up_PrimaryConstructor()
{
await Verifier
.VerifyAnalyzerAsync(
"""
using System.Net.Http;
using TUnit.Core;
public class Test() // note the use of primary constructor here
{
private HttpClient _client = null!;
[Before(HookType.Test)]
public void Setup()
{
_client = new HttpClient();
}
[After(HookType.Test)]
public void Cleanup()
{
_client.Dispose();
}
[Test]
public void TestMethod()
{
}
}
"""
);
}

[Test]
public async Task New_Disposable__Static_No_Issue_When_Cleaned_Up_Nullable()
{
Expand Down
12 changes: 11 additions & 1 deletion TUnit.Analyzers/DisposableFieldPropertyAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,17 @@ private static void CheckSetUps(SyntaxNodeAnalysisContext context, IMethodSymbol
var syntaxNodes = methodSymbol.DeclaringSyntaxReferences
.SelectMany(x => x.GetSyntax().DescendantNodesAndSelf()).ToArray();

methodSymbol.IsHookMethod(context.Compilation, out _, out var level, out _);
var isHookMethod = methodSymbol.IsHookMethod(context.Compilation, out _, out var level, out _);

if (!isHookMethod && methodSymbol.MethodKind != MethodKind.Constructor)
{
return;
}

if (methodSymbol.MethodKind == MethodKind.Constructor)
{
level = HookLevel.Test;
}

foreach (var assignment in syntaxNodes
.Where(x => x.IsKind(SyntaxKind.SimpleAssignmentExpression)))
Expand Down
2 changes: 1 addition & 1 deletion TUnit.Analyzers/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public static IEnumerable<INamedTypeSymbol> GetSelfAndBaseTypes(this INamedTypeS
{
var type = namedTypeSymbol;

while (type != null)
while (type != null && type.SpecialType != SpecialType.System_Object)
{
yield return type;
type = type.BaseType;
Expand Down
2 changes: 1 addition & 1 deletion TUnit.Assertions.Analyzers/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static IEnumerable<ITypeSymbol> GetSelfAndBaseTypes(this ITypeSymbol name
{
var type = namedTypeSymbol;

while (type != null)
while (type != null && type.SpecialType != SpecialType.System_Object)
{
yield return type;
type = type.BaseType;
Expand Down

0 comments on commit 2e48379

Please sign in to comment.