-
Notifications
You must be signed in to change notification settings - Fork 302
Add MSTEST0067 analyzer to flag Thread.Sleep/Task.Wait/Task<T>.Result in tests #8646
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
Merged
Evangelink
merged 5 commits into
main
from
dev/amauryleve/mstest0066-avoid-thread-sleep
May 28, 2026
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
728aaaf
Add MSTEST0066 analyzer to flag Thread.Sleep/Task.Wait/Task<T>.Result…
Evangelink e712ed4
Address review feedback
Evangelink 38f35f4
Address review: add Task.WaitAll/WaitAny detection and expand test co…
Evangelink eb563fb
Merge remote-tracking branch 'origin/main' into pr-8646
Evangelink 6d0be7b
Drop unused 'using System;' from derived attribute test
Evangelink 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
210 changes: 210 additions & 0 deletions
210
src/Analyzers/MSTest.Analyzers/AvoidThreadSleepAndTaskWaitInTestsAnalyzer.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,210 @@ | ||
| // 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; | ||
|
|
||
| namespace MSTest.Analyzers; | ||
|
|
||
| /// <summary> | ||
| /// MSTEST0067: <inheritdoc cref="Resources.AvoidThreadSleepAndTaskWaitInTestsTitle"/>. | ||
| /// </summary> | ||
| [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] | ||
| public sealed class AvoidThreadSleepAndTaskWaitInTestsAnalyzer : DiagnosticAnalyzer | ||
| { | ||
| private static readonly LocalizableResourceString Title = new(nameof(Resources.AvoidThreadSleepAndTaskWaitInTestsTitle), Resources.ResourceManager, typeof(Resources)); | ||
| private static readonly LocalizableResourceString MessageFormat = new(nameof(Resources.AvoidThreadSleepAndTaskWaitInTestsMessageFormat), Resources.ResourceManager, typeof(Resources)); | ||
| private static readonly LocalizableResourceString Description = new(nameof(Resources.AvoidThreadSleepAndTaskWaitInTestsDescription), Resources.ResourceManager, typeof(Resources)); | ||
|
|
||
| internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create( | ||
| DiagnosticIds.AvoidThreadSleepAndTaskWaitInTestsRuleId, | ||
| 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.EnableConcurrentExecution(); | ||
| context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); | ||
|
|
||
| context.RegisterCompilationStartAction(context => | ||
| { | ||
| Compilation compilation = context.Compilation; | ||
| INamedTypeSymbol? threadSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread); | ||
| INamedTypeSymbol? taskSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); | ||
| INamedTypeSymbol? taskOfTSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask1); | ||
|
|
||
| // Collect the set of attribute symbols that mark a method as "test code". | ||
| ImmutableHashSet<INamedTypeSymbol> testRelatedAttributeSymbols = GetTestRelatedAttributeSymbols(compilation); | ||
| INamedTypeSymbol? testMethodAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute); | ||
|
|
||
| // If no test attribute is available in this compilation, there is nothing to analyze. | ||
| if (testRelatedAttributeSymbols.IsEmpty && testMethodAttributeSymbol is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (threadSymbol is not null || taskSymbol is not null || taskOfTSymbol is not null) | ||
| { | ||
| context.RegisterOperationAction( | ||
| context => AnalyzeInvocation(context, threadSymbol, taskSymbol, taskOfTSymbol, testRelatedAttributeSymbols, testMethodAttributeSymbol), | ||
| OperationKind.Invocation); | ||
| } | ||
|
|
||
| if (taskOfTSymbol is not null) | ||
| { | ||
| context.RegisterOperationAction( | ||
| context => AnalyzePropertyReference(context, taskOfTSymbol, testRelatedAttributeSymbols, testMethodAttributeSymbol), | ||
| OperationKind.PropertyReference); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| private static void AnalyzeInvocation( | ||
| OperationAnalysisContext context, | ||
| INamedTypeSymbol? threadSymbol, | ||
| INamedTypeSymbol? taskSymbol, | ||
| INamedTypeSymbol? taskOfTSymbol, | ||
| ImmutableHashSet<INamedTypeSymbol> testRelatedAttributeSymbols, | ||
| INamedTypeSymbol? testMethodAttributeSymbol) | ||
| { | ||
| var invocation = (IInvocationOperation)context.Operation; | ||
| IMethodSymbol targetMethod = invocation.TargetMethod; | ||
|
|
||
| string? offendingApi = null; | ||
| if (threadSymbol is not null | ||
| && targetMethod is { Name: "Sleep", IsStatic: true } | ||
| && SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, threadSymbol)) | ||
| { | ||
| offendingApi = "Thread.Sleep"; | ||
| } | ||
| else if (targetMethod is { Name: "Wait", IsStatic: false } | ||
| && (SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, taskSymbol) | ||
| || (taskOfTSymbol is not null && IsConstructedFrom(targetMethod.ContainingType, taskOfTSymbol)))) | ||
| { | ||
| offendingApi = "Task.Wait"; | ||
| } | ||
| else if (taskSymbol is not null | ||
| && targetMethod is { Name: "WaitAll" or "WaitAny", IsStatic: true } | ||
| && SymbolEqualityComparer.Default.Equals(targetMethod.ContainingType, taskSymbol)) | ||
| { | ||
| offendingApi = $"Task.{targetMethod.Name}"; | ||
| } | ||
|
|
||
| if (offendingApi is null) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!IsInsideTestCode(context.ContainingSymbol, testRelatedAttributeSymbols, testMethodAttributeSymbol)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.ReportDiagnostic(invocation.CreateDiagnostic(Rule, offendingApi)); | ||
| } | ||
|
|
||
| private static void AnalyzePropertyReference( | ||
| OperationAnalysisContext context, | ||
| INamedTypeSymbol taskOfTSymbol, | ||
| ImmutableHashSet<INamedTypeSymbol> testRelatedAttributeSymbols, | ||
| INamedTypeSymbol? testMethodAttributeSymbol) | ||
| { | ||
| var propertyReference = (IPropertyReferenceOperation)context.Operation; | ||
| IPropertySymbol property = propertyReference.Property; | ||
|
|
||
| if (property is not { Name: "Result", IsStatic: false } | ||
| || !IsConstructedFrom(property.ContainingType, taskOfTSymbol)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| if (!IsInsideTestCode(context.ContainingSymbol, testRelatedAttributeSymbols, testMethodAttributeSymbol)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| context.ReportDiagnostic(propertyReference.CreateDiagnostic(Rule, "Task<TResult>.Result")); | ||
| } | ||
|
|
||
| private static bool IsConstructedFrom(INamedTypeSymbol? typeSymbol, INamedTypeSymbol genericDefinition) | ||
| => typeSymbol is not null && SymbolEqualityComparer.Default.Equals(typeSymbol.OriginalDefinition, genericDefinition); | ||
|
|
||
| private static bool IsInsideTestCode( | ||
| ISymbol? containingSymbol, | ||
| ImmutableHashSet<INamedTypeSymbol> testRelatedAttributeSymbols, | ||
| INamedTypeSymbol? testMethodAttributeSymbol) | ||
| { | ||
| // Walk up through local functions / lambdas to find the enclosing user-declared method. | ||
| ISymbol? current = containingSymbol; | ||
| while (current is IMethodSymbol method) | ||
| { | ||
| foreach (AttributeData attribute in method.GetAttributes()) | ||
| { | ||
| INamedTypeSymbol? attributeClass = attribute.AttributeClass; | ||
| if (attributeClass is null) | ||
| { | ||
| continue; | ||
| } | ||
|
|
||
| if (testRelatedAttributeSymbols.Contains(attributeClass)) | ||
| { | ||
| return true; | ||
| } | ||
|
|
||
| if (testMethodAttributeSymbol is not null && attributeClass.Inherits(testMethodAttributeSymbol)) | ||
| { | ||
| return true; | ||
| } | ||
| } | ||
|
Evangelink marked this conversation as resolved.
Dismissed
|
||
|
|
||
| // Continue walking only when the symbol is synthesized from a local function / lambda body. | ||
| if (method.MethodKind is MethodKind.LocalFunction or MethodKind.AnonymousFunction) | ||
| { | ||
| current = method.ContainingSymbol; | ||
| continue; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| private static ImmutableHashSet<INamedTypeSymbol> GetTestRelatedAttributeSymbols(Compilation compilation) | ||
| { | ||
| ImmutableHashSet<INamedTypeSymbol>.Builder builder = ImmutableHashSet.CreateBuilder<INamedTypeSymbol>(SymbolEqualityComparer.Default); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestInitializeAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestCleanupAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassInitializeAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingClassCleanupAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyInitializeAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssemblyCleanupAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestInitializeAttribute); | ||
| AddIfPresent(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingGlobalTestCleanupAttribute); | ||
| return builder.ToImmutable(); | ||
|
|
||
| void AddIfPresent(string metadataName) | ||
| { | ||
| if (compilation.GetOrCreateTypeByMetadataName(metadataName) is { } symbol) | ||
| { | ||
| builder.Add(symbol); | ||
| } | ||
| } | ||
| } | ||
| } | ||
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.