Skip to content

Commit da7942d

Browse files
nohwnd-botEvangelinkCopilot
authored
Fix #9595: TestContext API surface consistency gaps by @Evangelink in #9701 (backport to rel/4.3) (#9702)
Co-authored-by: Amaury Levé <amauryleve@microsoft.com> Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 9ee07d8 commit da7942d

3 files changed

Lines changed: 154 additions & 14 deletions

File tree

‎src/Analyzers/MSTest.Analyzers/TestContextPropertyUsageAnalyzer.cs‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,12 @@ public sealed class TestContextPropertyUsageAnalyzer : DiagnosticAnalyzer
4242
"TestDisplayName",
4343
"DataRow",
4444
"DataConnection",
45-
"TestName",
46-
"ManagedMethod");
45+
"TestName");
4746

4847
// Properties that cannot be accessed in assembly initialize or assembly cleanup
4948
private static readonly ImmutableHashSet<string> RestrictedInAssemblyMethods = ImmutableHashSet.Create(
5049
StringComparer.Ordinal,
51-
"FullyQualifiedTestClassName",
52-
"ManagedType");
50+
"FullyQualifiedTestClassName");
5351

5452
/// <inheritdoc />
5553
public override void Initialize(AnalysisContext context)
@@ -68,28 +66,39 @@ public override void Initialize(AnalysisContext context)
6866
return;
6967
}
7068

71-
context.RegisterOperationAction(context => AnalyzePropertyReference(context, testContextSymbol, assemblyInitializeAttributeSymbol, assemblyCleanupAttributeSymbol, classInitializeAttributeSymbol, classCleanupAttributeSymbol), OperationKind.PropertyReference);
69+
IPropertySymbol? propertiesSymbol = testContextSymbol.GetMembers("Properties").OfType<IPropertySymbol>().FirstOrDefault();
70+
71+
context.RegisterOperationAction(context => AnalyzePropertyReference(context, testContextSymbol, propertiesSymbol, assemblyInitializeAttributeSymbol, assemblyCleanupAttributeSymbol, classInitializeAttributeSymbol, classCleanupAttributeSymbol), OperationKind.PropertyReference);
7272
});
7373
}
7474

7575
private static void AnalyzePropertyReference(
7676
OperationAnalysisContext context,
7777
INamedTypeSymbol testContextSymbol,
78+
IPropertySymbol? propertiesSymbol,
7879
INamedTypeSymbol assemblyInitializeAttributeSymbol,
7980
INamedTypeSymbol assemblyCleanupAttributeSymbol,
8081
INamedTypeSymbol classInitializeAttributeSymbol,
8182
INamedTypeSymbol classCleanupAttributeSymbol)
8283
{
8384
var propertyReference = (IPropertyReferenceOperation)context.Operation;
8485

85-
// Check if the property is a TestContext property
86-
if (!SymbolEqualityComparer.Default.Equals(propertyReference.Property.ContainingType, testContextSymbol))
86+
string? propertyName;
87+
if (SymbolEqualityComparer.Default.Equals(propertyReference.Property.ContainingType, testContextSymbol))
88+
{
89+
// Direct typed property access, e.g. testContext.TestName.
90+
propertyName = propertyReference.Property.Name;
91+
}
92+
else if (TryGetRestrictedPropertiesIndexerKey(propertyReference, propertiesSymbol) is { } key)
93+
{
94+
// Indirect access through the string-keyed bag, e.g. testContext.Properties["TestName"].
95+
propertyName = key;
96+
}
97+
else
8798
{
8899
return;
89100
}
90101

91-
string propertyName = propertyReference.Property.Name;
92-
93102
// Check if we're in a forbidden context
94103
if (context.ContainingSymbol is not IMethodSymbol containingMethod)
95104
{
@@ -116,6 +125,38 @@ private static void AnalyzePropertyReference(
116125
}
117126
}
118127

128+
private static string? TryGetRestrictedPropertiesIndexerKey(IPropertyReferenceOperation propertyReference, IPropertySymbol? propertiesSymbol)
129+
{
130+
// We only care about indexer access such as testContext.Properties["TestName"].
131+
if (propertiesSymbol is null
132+
|| !propertyReference.Property.IsIndexer
133+
|| propertyReference.Arguments.Length != 1
134+
|| propertyReference.Instance is not IPropertyReferenceOperation instanceReference
135+
|| !IsTestContextPropertiesReference(instanceReference.Property, propertiesSymbol))
136+
{
137+
return null;
138+
}
139+
140+
// The key must be a compile-time constant string.
141+
return propertyReference.Arguments[0].Value.ConstantValue is { HasValue: true, Value: string key }
142+
? key
143+
: null;
144+
}
145+
146+
private static bool IsTestContextPropertiesReference(IPropertySymbol property, IPropertySymbol propertiesSymbol)
147+
{
148+
// Match TestContext.Properties as well as overrides of it in derived contexts.
149+
for (IPropertySymbol? current = property; current is not null; current = current.OverriddenProperty)
150+
{
151+
if (SymbolEqualityComparer.Default.Equals(current, propertiesSymbol))
152+
{
153+
return true;
154+
}
155+
}
156+
157+
return false;
158+
}
159+
119160
private static string GetMethodType(bool isAssemblyInitialize, bool isAssemblyCleanup, bool isClassInitialize, bool isClassCleanup)
120161
=> (isAssemblyInitialize, isAssemblyCleanup, isClassInitialize, isClassCleanup) switch
121162
{

‎src/TestFramework/TestFramework.Extensions/TestContext.cs‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -223,15 +223,13 @@ public static TestContext? Current
223223
where T : class
224224
{
225225
DebugEx.Assert(Properties is not null, "Properties is null");
226-
#if WINDOWS_UWP || WIN_UI
226+
227+
// Use TryGetValue rather than the indexer so a missing key returns null instead of throwing,
228+
// regardless of the IDictionary implementation a custom subclass provides.
227229
if (!Properties.TryGetValue(name, out object? propertyValue))
228230
{
229231
return null;
230232
}
231-
#else
232-
// This old API doesn't throw when key is not found, but returns null.
233-
object? propertyValue = Properties[name];
234-
#endif
235233

236234
// If propertyValue has a value, but it's not the right type
237235
if (propertyValue is not null and not T)

‎test/UnitTests/MSTest.Analyzers.UnitTests/TestContextPropertyUsageAnalyzerTests.cs‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,4 +315,105 @@ public static void AssemblyInit(TestContext testContext)
315315

316316
await VerifyCS.VerifyAnalyzerAsync(code);
317317
}
318+
319+
[TestMethod]
320+
public async Task WhenRestrictedPropertyAccessedThroughPropertiesBagInFixtureMethods_Diagnostic()
321+
{
322+
string code = """
323+
using Microsoft.VisualStudio.TestTools.UnitTesting;
324+
325+
[TestClass]
326+
public class MyTestClass
327+
{
328+
[AssemblyInitialize]
329+
public static void AssemblyInit(TestContext testContext)
330+
{
331+
_ = [|testContext.Properties["TestData"]|];
332+
_ = [|testContext.Properties["TestDisplayName"]|];
333+
_ = [|testContext.Properties["TestName"]|];
334+
_ = [|testContext.Properties["FullyQualifiedTestClassName"]|];
335+
}
336+
337+
[ClassInitialize]
338+
public static void ClassInit(TestContext testContext)
339+
{
340+
_ = [|testContext.Properties["TestName"]|];
341+
// FullyQualifiedTestClassName is allowed in class initialize.
342+
_ = testContext.Properties["FullyQualifiedTestClassName"];
343+
}
344+
}
345+
""";
346+
347+
await VerifyCS.VerifyAnalyzerAsync(code);
348+
}
349+
350+
[TestMethod]
351+
public async Task WhenRestrictedPropertyAccessedThroughPropertiesBagInTestMethod_NoDiagnostic()
352+
{
353+
string code = """
354+
using Microsoft.VisualStudio.TestTools.UnitTesting;
355+
356+
[TestClass]
357+
public class MyTestClass
358+
{
359+
public TestContext TestContext { get; set; }
360+
361+
[TestMethod]
362+
public void TestMethod()
363+
{
364+
_ = TestContext.Properties["TestName"];
365+
_ = TestContext.Properties["TestData"];
366+
}
367+
}
368+
""";
369+
370+
await VerifyCS.VerifyAnalyzerAsync(code);
371+
}
372+
373+
[TestMethod]
374+
public async Task WhenNonConstantOrUnrelatedKeyAccessedThroughPropertiesBagInFixtureMethods_NoDiagnostic()
375+
{
376+
string code = """
377+
using Microsoft.VisualStudio.TestTools.UnitTesting;
378+
379+
[TestClass]
380+
public class MyTestClass
381+
{
382+
[AssemblyInitialize]
383+
public static void AssemblyInit(TestContext testContext)
384+
{
385+
// Non-restricted key.
386+
_ = testContext.Properties["MyCustomKey"];
387+
// Non-constant key cannot be resolved.
388+
string key = "TestName";
389+
_ = testContext.Properties[key];
390+
}
391+
}
392+
""";
393+
394+
await VerifyCS.VerifyAnalyzerAsync(code);
395+
}
396+
397+
[TestMethod]
398+
public async Task WhenManagedMethodOrManagedTypeAccessedThroughPropertiesBagInFixtureMethods_NoDiagnostic()
399+
{
400+
// "ManagedMethod" and "ManagedType" are VSTest TestCase-level keys in the string-keyed
401+
// Properties bag; they are not restricted TestContext properties, so no diagnostic is reported.
402+
string code = """
403+
using Microsoft.VisualStudio.TestTools.UnitTesting;
404+
405+
[TestClass]
406+
public class MyTestClass
407+
{
408+
[AssemblyInitialize]
409+
public static void AssemblyInit(TestContext testContext)
410+
{
411+
_ = testContext.Properties["ManagedMethod"];
412+
_ = testContext.Properties["ManagedType"];
413+
}
414+
}
415+
""";
416+
417+
await VerifyCS.VerifyAnalyzerAsync(code);
418+
}
318419
}

0 commit comments

Comments
 (0)