-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathTestClassInfo.cs
More file actions
768 lines (674 loc) · 30.5 KB
/
TestClassInfo.cs
File metadata and controls
768 lines (674 loc) · 30.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Extensions;
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Extensions;
using Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UTFUnitTestOutcome = Microsoft.VisualStudio.TestTools.UnitTesting.UnitTestOutcome;
namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution;
/// <summary>
/// Defines the TestClassInfo object.
/// </summary>
#pragma warning disable CA1001 // Types that own disposable fields should be disposable - not important to dispose the SemaphoreSlim, we don't access AvailableWaitHandle.
internal sealed class TestClassInfo
#pragma warning restore CA1001 // Types that own disposable fields should be disposable
{
/// <summary>
/// Test context property name.
/// </summary>
private const string TestContextPropertyName = "TestContext";
private readonly SemaphoreSlim _testClassExecuteSyncSemaphore = new(1, 1);
private TestResult? _classInitializeResult;
/// <summary>
/// Initializes a new instance of the <see cref="TestClassInfo"/> class.
/// </summary>
/// <param name="type">Underlying test class type.</param>
/// <param name="constructor">Constructor for the test class.</param>
/// <param name="isParameterlessConstructor">Whether or not the test class constructor has no parameters.</param>
/// <param name="classAttribute">Test class attribute.</param>
/// <param name="parent">Parent assembly info.</param>
internal TestClassInfo(
Type type,
ConstructorInfo constructor,
bool isParameterlessConstructor,
TestClassAttribute classAttribute,
TestAssemblyInfo parent)
{
ClassType = type;
Constructor = constructor;
IsParameterlessConstructor = isParameterlessConstructor;
TestContextProperty = ResolveTestContext(type);
Parent = parent;
ClassAttribute = classAttribute;
}
/// <summary>
/// Gets the class attribute.
/// </summary>
public TestClassAttribute ClassAttribute { get; }
/// <summary>
/// Gets the class type.
/// </summary>
public Type ClassType { get; }
/// <summary>
/// Gets the constructor.
/// </summary>
public ConstructorInfo Constructor { get; }
internal bool IsParameterlessConstructor { get; }
/// <summary>
/// Gets the test context property.
/// </summary>
public PropertyInfo? TestContextProperty { get; }
/// <summary>
/// Gets the parent <see cref="TestAssemblyInfo"/>.
/// </summary>
public TestAssemblyInfo Parent { get; }
/// <summary>
/// Gets or sets the class initialize method.
/// </summary>
public MethodInfo? ClassInitializeMethod
{
get;
internal set
{
if (field != null)
{
string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorMultiClassInit, ClassType.FullName);
throw new TypeInspectionException(message);
}
field = value;
}
}
/// <summary>
/// Gets the timeout for the class initialize methods.
/// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy.
/// </summary>
internal Dictionary<MethodInfo, TimeoutInfo> ClassInitializeMethodTimeoutMilliseconds { get; } = [];
/// <summary>
/// Gets the timeout for the class cleanup methods.
/// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy.
/// </summary>
internal Dictionary<MethodInfo, TimeoutInfo> ClassCleanupMethodTimeoutMilliseconds { get; } = [];
/// <summary>
/// Gets the timeout for the test initialize methods.
/// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy.
/// </summary>
internal Dictionary<MethodInfo, TimeoutInfo> TestInitializeMethodTimeoutMilliseconds { get; } = [];
/// <summary>
/// Gets the timeout for the test cleanup methods.
/// We can use a dictionary because the MethodInfo is unique in an inheritance hierarchy.
/// </summary>
internal Dictionary<MethodInfo, TimeoutInfo> TestCleanupMethodTimeoutMilliseconds { get; } = [];
/// <summary>
/// Gets or sets a value indicating whether class initialize has executed.
/// </summary>
public bool IsClassInitializeExecuted { get; internal set; }
/// <summary>
/// Gets or sets a value indicating whether class cleanup has executed.
/// </summary>
public bool IsClassCleanupExecuted { get; internal set; }
internal List<MethodInfo> BaseClassInitMethods { get; } = [];
internal List<MethodInfo> BaseClassCleanupMethods { get; } = [];
/// <summary>
/// Gets or sets the exception thrown during <see cref="ClassInitializeAttribute"/> method invocation.
/// </summary>
public Exception? ClassInitializationException { get; internal set; }
/// <summary>
/// Gets or sets the exception thrown during <see cref="ClassCleanupAttribute"/> method invocation.
/// </summary>
public Exception? ClassCleanupException { get; internal set; }
/// <summary>
/// Gets or sets the class cleanup method.
/// </summary>
public MethodInfo? ClassCleanupMethod
{
get;
internal set
{
if (field != null)
{
string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorMultiClassClean, ClassType.FullName);
throw new TypeInspectionException(message);
}
field = value;
}
}
/// <summary>
/// Gets a value indicating whether this class info has a executable cleanup method.
/// </summary>
public bool HasExecutableCleanupMethod
{
get
{
// If class has a cleanup method, then it is executable.
if (ClassCleanupMethod is not null)
{
return true;
}
// Otherwise, if any base cleanups were pushed to the stack we need to run them
return BaseClassCleanupMethods.Count != 0;
}
}
/// <summary>
/// Gets or sets the test initialize method.
/// </summary>
public MethodInfo? TestInitializeMethod
{
get;
internal set
{
if (field != null)
{
string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorMultiInit, ClassType.FullName);
throw new TypeInspectionException(message);
}
field = value;
}
}
/// <summary>
/// Gets or sets the test cleanup method.
/// </summary>
public MethodInfo? TestCleanupMethod
{
get;
internal set
{
if (field != null)
{
string message = string.Format(CultureInfo.CurrentCulture, Resource.UTA_ErrorMultiClean, ClassType.FullName);
throw new TypeInspectionException(message);
}
field = value;
}
}
internal ExecutionContext? ExecutionContext { get; set; }
/// <summary>
/// Gets a queue of test initialize methods to call for this type.
/// </summary>
public Queue<MethodInfo> BaseTestInitializeMethodsQueue { get; } = new();
/// <summary>
/// Gets a queue of test cleanup methods to call for this type.
/// </summary>
public Queue<MethodInfo> BaseTestCleanupMethodsQueue { get; } = new();
/// <summary>
/// Runs the class initialize method.
/// </summary>
/// <param name="testContext"> The test context. </param>
/// <exception cref="TestFailedException"> Throws a test failed exception if the initialization method throws an exception. </exception>
internal async Task RunClassInitializeAsync(TestContext testContext)
{
// If no class initialize and no base class initialize, return
if (ClassInitializeMethod is null && BaseClassInitMethods.Count == 0)
{
DebugEx.Assert(false, "Caller shouldn't call us if nothing to execute");
IsClassInitializeExecuted = true;
return;
}
if (testContext == null)
{
// TODO: Change this exception type to ArgumentNullException
#pragma warning disable CA2201 // Do not raise reserved exception types
throw new NullReferenceException(Resource.TestContextIsNull);
#pragma warning restore CA2201 // Do not raise reserved exception types
}
MethodInfo? initializeMethod = null;
string? failedClassInitializeMethodName = string.Empty;
// If class initialization is not done, then do it.
DebugEx.Assert(!IsClassInitializeExecuted, "Caller shouldn't call us if it was executed.");
if (!IsClassInitializeExecuted)
{
try
{
// We have discovered the methods from bottom (most derived) to top (less derived) but we want to execute
// from top to bottom.
for (int i = BaseClassInitMethods.Count - 1; i >= 0; i--)
{
initializeMethod = BaseClassInitMethods[i];
ClassInitializationException = await InvokeInitializeMethodAsync(initializeMethod, testContext).ConfigureAwait(false);
if (ClassInitializationException is not null)
{
break;
}
}
if (ClassInitializationException is null)
{
initializeMethod = ClassInitializeMethod;
ClassInitializationException = await InvokeInitializeMethodAsync(ClassInitializeMethod, testContext).ConfigureAwait(false);
}
}
catch (Exception ex)
{
ClassInitializationException = ex;
failedClassInitializeMethodName = initializeMethod?.Name ?? ClassInitializeMethod?.Name;
}
finally
{
IsClassInitializeExecuted = true;
}
}
// If classInitialization was successful, then don't do anything
if (ClassInitializationException == null)
{
return;
}
// If the exception is already a `TestFailedException` we throw it as-is
if (ClassInitializationException is TestFailedException)
{
throw ClassInitializationException;
}
// Fail the current test if it was a failure.
Exception realException = ClassInitializationException.GetRealException();
UTFUnitTestOutcome outcome = realException is AssertInconclusiveException ? UTFUnitTestOutcome.Inconclusive : UTFUnitTestOutcome.Failed;
// Do not use StackTraceHelper.GetFormattedExceptionMessage(realException) as it prefixes the message with the exception type name.
string exceptionMessage = realException.TryGetMessage();
string errorMessage = string.Format(
CultureInfo.CurrentCulture,
Resource.UTA_ClassInitMethodThrows,
ClassType.FullName,
failedClassInitializeMethodName,
realException.GetType().ToString(),
exceptionMessage);
StackTraceInformation? exceptionStackTraceInfo = realException.GetStackTraceInformation();
var testFailedException = new TestFailedException(outcome, errorMessage, exceptionStackTraceInfo, realException);
ClassInitializationException = testFailedException;
throw testFailedException;
}
private TestResult? TryGetClonedCachedClassInitializeResult()
// Historically, we were not caching class initialize result, and were always going through the logic in GetResultOrRunClassInitialize.
// When caching is introduced, we found out that using the cached instance can change the behavior in some cases. For example,
// if you have Console.WriteLine in class initialize, those will be present on the TestResult.
// Before caching was introduced, these logs will be only in the first class initialize result (attached to the first test run in class)
// By re-using the cached instance, it's now part of all tests.
// To preserve the original behavior, we clone the cached instance so we keep only the information we are sure should be reused.
=> _classInitializeResult is null
? null
: new()
{
Outcome = _classInitializeResult.Outcome,
IgnoreReason = _classInitializeResult.IgnoreReason,
TestFailureException = _classInitializeResult.TestFailureException,
};
internal async Task<TestResult> GetResultOrRunClassInitializeAsync(ITestContext testContext, string? initializationLogs, string? initializationErrorLogs, string? initializationTrace, string? initializationTestContextMessages)
{
TestResult? clonedInitializeResult = TryGetClonedCachedClassInitializeResult();
// Optimization: If we already ran before and know the result, return it.
if (clonedInitializeResult is not null)
{
DebugEx.Assert(IsClassInitializeExecuted, "Class initialize result should be available if and only if class initialize was executed");
return clonedInitializeResult;
}
// For optimization purposes, return right away if there is nothing to execute.
// For STA, this avoids starting a thread when we know it will do nothing.
// But we still return early even not STA.
if (ClassInitializeMethod is null && BaseClassInitMethods.Count == 0)
{
IsClassInitializeExecuted = true;
return _classInitializeResult = new() { Outcome = TestTools.UnitTesting.UnitTestOutcome.Passed };
}
// At this point, maybe class initialize was executed by another thread such
// that TryGetClonedCachedClassInitializeResult would return non-null.
// Now, we need to check again, but under a lock.
// Note that we are duplicating the logic above.
// We could keep the logic in lock only and not duplicate, but we don't want to pay
// the lock cost unnecessarily for a common case.
// We also need to lock to avoid concurrency issues and guarantee that class init is called only once.
try
{
await _testClassExecuteSyncSemaphore.WaitAsync().ConfigureAwait(false);
clonedInitializeResult = TryGetClonedCachedClassInitializeResult();
// Optimization: If we already ran before and know the result, return it.
if (clonedInitializeResult is not null)
{
DebugEx.Assert(IsClassInitializeExecuted, "Class initialize result should be available if and only if class initialize was executed");
return clonedInitializeResult;
}
DebugEx.Assert(!IsClassInitializeExecuted, "If class initialize was executed, we should have been in the previous if were we have a result available.");
bool isSTATestClass = ClassAttribute is STATestClassAttribute;
bool isWindowsOS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isSTATestClass
&& isWindowsOS
&& Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
var result = new TestResult
{
Outcome = TestTools.UnitTesting.UnitTestOutcome.Error,
IgnoreReason = "MSTest STATestClass ClassInitialize didn't complete",
};
Thread entryPointThread = new(() => result = DoRunAsync().GetAwaiter().GetResult())
{
Name = "MSTest STATestClass ClassInitialize",
};
entryPointThread.SetApartmentState(ApartmentState.STA);
entryPointThread.Start();
try
{
entryPointThread.Join();
return result;
}
catch (Exception ex)
{
PlatformServiceProvider.Instance.AdapterTraceLogger.LogError(ex.ToString());
return new TestResult
{
TestFailureException = new TestFailedException(UTFUnitTestOutcome.Error, ex.TryGetMessage(), ex.TryGetStackTraceInformation()),
Outcome = UTFUnitTestOutcome.Error,
};
}
}
else
{
// If the requested apartment state is STA and the OS is not Windows, then warn the user.
if (!isWindowsOS && isSTATestClass)
{
PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.STAIsOnlySupportedOnWindowsWarning);
}
return await DoRunAsync().ConfigureAwait(false);
}
}
finally
{
_testClassExecuteSyncSemaphore.Release();
}
// Local functions
async Task<TestResult> DoRunAsync()
{
var result = new TestResult
{
Outcome = TestTools.UnitTesting.UnitTestOutcome.Passed,
};
try
{
// This runs the ClassInitialize methods only once but saves the
await RunClassInitializeAsync(testContext.Context).ConfigureAwait(false);
}
catch (TestFailedException ex)
{
result = new TestResult { TestFailureException = ex, Outcome = ex.Outcome };
}
catch (Exception ex)
{
result = new TestResult
{
TestFailureException = new TestFailedException(UTFUnitTestOutcome.Error, ex.TryGetMessage(), ex.TryGetStackTraceInformation()),
Outcome = UTFUnitTestOutcome.Error,
};
}
finally
{
// Assembly initialize and class initialize logs are pre-pended to the first result.
var testContextImpl = testContext as TestContextImplementation;
result.LogOutput = initializationLogs + testContextImpl?.GetOut();
result.LogError = initializationErrorLogs + testContextImpl?.GetErr();
result.DebugTrace = initializationTrace + testContextImpl?.GetTrace();
result.TestContextMessages = initializationTestContextMessages + testContext.GetAndClearDiagnosticMessages();
}
_classInitializeResult = result;
return result;
}
}
private async Task<TestFailedException?> InvokeInitializeMethodAsync(MethodInfo? methodInfo, TestContext testContext)
{
if (methodInfo is null)
{
return null;
}
TimeoutInfo? timeout = null;
if (ClassInitializeMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout))
{
timeout = localTimeout;
}
TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync(
async () =>
{
// NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture.
// It's safer to reset it before the capture.
using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation))
{
Task? task = methodInfo.GetInvokeResultAsync(null, testContext);
if (task is not null)
{
await task.ConfigureAwait(false);
}
}
// **After** we have executed the class initialize, we save the current context.
// This context will contain async locals set by the class initialize method.
ExecutionContext = ExecutionContext.Capture();
},
testContext.CancellationTokenSource,
timeout,
methodInfo,
ExecutionContext ?? Parent?.ExecutionContext,
Resource.ClassInitializeWasCancelled,
Resource.ClassInitializeTimedOut).ConfigureAwait(false);
return result;
}
/// <summary>
/// Execute current and base class cleanups.
/// </summary>
/// <remarks>
/// This is a replacement for RunClassCleanup but as we are on a bug fix version, we do not want to change
/// the public API, hence this method.
/// </remarks>
internal async Task<TestFailedException?> ExecuteClassCleanupAsync(TestContext testContext)
{
if ((ClassCleanupMethod is null && BaseClassCleanupMethods.Count == 0)
|| IsClassCleanupExecuted)
{
return null;
}
MethodInfo? classCleanupMethod = ClassCleanupMethod;
try
{
await _testClassExecuteSyncSemaphore.WaitAsync().ConfigureAwait(false);
if (IsClassCleanupExecuted
// If ClassInitialize method has not been executed, then we should not execute ClassCleanup
// Note that if there is no ClassInitialze method at all, we will still set
// IsClassInitializeExecuted to true in RunClassInitialize
// IsClassInitializeExecuted can be false if all tests in the class are ignored.
|| !IsClassInitializeExecuted)
{
return null;
}
try
{
if (classCleanupMethod is not null)
{
if (!classCleanupMethod.DeclaringType!.IsIgnored(out _))
{
ClassCleanupException = await InvokeCleanupMethodAsync(classCleanupMethod, testContext).ConfigureAwait(false);
}
}
if (ClassCleanupException is null)
{
for (int i = 0; i < BaseClassCleanupMethods.Count; i++)
{
classCleanupMethod = BaseClassCleanupMethods[i];
if (!classCleanupMethod.DeclaringType!.IsIgnored(out _))
{
ClassCleanupException = await InvokeCleanupMethodAsync(classCleanupMethod, testContext).ConfigureAwait(false);
if (ClassCleanupException is not null)
{
break;
}
}
}
}
}
catch (Exception exception)
{
ClassCleanupException = exception;
}
finally
{
IsClassCleanupExecuted = true;
}
}
finally
{
_testClassExecuteSyncSemaphore.Release();
}
// If ClassCleanup was successful, then don't do anything
if (ClassCleanupException == null)
{
return null;
}
// If the exception is already a `TestFailedException` we throw it as-is
if (ClassCleanupException is TestFailedException classCleanupEx)
{
return classCleanupEx;
}
Exception realException = ClassCleanupException.GetRealException();
// special case AssertFailedException to trim off part of the stack trace
string errorMessage = realException is AssertFailedException or AssertInconclusiveException
? realException.Message
: realException.GetFormattedExceptionMessage();
StackTraceInformation? exceptionStackTraceInfo = realException.TryGetStackTraceInformation();
var testFailedException = new TestFailedException(
UTFUnitTestOutcome.Failed,
string.Format(
CultureInfo.CurrentCulture,
Resource.UTA_ClassCleanupMethodWasUnsuccesful,
classCleanupMethod!.DeclaringType!.Name,
classCleanupMethod.Name,
errorMessage,
exceptionStackTraceInfo?.ErrorStackTrace),
exceptionStackTraceInfo,
realException);
ClassCleanupException = testFailedException;
return testFailedException;
}
internal async Task RunClassCleanupAsync(ITestContext testContext, TestResult[] results)
{
if (!HasExecutableCleanupMethod || IsClassCleanupExecuted)
{
// DoRun will already do nothing for this condition. So, we gain a bit of performance.
return;
}
bool isSTATestClass = ClassAttribute is STATestClassAttribute;
bool isWindowsOS = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
if (isSTATestClass
&& isWindowsOS
&& Thread.CurrentThread.GetApartmentState() != ApartmentState.STA)
{
var entryPointThread = new Thread(() => DoRunAsync().GetAwaiter().GetResult())
{
Name = "MSTest STATestClass ClassCleanup",
};
entryPointThread.SetApartmentState(ApartmentState.STA);
entryPointThread.Start();
try
{
entryPointThread.Join();
}
catch (Exception ex)
{
PlatformServiceProvider.Instance.AdapterTraceLogger.LogError(ex.ToString());
}
}
else
{
// If the requested apartment state is STA and the OS is not Windows, then warn the user.
if (!isWindowsOS && isSTATestClass)
{
PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning(Resource.STAIsOnlySupportedOnWindowsWarning);
}
await DoRunAsync().ConfigureAwait(false);
}
// Local functions
async Task DoRunAsync()
{
try
{
TestFailedException? ex = await ExecuteClassCleanupAsync(testContext.Context).ConfigureAwait(false);
if (ex is not null && results.Length > 0)
{
#pragma warning disable IDE0056 // Use index operator
TestResult lastResult = results[results.Length - 1];
#pragma warning restore IDE0056 // Use index operator
lastResult.Outcome = TestTools.UnitTesting.UnitTestOutcome.Error;
lastResult.TestFailureException = ex;
}
}
finally
{
if (results.Length > 0)
{
#pragma warning disable IDE0056 // Use index operator
TestResult lastResult = results[results.Length - 1];
#pragma warning restore IDE0056 // Use index operator
var testContextImpl = testContext as TestContextImplementation;
lastResult.LogOutput += testContextImpl?.GetOut();
lastResult.LogError += testContextImpl?.GetErr();
lastResult.DebugTrace += testContextImpl?.GetTrace();
lastResult.TestContextMessages += testContext.GetAndClearDiagnosticMessages();
}
}
}
}
private async Task<TestFailedException?> InvokeCleanupMethodAsync(MethodInfo methodInfo, TestContext testContext)
{
TimeoutInfo? timeout = null;
if (ClassCleanupMethodTimeoutMilliseconds.TryGetValue(methodInfo, out TimeoutInfo localTimeout))
{
timeout = localTimeout;
}
TestFailedException? result = await FixtureMethodRunner.RunWithTimeoutAndCancellationAsync(
async () =>
{
// NOTE: It's unclear what the effect is if we reset the current test context before vs after the capture.
// It's safer to reset it before the capture.
using (TestContextImplementation.SetCurrentTestContext(testContext as TestContextImplementation))
{
Task? task = methodInfo.GetParameters().Length == 0
? methodInfo.GetInvokeResultAsync(null)
: methodInfo.GetInvokeResultAsync(null, testContext);
if (task is not null)
{
await task.ConfigureAwait(false);
}
}
// **After** we have executed the class cleanup, we save the current context.
// This context will contain async locals set by the current class cleanup method.
// This is essential to propagate async locals between multiple class cleanup methods.
ExecutionContext = ExecutionContext.Capture();
},
testContext.CancellationTokenSource,
timeout,
methodInfo,
ExecutionContext ?? Parent.ExecutionContext,
Resource.ClassCleanupWasCancelled,
Resource.ClassCleanupTimedOut).ConfigureAwait(false);
return result;
}
/// <summary>
/// Resolves the test context property.
/// </summary>
/// <param name="classType"> The class Type. </param>
/// <returns> The <see cref="PropertyInfo"/> for TestContext property. Null if not defined. </returns>
private static PropertyInfo? ResolveTestContext(Type classType)
{
try
{
PropertyInfo? testContextProperty = PlatformServiceProvider.Instance.ReflectionOperations.GetRuntimeProperty(classType, TestContextPropertyName, includeNonPublic: false);
if (testContextProperty == null)
{
// that's okay may be the property was not defined
return null;
}
// check if testContextProperty is of correct type
if (!string.Equals(testContextProperty.PropertyType.FullName, typeof(TestContext).FullName, StringComparison.Ordinal))
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.UTA_TestContextTypeMismatchLoadError, classType.FullName);
throw new TypeInspectionException(errorMessage);
}
return testContextProperty;
}
catch (AmbiguousMatchException ex)
{
string errorMessage = string.Format(CultureInfo.CurrentCulture, Resource.UTA_TestContextLoadError, classType.FullName, ex.Message);
throw new TypeInspectionException(errorMessage);
}
}
}