Skip to content

Commit b3f3c98

Browse files
EvangelinkCopilot
andauthored
Preserve MSTest global cleanup after local cancellation (#12225)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 1f353a4 commit b3f3c98

8 files changed

Lines changed: 1528 additions & 156 deletions

File tree

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.Timeout.cs‎

Lines changed: 176 additions & 84 deletions
Large diffs are not rendered by default.

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Lifecycle.cs‎

Lines changed: 106 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,9 @@ internal partial class TestMethodInfo
2323
/// <param name="result">Instance of TestResult.</param>
2424
/// <param name="timeoutTokenSource">The timeout token source.</param>
2525
/// <param name="invocationState">The activation and cleanup state for this invocation.</param>
26+
/// <returns>Whether this caller claimed and completed cleanup.</returns>
2627
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Requirement is to handle all kinds of user exceptions and message appropriately.")]
27-
private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
28+
private async SynchronizationContextPreservingTask<bool> RunTestCleanupMethodAsync(
2829
TestResult result,
2930
CancellationTokenSource? timeoutTokenSource,
3031
TestInvocationState invocationState)
@@ -33,7 +34,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
3334

3435
if (!invocationState.TryGetCleanupSnapshot(out TestInvocationCleanupSnapshot snapshot))
3536
{
36-
return;
37+
return false;
3738
}
3839

3940
bool hasCleanupsToInvoke = HasCleanupsToInvoke(snapshot.ClassInstanceLease);
@@ -42,7 +43,13 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
4243
if ((!hasCleanupsToInvoke && !shouldResetCancellationTokenSource)
4344
|| !invocationState.TryBeginCleanup())
4445
{
45-
return;
46+
return false;
47+
}
48+
49+
CancellationToken? cleanupRunCancellationToken = PlatformServiceProvider.Instance.TestRunCancellationToken?.CancellationToken;
50+
if (cleanupRunCancellationToken is { IsCancellationRequested: true })
51+
{
52+
cleanupRunCancellationToken = null;
4653
}
4754

4855
if (shouldResetCancellationTokenSource)
@@ -52,7 +59,7 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
5259

5360
if (!hasCleanupsToInvoke)
5461
{
55-
return;
62+
return true;
5663
}
5764

5865
if (!snapshot.IsTestContextSet)
@@ -70,24 +77,27 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
7077
result.TestFailureException = exception;
7178
}
7279

73-
return;
80+
return true;
7481
}
7582

7683
MethodInfo? testCleanupMethod = Parent.TestCleanupMethod;
77-
Exception? testCleanupException;
78-
TestFailedException? globalTestCleanupException = null;
84+
Exception? testCleanupException = null;
85+
Exception? globalTestCleanupException = null;
7986
MethodInfo? globalTestCleanupFailingMethod = null;
8087
MethodInfo? currentGlobalTestCleanupMethod = null;
88+
// Retain only deadlines still active when cleanup starts; an already-expired test gets fresh teardown.
89+
CancellationToken? cleanupTimeoutToken = timeoutTokenSource is { IsCancellationRequested: false }
90+
? timeoutTokenSource.Token
91+
: null;
92+
using CancellationTokenRegistration? cleanupRunRegistration = shouldResetCancellationTokenSource
93+
? cleanupRunCancellationToken?.Register(TestContext.Context.CancellationTokenSource.Cancel)
94+
: null;
95+
using CancellationTokenRegistration? cleanupTimeoutRegistration =
96+
cleanupTimeoutToken?.Register(TestContext.Context.CancellationTokenSource.Cancel);
8197
try
8298
{
8399
try
84100
{
85-
// 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.
86-
if (timeoutTokenSource is { IsCancellationRequested: false })
87-
{
88-
timeoutTokenSource?.Token.Register(TestContext.Context.CancellationTokenSource.Cancel);
89-
}
90-
91101
// Test cleanups are called in the order of discovery
92102
// Current TestClass -> Parent -> Grandparent
93103
testCleanupException = testCleanupMethod is not null
@@ -106,17 +116,57 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
106116
}
107117
}
108118
}
119+
catch (Exception ex)
120+
{
121+
testCleanupException = ex;
122+
}
109123
finally
110124
{
111125
if (snapshot.ClassInstanceLease is { RequiresCleanup: true } classInstanceLease)
112126
{
113127
await classInstanceLease.DisposeAsync().ConfigureAwait(false);
114128
}
115129

130+
CancellationTokenSource? globalCleanupSource = null;
131+
if (Parent.Parent.GlobalTestCleanups.Count > 0
132+
&& TestContext.Context.CancellationTokenSource.IsCancellationRequested
133+
&& cleanupTimeoutToken?.IsCancellationRequested != true
134+
&& cleanupRunCancellationToken?.IsCancellationRequested != true)
135+
{
136+
if (testCleanupException is null)
137+
{
138+
MethodInfo canceledMethod = testCleanupMethod ?? Parent.Parent.GlobalTestCleanups[0].Method;
139+
string canceledMessage = testCleanupMethod is null
140+
? Resource.GlobalTestCleanupWasCancelled
141+
: Resource.TestCleanupWasCancelled;
142+
testCleanupMethod = canceledMethod;
143+
testCleanupException = new TestFailedException(
144+
UnitTestOutcome.Timeout,
145+
string.Format(CultureInfo.InvariantCulture, canceledMessage, canceledMethod.DeclaringType!.FullName, canceledMethod.Name));
146+
}
147+
148+
// A local fixture timeout must not cancel independent global teardown or restart an active test/run deadline.
149+
// Keep the context-owned source usable after cleanup; only its deadline/run registrations are scoped.
150+
TestContext.Context.CancellationTokenSource = globalCleanupSource = new CancellationTokenSource();
151+
}
152+
153+
using CancellationTokenRegistration? globalTimeoutRegistration = globalCleanupSource is null
154+
? null
155+
: cleanupTimeoutToken?.Register(globalCleanupSource.Cancel);
156+
using CancellationTokenRegistration? globalRunRegistration = globalCleanupSource is null
157+
? null
158+
: cleanupRunCancellationToken?.Register(globalCleanupSource.Cancel);
116159
foreach ((MethodInfo method, TimeoutInfo? timeoutInfo) in Parent.Parent.GlobalTestCleanups)
117160
{
118161
currentGlobalTestCleanupMethod = method;
119-
globalTestCleanupException = await InvokeGlobalCleanupMethodAsync(method, timeoutInfo, timeoutTokenSource).ConfigureAwait(false);
162+
try
163+
{
164+
globalTestCleanupException = await InvokeGlobalCleanupMethodAsync(method, timeoutInfo, timeoutTokenSource).ConfigureAwait(false);
165+
}
166+
catch (Exception ex)
167+
{
168+
globalTestCleanupException = ex;
169+
}
120170

121171
if (globalTestCleanupException is not null)
122172
{
@@ -154,34 +204,50 @@ private async SynchronizationContextPreservingTask RunTestCleanupMethodAsync(
154204
// If testCleanup was successful, then don't do anything
155205
if (testCleanupException is null)
156206
{
157-
return;
207+
return true;
158208
}
159209

160-
Exception realException = testCleanupException.GetRealException();
161-
162-
// Check `realException` (not `testCleanupException`) so that a `TestFailedException` wrapped in
163-
// a `TargetInvocationException` / `TypeInitializationException` still preserves its Outcome
164-
// (for example a Timeout outcome must not be silently downgraded to Failed).
165-
UnitTestOutcome outcomeFromRealException = realException is TestFailedException testFailedException
166-
? testFailedException.Outcome
167-
: realException is AssertInconclusiveException
168-
? UnitTestOutcome.Inconclusive
169-
: UnitTestOutcome.Failed;
170-
result.Outcome = result.Outcome.GetMoreImportantOutcome(outcomeFromRealException);
171-
172-
realException = testCleanupMethod is not null
173-
? new TestFailedException(
174-
outcomeFromRealException,
175-
string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrows, TestClassName, testCleanupMethod.Name, realException.GetFormattedExceptionMessage()),
176-
realException.TryGetStackTraceInformation(),
177-
realException)
178-
: new TestFailedException(
179-
outcomeFromRealException,
180-
string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrowsGeneralError, TestClassName, realException.GetFormattedExceptionMessage()),
181-
realException.TryGetStackTraceInformation(),
182-
realException);
183-
184-
result.TestFailureException = realException;
210+
TestFailedException cleanupFailure = CreateCleanupFailureException(testCleanupException, testCleanupMethod);
211+
result.Outcome = result.Outcome.GetMoreImportantOutcome(cleanupFailure.Outcome);
212+
result.TestFailureException = cleanupFailure;
213+
if (globalTestCleanupException is not null && testCleanupException != globalTestCleanupException)
214+
{
215+
TestFailedException globalFailure = CreateCleanupFailureException(globalTestCleanupException, globalTestCleanupFailingMethod);
216+
// Preserve the local timeout classification, but do not hide an independent global cleanup failure.
217+
if (cleanupFailure.Outcome != UnitTestOutcome.Timeout)
218+
{
219+
result.Outcome = result.Outcome.GetMoreImportantOutcome(globalFailure.Outcome);
220+
}
221+
222+
result.TestFailureException = globalFailure;
223+
}
224+
225+
return true;
226+
227+
TestFailedException CreateCleanupFailureException(Exception exception, MethodInfo? method)
228+
{
229+
Exception realException = exception.GetRealException();
230+
UnitTestOutcome outcome = realException is TestFailedException testFailedException
231+
? testFailedException.Outcome
232+
: realException is AssertInconclusiveException
233+
? UnitTestOutcome.Inconclusive
234+
: UnitTestOutcome.Failed;
235+
string cleanupClassName = method is not null && method == globalTestCleanupFailingMethod
236+
? method.DeclaringType!.FullName!
237+
: TestClassName;
238+
239+
return method is not null
240+
? new TestFailedException(
241+
outcome,
242+
string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrows, cleanupClassName, method.Name, realException.GetFormattedExceptionMessage()),
243+
realException.TryGetStackTraceInformation(),
244+
realException)
245+
: new TestFailedException(
246+
outcome,
247+
string.Format(CultureInfo.CurrentCulture, Resource.UTA_CleanupMethodThrowsGeneralError, TestClassName, realException.GetFormattedExceptionMessage()),
248+
realException.TryGetStackTraceInformation(),
249+
realException);
250+
}
185251
}
186252

187253
private bool HasCleanupsToInvoke(ITestClassInstanceLease? classInstanceLease) =>

‎src/Platform/Microsoft.Testing.Platform.ServerMode.Client.Sources/Client/MtpServerProcess.Startup.cs‎

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,18 @@ public static MtpServerProcess Start(string source, MtpServerClientOptions? opti
2525
/// <param name="source">Path to the managed test application or native executable.</param>
2626
/// <param name="options">Client options (name, connection timeout, environment, logger).</param>
2727
/// <param name="cancellationToken">Cancels the launch and connection wait.</param>
28-
public static async Task<MtpServerProcess> StartAsync(
28+
public static Task<MtpServerProcess> StartAsync(
2929
string source,
3030
MtpServerClientOptions? options = null,
3131
CancellationToken cancellationToken = default)
32+
=> StartAsync(source, options, cancellationToken, processFactory: null);
33+
34+
// Keep process ownership observable per launch without a process-wide factory override.
35+
internal static async Task<MtpServerProcess> StartAsync(
36+
string source,
37+
MtpServerClientOptions? options,
38+
CancellationToken cancellationToken,
39+
Func<Process>? processFactory)
3240
{
3341
if (source is null)
3442
{
@@ -84,7 +92,9 @@ public static async Task<MtpServerProcess> StartAsync(
8492
startInfo.Environment[variable.Key] = variable.Value;
8593
}
8694

87-
process = CreateProcess(startInfo, standardError, out Task standardErrorDrained);
95+
process = processFactory is null
96+
? CreateProcess(startInfo, standardError, out Task standardErrorDrained)
97+
: CreateProcess(processFactory(), startInfo, standardError, out standardErrorDrained);
8898
try
8999
{
90100
process.Start();
@@ -100,7 +110,9 @@ public static async Task<MtpServerProcess> StartAsync(
100110
MtpClientLogLevel.Warning,
101111
$"The sibling apphost could not be executed; retrying through '{launch.FileName} {launch.Arguments}'.");
102112

103-
process = CreateProcess(startInfo, standardError, out standardErrorDrained);
113+
process = processFactory is null
114+
? CreateProcess(startInfo, standardError, out standardErrorDrained)
115+
: CreateProcess(processFactory(), startInfo, standardError, out standardErrorDrained);
104116
process.Start();
105117
}
106118

@@ -232,11 +244,15 @@ private static string GetStandardError(StringBuilder buffer)
232244
}
233245

234246
private static Process CreateProcess(ProcessStartInfo startInfo, StringBuilder standardError, out Task standardErrorDrained)
247+
=> CreateProcess(new Process(), startInfo, standardError, out standardErrorDrained);
248+
249+
private static Process CreateProcess(Process process, ProcessStartInfo startInfo, StringBuilder standardError, out Task standardErrorDrained)
235250
{
236251
var standardErrorDrainedSource = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
237252
standardErrorDrained = standardErrorDrainedSource.Task;
238253

239-
var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true };
254+
process.StartInfo = startInfo;
255+
process.EnableRaisingEvents = true;
240256
process.ErrorDataReceived += (_, e) =>
241257
{
242258
if (e.Data is null)

‎src/TestFramework/TestFramework/Attributes/TestMethod/TestResult.cs‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,11 @@ public Exception? TestFailureException
9595
? new AggregateException(aggregateException.InnerExceptions.Concat([value]))
9696
: new AggregateException(field, value);
9797

98+
#if NETFRAMEWORK
99+
ExceptionMessage = GetExceptionMessage(field);
100+
#else
98101
ExceptionMessage = field.Message;
102+
#endif
99103
ExceptionStackTrace = field.StackTrace;
100104

101105
// Capture the structured assertion values as strings, for the same reason ExceptionMessage and
@@ -257,6 +261,25 @@ internal static TestResult CreateIgnoredResult(string? ignoreReason)
257261
IgnoreReason = ignoreReason,
258262
};
259263

264+
#if NETFRAMEWORK
265+
private static string GetExceptionMessage(Exception exception)
266+
{
267+
if (exception is not AggregateException aggregate)
268+
{
269+
return exception.Message;
270+
}
271+
272+
// Unlike modern .NET, .NET Framework omits inner messages from AggregateException.Message.
273+
var message = new StringBuilder(aggregate.Message);
274+
foreach (Exception innerException in aggregate.InnerExceptions)
275+
{
276+
message.Append(" (").Append(GetExceptionMessage(innerException)).Append(')');
277+
}
278+
279+
return message.ToString();
280+
}
281+
#endif
282+
260283
/// <summary>
261284
/// Counts the assertion failures that carry comparison values (capped at 2) and reports the values of the
262285
/// first one.

0 commit comments

Comments
 (0)