@@ -11,6 +11,9 @@ namespace Microsoft.Testing.Platform.UnitTests;
1111[ TestClass ]
1212public sealed class DiagnosticLoggingInformationTests
1313{
14+ private static readonly TimeSpan CompletionLimit = TimeSpan . FromSeconds ( 30 ) ;
15+ private static readonly TimeSpan CleanupLimit = TimeSpan . FromSeconds ( 30 ) ;
16+
1417 public TestContext TestContext { get ; set ; } = null ! ;
1518
1619 [ DataRow ( false ) ]
@@ -187,76 +190,107 @@ public async Task RelocationUsesUniqueReplacementBeforeRethrowingMoveFailure()
187190#endif
188191 }
189192
193+ [ DataRow ( false ) ]
194+ [ DataRow ( true ) ]
190195 [ TestMethod ]
191- public async Task SynchronousLoggerCreatedBeforeRelocationWaitsForReplacement ( )
196+ public async Task SynchronousLoggerCreatedBeforeRelocationWaitsForReplacement ( bool useAsync )
192197 {
193198 string initialDirectory = Path . Combine ( "initial" , "diagnostics" ) ;
194199 string resultsDirectory = Path . Combine ( "final" , "results" ) ;
195200 const string FileName = "test.diag" ;
201+ const string Message = "Written during relocation." ;
196202
197203 var disposeStarted = new TaskCompletionSource < bool > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
198204 var allowDispose = new TaskCompletionSource < bool > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
199- using var logThreadStarted = new ManualResetEventSlim ( ) ;
200- var logThreadCompleted = new TaskCompletionSource < bool > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
201- Exception ? logException = null ;
205+ var synchronousWaitAttempted = new TaskCompletionSource < bool > ( TaskCreationOptions . RunContinuationsAsynchronously ) ;
202206
203207 Mock < IFileSystem > fileSystem = CreateFileSystemMock ( ) ;
204208
205209 int streamIndex = 0 ;
210+ MemoryStream ? replacementStream = null ;
206211 var fileStreamFactory = new Mock < IFileStreamFactory > ( ) ;
207212 fileStreamFactory
208213 . Setup ( x => x . Create ( It . IsAny < string > ( ) , It . IsAny < FileMode > ( ) , It . IsAny < FileAccess > ( ) , It . IsAny < FileShare > ( ) ) )
209214 . Returns ( ( string path , FileMode _ , FileAccess _ , FileShare _ ) =>
210- CreateFileStream ( path , Interlocked . Increment ( ref streamIndex ) == 1 ? BlockFirstStreamDisposalAsync : null ) ) ;
215+ {
216+ var stream = new MemoryStream ( ) ;
217+ int currentStreamIndex = Interlocked . Increment ( ref streamIndex ) ;
218+ if ( currentStreamIndex == 2 )
219+ {
220+ replacementStream = stream ;
221+ }
222+
223+ return CreateFileStream ( path , currentStreamIndex == 1 ? BlockFirstStreamDisposalAsync : null , stream ) ;
224+ } ) ;
211225
212226 using FileLoggerProvider provider = CreateProvider ( fileSystem , fileStreamFactory , initialDirectory , syncFlush : true , fileName : FileName ) ;
213227 ILogger logger = provider . CreateLogger ( "test" ) ;
214228
215229 var relocationTask = Task . Run (
216230 ( ) => provider . CheckLogFolderAndMoveToTheNewIfNeededAsync ( resultsDirectory ) ,
217- TestContext . CancellationToken ) ;
218- await disposeStarted . Task ;
231+ CancellationToken . None ) ;
232+ Task logTask = Task . CompletedTask ;
219233
220- var logThread = new Thread (
221- ( ) =>
234+ try
235+ {
236+ await disposeStarted . Task . WaitAsync ( CompletionLimit , TestContext . CancellationToken ) ;
237+
238+ logTask = useAsync
239+ ? logger . LogAsync ( LogLevel . Debug , Message , null , LoggingExtensions . Formatter )
240+ : Task . Factory . StartNew (
241+ LogSynchronouslyAfterWaitProbe ,
242+ CancellationToken . None ,
243+ TaskCreationOptions . LongRunning ,
244+ TaskScheduler . Default ) ;
245+ if ( ! useAsync )
246+ {
247+ Task first = await Task . WhenAny ( synchronousWaitAttempted . Task , logTask ) . WaitAsync ( CompletionLimit , TestContext . CancellationToken ) ;
248+ Assert . AreSame ( synchronousWaitAttempted . Task , first , "Synchronous logging did not attempt the held relocation gate." ) ;
249+ }
250+
251+ Assert . IsFalse ( logTask . IsCompleted , "Logging completed before relocation installed the replacement logger." ) ;
252+ }
253+ finally
254+ {
255+ allowDispose . TrySetResult ( true ) ;
256+ await Task . WhenAll ( relocationTask , logTask ) . WaitAsync ( CleanupLimit , CancellationToken . None ) ;
257+ }
258+
259+ Assert . IsNotNull ( replacementStream ) ;
260+ Assert . Contains ( Message , Encoding . UTF8 . GetString ( replacementStream . ToArray ( ) ) ) ;
261+
262+ #pragma warning disable CA1416 // Thread interruption is unavailable on browser, but this test runs on desktop test hosts.
263+ void LogSynchronouslyAfterWaitProbe ( )
264+ {
265+ Assert . IsFalse ( Thread . CurrentThread . IsThreadPoolThread , "The wait probe must not interrupt a thread-pool worker." ) ;
266+ try
267+ {
268+ Assert . ThrowsExactly < ThreadInterruptedException > (
269+ ( ) => logger . Log ( LogLevel . Debug , Message , null , InterruptOnNextWait ) ) ;
270+ }
271+ finally
222272 {
223- logThreadStarted . Set ( ) ;
224273 try
225274 {
226- logger . LogDebug ( "Written during relocation." ) ;
227- }
228- catch ( Exception ex )
229- {
230- logException = ex ;
275+ Thread . Sleep ( 0 ) ;
231276 }
232- finally
277+ catch ( ThreadInterruptedException )
233278 {
234- logThreadCompleted . TrySetResult ( true ) ;
279+ // Clear this probe's pending interrupt if logging failed before it could block.
235280 }
236- } ) ;
237- #pragma warning disable CA1416 // Threading is unavailable on browser, but this unit test runs on desktop test hosts.
238- logThread . Start ( ) ;
239-
240- try
241- {
242- logThreadStarted . Wait ( TestContext . CancellationToken ) ;
243- bool reachedRelocationGate = SpinWait . SpinUntil (
244- ( ) => ( logThread . ThreadState & System . Threading . ThreadState . WaitSleepJoin ) != 0 || logThreadCompleted . Task . IsCompleted ,
245- TimeSpan . FromSeconds ( 5 ) ) ;
246- #pragma warning restore CA1416
281+ }
247282
248- Assert . IsTrue ( reachedRelocationGate , "The logging thread did not reach the relocation gate." ) ;
249- Assert . IsFalse ( logThreadCompleted . Task . IsCompleted , $ "Logging completed before relocation installed the replacement logger: { logException } " ) ;
283+ synchronousWaitAttempted . TrySetResult ( true ) ;
284+ logger . LogDebug ( Message ) ;
250285 }
251- finally
286+
287+ static string InterruptOnNextWait ( string state , Exception ? exception )
252288 {
253- allowDispose . TrySetResult ( true ) ;
289+ // Returning from this formatter enters the relocation wait; only blocking consumes the interrupt.
290+ Thread . CurrentThread . Interrupt ( ) ;
291+ return state ;
254292 }
255-
256- await relocationTask ;
257- await logThreadCompleted . Task . WaitAsync ( TestContext . CancellationToken ) ;
258- logThread . Join ( ) ;
259- Assert . IsNull ( logException ) ;
293+ #pragma warning restore CA1416
260294
261295 async Task BlockFirstStreamDisposalAsync ( )
262296 {
0 commit comments