@@ -12,6 +12,190 @@ namespace MSTest.Analyzers.Test;
1212[ TestClass ]
1313public sealed class AnalyzerDiagnosticContinuationTests
1414{
15+ [ TestMethod ]
16+ [ DataRow ( "Nullable" ) ]
17+ [ DataRow ( "Unused" ) ]
18+ [ DataRow ( "AsyncMethod" ) ]
19+ [ DataRow ( "AsyncFixture" ) ]
20+ public async Task Suppressors_MissingFramework_DoNotSuppressUnrelatedWarnings ( string scenario )
21+ {
22+ DiagnosticSuppressor suppressor = scenario switch
23+ {
24+ "Nullable" => new NonNullableReferenceNotInitializedSuppressor ( ) ,
25+ "Unused" => new UnusedParameterSuppressor ( ) ,
26+ "AsyncMethod" => new UseAsyncSuffixTestMethodSuppressor ( ) ,
27+ "AsyncFixture" => new UseAsyncSuffixTestFixtureMethodSuppressor ( ) ,
28+ _ => throw new ArgumentOutOfRangeException ( nameof ( scenario ) ) ,
29+ } ;
30+ string source = scenario switch
31+ {
32+ "Nullable" => "#nullable enable\n public class C { public string Value { get; set; } }" ,
33+ "Unused" => "public class C { public void Check(int value) { } }" ,
34+ _ => "public class C { public System.Threading.Tasks.Task Check() => System.Threading.Tasks.Task.CompletedTask; }" ,
35+ } ;
36+ using var workspace = new AdhocWorkspace ( ) ;
37+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source , includeMSTest : false ) ;
38+ Compilation compilation = ( await document . Project . GetCompilationAsync ( ) ) ! ;
39+ AnalyzerContinuationTestHelpers . AssertCompilerErrors ( compilation ) ;
40+ List < DiagnosticAnalyzer > analyzers = [ suppressor ] ;
41+ if ( scenario == "Unused" )
42+ {
43+ analyzers . Add ( new UnitTests . UnusedParameterSuppressorTests . WarnForUnusedParameters ( ) ) ;
44+ }
45+ else if ( scenario == "AsyncMethod" )
46+ {
47+ analyzers . Add ( new UnitTests . UseAsyncSuffixTestMethodSuppressorTests . WarnForMissingAsyncSuffix ( ) ) ;
48+ }
49+ else if ( scenario == "AsyncFixture" )
50+ {
51+ analyzers . Add ( new UnitTests . UseAsyncSuffixTestFixtureMethodSuppressorTests . WarnForMissingAsyncSuffix ( ) ) ;
52+ }
53+
54+ ImmutableArray < Diagnostic > diagnostics = await compilation . WithAnalyzers (
55+ analyzers . ToImmutableArray ( ) ,
56+ new CompilationWithAnalyzersOptions ( new AnalyzerOptions ( [ ] ) , onAnalyzerException : null ,
57+ concurrentAnalysis : true , logAnalyzerExecutionTime : false , reportSuppressedDiagnostics : true ) ) . GetAllDiagnosticsAsync ( ) ;
58+ Diagnostic warning = Assert . ContainsSingle ( diagnostics ) ;
59+ Assert . AreEqual ( suppressor . SupportedSuppressions [ 0 ] . SuppressedDiagnosticId , warning . Id ) ;
60+ Assert . AreEqual ( DiagnosticSeverity . Warning , warning . Severity ) ;
61+ Assert . IsFalse ( warning . IsSuppressed ) ;
62+ Assert . IsTrue ( warning . Location . IsInSource ) ;
63+ }
64+
65+ [ TestMethod ]
66+ [ DataRow ( "() => { int value = 17; System.GC.KeepAlive(value); System.Threading.Tasks.Task.CompletedTask.GetAwaiter().GetResult(); }" , DisplayName = "MultipleStatements" ) ]
67+ [ DataRow ( "() => { ; System.Threading.Tasks.Task.CompletedTask.GetAwaiter().GetResult(); }" , DisplayName = "ExplicitEmptyStatement" ) ]
68+ [ DataRow ( "() => new Awaitable().GetAwaiter().GetResult()" , DisplayName = "NonTaskAwaitable" ) ]
69+ public async Task AsyncAssertion_UnsupportedDelegateBodies_DoNotChangeTheirSemantics ( string action )
70+ {
71+ string source = $$ """
72+ using Microsoft.VisualStudio.TestTools.UnitTesting;
73+ public class Awaitable
74+ {
75+ public Awaiter GetAwaiter() => new Awaiter();
76+ }
77+ public class Awaiter
78+ {
79+ public void GetResult() { }
80+ }
81+ public class Tests
82+ {
83+ [TestMethod]
84+ public void Check() { Assert.ThrowsExactly<System.Exception>({{ action }} ); }
85+ }
86+ """ ;
87+ using var workspace = new AdhocWorkspace ( ) ;
88+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source ) ;
89+ Assert . IsEmpty ( await AnalyzerContinuationTestHelpers . AnalyzeAsync ( document , new PreferAsyncAssertionAnalyzer ( ) ) ) ;
90+ }
91+
92+ [ TestMethod ]
93+ public async Task AsyncAssertion_UnknownActionParameterName_DoesNotGuessAnUnsafeRewrite ( )
94+ {
95+ const string source = """
96+ using System;
97+ using System.Threading.Tasks;
98+ using Microsoft.VisualStudio.TestTools.UnitTesting;
99+ namespace Microsoft.VisualStudio.TestTools.UnitTesting
100+ {
101+ public class TestMethodAttribute : Attribute { }
102+ public static class Assert { public static void Throws(Action callback) { } }
103+ }
104+ public class Tests
105+ {
106+ [TestMethod]
107+ public void Check() { Assert.Throws(() => Task.CompletedTask.GetAwaiter().GetResult()); }
108+ }
109+ """ ;
110+ using var workspace = new AdhocWorkspace ( ) ;
111+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source , includeMSTest : false ) ;
112+ Assert . IsEmpty ( await AnalyzerContinuationTestHelpers . AnalyzeAsync ( document , new PreferAsyncAssertionAnalyzer ( ) ) ) ;
113+ }
114+
115+ [ TestMethod ]
116+ public async Task ProperAssert_RuntimeCardinality_DoesNotReplaceWithAZeroOrOneAssertion ( )
117+ {
118+ const string source = """
119+ using System.Collections.Generic;
120+ using Microsoft.VisualStudio.TestTools.UnitTesting;
121+ public class Tests
122+ {
123+ public void Check(int count, List<string> values) { Assert.HasCount(count, values); }
124+ }
125+ """ ;
126+ using var workspace = new AdhocWorkspace ( ) ;
127+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source ) ;
128+ Assert . IsEmpty ( await AnalyzerContinuationTestHelpers . AnalyzeAsync ( document , new UseProperAssertMethodsAnalyzer ( ) ) ) ;
129+ }
130+
131+ [ TestMethod ]
132+ [ DataRow ( "Process" ) ]
133+ [ DataRow ( "Directory" ) ]
134+ [ DataRow ( "File" ) ]
135+ [ DataRow ( "Culture" ) ]
136+ public async Task ParallelMutations_OutsideTestMethods_DoNotFlagHelpersOrFieldLambdas ( string scenario )
137+ {
138+ ( DiagnosticAnalyzer Analyzer , string Statement ) setup = scenario switch
139+ {
140+ "Process" => ( new UndeclaredProcessGlobalStateMutationAnalyzer ( ) , "Environment.SetEnvironmentVariable(\" fixture\" , \" value\" )" ) ,
141+ "Directory" => ( new CurrentDirectoryMutationUnderParallelizationAnalyzer ( ) , "Directory.SetCurrentDirectory(\" fixture\" )" ) ,
142+ "File" => ( new SharedFileSystemPathInTestAnalyzer ( ) , "File.WriteAllText(\" shared.txt\" , \" value\" )" ) ,
143+ "Culture" => ( new CultureMutationUnderParallelizationAnalyzer ( ) , "CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture" ) ,
144+ _ => throw new ArgumentOutOfRangeException ( nameof ( scenario ) ) ,
145+ } ;
146+ string source = $$ """
147+ using System;
148+ using System.Globalization;
149+ using System.IO;
150+ using Microsoft.VisualStudio.TestTools.UnitTesting;
151+ [assembly: Parallelize(Scope = ExecutionScope.MethodLevel)]
152+ [TestClass]
153+ public class Tests
154+ {
155+ private static readonly Action Hook = () => { {{ setup . Statement }} ; };
156+ public void Helper() { {{ setup . Statement }} ; }
157+ [TestMethod]
158+ public void Check() { }
159+ }
160+ """ ;
161+ using var workspace = new AdhocWorkspace ( ) ;
162+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source ) ;
163+ Assert . IsEmpty ( await AnalyzerContinuationTestHelpers . AnalyzeAsync ( document , setup . Analyzer ) ) ;
164+ }
165+
166+ public static IEnumerable < object [ ] > MissingFrameworkCases
167+ => typeof ( DataRowShouldBeValidAnalyzer ) . Assembly . GetTypes ( )
168+ . Where ( type => type . IsPublic && ! type . IsAbstract && typeof ( DiagnosticAnalyzer ) . IsAssignableFrom ( type ) )
169+ . OrderBy ( type => type . Name , StringComparer . Ordinal )
170+ . SelectMany ( type => new [ ] { new object [ ] { type . Name , type , false } , new object [ ] { type . Name , type , true } } ) ;
171+
172+ public static string MissingFrameworkDisplayName ( MethodInfo method , object [ ] data )
173+ => $ "{ method . Name } _{ data [ 0 ] } _{ ( ( bool ) data [ 2 ] ? "PartialFramework" : "NoFramework" ) } ";
174+
175+ [ TestMethod ]
176+ [ DynamicData ( nameof ( MissingFrameworkCases ) , DynamicDataDisplayName = nameof ( MissingFrameworkDisplayName ) ) ]
177+ public async Task MissingMSTestSymbols_DoNotReportInUnrelatedCSharpCompilation ( string analyzerName , Type analyzerType , bool partialFramework )
178+ {
179+ string source = partialFramework
180+ ? """
181+ namespace Microsoft.VisualStudio.TestTools.UnitTesting
182+ {
183+ public class TestMethodAttribute : System.Attribute
184+ {
185+ public TestMethodAttribute(
186+ [System.Runtime.CompilerServices.CallerFilePath] string file = "",
187+ [System.Runtime.CompilerServices.CallerLineNumber] int line = 0) { }
188+ }
189+ }
190+ public class Unrelated { public void Check() { } }
191+ """
192+ : "public class Unrelated { public void Check() { } }" ;
193+ using var workspace = new AdhocWorkspace ( ) ;
194+ Document document = await AnalyzerContinuationTestHelpers . CreateDocumentAsync ( workspace , source , includeMSTest : false ) ;
195+ var analyzer = ( DiagnosticAnalyzer ) Activator . CreateInstance ( analyzerType ) ! ;
196+ Assert . IsEmpty ( await AnalyzerContinuationTestHelpers . AnalyzeAsync ( document , analyzer ) , analyzerName ) ;
197+ }
198+
15199 [ TestMethod ]
16200 [ DataRow ( ReportDiagnostic . Error , ReportDiagnostic . Error , DiagnosticSeverity . Error , true ) ]
17201 [ DataRow ( ReportDiagnostic . Error , ReportDiagnostic . Warn , DiagnosticSeverity . Error , true ) ]
0 commit comments