@@ -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 ) =>
0 commit comments