From 0a9a932a7af6780b749d4d040ea8f38336ef339b Mon Sep 17 00:00:00 2001 From: Copilot Date: Mon, 9 Nov 2026 16:02:14 +0100 Subject: [PATCH] Backport cleanup cancellation review corrections to rel/4.5 Apply the servicing follow-up from #12225 (upstream b3f3c980c480c5d97976d658ac367b1e246502be) on top of the original #12220 release isolation fix. Preserve release file layout and targets, cleanup ownership/deadlines, independent failures and Framework aggregate messages. Retained tests execute against actual prior production: 12 of 136 lifecycle cases and 4 of 13 packed consumers fail for the intended missing corrections. Corrected code passes 732 focused unit executions, all 13 packaged consumers, and both 10-case source-generation opt-out plans. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../Execution/TestMethodInfo.Execution.cs | 260 ++++++---- .../Execution/TestMethodInfo.Lifecycle.cs | 96 ++-- .../Attributes/TestMethod/TestResult.cs | 23 + .../CleanupCancellationIsolationTests.cs | 204 +++++++- .../Execution/TestMethodInfoTests.cs | 453 ++++++++++++++++-- .../TestResultTests.cs | 15 + 6 files changed, 881 insertions(+), 170 deletions(-) diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs index 7f4075b96e..822032cf7c 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs @@ -381,139 +381,231 @@ async SynchronizationContextPreservingTask ExecuteWithTimeoutTokenAs TestResult? result = null; Exception? failure = null; var invocationState = new TestInvocationState(); + var executionCompletion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); CancellationTokenSource cancellationTokenSource = TestContext.Context.CancellationTokenSource; + CancellationToken? runCancellationToken = PlatformServiceProvider.Instance.TestRunCancellationToken?.CancellationToken; + CancellationTokenSource timeoutTokenSource = new(); + int timeoutSourceOwners = 2; + int executionState = 0; + using CancellationTokenSource monitorCancellationTokenSource = new(); + using CancellationTokenRegistration testCancellationRegistration = cancellationTokenSource.Token.Register(() => + { + // Fixture cancellation must not end the whole-test wait while cleanup is still running. + if (!invocationState.IsCleanupStarted) + { + monitorCancellationTokenSource.Cancel(); + } + }); + using CancellationTokenRegistration? runCancellationRegistration = + runCancellationToken?.Register(monitorCancellationTokenSource.Cancel); + using CancellationTokenRegistration timeoutRegistration = + timeoutTokenSource.Token.Register(() => TestContext.Context.CancellationTokenSource.Cancel()); TaskScheduler? synchronizationContextScheduler = SynchronizationContext.Current is null ? null : TaskScheduler.FromCurrentSynchronizationContext(); bool executionCompleted; + var executionTimer = Stopwatch.StartNew(); - if (synchronizationContextScheduler is null) - { - executionCompleted = PlatformServiceProvider.Instance.ThreadOperations.Execute( - ExecuteAsyncAction, TimeoutInfo.Timeout, cancellationTokenSource.Token); - } - else + try { - // Queue the invocation on its original dispatcher without blocking the message pump. - // A new STA thread cannot access controls owned by this UI thread. - Task executionTask = Task.Factory.StartNew( - ExecuteOnSynchronizationContextAsync, - cancellationTokenSource.Token, - TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, - synchronizationContextScheduler).Unwrap(); - using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationTokenSource.Token); - var timeoutTask = Task.Delay(TimeoutInfo.Timeout, timeoutCancellation.Token); - Task completedTask = await Task.WhenAny(executionTask, timeoutTask).ConfigureAwait(false); - executionCompleted = completedTask == executionTask && !executionTask.IsCanceled; + if (synchronizationContextScheduler is null) + { + executionCompleted = PlatformServiceProvider.Instance.ThreadOperations.Execute( + ExecuteAsyncAction, TimeoutInfo.Timeout, monitorCancellationTokenSource.Token); + } + else + { + // Queue the invocation on its original dispatcher without blocking the message pump. + // A new STA thread cannot access controls owned by this UI thread. + Task executionTask = Task.Factory.StartNew( + ExecuteOnSynchronizationContextAsync, + monitorCancellationTokenSource.Token, + TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, + synchronizationContextScheduler).Unwrap(); + using var timeoutCancellation = CancellationTokenSource.CreateLinkedTokenSource(monitorCancellationTokenSource.Token); + var timeoutTask = Task.Delay(TimeoutInfo.Timeout, timeoutCancellation.Token); + Task completedTask = await Task.WhenAny(executionTask, timeoutTask).ConfigureAwait(false); + executionCompleted = completedTask == executionTask && !executionTask.IsCanceled; #pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks. - timeoutCancellation.Cancel(); + timeoutCancellation.Cancel(); #pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks. - } + } - if (executionCompleted) - { - if (failure != null) + if (executionCompleted) { - throw failure; - } + if (failure is not null) + { + throw failure; + } - DebugEx.Assert(result is not null, "result is not null"); - return result; - } + DebugEx.Assert(result is not null, "result is not null"); + if (result.Outcome == UnitTestOutcome.Passed + && (cancellationTokenSource.IsCancellationRequested || TestContext.Context.CancellationTokenSource.IsCancellationRequested)) + { + result.Outcome = UnitTestOutcome.Timeout; + result.TestFailureException = new TestFailedException( + UnitTestOutcome.Timeout, + string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName)); + } - // Timed out or canceled - string errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Timeout, TestMethodName, TimeoutInfo.Timeout); - if (cancellationTokenSource.IsCancellationRequested) - { - errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName); - } - else - { - // Cancel the token source as test has timed out + return result; + } + + int remainingTimeout = (int)Math.Max(0, TimeoutInfo.Timeout - executionTimer.ElapsedMilliseconds); + bool isTimeout = !monitorCancellationTokenSource.IsCancellationRequested || remainingTimeout == 0; + string errorMessage = isTimeout + ? string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Timeout, TestMethodName, TimeoutInfo.Timeout) + : string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, TestMethodName); #pragma warning disable VSTHRD103 // Call async methods when in an async method - likely fine in this context. CancelAsync is .NET Core only. We prefer having the same behavior between .NET Core and .NET Framework. - cancellationTokenSource.Cancel(); + if (isTimeout) + { + timeoutTokenSource.Cancel(); + } + else + { + if (runCancellationToken?.IsCancellationRequested == true) + { + TestContext.Context.CancellationTokenSource.Cancel(); + } + + // A body cancellation may already have been consumed by fresh cleanup; only the original deadline may cancel it again. + timeoutTokenSource.CancelAfter(remainingTimeout); + } #pragma warning restore VSTHRD103 // Call async methods when in an async method - } - TestResult timeoutResult = new() { Outcome = UnitTestOutcome.Timeout, TestFailureException = new TestFailedException(UnitTestOutcome.Timeout, errorMessage) }; + TestResult timeoutResult = new() { Outcome = UnitTestOutcome.Timeout, TestFailureException = new TestFailedException(UnitTestOutcome.Timeout, errorMessage) }; + CancellationTokenSource? cleanupTimeoutSource = isTimeout ? null : timeoutTokenSource; + bool cleanupCompleted = false; - // Execution context propagation here may still not be accurate. - // if test init was successfully executed by ExecuteAsyncAction, but then the test itself timed out or cancelled, - // then at this point we will run the cleanup on an execution context that doesn't have any state set by the test initialize. - if (synchronizationContextScheduler is null) - { - await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false); - } - else if (!invocationState.IsCleanupStarted - && invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot)) - { - if (!HasCleanupsToInvoke(snapshot.ClassInstanceLease)) + // Execution context propagation here may still not be accurate. + // if test init was successfully executed by ExecuteAsyncAction, but then the test itself timed out or cancelled, + // then at this point we will run the cleanup on an execution context that doesn't have any state set by the test initialize. + if (synchronizationContextScheduler is null) { - // Cancellation bookkeeping does not need a dispatcher blocked by synchronous user code. - await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false); + cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false); } - else + else if (!invocationState.IsCleanupStarted + && invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot)) { - const int CleanupDispatchTimeoutMilliseconds = 1_000; - int cleanupDispatchClaimed = 0; - Task cleanupTask = Task.Factory.StartNew( - async () => - { - // Either the dispatcher starts cleanup, or the monitor leaves it to the original invocation. - if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) == 0) - { - await RunTestCleanupMethodAsync(timeoutResult, null, invocationState).ConfigureAwait(false); - } - }, - CancellationToken.None, - TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, - synchronizationContextScheduler).Unwrap(); - using var dispatchTimeoutCancellation = new CancellationTokenSource(); - await Task.WhenAny( - cleanupTask, - Task.Delay(CleanupDispatchTimeoutMilliseconds, dispatchTimeoutCancellation.Token)).ConfigureAwait(false); -#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks. - dispatchTimeoutCancellation.Cancel(); -#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks. - if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) != 0) + if (!HasCleanupsToInvoke(snapshot.ClassInstanceLease)) { - await cleanupTask.ConfigureAwait(false); + // Cancellation bookkeeping does not need a dispatcher blocked by synchronous user code. + cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false); } - else if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsVerboseEnabled) + else { - PlatformServiceProvider.Instance.AdapterTraceLogger.Verbose( - "MSTest.TestMethodInfo: Cleanup for timed out test '{0}' is deferred because its synchronization context did not become available within {1}ms.", - TestMethodName, - CleanupDispatchTimeoutMilliseconds); + const int CleanupDispatchTimeoutMilliseconds = 1_000; + int cleanupDispatchClaimed = 0; + Task cleanupTask = Task.Factory.StartNew( + async () => + { + // Either the dispatcher starts cleanup, or the monitor leaves it to the original invocation. + if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) == 0) + { + cleanupCompleted = await RunTestCleanupMethodAsync(timeoutResult, cleanupTimeoutSource, invocationState).ConfigureAwait(false); + } + }, + CancellationToken.None, + TaskCreationOptions.DenyChildAttach | TaskCreationOptions.HideScheduler, + synchronizationContextScheduler).Unwrap(); + using var dispatchTimeoutCancellation = new CancellationTokenSource(); + await Task.WhenAny( + cleanupTask, + Task.Delay(CleanupDispatchTimeoutMilliseconds, dispatchTimeoutCancellation.Token)).ConfigureAwait(false); +#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks. + dispatchTimeoutCancellation.Cancel(); +#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks. + if (Interlocked.CompareExchange(ref cleanupDispatchClaimed, 1, 0) != 0) + { + await cleanupTask.ConfigureAwait(false); + } + else if (PlatformServiceProvider.Instance.AdapterTraceLogger.IsVerboseEnabled) + { + PlatformServiceProvider.Instance.AdapterTraceLogger.Verbose( + "MSTest.TestMethodInfo: Cleanup for timed out test '{0}' is deferred because its synchronization context did not become available within {1}ms.", + TestMethodName, + CleanupDispatchTimeoutMilliseconds); + } } } + + if (!cleanupCompleted && invocationState.IsCleanupStarted && !timeoutTokenSource.IsCancellationRequested) + { + using var cleanupWaitCancellation = CancellationTokenSource.CreateLinkedTokenSource( + timeoutTokenSource.Token, + runCancellationToken ?? CancellationToken.None); + await Task.WhenAny( + executionCompletion.Task, + Task.Delay(Timeout.Infinite, cleanupWaitCancellation.Token)).ConfigureAwait(false); +#pragma warning disable VSTHRD103 // CancelAsync is not available on all supported target frameworks. + cleanupWaitCancellation.Cancel(); +#pragma warning restore VSTHRD103 // CancelAsync is not available on all supported target frameworks. + } + + return timeoutResult; } + finally + { + if (Interlocked.CompareExchange(ref executionState, 2, 0) == 0) + { + ReleaseTimeoutSource(); + } - return timeoutResult; + ReleaseTimeoutSource(); + } // Local functions async Task ExecuteOnSynchronizationContextAsync() { + if (Interlocked.CompareExchange(ref executionState, 1, 0) != 0) + { + return; + } + try { - result = await ExecuteInternalAsync(arguments, null, invocationState).ConfigureAwait(false); + result = await ExecuteInternalAsync(arguments, timeoutTokenSource, invocationState).ConfigureAwait(false); } catch (Exception ex) { failure = ex; } + finally + { + ReleaseTimeoutSource(); + executionCompletion.TrySetResult(true); + } } void ExecuteAsyncAction() { + if (Interlocked.CompareExchange(ref executionState, 1, 0) != 0) + { + return; + } + try { - result = ExecuteInternalAsync(arguments, null, invocationState).GetAwaiter().GetResult(); + result = ExecuteInternalAsync(arguments, timeoutTokenSource, invocationState).GetAwaiter().GetResult(); } catch (Exception ex) { failure = ex; } + finally + { + ReleaseTimeoutSource(); + executionCompletion.TrySetResult(true); + } + } + + void ReleaseTimeoutSource() + { + // A timed-out worker may still be unwinding after the monitor returns. + if (Interlocked.Decrement(ref timeoutSourceOwners) == 0) + { + timeoutTokenSource.Dispose(); + } } } diff --git a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Lifecycle.cs b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Lifecycle.cs index 8a03af77d3..d7207a55ea 100644 --- a/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Lifecycle.cs +++ b/src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Lifecycle.cs @@ -23,8 +23,9 @@ internal partial class TestMethodInfo /// Instance of TestResult. /// The timeout token source. /// The activation and cleanup state for this invocation. + /// Whether this caller claimed and completed cleanup. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")] - private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( + private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( TestResult result, CancellationTokenSource? timeoutTokenSource, TestInvocationState invocationState) @@ -33,7 +34,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( if (!invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot)) { - return; + return false; } bool hasCleanupsToInvoke = HasCleanupsToInvoke(snapshot.ClassInstanceLease); @@ -42,7 +43,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( if ((!hasCleanupsToInvoke && !shouldResetCancellationTokenSource) || !invocationState.TryBeginCleanup()) { - return; + return false; } CancellationToken? cleanupRunCancellationToken = PlatformServiceProvider.Instance.TestRunCancellationToken?.CancellationToken; @@ -58,7 +59,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( if (!hasCleanupsToInvoke) { - return; + return true; } if (!snapshot.IsTestContextSet) @@ -76,7 +77,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( result.TestFailureException = exception; } - return; + return true; } MethodInfo? testCleanupMethod = Parent.TestCleanupMethod; @@ -84,21 +85,19 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( Exception? globalTestCleanupException = null; MethodInfo? globalTestCleanupFailingMethod = null; MethodInfo? currentGlobalTestCleanupMethod = null; - CancellationToken? cleanupTimeoutToken = null; + // Retain only deadlines still active when cleanup starts; an already-expired test gets fresh teardown. + CancellationToken? cleanupTimeoutToken = timeoutTokenSource is { IsCancellationRequested: false } + ? timeoutTokenSource.Token + : null; using CancellationTokenRegistration? cleanupRunRegistration = shouldResetCancellationTokenSource ? cleanupRunCancellationToken?.Register(TestContext.Context.CancellationTokenSource.Cancel) : null; + using CancellationTokenRegistration? cleanupTimeoutRegistration = + cleanupTimeoutToken?.Register(TestContext.Context.CancellationTokenSource.Cancel); try { try { - // If we are running with a method timeout, we need to cancel the cleanup when the overall timeout expires. If it already expired, nothing to do. - if (timeoutTokenSource is { IsCancellationRequested: false }) - { - cleanupTimeoutToken = timeoutTokenSource.Token; - timeoutTokenSource.Token.Register(TestContext.Context.CancellationTokenSource.Cancel); - } - // Test cleanups are called in the order of discovery // Current TestClass -> Parent -> Grandparent testCleanupException = testCleanupMethod is not null @@ -147,6 +146,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( } // A local fixture timeout must not cancel independent global teardown or restart an active test/run deadline. + // Keep the context-owned source usable after cleanup; only its deadline/run registrations are scoped. TestContext.Context.CancellationTokenSource = globalCleanupSource = new CancellationTokenSource(); } @@ -202,36 +202,52 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync( } // If testCleanup was successful, then don't do anything - if (testCleanupException == null) + if (testCleanupException is null) + { + return true; + } + + TestFailedException cleanupFailure = CreateCleanupFailureException(testCleanupException, testCleanupMethod); + result.Outcome = result.Outcome.GetMoreImportantOutcome(cleanupFailure.Outcome); + result.TestFailureException = cleanupFailure; + if (globalTestCleanupException is not null && testCleanupException != globalTestCleanupException) { - return; + TestFailedException globalFailure = CreateCleanupFailureException(globalTestCleanupException, globalTestCleanupFailingMethod); + // Preserve the local timeout classification, but do not hide an independent global cleanup failure. + if (cleanupFailure.Outcome != UnitTestOutcome.Timeout) + { + result.Outcome = result.Outcome.GetMoreImportantOutcome(globalFailure.Outcome); + } + + result.TestFailureException = globalFailure; } - Exception realException = testCleanupException.GetRealException(); - - // Check `realException` (not `testCleanupException`) so that a `TestFailedException` wrapped in - // a `TargetInvocationException` / `TypeInitializationException` still preserves its Outcome - // (for example a Timeout outcome must not be silently downgraded to Failed). - UnitTestOutcome outcomeFromRealException = realException is TestFailedException testFailedException - ? testFailedException.Outcome - : realException is AssertInconclusiveException - ? UnitTestOutcome.Inconclusive - : UnitTestOutcome.Failed; - result.Outcome = result.Outcome.GetMoreImportantOutcome(outcomeFromRealException); - - realException = testCleanupMethod != null - ? new TestFailedException( - outcomeFromRealException, - string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrows, TestClassName, testCleanupMethod.Name, realException.GetFormattedExceptionMessage()), - realException.TryGetStackTraceInformation(), - realException) - : new TestFailedException( - outcomeFromRealException, - string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrowsGeneralError, TestClassName, realException.GetFormattedExceptionMessage()), - realException.TryGetStackTraceInformation(), - realException); - - result.TestFailureException = realException; + return true; + + TestFailedException CreateCleanupFailureException(Exception exception, MethodInfo? method) + { + Exception realException = exception.GetRealException(); + UnitTestOutcome outcome = realException is TestFailedException testFailedException + ? testFailedException.Outcome + : realException is AssertInconclusiveException + ? UnitTestOutcome.Inconclusive + : UnitTestOutcome.Failed; + string cleanupClassName = method is not null && method == globalTestCleanupFailingMethod + ? method.DeclaringType!.FullName! + : TestClassName; + + return method is not null + ? new TestFailedException( + outcome, + string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrows, cleanupClassName, method.Name, realException.GetFormattedExceptionMessage()), + realException.TryGetStackTraceInformation(), + realException) + : new TestFailedException( + outcome, + string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrowsGeneralError, TestClassName, realException.GetFormattedExceptionMessage()), + realException.TryGetStackTraceInformation(), + realException); + } } private bool HasCleanupsToInvoke(ITestClassInstanceLease? classInstanceLease) => diff --git a/src/TestFramework/TestFramework/Attributes/TestMethod/TestResult.cs b/src/TestFramework/TestFramework/Attributes/TestMethod/TestResult.cs index 3d337e889d..e987281b89 100644 --- a/src/TestFramework/TestFramework/Attributes/TestMethod/TestResult.cs +++ b/src/TestFramework/TestFramework/Attributes/TestMethod/TestResult.cs @@ -95,7 +95,11 @@ public Exception? TestFailureException ? new AggregateException(aggregateException.InnerExceptions.Concat([value])) : new AggregateException(field, value); +#if NETFRAMEWORK + ExceptionMessage = GetExceptionMessage(field); +#else ExceptionMessage = field.Message; +#endif ExceptionStackTrace = field.StackTrace; // Capture the structured assertion values as strings, for the same reason ExceptionMessage and @@ -257,6 +261,25 @@ internal static TestResult CreateIgnoredResult(string? ignoreReason) IgnoreReason = ignoreReason, }; +#if NETFRAMEWORK + private static string GetExceptionMessage(Exception exception) + { + if (exception is not AggregateException aggregate) + { + return exception.Message; + } + + // Unlike modern .NET, .NET Framework omits inner messages from AggregateException.Message. + var message = new StringBuilder(aggregate.Message); + foreach (Exception innerException in aggregate.InnerExceptions) + { + message.Append(" (").Append(GetExceptionMessage(innerException)).Append(')'); + } + + return message.ToString(); + } +#endif + /// /// Counts the assertion failures that carry comparison values (capped at 2) and reports the values of the /// first one. diff --git a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CleanupCancellationIsolationTests.cs b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CleanupCancellationIsolationTests.cs index 605d819b2b..5a305bf7e1 100644 --- a/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CleanupCancellationIsolationTests.cs +++ b/test/IntegrationTests/MSTest.Acceptance.IntegrationTests/CleanupCancellationIsolationTests.cs @@ -1,6 +1,8 @@ // 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.IO.Compression; +using System.Security.Cryptography; using System.Xml.Linq; using Microsoft.Testing.Platform.Acceptance.IntegrationTests; @@ -14,29 +16,65 @@ public sealed class CleanupCancellationIsolationTests : AcceptanceTestBase TargetFrameworks.Net[^1]; + public static IEnumerable> CleanupCases + { + get + { + yield return new(("normal", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_Normal" }; + yield return new(("error", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_UnrelatedLocalFailure" }; + yield return new(("cancel-return", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_LocalCancellationWithoutException" }; + yield return new(("cancel-throw", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_LocalCancellationException" }; + yield return new(("cancel-unrelated", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_CancellationWithUnrelatedLocalFailure" }; + yield return new(("timeout", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_LocalCooperativeTimeout" }; + yield return new(("timeout-global-throw", MetadataMode.Reflection, false)) { DisplayName = "GlobalCleanup_PreservesLocalTimeoutWhenGlobalCleanupThrows" }; + yield return new(("timeout", MetadataMode.Reflection, true)) { DisplayName = "GlobalCleanup_LocalCooperativeTimeout_NonCooperativeTest" }; + yield return new(("global-cancel-return", MetadataMode.Reflection, true)) { DisplayName = "GlobalCleanup_TerminalCancellation_NonCooperativeTest" }; + if (!AcceptanceSourceGen.IsGloballyDisabled) + { + yield return new(("timeout", MetadataMode.SourceGeneration, false)) { DisplayName = "GlobalCleanup_LocalCooperativeTimeout_SourceGeneration" }; + yield return new(("timeout", MetadataMode.SourceGeneration, true)) { DisplayName = "GlobalCleanup_LocalCooperativeTimeout_NonCooperativeTest_SourceGeneration" }; + yield return new(("global-cancel-return", MetadataMode.SourceGeneration, true)) { DisplayName = "GlobalCleanup_TerminalCancellation_NonCooperativeTest_SourceGeneration" }; + } + } + } + [TestMethod] - [DataRow("normal", MetadataMode.Reflection, DisplayName = "GlobalCleanup_Normal")] - [DataRow("error", MetadataMode.Reflection, DisplayName = "GlobalCleanup_UnrelatedLocalFailure")] - [DataRow("cancel-return", MetadataMode.Reflection, DisplayName = "GlobalCleanup_LocalCancellationWithoutException")] - [DataRow("cancel-throw", MetadataMode.Reflection, DisplayName = "GlobalCleanup_LocalCancellationException")] - [DataRow("cancel-unrelated", MetadataMode.Reflection, DisplayName = "GlobalCleanup_CancellationWithUnrelatedLocalFailure")] - [DataRow("timeout", MetadataMode.Reflection, DisplayName = "GlobalCleanup_LocalCooperativeTimeout")] - [DataRow("timeout-global-throw", MetadataMode.Reflection, DisplayName = "GlobalCleanup_PreservesLocalTimeoutWhenGlobalCleanupThrows")] - [DataRow("timeout", MetadataMode.SourceGeneration, DisplayName = "GlobalCleanup_LocalCooperativeTimeout_SourceGeneration")] - public async Task GlobalCleanupAfterLocalCancellationReleasesOwnedResource(string scenario, MetadataMode metadataMode) + [DynamicData(nameof(CleanupCases))] + public async Task GlobalCleanupAfterLocalCancellationReleasesOwnedResource(string scenario, MetadataMode metadataMode, bool nonCooperativeTimeout) { using TempDirectory results = new(); string evidenceDirectory = Path.Combine(results.Path, "evidence"); + using ZipArchive package = ZipFile.OpenRead(Path.Combine(Constants.ArtifactsPackagesShipping, $"MSTest.TestAdapter.{MSTestVersion}.nupkg")); + ZipArchiveEntry? adapterPayload = package.GetEntry($"buildTransitive/{ConsumerTargetFramework}/MSTestAdapter.PlatformServices.dll"); + Assert.IsNotNull(adapterPayload); + using Stream adapterStream = adapterPayload.Open(); + string expectedAdapterHash = Convert.ToHexString(SHA256.HashData(adapterStream)); + string filter = nonCooperativeTimeout + ? "Name=NoBaseTestNonCooperative|Name=WithBaseTestNonCooperative" + : "Name=NoBaseTest|Name=WithBaseTest"; var host = TestHost.LocateFrom(AssetFixture.ProjectPath, TestAssetFixture.ProjectName, ConsumerTargetFramework, metadataMode: metadataMode); TestHostResult result = await host.ExecuteAsync( - $"--report-trx --report-trx-filename cleanup.trx --results-directory \"{results.Path}\"", + $"--filter \"{filter}\" --report-trx --report-trx-filename cleanup.trx --results-directory \"{results.Path}\"", environmentVariables: new() { ["LOCAL_CLEANUP_SCENARIO"] = scenario, ["CLEANUP_EVIDENCE_DIRECTORY"] = evidenceDirectory, + ["NONCOOPERATIVE_TEST_TIMEOUT"] = nonCooperativeTimeout.ToString(), + ["DOTNET_CLI_UI_LANGUAGE"] = "en-US", }, cancellationToken: TestContext.CancellationToken); + string[] expectedClasses = ["NoBaseCleanup", "WithBaseCleanup"]; + foreach (string className in expectedClasses) + { + string[] provenance = File.ReadAllLines(Path.Combine(evidenceDirectory, className, "product-provenance.txt")); + Assert.HasCount(3, provenance); + Assert.AreEqual("MSTestAdapter.PlatformServices.dll", Path.GetFileName(provenance[0])); + Assert.Contains(MSTestVersion, provenance[1]); + Assert.AreEqual(expectedAdapterHash, provenance[2], $"Loaded adapter does not match the current package for {className}."); + TestContext.WriteLine($"Loaded adapter for {className}: {string.Join(" | ", provenance)}"); + } + bool passed = scenario == "normal"; result.AssertExitCodeIs(passed ? 0 : 2); result.AssertOutputContainsSummary(failed: passed ? 0 : 2, passed: passed ? 2 : 0, skipped: 0); @@ -46,8 +84,11 @@ public async Task GlobalCleanupAfterLocalCancellationReleasesOwnedResource(strin XElement[] testResults = report.Descendants(ns + "UnitTestResult") .Where(testResult => !testResult.Descendants(ns + "UnitTestResult").Any()) .ToArray(); + string[] expectedNames = nonCooperativeTimeout + ? ["NoBaseTestNonCooperative", "WithBaseTestNonCooperative"] + : ["NoBaseTest", "WithBaseTest"]; Assert.AreSequenceEqual( - ["NoBaseTest", "WithBaseTest"], + expectedNames, testResults.Select(testResult => (string?)testResult.Attribute("testName")).OrderBy(name => name, StringComparer.Ordinal).ToArray()); Assert.AreEqual(2, testResults.Select(testResult => (string?)testResult.Attribute("executionId")).Distinct().Count()); var classes = report.Descendants(ns + "UnitTest") @@ -59,13 +100,13 @@ public async Task GlobalCleanupAfterLocalCancellationReleasesOwnedResource(strin foreach (XElement testResult in testResults) { string testName = (string)testResult.Attribute("testName")!; - string className = testName == "NoBaseTest" ? "NoBaseCleanup" : "WithBaseCleanup"; + string className = testName == expectedNames[0] ? expectedClasses[0] : expectedClasses[1]; Assert.AreEqual(className, classes[(string)testResult.Attribute("testId")!]); Assert.AreEqual(passed ? "Passed" : "Failed", (string?)testResult.Attribute("outcome"), testName); string directory = Path.Combine(evidenceDirectory, className); Assert.IsFalse(File.Exists(Path.Combine(directory, "owned-resource.txt")), $"Global cleanup did not release {className}'s resource in {scenario}."); - string expectedTrace = passed && className == "WithBaseCleanup" + string expectedTrace = scenario is ("normal" or "global-cancel-return") && className == "WithBaseCleanup" ? """ global-initialize test-body @@ -93,16 +134,122 @@ public async Task GlobalCleanupAfterLocalCancellationReleasesOwnedResource(strin string error = testResult.Descendants(ns + "Message").Single().Value; Assert.Contains($"{className}.Cleanup", error); Assert.Contains("timed out after 1000ms", error); + if (scenario == "timeout-global-throw") + { + Assert.Contains("global cleanup also failed", error); + Assert.Contains("GlobalFixtures.Cleanup", error); + } } else if (scenario is "error" or "cancel-unrelated") { Assert.Contains("local cleanup failed", testResult.Descendants(ns + "Message").Single().Value); } + else if (scenario == "global-cancel-return") + { + Assert.AreEqual($"Test '{testName}' was canceled", testResult.Descendants(ns + "Message").Single().Value); + } } } public TestContext TestContext { get; set; } = null!; + [TestMethod] + [OSCondition(ConditionMode.Include, OperatingSystems.Windows, IgnoreMessage = "Requires .NET Framework.")] + public async Task NetFrameworkCleanupFailureMessagesRetainBothMethodIdentities() + { + using TempDirectory directory = new(); + using TestAsset asset = await TestAsset.GenerateAssetAsync( + "NetFrameworkCleanupFailureMessages", + NetFrameworkSourceCode + .PatchCodeWithReplace("$MSTestVersion$", MSTestVersion) + .PatchCodeWithReplace("$MicrosoftTestingPlatformVersion$", MicrosoftTestingPlatformVersion), + directory); + _ = await DotnetCli.RunAsync( + $"build \"{asset.TargetAssetPath}\" -c Release", + cancellationToken: TestContext.CancellationToken); + string provenancePath = Path.Combine(directory.Path, "framework-provenance.txt"); + var host = TestHost.LocateFrom(asset.TargetAssetPath, "NetFrameworkCleanupFailureMessages", "net462"); + TestHostResult result = await host.ExecuteAsync( + $"--report-trx --report-trx-filename cleanup-netfx.trx --results-directory \"{directory.Path}\"", + environmentVariables: new() + { + ["FRAMEWORK_PROVENANCE"] = provenancePath, + ["DOTNET_CLI_UI_LANGUAGE"] = "en-US", + }, + cancellationToken: TestContext.CancellationToken); + + string[] provenance = File.ReadAllLines(provenancePath); + Assert.HasCount(2, provenance); + using ZipArchive package = ZipFile.OpenRead(Path.Combine(Constants.ArtifactsPackagesShipping, $"MSTest.TestFramework.{MSTestVersion}.nupkg")); + ZipArchiveEntry? payload = package.GetEntry("lib/net462/MSTest.TestFramework.dll"); + Assert.IsNotNull(payload); + using Stream stream = payload.Open(); + Assert.AreEqual(Convert.ToHexString(SHA256.HashData(stream)), provenance[1]); + TestContext.WriteLine($"Loaded framework: {string.Join(" | ", provenance)}"); + result.AssertExitCodeIs(2); + result.AssertOutputContainsSummary(failed: 1, passed: 0, skipped: 0); + + XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010"; + var report = XDocument.Load(Path.Combine(directory.Path, "cleanup-netfx.trx")); + XElement testResult = Assert.ContainsSingle(report.Descendants(ns + "UnitTestResult")); + Assert.AreEqual("SampleTest", (string?)testResult.Attribute("testName")); + Assert.AreEqual("Failed", (string?)testResult.Attribute("outcome")); + string message = Assert.ContainsSingle(testResult.Descendants(ns + "Message")).Value; + Assert.Contains("FailingCleanupTests.LocalCleanup", message); + Assert.Contains("local cleanup failed", message); + Assert.Contains("GlobalCleanupFixtures.GlobalCleanup", message); + Assert.Contains("global cleanup failed", message); + } + + private const string NetFrameworkSourceCode = """ +#file NetFrameworkCleanupFailureMessages.csproj + + + Exe + true + net462 + preview + enable + enable + + + + + + + + +#file Tests.cs +using System.Security.Cryptography; +using Microsoft.VisualStudio.TestTools.UnitTesting; + +[TestClass] +public sealed class GlobalCleanupFixtures +{ + [GlobalTestCleanup] + public static void GlobalCleanup(TestContext context) => throw new InvalidOperationException("global cleanup failed"); +} + +[TestClass] +public sealed class FailingCleanupTests +{ + [TestMethod] + public void SampleTest() + { + string location = typeof(Assert).Assembly.Location; + using SHA256 algorithm = SHA256.Create(); + File.WriteAllLines(Environment.GetEnvironmentVariable("FRAMEWORK_PROVENANCE")!, + [ + location, + BitConverter.ToString(algorithm.ComputeHash(File.ReadAllBytes(location))).Replace("-", string.Empty), + ]); + } + + [TestCleanup] + public void LocalCleanup() => throw new InvalidOperationException("local cleanup failed"); +} +"""; + public sealed class TestAssetFixture : TestAssetFixtureBase { public const string ProjectName = "CleanupCancellationIsolation"; @@ -148,8 +295,15 @@ public static void Initialize(TestContext context) Directory.CreateDirectory(Probe.DirectoryFor(context)); File.WriteAllText(Probe.ResourceFor(context), "resource owned by global initialization"); Probe.Record(context, "global-initialize"); - Assembly adapter = AppDomain.CurrentDomain.GetAssemblies() - .Single(assembly => assembly.GetName().Name == "MSTestAdapter.PlatformServices"); + Assembly[] adapters = AppDomain.CurrentDomain.GetAssemblies() + .Where(assembly => assembly.GetName().Name == "MSTestAdapter.PlatformServices") + .ToArray(); + if (adapters.Length != 1) + { + throw new InvalidOperationException($"Expected one loaded MSTestAdapter.PlatformServices assembly, found {adapters.Length}."); + } + + Assembly adapter = adapters[0]; File.WriteAllLines(Path.Combine(Probe.DirectoryFor(context), "product-provenance.txt"), [ adapter.Location, @@ -159,10 +313,20 @@ public static void Initialize(TestContext context) } [GlobalTestCleanup] - public static void Cleanup(TestContext context) + public static async Task Cleanup(TestContext context) { Probe.Record(context, "global-cleanup"); + if (Environment.GetEnvironmentVariable("NONCOOPERATIVE_TEST_TIMEOUT") == "True") + { + await Task.Delay(500, context.CancellationToken); + } + File.Delete(Probe.ResourceFor(context)); + if (Probe.Scenario == "global-cancel-return") + { + context.CancellationTokenSource.Cancel(); + } + if (Probe.Scenario == "timeout-global-throw") { throw new InvalidOperationException("global cleanup also failed"); @@ -191,6 +355,10 @@ public sealed class NoBaseCleanup : ProbeBase [TestMethod] public void NoBaseTest() => Probe.Record(TestContext, "test-body"); + [TestMethod] + [Timeout(10000)] + public void NoBaseTestNonCooperative() => Probe.Record(TestContext, "test-body"); + [TestCleanup] [Timeout(1000, CooperativeCancellation = true)] public async Task Cleanup() => await Probe.CleanupAsync(TestContext); @@ -202,6 +370,10 @@ public sealed class WithBaseCleanup : InheritedCleanup [TestMethod] public void WithBaseTest() => Probe.Record(TestContext, "test-body"); + [TestMethod] + [Timeout(10000)] + public void WithBaseTestNonCooperative() => Probe.Record(TestContext, "test-body"); + [TestCleanup] [Timeout(1000, CooperativeCancellation = true)] public async Task Cleanup() => await Probe.CleanupAsync(TestContext); diff --git a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs index db7c9a5b5f..aa02fa2063 100644 --- a/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs +++ b/test/UnitTests/MSTestAdapter.PlatformServices.UnitTests/Execution/TestMethodInfoTests.cs @@ -1747,9 +1747,81 @@ public Task GlobalCleanupAfterLocalCancellationKeepsOriginalUnrelatedFailure() public Task GlobalCleanupFailureDoesNotMaskLocalCancellation() => VerifyGlobalCleanupAfterLocalCancellationAsync(throwCancellation: true, throwGlobalFailure: true); + public Task GlobalCleanupFailureDoesNotMaskLocalUnrelatedFailureAfterCancellation() + => VerifyGlobalCleanupAfterLocalCancellationAsync(throwCancellation: false, throwUnrelatedFailure: true, throwGlobalFailure: true); + + public Task GlobalCleanupFailureDoesNotMaskUncancelledLocalFailure() + => VerifyGlobalCleanupAfterLocalCancellationAsync(throwCancellation: false, throwUnrelatedFailure: true, throwGlobalFailure: true, cancelLocal: false); + + public async Task GlobalCleanupFailureFailsInconclusiveLocalCleanup() + { + DummyTestClass.TestCleanupMethodBody = _ => throw new AssertInconclusiveException("local cleanup was inconclusive"); + DummyTestClass.GlobalTestCleanupMethodBodyAsync = _ => throw new InvalidOperationException("global cleanup failed"); + _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; + _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeout(0); + + TestResult result = await _testMethodInfo.InvokeAsync(null); + + result.Outcome.Should().Be(UnitTestOutcome.Failed); + AggregateException failures = result.TestFailureException.Should().BeOfType().Subject; + failures.InnerExceptions.Should().HaveCount(2); + failures.InnerExceptions[0].Should().BeOfType().Which.Outcome.Should().Be(UnitTestOutcome.Inconclusive); + failures.InnerExceptions[1].Should().BeOfType().Which.Outcome.Should().Be(UnitTestOutcome.Failed); + } + public Task GlobalCleanupAfterLocalCancellationKeepsInheritedCleanupFailFast() => VerifyGlobalCleanupAfterLocalCancellationAsync(throwCancellation: true, hasBaseCleanup: true); + public Task NonCooperativeTimeoutWaitsForGlobalCleanupAfterLocalCancellation() + => VerifyNonCooperativeGlobalCleanupAsync(useSynchronizationContext: false, expireDeadline: false); + + public Task NonCooperativeTimeoutOnSynchronizationContextWaitsForGlobalCleanupAfterLocalCancellation() + => VerifyNonCooperativeGlobalCleanupAsync(useSynchronizationContext: true, expireDeadline: false); + + public Task NonCooperativeTimeoutCancelsRenewedGlobalCleanupAtOriginalDeadline() + => VerifyNonCooperativeGlobalCleanupAsync(useSynchronizationContext: false, expireDeadline: true); + + public Task NonCooperativeTimeoutReportsTerminalLocalCleanupCancellation() + => VerifyNonCooperativeTerminalCleanupCancellationAsync(globalCleanup: false, useSynchronizationContext: false); + + public Task NonCooperativeTimeoutOnSynchronizationContextReportsTerminalLocalCleanupCancellation() + => VerifyNonCooperativeTerminalCleanupCancellationAsync(globalCleanup: false, useSynchronizationContext: true); + + public Task NonCooperativeTimeoutReportsTerminalGlobalCleanupCancellation() + => VerifyNonCooperativeTerminalCleanupCancellationAsync(globalCleanup: true, useSynchronizationContext: false); + + public Task NonCooperativeTimeoutOnSynchronizationContextReportsTerminalGlobalCleanupCancellation() + => VerifyNonCooperativeTerminalCleanupCancellationAsync(globalCleanup: true, useSynchronizationContext: true); + + public Task NonCooperativeBodyCancellationDoesNotCancelRenewedCleanup() + => VerifyNonCooperativeBodyCancellationAsync(cancelRunDuringCleanup: false, expireDeadline: false); + + public Task NonCooperativeBodyCancellationPreservesActiveRunCancellation() + => VerifyNonCooperativeBodyCancellationAsync(cancelRunDuringCleanup: true, expireDeadline: false); + + public Task NonCooperativeBodyCancellationRetainsCleanupDeadline() + => VerifyNonCooperativeBodyCancellationAsync(cancelRunDuringCleanup: false, expireDeadline: true); + + public Task NonCooperativeBodyCancellationDoesNotRestartElapsedCleanupDeadline() + => VerifyNonCooperativeBodyCancellationAsync(cancelRunDuringCleanup: false, expireDeadline: true, expireBeforeMonitorReturns: true); + + public async Task GlobalCleanupRenewedSourceRemainsUsableAfterInvocation() + { + DummyTestClass.TestCleanupMethodBody = _ => _testContextImplementation.CancellationTokenSource.Cancel(); + _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; + _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeout(0); + + TestResult result = await _testMethodInfo.InvokeAsync(null); + + result.Outcome.Should().Be(UnitTestOutcome.Timeout); + int cancellationCalls = 0; + using CancellationTokenRegistration registration = _testContextImplementation.CancellationToken.Register(() => cancellationCalls++); + _testContextImplementation.CancellationTokenSource.Cancel(); + cancellationCalls.Should().Be(1); + } + public async Task GlobalCleanupDoesNotRefreshHealthyToken() { CancellationTokenSource originalSource = _testContextImplementation.CancellationTokenSource; @@ -1771,23 +1843,21 @@ public async Task GlobalCleanupDoesNotRefreshHealthyToken() public async Task GlobalCleanupRetainsActiveTestDeadlineAfterLocalCancellation() { - using CancellationTokenSource deadline = new(); CancellationToken globalToken = default; DummyTestClass.TestCleanupMethodBody = _ => { _testContextImplementation.CancellationTokenSource.Cancel(); _testContextImplementation.CancellationToken.ThrowIfCancellationRequested(); }; - DummyTestClass.GlobalTestCleanupMethodBodyAsync = context => + DummyTestClass.GlobalTestCleanupMethodBodyAsync = async context => { globalToken = context.CancellationToken; - deadline.Cancel(); - return Task.CompletedTask; + await Task.Delay(Timeout.Infinite, globalToken); }; _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); - TestResult result = await InvokeWithTestDeadlineAsync(deadline); + TestResult result = await InvokeWithTestDeadlineAsync(); globalToken.CanBeCanceled.Should().BeTrue(); globalToken.IsCancellationRequested.Should().BeTrue(); @@ -1797,14 +1867,9 @@ public async Task GlobalCleanupRetainsActiveTestDeadlineAfterLocalCancellation() public async Task GlobalCleanupDoesNotRestartExpiredTestDeadline() { - using CancellationTokenSource deadline = new(); CancellationTokenSource originalSource = _testContextImplementation.CancellationTokenSource; bool globalEntered = false; - DummyTestClass.TestCleanupMethodBody = _ => - { - deadline.Cancel(); - _testContextImplementation.CancellationToken.ThrowIfCancellationRequested(); - }; + DummyTestClass.TestCleanupMethodBody = _ => Task.Delay(Timeout.Infinite, _testContextImplementation.CancellationToken).GetAwaiter().GetResult(); DummyTestClass.GlobalTestCleanupMethodBodyAsync = _ => { globalEntered = true; @@ -1813,7 +1878,7 @@ public async Task GlobalCleanupDoesNotRestartExpiredTestDeadline() _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); - TestResult result = await InvokeWithTestDeadlineAsync(deadline); + TestResult result = await InvokeWithTestDeadlineAsync(); globalEntered.Should().BeFalse(); _testContextImplementation.CancellationTokenSource.Should().BeSameAs(originalSource); @@ -1823,14 +1888,9 @@ public async Task GlobalCleanupDoesNotRestartExpiredTestDeadline() public async Task GlobalCleanupAfterLocalCancellationIgnoresAlreadyExpiredTestDeadline() { - using CancellationTokenSource deadline = new(); CancellationTokenSource? localSource = null; CancellationTokenSource? globalSource = null; - DummyTestClass.TestMethodBody = _ => - { - deadline.Cancel(); - _testContextImplementation.CancellationToken.ThrowIfCancellationRequested(); - }; + DummyTestClass.TestMethodBody = _ => Task.Delay(Timeout.Infinite, _testContextImplementation.CancellationToken).GetAwaiter().GetResult(); DummyTestClass.TestCleanupMethodBody = _ => { localSource = _testContextImplementation.CancellationTokenSource; @@ -1845,7 +1905,7 @@ public async Task GlobalCleanupAfterLocalCancellationIgnoresAlreadyExpiredTestDe _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); - TestResult result = await InvokeWithTestDeadlineAsync(deadline); + TestResult result = await InvokeWithTestDeadlineAsync(); globalSource.Should().NotBeNull().And.NotBeSameAs(localSource); globalSource!.IsCancellationRequested.Should().BeFalse(); @@ -2618,16 +2678,22 @@ private async Task VerifyGlobalCleanupAfterLocalCancellationAsync( bool throwCancellation, bool throwUnrelatedFailure = false, bool throwGlobalFailure = false, - bool hasBaseCleanup = false) + bool hasBaseCleanup = false, + bool cancelLocal = true) { List events = []; CancellationTokenSource originalSource = _testContextImplementation.CancellationTokenSource; CancellationTokenSource? globalSource = null; var localFailure = new InvalidOperationException("local cleanup failed after cancellation"); + var globalFailure = new InvalidOperationException("global cleanup also failed"); DummyTestClass.TestCleanupMethodBody = _ => { events.Add("local"); - originalSource.Cancel(); + if (cancelLocal) + { + originalSource.Cancel(); + } + if (throwUnrelatedFailure) { throw localFailure; @@ -2643,7 +2709,7 @@ private async Task VerifyGlobalCleanupAfterLocalCancellationAsync( events.Add("global"); globalSource = context.CancellationTokenSource; return throwGlobalFailure - ? throw new InvalidOperationException("global cleanup also failed") + ? throw globalFailure : Task.CompletedTask; }; MethodInfo localCleanup = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethod))!; @@ -2659,25 +2725,352 @@ private async Task VerifyGlobalCleanupAfterLocalCancellationAsync( TestResult result = await _testMethodInfo.InvokeAsync(null); events.Should().Equal("local", "global"); - originalSource.IsCancellationRequested.Should().BeTrue(); - globalSource.Should().NotBeNull().And.NotBeSameAs(originalSource); + originalSource.IsCancellationRequested.Should().Be(cancelLocal); + globalSource.Should().NotBeNull(); + if (cancelLocal) + { + globalSource.Should().NotBeSameAs(originalSource); + } + else + { + globalSource.Should().BeSameAs(originalSource); + } + globalSource!.IsCancellationRequested.Should().BeFalse(); result.Outcome.Should().Be(throwUnrelatedFailure ? UnitTestOutcome.Failed : UnitTestOutcome.Timeout); - TestFailedException failure = result.TestFailureException.Should().BeOfType().Subject; + TestFailedException failure; + if (throwGlobalFailure) + { + AggregateException failures = result.TestFailureException.Should().BeOfType().Subject; + failures.InnerExceptions.Should().HaveCount(2); + failure = failures.InnerExceptions[0].Should().BeOfType().Subject; + TestFailedException globalCleanupFailure = failures.InnerExceptions[1].Should().BeOfType().Subject; + globalCleanupFailure.InnerException.Should().BeSameAs(globalFailure); + globalCleanupFailure.Message.Should().Contain(nameof(DummyTestClass.DummyGlobalTestCleanupMethod)); + } + else + { + failure = result.TestFailureException.Should().BeOfType().Subject; + } + failure.Message.Should().Contain(localCleanup.Name); + failure.Outcome.Should().Be(throwUnrelatedFailure ? UnitTestOutcome.Failed : UnitTestOutcome.Timeout); if (throwUnrelatedFailure) { failure.InnerException.Should().BeSameAs(localFailure); } } - private async Task InvokeWithTestDeadlineAsync(CancellationTokenSource deadline) + private Task InvokeWithTestDeadlineAsync() + { + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeoutAttribute(new TimeoutAttribute(1_000) { CooperativeCancellation = true }); + + return _testMethodInfo.InvokeAsync(null); + } + + private async Task VerifyNonCooperativeTerminalCleanupCancellationAsync(bool globalCleanup, bool useSynchronizationContext) { - _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeoutAttribute(new TimeoutAttribute(10_000) { CooperativeCancellation = true }); - using CancellationTokenRegistration registration = deadline.Token.Register(_testMethodInfo.TestContext.Context.CancellationTokenSource.Cancel); - MethodInfo execute = typeof(TestMethodInfo).GetMethod("ExecuteInternalAsync", BindingFlags.Instance | BindingFlags.NonPublic)!; + var cleanupEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseCleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var workerCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + bool cleanupCompleted = false; + IPlatformServiceProvider previousServices = PlatformServiceProvider.Instance; + var services = new TestablePlatformServiceProvider(); + services.MockThreadOperations + .Setup(operations => operations.Execute(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Action action, int timeout, CancellationToken token) => new ThreadOperations().Execute( + () => + { + try + { + action(); + } + finally + { + workerCompleted.TrySetResult(true); + } + }, + timeout, + token)); - return await (Task)execute.Invoke(_testMethodInfo, [null, deadline, null])!; + async Task CancelDuringCleanupAsync() + { + _testContextImplementation.CancellationTokenSource.Cancel(); + cleanupEntered.TrySetResult(true); + await releaseCleanup.Task; + cleanupCompleted = true; + } + + if (globalCleanup) + { + DummyTestClass.GlobalTestCleanupMethodBodyAsync = _ => CancelDuringCleanupAsync(); + _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); + } + else + { + DummyTestClass.TestCleanupMethodBodyAsync = _ => CancelDuringCleanupAsync(); + _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethodAsync))!; + } + + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeout(30_000); + using SingleThreadedSynchronizationContextForTesting? synchronizationContext = useSynchronizationContext ? new SingleThreadedSynchronizationContextForTesting() : null; + PlatformServiceProvider.Instance = services; + Task invocation = useSynchronizationContext + ? RunInvokeAsyncOnContextAsync(_testMethodInfo, synchronizationContext!) + : Task.Run(() => _testMethodInfo.InvokeAsync(null)); + TestResult result; + try + { + await WaitForCompletionAsync(cleanupEntered.Task); + invocation.IsCompleted.Should().BeFalse("cancellation must not end the wait for an already-running cleanup"); + releaseCleanup.TrySetResult(true); + await WaitForCompletionAsync(invocation); + result = await invocation; + } + finally + { + releaseCleanup.TrySetResult(true); + try + { + await WaitForCompletionAsync(Task.WhenAll( + invocation, + useSynchronizationContext ? Task.WhenAll(synchronizationContext!.DispatchedTasks) : workerCompleted.Task)); + } + finally + { + PlatformServiceProvider.Instance = previousServices; + } + } + + cleanupCompleted.Should().BeTrue(); + result.Outcome.Should().Be(UnitTestOutcome.Timeout); + result.TestFailureException.Should().BeOfType().Which.Message.Should().Be(string.Format( + CultureInfo.CurrentCulture, + Resource.Execution_Test_Cancelled, + _testMethodInfo.TestMethodName)); + } + + private async Task VerifyNonCooperativeBodyCancellationAsync( + bool cancelRunDuringCleanup, + bool expireDeadline, + bool expireBeforeMonitorReturns = false) + { + const int CleanupDeadlineMilliseconds = 5_000; + const int DeadlineExpiryMarginMilliseconds = 100; + using ManualResetEventSlim cleanupEntered = new(); + var releaseCleanup = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var cleanupCanceled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var runCancellation = new TestRunCancellationToken(); + CancellationTokenSource? cleanupSource = null; + Task? worker = null; + Task? invocation = null; + int globalCalls = 0; + IPlatformServiceProvider previousServices = PlatformServiceProvider.Instance; + var services = new TestablePlatformServiceProvider { TestRunCancellationToken = runCancellation }; + services.MockThreadOperations + .Setup(operations => operations.Execute(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Action action, int timeout, CancellationToken token) => + { + worker = Task.Run(action, CancellationToken.None); + cleanupEntered.Wait(TimeSpan.FromSeconds(30), CancellationToken.None).Should().BeTrue(); + token.IsCancellationRequested.Should().BeTrue(); + if (expireBeforeMonitorReturns) + { + // The margin avoids timer-tick rounding when proving that the original budget is exhausted. + using var deadline = new CancellationTokenSource(timeout + DeadlineExpiryMarginMilliseconds); + deadline.Token.WaitHandle.WaitOne(TimeSpan.FromSeconds(30)).Should().BeTrue(); + } + + return false; + }); + DummyTestClass.TestMethodBody = _ => + { + _testContextImplementation.CancellationTokenSource.Cancel(); + throw new InvalidOperationException("test body failed after cancellation"); + }; + DummyTestClass.TestCleanupMethodBodyAsync = async _ => + { + cleanupSource = _testContextImplementation.CancellationTokenSource; + using CancellationTokenRegistration registration = cleanupSource.Token.Register(() => cleanupCanceled.TrySetResult(true)); + cleanupEntered.Set(); + await releaseCleanup.Task; + }; + DummyTestClass.GlobalTestCleanupMethodBodyAsync = _ => + { + globalCalls++; + return Task.CompletedTask; + }; + _testClassInfo.TestCleanupMethod = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethodAsync))!; + _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeout(expireDeadline ? CleanupDeadlineMilliseconds : 30_000); + PlatformServiceProvider.Instance = services; + TestResult result; + try + { + // Execute returns only after the worker renewed its cleanup source, fixing the monitor/worker interleaving. + invocation = _testMethodInfo.InvokeAsync(null); + cleanupSource.Should().NotBeNull(); + cleanupSource!.IsCancellationRequested.Should().Be( + expireBeforeMonitorReturns, + "only an elapsed whole-test deadline may cancel the renewed source at this point"); + if (!expireBeforeMonitorReturns) + { + invocation.IsCompleted.Should().BeFalse("the original test budget still permits cleanup to finish"); + } + + if (cancelRunDuringCleanup) + { + runCancellation.Cancel(); + } + + if (cancelRunDuringCleanup || expireDeadline) + { + await WaitForCompletionAsync(cleanupCanceled.Task); + } + + releaseCleanup.TrySetResult(true); + await WaitForCompletionAsync(invocation); + result = await invocation; + } + finally + { + releaseCleanup.TrySetResult(true); + try + { + try + { + if (invocation is not null) + { + await WaitForCompletionAsync(invocation); + } + } + finally + { + if (worker is not null) + { + await WaitForCompletionAsync(worker); + } + } + } + finally + { + PlatformServiceProvider.Instance = previousServices; + } + } + + globalCalls.Should().Be(cancelRunDuringCleanup || expireDeadline ? 0 : 1); + cleanupSource!.IsCancellationRequested.Should().Be(cancelRunDuringCleanup || expireDeadline); + result.Outcome.Should().Be(UnitTestOutcome.Timeout); + result.ExceptionMessage.Should().Be(expireBeforeMonitorReturns + ? string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Timeout, _testMethodInfo.TestMethodName, CleanupDeadlineMilliseconds) + : string.Format(CultureInfo.CurrentCulture, Resource.Execution_Test_Cancelled, _testMethodInfo.TestMethodName)); + } + + private async Task VerifyNonCooperativeGlobalCleanupAsync(bool useSynchronizationContext, bool expireDeadline) + { + const int TestDeadlineMilliseconds = 5_000; + var globalEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseGlobal = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var workerCompleted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + bool globalCompleted = false; + bool globalCancellationRequested = false; + bool monitorCanceledByLocalCleanup = false; + CancellationToken monitorToken = default; + IPlatformServiceProvider previousServices = PlatformServiceProvider.Instance; + var services = new TestablePlatformServiceProvider(); + services.MockThreadOperations + .Setup(operations => operations.Execute(It.IsAny(), It.IsAny(), It.IsAny())) + .Returns((Action action, int timeout, CancellationToken token) => + { + monitorToken = token; + return new ThreadOperations().Execute( + () => + { + try + { + action(); + } + finally + { + workerCompleted.TrySetResult(true); + } + }, + timeout, + token); + }); + MethodInfo localCleanup = typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyTestCleanupMethodAsync))!; + _testClassInfo.TestCleanupMethod = localCleanup; + _testClassInfo.TestCleanupMethodTimeoutMilliseconds[localCleanup] = + TimeoutInfo.FromTimeoutAttribute(new TimeoutAttribute(100) { CooperativeCancellation = true }); + _testAssemblyInfo.GlobalTestCleanups.Add((typeof(DummyTestClass).GetMethod(nameof(DummyTestClass.DummyGlobalTestCleanupMethod))!, null)); + _testMethodInfo.TimeoutInfo = TimeoutInfo.FromTimeout(TestDeadlineMilliseconds); + DummyTestClass.TestCleanupMethodBodyAsync = _ => Task.Delay(Timeout.Infinite, _testContextImplementation.CancellationToken); + DummyTestClass.GlobalTestCleanupMethodBodyAsync = async context => + { + monitorCanceledByLocalCleanup = monitorToken.IsCancellationRequested; + globalEntered.TrySetResult(true); + if (expireDeadline) + { + await Task.WhenAny(releaseGlobal.Task, Task.Delay(Timeout.Infinite, context.CancellationToken)); + globalCancellationRequested = context.CancellationToken.IsCancellationRequested; + } + else + { + await releaseGlobal.Task; + } + + globalCompleted = true; + }; + + using SingleThreadedSynchronizationContextForTesting? synchronizationContext = useSynchronizationContext ? new SingleThreadedSynchronizationContextForTesting() : null; + PlatformServiceProvider.Instance = services; + Task invocation = useSynchronizationContext + ? RunInvokeAsyncOnContextAsync(_testMethodInfo, synchronizationContext!) + : Task.Run(() => _testMethodInfo.InvokeAsync(null)); + TestResult result; + try + { + await WaitForCompletionAsync(globalEntered.Task); + if (!expireDeadline) + { + releaseGlobal.TrySetResult(true); + } + + await WaitForCompletionAsync(invocation); + result = await invocation; + } + finally + { + releaseGlobal.TrySetResult(true); + try + { + await WaitForCompletionAsync(invocation); + await WaitForCompletionAsync(useSynchronizationContext + ? Task.WhenAll(synchronizationContext!.DispatchedTasks) + : workerCompleted.Task); + } + finally + { + PlatformServiceProvider.Instance = previousServices; + } + } + + globalCompleted.Should().BeTrue(); + monitorCanceledByLocalCleanup.Should().BeFalse(); + result.Outcome.Should().Be(UnitTestOutcome.Timeout); + if (expireDeadline) + { + globalCancellationRequested.Should().BeTrue(); + result.ExceptionMessage.Should().Be(string.Format( + CultureInfo.CurrentCulture, + Resource.Execution_Test_Timeout, + _testMethodInfo.TestMethodName, + TestDeadlineMilliseconds)); + } + else + { + result.ExceptionMessage.Should().Contain(localCleanup.Name); + } } private static async Task RunWithTestablePlatformService(TestablePlatformServiceProvider testablePlatformServiceProvider, Func action) diff --git a/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs b/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs index b14949a7f6..41a229d8de 100644 --- a/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs +++ b/test/UnitTests/TestFramework.UnitTests/TestResultTests.cs @@ -22,12 +22,14 @@ public void SettingTestFailureExceptionShouldAggregatePreviouslySetExceptions() // We use GetType() == typeof(...) to do a strict type match. testResult.TestFailureException.Should().BeOfType() .Which.Message.Should().Be("Failure1"); + testResult.ExceptionMessage.Should().Be("Failure1"); testResult.TestFailureException = new ArgumentException("Failure2"); var aggregateException = (AggregateException)testResult.TestFailureException; aggregateException.InnerExceptions.Should().HaveCount(2); aggregateException.InnerExceptions[0].Message.Should().Be("Failure1"); aggregateException.InnerExceptions[1].Message.Should().Be("Failure2"); + testResult.ExceptionMessage.Should().Be($"{new AggregateException().Message} (Failure1) (Failure2)"); testResult.TestFailureException = new ArgumentException("Failure3"); aggregateException = (AggregateException)testResult.TestFailureException; @@ -35,6 +37,19 @@ public void SettingTestFailureExceptionShouldAggregatePreviouslySetExceptions() aggregateException.InnerExceptions[0].Message.Should().Be("Failure1"); aggregateException.InnerExceptions[1].Message.Should().Be("Failure2"); aggregateException.InnerExceptions[2].Message.Should().Be("Failure3"); + testResult.ExceptionMessage.Should().Be($"{new AggregateException().Message} (Failure1) (Failure2) (Failure3)"); + } + + public void SettingTestFailureExceptionShouldPreserveNestedAggregateMessages() + { + var exception = new AggregateException( + "outer failure", + new AggregateException("nested failure", new InvalidOperationException("first failure"), new ArgumentException("second failure")), + new InvalidOperationException("third failure")); + + var testResult = new TestResult { TestFailureException = exception }; + + testResult.ExceptionMessage.Should().Be("outer failure (nested failure (first failure) (second failure)) (third failure)"); } public void SettingTestFailureExceptionShouldCaptureAssertionTextsFromDirectAssertFailedException()