Skip to content

Commit e57e52b

Browse files
Fix test property lifecycle scope by @Evangelink in #10080 (backport to rel/4.3) (#10110)
Co-authored-by: Amaury Levé <amauryleve@microsoft.com>
1 parent f517666 commit e57e52b

5 files changed

Lines changed: 246 additions & 13 deletions

File tree

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestExecutionManager.Runner.cs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,8 @@ private async Task ExecuteTestsWithTestRunnerAsync(
9595
? new RemotingMessageLogger(testExecutionRecorder)
9696
: testExecutionRecorder;
9797

98+
Dictionary<string, object?> lifecycleContextProperties = [with(sourceLevelParameters!)];
99+
98100
foreach (TestCase currentTest in orderedTests)
99101
{
100102
_testRunCancellationToken?.ThrowIfCancellationRequested();
@@ -128,12 +130,12 @@ private async Task ExecuteTestsWithTestRunnerAsync(
128130
// Alternatively, if we want to use RunSingleTestAsync for the case of STA, we should have:
129131
// 1. A custom single threaded synchronization context that keeps us in STA.
130132
// 2. Use ConfigureAwait(true).
131-
unitTestResult = testRunner.RunSingleTest(unitTestElement, testContextProperties, remotingMessageLogger);
133+
unitTestResult = testRunner.RunSingleTest(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger);
132134
#pragma warning restore VSTHRD103 // Call async methods when in an async method
133135
}
134136
else
135137
{
136-
unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement, testContextProperties, remotingMessageLogger).ConfigureAwait(false);
138+
unitTestResult = await testRunner.RunSingleTestAsync(unitTestElement, testContextProperties, lifecycleContextProperties, remotingMessageLogger).ConfigureAwait(false);
137139
}
138140

139141
if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsInfoEnabled)

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.RunSingleTest.cs‎

Lines changed: 34 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,15 @@ internal sealed partial class UnitTestRunner
1717
internal TestResult[] RunSingleTest(UnitTestElement unitTestElement, IDictionary<string, object?> testContextProperties, IMessageLogger messageLogger)
1818
=> RunSingleTestAsync(unitTestElement, testContextProperties, messageLogger).GetAwaiter().GetResult();
1919

20+
// Task cannot cross app domains.
21+
// For now, TestExecutionManager will call this sync method which is hacky.
22+
internal TestResult[] RunSingleTest(
23+
UnitTestElement unitTestElement,
24+
IDictionary<string, object?> testContextProperties,
25+
IDictionary<string, object?> lifecycleContextProperties,
26+
IMessageLogger messageLogger)
27+
=> RunSingleTestAsync(unitTestElement, testContextProperties, lifecycleContextProperties, messageLogger).GetAwaiter().GetResult();
28+
2029
/// <summary>
2130
/// Runs a single test.
2231
/// </summary>
@@ -25,6 +34,21 @@ internal TestResult[] RunSingleTest(UnitTestElement unitTestElement, IDictionary
2534
/// <param name="messageLogger"> The message logger. </param>
2635
/// <returns> The <see cref="TestResult"/>. </returns>
2736
internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestElement, IDictionary<string, object?> testContextProperties, IMessageLogger messageLogger)
37+
=> await RunSingleTestAsync(unitTestElement, testContextProperties, testContextProperties, messageLogger).ConfigureAwait(false);
38+
39+
/// <summary>
40+
/// Runs a single test.
41+
/// </summary>
42+
/// <param name="unitTestElement">The test method.</param>
43+
/// <param name="testContextProperties">Properties scoped to this test.</param>
44+
/// <param name="lifecycleContextProperties">Properties scoped to assembly and class lifecycle methods.</param>
45+
/// <param name="messageLogger">The message logger.</param>
46+
/// <returns>The <see cref="TestResult"/>.</returns>
47+
internal async Task<TestResult[]> RunSingleTestAsync(
48+
UnitTestElement unitTestElement,
49+
IDictionary<string, object?> testContextProperties,
50+
IDictionary<string, object?> lifecycleContextProperties,
51+
IMessageLogger messageLogger)
2852
{
2953
if (unitTestElement is null)
3054
{
@@ -36,6 +60,11 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
3660
throw new ArgumentNullException(nameof(testContextProperties));
3761
}
3862

63+
if (lifecycleContextProperties is null)
64+
{
65+
throw new ArgumentNullException(nameof(lifecycleContextProperties));
66+
}
67+
3968
TestMethod testMethod = unitTestElement.TestMethod;
4069
ITestContext? testContextForTestExecution = null;
4170
ITestContext? testContextForAssemblyInit = null;
@@ -56,7 +85,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
5685
{
5786
return await FinishFilteredOutTestAsync(
5887
testMethod,
59-
testContextProperties,
88+
lifecycleContextProperties,
6089
messageLogger,
6190
filterResult,
6291
testContextForTestExecution).ConfigureAwait(false);
@@ -84,7 +113,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
84113
}
85114
else
86115
{
87-
testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
116+
testContextForAssemblyInit = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, lifecycleContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
88117
assemblyInitializeResult = await RunAssemblyInitializeIfNeededAsync(testMethodInfo, testContextForAssemblyInit).ConfigureAwait(false);
89118
}
90119

@@ -116,7 +145,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
116145
}
117146
else
118147
{
119-
testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, testContextProperties, messageLogger, UnitTestOutcome.InProgress);
148+
testContextForClassInit = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, lifecycleContextProperties, messageLogger, UnitTestOutcome.InProgress);
120149

121150
// Flow properties set during AssemblyInitialize into the class-init context so the
122151
// ClassInitialize method observes them.
@@ -170,7 +199,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
170199
{
171200
// Defer TestContextImplementation allocation to only the last test in each class,
172201
// saving one dict-copy + CancellationTokenRegistration per non-last test.
173-
testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
202+
testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, lifecycleContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
174203

175204
if (testMethodInfo is not null)
176205
{
@@ -208,7 +237,7 @@ internal async Task<TestResult[]> RunSingleTestAsync(UnitTestElement unitTestEle
208237
// testContextForClassCleanup is guaranteed non-null here: ShouldRunEndOfAssemblyCleanup
209238
// becomes true only after MarkClassComplete, which is called exclusively inside the
210239
// isLastTestInClass block above — where testContextForClassCleanup is allocated.
211-
testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, testContextProperties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome);
240+
testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, lifecycleContextProperties, messageLogger, testContextForClassCleanup.Context.CurrentTestOutcome);
212241

213242
TestResult? assemblyCleanupResult = await RunAssemblyCleanupAsync(testContextForAssemblyCleanup, _typeCache, result).ConfigureAwait(false);
214243
if (assemblyCleanupResult is not null)

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/UnitTestRunner.TestFilter.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -143,13 +143,13 @@ private static TestFilterContext CreateFilterContext(UnitTestElement element)
143143
/// <summary>
144144
/// Handles the bookkeeping (class-cleanup countdown, class cleanup, end-of-assembly cleanup) for a
145145
/// test that was filtered out by a <see cref="ITestFilter"/>. Mirrors the tail of
146-
/// <see cref="RunSingleTestAsync"/>. The filtered-out test never loaded its own type, but if a
146+
/// normal test execution path. The filtered-out test never loaded its own type, but if a
147147
/// sibling test of the same class already ran in this worker the class was initialized and still
148148
/// owes its <c>[ClassCleanup]</c>, so it is executed here when this is the last test of the class.
149149
/// </summary>
150150
private async Task<TestResult[]> FinishFilteredOutTestAsync(
151151
TestMethod testMethod,
152-
IDictionary<string, object?> testContextProperties,
152+
IDictionary<string, object?> lifecycleContextProperties,
153153
IMessageLogger messageLogger,
154154
TestResult[] filterResult,
155155
ITestContext testContextForTestExecution)
@@ -172,7 +172,7 @@ private async Task<TestResult[]> FinishFilteredOutTestAsync(
172172
TestMethodInfo? testMethodInfo = _typeCache.GetTestMethodInfo(lastRunnableTest.TestMethod);
173173
if (testMethodInfo is not null)
174174
{
175-
ITestContext testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
175+
ITestContext testContextForClassCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, testMethod.FullClassName, lifecycleContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
176176
try
177177
{
178178
// Flow properties set during AssemblyInitialize and ClassInitialize so the
@@ -212,7 +212,7 @@ private async Task<TestResult[]> FinishFilteredOutTestAsync(
212212
ITestContext? testContextForAssemblyCleanup = null;
213213
try
214214
{
215-
testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, testContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
215+
testContextForAssemblyCleanup = PlatformServiceProvider.Instance.GetTestContext(testMethod: null, null, lifecycleContextProperties, messageLogger, testContextForTestExecution.Context.CurrentTestOutcome);
216216

217217
TestResult? assemblyCleanupResult = await RunAssemblyCleanupAsync(testContextForAssemblyCleanup, _typeCache, filterResult).ConfigureAwait(false);
218218
if (assemblyCleanupResult is not null)

‎test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs‎

Lines changed: 116 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,22 @@ public async Task PropertiesSetInAssemblyInitAndClassInitAreVisibleEverywhere(st
2626
// PropertyFlowTests: TestMethodOne + TestMethodTwo = 2
2727
// SecondClassTests: TestMethod = 1
2828
// DataRowFlowTests: two data rows = 2
29-
// Total = 5
30-
testHostResult.AssertOutputContainsSummary(failed: 0, passed: 5, skipped: 0);
29+
// PerTestPropertyScopeTests: TestWithFirstProperties + TestWithSecondProperties = 2
30+
// Total = 7
31+
testHostResult.AssertOutputContainsSummary(failed: 0, passed: 7, skipped: 0);
32+
}
33+
34+
[TestMethod]
35+
[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
36+
public async Task PerTestPropertiesAreScopedToTheirTest(string tfm)
37+
{
38+
var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm);
39+
TestHostResult testHostResult = await testHost.ExecuteAsync(
40+
"--filter ClassName=PerTestPropertyScopeTests",
41+
cancellationToken: TestContext.CancellationToken);
42+
43+
testHostResult.AssertExitCodeIs(0);
44+
testHostResult.AssertOutputContainsSummary(failed: 0, passed: 2, skipped: 0);
3145
}
3246

3347
public sealed class TestAssetFixture() : TestAssetFixtureBase()
@@ -70,6 +84,7 @@ public sealed class PropertyFlowTests
7084
[AssemblyInitialize]
7185
public static void AssemblyInit(TestContext context)
7286
{
87+
PropertyScopeAssertions.AssertNoPerTestProperties(context);
7388
context.Properties["AssemblyInitKey"] = "AssemblyInitValue";
7489
context.Properties["SharedKey"] = "FromAssemblyInit";
7590
}
@@ -129,6 +144,7 @@ public static void ClassCleanup(TestContext context)
129144
[AssemblyCleanup]
130145
public static void AssemblyCleanup(TestContext context)
131146
{
147+
PropertyScopeAssertions.AssertNoPerTestProperties(context);
132148
// AssemblyCleanup must see AssemblyInit-set properties, including any override the
133149
// AssemblyInit itself made. It must NOT see ClassInit-set properties (those are class-scoped).
134150
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
@@ -143,6 +159,104 @@ public static void AssemblyCleanup(TestContext context)
143159
}
144160
}
145161
162+
internal static class PropertyScopeAssertions
163+
{
164+
private static readonly string[] PerTestPropertyKeys =
165+
[
166+
"FirstTestProperty",
167+
"FirstTestCategory",
168+
"SecondTestProperty",
169+
"SecondTestCategory",
170+
];
171+
172+
public static void AssertNoPerTestProperties(TestContext context)
173+
{
174+
foreach (string key in PerTestPropertyKeys)
175+
{
176+
Assert.IsFalse(
177+
context.Properties.ContainsKey(key),
178+
$"Per-test property '{key}' must not be visible in a lifecycle or sibling-test context.");
179+
}
180+
}
181+
}
182+
183+
// Regression coverage for https://github.com/microsoft/testfx/issues/10041. The test that
184+
// triggers ClassInitialize may carry method-level properties, categories, or host metadata.
185+
// Those values belong only to that test's execution context and must not be captured in the
186+
// class lifecycle snapshot or flow to sibling tests.
187+
[TestClass]
188+
public sealed class PerTestPropertyScopeTests : System.IDisposable
189+
{
190+
private readonly TestContext _testContext;
191+
192+
public PerTestPropertyScopeTests(TestContext testContext)
193+
{
194+
_testContext = testContext;
195+
AssertExpectedPerTestProperties(testContext);
196+
}
197+
198+
[ClassInitialize]
199+
public static void ClassInit(TestContext context)
200+
{
201+
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
202+
PropertyScopeAssertions.AssertNoPerTestProperties(context);
203+
context.Properties["PerTestScopeClassInitKey"] = "PerTestScopeClassInitValue";
204+
}
205+
206+
[TestInitialize]
207+
public void TestInit() => AssertExpectedPerTestProperties(_testContext);
208+
209+
[TestMethod]
210+
[TestProperty("FirstTestProperty", "FirstTestValue")]
211+
[TestCategory("FirstTestCategory")]
212+
public void TestWithFirstProperties() => AssertExpectedPerTestProperties(_testContext);
213+
214+
[TestMethod]
215+
[TestProperty("SecondTestProperty", "SecondTestValue")]
216+
[TestCategory("SecondTestCategory")]
217+
public void TestWithSecondProperties() => AssertExpectedPerTestProperties(_testContext);
218+
219+
[TestCleanup]
220+
public void TestCleanup() => AssertExpectedPerTestProperties(_testContext);
221+
222+
public void Dispose() => AssertExpectedPerTestProperties(_testContext);
223+
224+
[ClassCleanup]
225+
public static void ClassCleanup(TestContext context)
226+
{
227+
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
228+
Assert.AreEqual("PerTestScopeClassInitValue", context.Properties["PerTestScopeClassInitKey"]);
229+
PropertyScopeAssertions.AssertNoPerTestProperties(context);
230+
}
231+
232+
private static void AssertExpectedPerTestProperties(TestContext context)
233+
{
234+
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
235+
Assert.AreEqual("PerTestScopeClassInitValue", context.Properties["PerTestScopeClassInitKey"]);
236+
237+
switch (context.TestName)
238+
{
239+
case nameof(TestWithFirstProperties):
240+
Assert.AreEqual("FirstTestValue", context.Properties["FirstTestProperty"]);
241+
Assert.IsTrue(context.Properties.ContainsKey("FirstTestCategory"));
242+
Assert.IsFalse(context.Properties.ContainsKey("SecondTestProperty"));
243+
Assert.IsFalse(context.Properties.ContainsKey("SecondTestCategory"));
244+
break;
245+
246+
case nameof(TestWithSecondProperties):
247+
Assert.AreEqual("SecondTestValue", context.Properties["SecondTestProperty"]);
248+
Assert.IsTrue(context.Properties.ContainsKey("SecondTestCategory"));
249+
Assert.IsFalse(context.Properties.ContainsKey("FirstTestProperty"));
250+
Assert.IsFalse(context.Properties.ContainsKey("FirstTestCategory"));
251+
break;
252+
253+
default:
254+
Assert.Fail($"Unexpected test name '{context.TestName}'.");
255+
break;
256+
}
257+
}
258+
}
259+
146260
// Second class to verify that the assembly-init snapshot flows here too, AND that the
147261
// FIRST class's class-init snapshot does NOT leak into THIS class's contexts.
148262
[TestClass]

0 commit comments

Comments
 (0)