Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,18 @@ internal set
/// assembly-cleanup context, because <c>AssemblyCleanup</c> is assembly-scoped and runs
/// once across many classes; including a single class's snapshot would be arbitrary.
/// </para>
/// <para>
/// Reads and writes use <see cref="Volatile"/> so that callers on the
/// <see cref="IsAssemblyInitializeExecuted"/> fast path (which intentionally bypasses
/// <see cref="_assemblyInfoExecuteSyncSemaphore"/>) safely observe the snapshot published
/// by the thread that ran <c>AssemblyInitialize</c>.
/// </para>
/// </summary>
internal IReadOnlyDictionary<string, object?>? PostAssemblyInitProperties { get; private set; }
internal IReadOnlyDictionary<string, object?>? PostAssemblyInitProperties
{
get => Volatile.Read(ref field);
private set => Volatile.Write(ref field, value);
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

/// <summary>
/// Gets the assembly cleanup exception.
Expand Down Expand Up @@ -190,13 +200,10 @@ public async Task<TestResult> RunAssemblyInitializeAsync(TestContext testContext
// Capture a snapshot of TestContext.Properties so that values
// set during AssemblyInitialize flow to subsequent contexts
// (class init, test execution, class cleanup, assembly cleanup).
// TODO: PostAssemblyInitProperties is published outside the
// _assemblyInfoExecuteSyncSemaphore via the
// IsAssemblyInitializeExecuted fast path in this method. This
// is consistent with the existing pattern used by
// AssemblyInitializationException and ExecutionContext;
// revisit memory-barrier semantics for all three together
// if it becomes a problem.
// PostAssemblyInitProperties uses Volatile.Read/Write so that
// callers on the IsAssemblyInitializeExecuted fast path
// (which bypasses _assemblyInfoExecuteSyncSemaphore) safely
// observe the published snapshot.
PostAssemblyInitProperties = testContextImpl.CaptureLifecycleProperties();
}
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,18 @@ internal set
/// The snapshot is shallow: reference-type values stored in the bag are shared (aliased)
/// across every context the snapshot is merged into.
/// </para>
/// <para>
/// Reads and writes use <see cref="Volatile"/> so that callers on the cached-result fast
/// path of <see cref="GetResultOrRunClassInitializeAsync"/> (which intentionally bypasses
/// <see cref="_testClassExecuteSyncSemaphore"/>) safely observe the snapshot published by
/// the thread that ran <c>ClassInitialize</c>.
/// </para>
/// </summary>
internal IReadOnlyDictionary<string, object?>? PostClassInitProperties { get; private set; }
internal IReadOnlyDictionary<string, object?>? PostClassInitProperties
{
get => Volatile.Read(ref field);
private set => Volatile.Write(ref field, value);
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

/// <summary>
/// Gets or sets the class cleanup method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,14 @@ public void AddProperty(string propertyName, string propertyValue)
/// <see cref="TestContext.TestNameLabel"/>, which are preserved).
/// Used to flow properties set during <c>AssemblyInitialize</c> / <c>ClassInitialize</c>
/// into subsequent contexts.
/// <para>
/// Merge precedence: keys in <paramref name="propertiesToMerge"/> WIN over keys already
/// present in this context's bag. This is intentional — lifecycle snapshots typically
/// flow on top of the seeded source-level parameters (e.g. <c>TestRunParameters</c> from
/// <c>.runsettings</c>), so a user's explicit assignment in <c>AssemblyInitialize</c> /
/// <c>ClassInitialize</c> overrides any same-named runsettings value for the rest of
/// the lifecycle (class init, tests, class cleanup, assembly cleanup).
/// </para>
/// </summary>
/// <param name="propertiesToMerge">The properties to merge in. May be <see langword="null"/>.</param>
internal void MergeProperties(IReadOnlyDictionary<string, object?>? propertiesToMerge)
Expand Down Expand Up @@ -326,19 +334,34 @@ internal void MergeProperties(IReadOnlyDictionary<string, object?>? propertiesTo
/// shared across every context the snapshot is later merged into. Mutations of those
/// reference-type instances are visible everywhere.
/// </para>
/// <para>
/// Enumeration is performed under a lock on <c>_properties</c> so that snapshot capture
/// is safe against concurrent calls to this method or <see cref="MergeProperties"/> on
Comment thread
Evangelink marked this conversation as resolved.
Resolved
/// the same context. Note: writes made via the public <see cref="Properties"/> indexer
/// do NOT take this lock, so a lifecycle method that spawns a background thread which
/// keeps mutating <see cref="Properties"/> past method return can still race with the
/// capture - that is treated as user error and is consistent with the pre-existing
/// thread-affinity expectation of <c>AssemblyInitialize</c> / <c>ClassInitialize</c>.
/// </para>
/// </summary>
/// <returns>A read-only snapshot of the current properties.</returns>
internal IReadOnlyDictionary<string, object?> CaptureLifecycleProperties()
{
var snapshot = new Dictionary<string, object?>(_properties.Count);
foreach (KeyValuePair<string, object?> kvp in _properties)
Dictionary<string, object?> snapshot;
lock (_properties)
{
if (kvp.Key == FullyQualifiedTestClassNameLabel || kvp.Key == TestNameLabel)
#pragma warning disable IDE0028 // Collection initialization can be simplified - capacity hint is intentional.
snapshot = new Dictionary<string, object?>(_properties.Count);
#pragma warning restore IDE0028
foreach (KeyValuePair<string, object?> kvp in _properties)
{
continue;
}
if (kvp.Key == FullyQualifiedTestClassNameLabel || kvp.Key == TestNameLabel)
{
continue;
}

snapshot[kvp.Key] = kvp.Value;
snapshot[kvp.Key] = kvp.Value;
}
}

return new ReadOnlyDictionary<string, object?>(snapshot);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using Microsoft.Testing.Platform.Acceptance.IntegrationTests;
using Microsoft.Testing.Platform.Acceptance.IntegrationTests.Helpers;
using Microsoft.Testing.Platform.Helpers;

namespace MSTest.Acceptance.IntegrationTests;

Expand Down Expand Up @@ -201,3 +202,115 @@

public TestContext TestContext { get; set; } = null!;
}

/// <summary>
/// Acceptance test for the <c>ClassCleanupManager.ForceCleanup</c> fallback path that runs
/// when execution stops early (e.g. via <c>--maximum-failed-tests</c>). It validates that
/// <c>ClassCleanup</c> and <c>AssemblyCleanup</c> invoked via that fallback still observe
/// the lifecycle property snapshots captured during <c>AssemblyInitialize</c> and
/// <c>ClassInitialize</c>.
/// </summary>
[TestClass]
public sealed class TestContextPropertyFlowForceCleanupTests : AcceptanceTestBase<TestContextPropertyFlowForceCleanupTests.TestAssetFixture>
{
private const string ClassCleanupMarker = "FORCECLEANUP_CLASSCLEANUP_OK";
private const string AssemblyCleanupMarker = "FORCECLEANUP_ASSEMBLYCLEANUP_OK";

[TestMethod]
[DynamicData(nameof(TargetFrameworks.AllForDynamicData), typeof(TargetFrameworks))]
public async Task ForceCleanupSeesAssemblyAndClassInitProperties(string tfm)
{
var testHost = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, tfm);
TestHostResult testHostResult = await testHost.ExecuteAsync("--maximum-failed-tests 1", cancellationToken: TestContext.CancellationToken);

testHostResult.AssertExitCodeIs(ExitCode.TestExecutionStoppedForMaxFailedTests);
// ClassCleanup and AssemblyCleanup invoked via ForceCleanup must see both snapshots.
// The cleanup methods emit a sentinel marker only when their assertions pass; the
// markers' presence proves the snapshots flowed correctly into the fallback contexts.
Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput);

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx (Build Linux Debug)

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net10.0") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 05/20/2026) [linux-x64 - .NET 10.0.8]\nfailed TestA_Fails (32ms)\n Assertion failed.\n intentional fail to trigger graceful stop\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message) in /_/src/TestFramework/TestFramework/Assertions/Assert.Fail.cs:30\n at ForceCleanupFlowTests.TestA_Fails() in /mnt/vss/_work/1/s/artifacts/tmp/Debug/testsuite/5lPgA/TestContextPropertyFlowForceCleanup/UnitTest1.cs:21\n at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)\n at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\nTest run summary: Failed! - /mnt/vss/_work/1/s/artifacts/tmp/Debug/testsuite/5lPgA/TestContextPropertyFlowForceCleanup/bin/Release/net10.0/TestContextPropertyFlowForceCleanup.dll (net10.0|x64)\n total: 3\n failed: 1\n succeeded: 2\n skipped: 0\n duration: 325ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx (Build Windows Debug)

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net10.0") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 5/20/2026) [win-x64 - .NET 10.0.8]\r\nfailed TestA_Fails (45ms)\r\n Assertion failed.\r\n intentional fail to trigger graceful stop\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message) in /_/src/TestFramework/TestFramework/Assertions/Assert.Fail.cs:30\r\n at ForceCleanupFlowTests.TestA_Fails() in D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\UnitTest1.cs:21\r\n at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)\r\n at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)\r\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\r\nTest run summary: Failed! - D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\bin\\Release\\net10.0\\TestContextPropertyFlowForceCleanup.dll (net10.0|x64)\r\n total: 3\r\n failed: 1\r\n succeeded: 2\r\n skipped: 0\r\n duration: 490ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx (Build Windows Debug)

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net462") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 5/20/2026) [x64 - .NET Framework 4.8.9325.0]\r\nfailed TestA_Fails (25ms)\r\n Assertion failed.\r\n intentional fail to trigger graceful stop\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowAssertFailed(StructuredAssertionMessage structuredMessage)\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message)\r\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\r\nTest run summary: Failed! - D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\bin\\Release\\net462\\TestContextPropertyFlowForceCleanup.exe (net462|x64)\r\n total: 3\r\n failed: 1\r\n succeeded: 2\r\n skipped: 0\r\n duration: 638ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx (Build MacOS Debug)

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net10.0") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 5/20/2026) [osx-x64 - .NET 10.0.8]\nfailed TestA_Fails (48ms)\n Assertion failed.\n intentional fail to trigger graceful stop\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message) in /_/src/TestFramework/TestFramework/Assertions/Assert.Fail.cs:30\n at ForceCleanupFlowTests.TestA_Fails() in /Users/runner/work/1/s/artifacts/tmp/Debug/testsuite/J9EKT/TestContextPropertyFlowForceCleanup/UnitTest1.cs:21\n at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)\n at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\nTest run summary: Failed! - /Users/runner/work/1/s/artifacts/tmp/Debug/testsuite/J9EKT/TestContextPropertyFlowForceCleanup/bin/Release/net10.0/TestContextPropertyFlowForceCleanup.dll (net10.0|x64)\n total: 2\n failed: 1\n succeeded: 1\n skipped: 0\n duration: 1s 896ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net10.0") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 5/20/2026) [win-x64 - .NET 10.0.8]\r\nfailed TestA_Fails (45ms)\r\n Assertion failed.\r\n intentional fail to trigger graceful stop\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message) in /_/src/TestFramework/TestFramework/Assertions/Assert.Fail.cs:30\r\n at ForceCleanupFlowTests.TestA_Fails() in D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\UnitTest1.cs:21\r\n at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)\r\n at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)\r\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\r\nTest run summary: Failed! - D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\bin\\Release\\net10.0\\TestContextPropertyFlowForceCleanup.dll (net10.0|x64)\r\n total: 3\r\n failed: 1\r\n succeeded: 2\r\n skipped: 0\r\n duration: 490ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net462") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 5/20/2026) [x64 - .NET Framework 4.8.9325.0]\r\nfailed TestA_Fails (25ms)\r\n Assertion failed.\r\n intentional fail to trigger graceful stop\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.ThrowAssertFailed(StructuredAssertionMessage structuredMessage)\r\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message)\r\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\r\nTest run summary: Failed! - D:\\a\\_work\\1\\s\\artifacts\\tmp\\Debug\\testsuite\\SFHoL\\TestContextPropertyFlowForceCleanup\\bin\\Release\\net462\\TestContextPropertyFlowForceCleanup.exe (net462|x64)\r\n total: 3\r\n failed: 1\r\n succeeded: 2\r\n skipped: 0\r\n duration: 638ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)

Check failure on line 230 in test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs

View check run for this annotation

Azure Pipelines / microsoft.testfx

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs#L230

test/IntegrationTests/MSTest.Acceptance.IntegrationTests/TestContextPropertyFlowTests.cs(230,1): error : ForceCleanupSeesAssemblyAndClassInitProperties ("net10.0") [net11.0] Assertion failed. Expected string to contain the specified substring. expected substring: "FORCECLEANUP_CLASSCLEANUP_OK" actual: "MSTest v4.3.0-ci (UTC 05/20/2026) [linux-x64 - .NET 10.0.8]\nfailed TestA_Fails (32ms)\n Assertion failed.\n intentional fail to trigger graceful stop\n at Microsoft.VisualStudio.TestTools.UnitTesting.Assert.Fail(String message) in /_/src/TestFramework/TestFramework/Assertions/Assert.Fail.cs:30\n at ForceCleanupFlowTests.TestA_Fails() in /mnt/vss/_work/1/s/artifacts/tmp/Debug/testsuite/5lPgA/TestContextPropertyFlowForceCleanup/UnitTest1.cs:21\n at System.Reflection.MethodBaseInvoker.InterpretedInvoke_Method(Object obj, IntPtr* args)\n at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)\nTest session is aborting due to reaching failures ('1') specified by the '--maximum-failed-tests' option.\nTest run summary: Failed! - /mnt/vss/_work/1/s/artifacts/tmp/Debug/testsuite/5lPgA/TestContextPropertyFlowForceCleanup/bin/Release/net10.0/TestContextPropertyFlowForceCleanup.dll (net10.0|x64)\n total: 3\n failed: 1\n succeeded: 2\n skipped: 0\n duration: 325ms" comparison: Ordinal Assert.Contains(ClassCleanupMarker, testHostResult.StandardOutput)
Assert.Contains(AssemblyCleanupMarker, testHostResult.StandardOutput);
}

public sealed class TestAssetFixture() : TestAssetFixtureBase()
{
public const string ProjectName = "TestContextPropertyFlowForceCleanup";

public string ProjectPath => GetAssetPath(ProjectName);

public override (string ID, string Name, string Code) GetAssetsToGenerate() => (ProjectName, ProjectName,
SourceCode
.PatchTargetFrameworks(TargetFrameworks.All)
.PatchCodeWithReplace("$MSTestVersion$", MSTestVersion));

private const string SourceCode = """
#file TestContextPropertyFlowForceCleanup.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<EnableMSTestRunner>true</EnableMSTestRunner>
<TargetFrameworks>$TargetFrameworks$</TargetFrameworks>
<LangVersion>preview</LangVersion>
<EnableMicrosoftTestingPlatform>true</EnableMicrosoftTestingPlatform>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MSTest" Version="$MSTestVersion$" />
</ItemGroup>

</Project>

#file UnitTest1.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public sealed class ForceCleanupFlowTests
{
public TestContext TestContext { get; set; } = null!;

[AssemblyInitialize]
public static void AssemblyInit(TestContext context)
=> context.Properties["AssemblyInitKey"] = "AssemblyInitValue";

[ClassInitialize]
public static void ClassInit(TestContext context)
=> context.Properties["ClassInitKey"] = "ClassInitValue";

// Failing test triggers --maximum-failed-tests=1 graceful stop, leaving the
// remaining tests un-run; the normal end-of-class / end-of-assembly cleanup is
// skipped, so cleanup must come through the ForceCleanup fallback path.
[TestMethod]
public void TestA_Fails() => Assert.Fail("intentional fail to trigger graceful stop");

[TestMethod]
public void TestB_Passes() { }

[TestMethod]
public void TestC_Passes() { }

[ClassCleanup]
public static void ClassCleanup(TestContext context)
{
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
Assert.AreEqual("ClassInitValue", context.Properties["ClassInitKey"]);
Console.WriteLine("FORCECLEANUP_CLASSCLEANUP_OK");
}

[AssemblyCleanup]
public static void AssemblyCleanup(TestContext context)
{
// AssemblyCleanup must see AssemblyInit-set values. ClassInit-set values are
// class-scoped and must NOT flow to AssemblyCleanup even via the fallback path.
Assert.AreEqual("AssemblyInitValue", context.Properties["AssemblyInitKey"]);
Assert.IsFalse(
context.Properties.ContainsKey("ClassInitKey"),
"Properties set by ClassInitialize must not flow to AssemblyCleanup, even via ForceCleanup.");
Console.WriteLine("FORCECLEANUP_ASSEMBLYCLEANUP_OK");
}
}
""";
}

public TestContext TestContext { get; set; } = null!;
}
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,26 @@ public void MergePropertiesShouldOverwriteExistingKeys()
_testContextImplementation.Properties["Key"].Should().Be("Overwritten");
}

public void MergePropertiesShouldOverrideSeededSourceLevelParameters()
{
// Seeded source-level parameters (the bag the runner forwards from runsettings
// TestRunParameters) sit in _properties at construction time; lifecycle snapshots
// from AssemblyInitialize / ClassInitialize MUST override them on key collision so
// a user's explicit assignment wins for the rest of the lifecycle.
var seeded = new Dictionary<string, object?>
{
["RunSettingsKey"] = "FromRunSettings",
};
_testContextImplementation = new TestContextImplementation(_testMethod.Object, null, seeded, null, null);

_testContextImplementation.MergeProperties(new Dictionary<string, object?>
{
["RunSettingsKey"] = "FromAssemblyInit",
});

_testContextImplementation.Properties["RunSettingsKey"].Should().Be("FromAssemblyInit");
}

public void MergePropertiesShouldIgnoreNull()
{
_testContextImplementation = CreateTestContextImplementation();
Expand Down
Loading