-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathSingleTestExecutor.cs
More file actions
528 lines (452 loc) · 19.9 KB
/
SingleTestExecutor.cs
File metadata and controls
528 lines (452 loc) · 19.9 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
using System.Runtime.ExceptionServices;
using Microsoft.Testing.Platform.Extensions.Messages;
using Microsoft.Testing.Platform.TestHost;
using TUnit.Core;
using TUnit.Core.Exceptions;
using TUnit.Core.Logging;
using TUnit.Engine.Exceptions;
using TUnit.Engine.Extensions;
using TUnit.Engine.Interfaces;
using TUnit.Engine.Logging;
namespace TUnit.Engine.Services;
/// Handles ExecutionContext restoration for AsyncLocal support and test lifecycle management
internal class SingleTestExecutor : ISingleTestExecutor
{
private readonly TUnitFrameworkLogger _logger;
private readonly ITestResultFactory _resultFactory;
private readonly EventReceiverOrchestrator _eventReceiverOrchestrator;
private readonly IHookCollectionService _hookCollectionService;
private readonly EngineCancellationToken _engineCancellationToken;
private SessionUid _sessionUid;
public SingleTestExecutor(TUnitFrameworkLogger logger,
EventReceiverOrchestrator eventReceiverOrchestrator,
IHookCollectionService hookCollectionService,
EngineCancellationToken engineCancellationToken,
SessionUid sessionUid)
{
_logger = logger;
_eventReceiverOrchestrator = eventReceiverOrchestrator;
_hookCollectionService = hookCollectionService;
_engineCancellationToken = engineCancellationToken;
_sessionUid = sessionUid;
_resultFactory = new TestResultFactory();
}
public void SetSessionId(SessionUid sessionUid)
{
_sessionUid = sessionUid;
}
public async Task<TestNodeUpdateMessage> ExecuteTestAsync(
AbstractExecutableTest test,
CancellationToken cancellationToken)
{
await ExecuteTestInternalAsync(test, cancellationToken);
if (test.State == TestState.Running)
{
test.State = TestState.Failed;
test.Result ??= new TestResult
{
State = TestState.Failed,
Start = test.StartTime ?? DateTimeOffset.UtcNow,
End = DateTimeOffset.UtcNow,
Duration = TimeSpan.Zero,
Exception = new InvalidOperationException($"Test execution completed but state was not updated properly"),
ComputerName = Environment.MachineName,
TestContext = test.Context
};
}
return CreateUpdateMessage(test);
}
private async Task<TestResult> ExecuteTestInternalAsync(
AbstractExecutableTest test,
CancellationToken cancellationToken)
{
try
{
if (test is { State: TestState.Failed, Result: not null })
{
return test.Result;
}
TestContext.Current = test.Context;
test.StartTime = DateTimeOffset.Now;
test.State = TestState.Running;
if (!string.IsNullOrEmpty(test.Context.SkipReason))
{
return await HandleSkippedTestInternalAsync(test, cancellationToken);
}
if (test.Context.TestDetails.ClassInstance is SkippedTestInstance)
{
return await HandleSkippedTestInternalAsync(test, cancellationToken);
}
if (test.Context.TestDetails.ClassInstance is PlaceholderInstance)
{
var createdInstance = await test.CreateInstanceAsync();
if (createdInstance == null)
{
throw new InvalidOperationException($"CreateInstanceAsync returned null for test {test.Context.GetDisplayName()}. This is likely a framework bug.");
}
test.Context.TestDetails.ClassInstance = createdInstance;
}
var instance = test.Context.TestDetails.ClassInstance;
if (instance == null)
{
throw new InvalidOperationException(
$"Test instance is null for test {test.Context.GetDisplayName()} after instance creation. ClassInstance type: {test.Context.TestDetails.ClassInstance?.GetType()?.Name ?? "null"}");
}
if (instance is PlaceholderInstance)
{
throw new InvalidOperationException($"Test instance is still PlaceholderInstance for test {test.Context.GetDisplayName()}. This should have been replaced.");
}
await PropertyInjectionService.InjectPropertiesIntoArgumentsAsync(test.ClassArguments, test.Context.ObjectBag, test.Context.TestDetails.MethodMetadata,
test.Context.Events);
await PropertyInjectionService.InjectPropertiesIntoArgumentsAsync(test.Arguments, test.Context.ObjectBag, test.Context.TestDetails.MethodMetadata,
test.Context.Events);
await PropertyInjectionService.InjectPropertiesAsync(
test.Context,
instance,
test.Metadata.PropertyDataSources,
test.Metadata.PropertyInjections,
test.Metadata.MethodMetadata,
test.Context.TestDetails.TestId);
await _eventReceiverOrchestrator.InitializeAllEligibleObjectsAsync(test.Context, cancellationToken);
CheckDependenciesAndThrowIfShouldSkip(test);
var classContext = test.Context.ClassContext;
var assemblyContext = classContext.AssemblyContext;
var sessionContext = assemblyContext.TestSessionContext;
await _eventReceiverOrchestrator.InvokeFirstTestInSessionEventReceiversAsync(test.Context, sessionContext, cancellationToken);
await _eventReceiverOrchestrator.InvokeFirstTestInAssemblyEventReceiversAsync(test.Context, assemblyContext, cancellationToken);
await _eventReceiverOrchestrator.InvokeFirstTestInClassEventReceiversAsync(test.Context, classContext, cancellationToken);
await _eventReceiverOrchestrator.InvokeTestStartEventReceiversAsync(test.Context, cancellationToken);
try
{
if (!string.IsNullOrEmpty(test.Context.SkipReason))
{
return await HandleSkippedTestInternalAsync(test, cancellationToken);
}
if (test.Context is { RetryFunc: not null, TestDetails.RetryLimit: > 0 })
{
await ExecuteTestWithRetries(() => ExecuteTestWithHooksAsync(test, instance, cancellationToken), test.Context, cancellationToken);
}
else
{
await ExecuteTestWithHooksAsync(test, instance, cancellationToken);
}
}
catch (TestDependencyException e)
{
test.Context.SkipReason = e.Message;
return await HandleSkippedTestInternalAsync(test, cancellationToken);
}
catch (Exception exception) when (_engineCancellationToken.Token.IsCancellationRequested && exception is OperationCanceledException or TaskCanceledException)
{
HandleCancellation(test);
}
catch (Exception ex)
{
HandleTestFailure(test, ex);
}
finally
{
test.EndTime = DateTimeOffset.Now;
await _eventReceiverOrchestrator.InvokeTestEndEventReceiversAsync(test.Context!, cancellationToken);
}
if (test.Result == null)
{
test.State = TestState.Failed;
test.Result = new TestResult
{
State = TestState.Failed,
Start = test.StartTime ?? DateTimeOffset.UtcNow,
End = DateTimeOffset.UtcNow,
Duration = TimeSpan.Zero,
Exception = new InvalidOperationException("Test execution completed but no result was set"),
ComputerName = Environment.MachineName,
TestContext = test.Context
};
}
return test.Result;
}
catch (Exception ex)
{
test.State = TestState.Failed;
test.EndTime = DateTimeOffset.Now;
test.Result = new TestResult
{
State = TestState.Failed,
Start = test.StartTime ?? DateTimeOffset.UtcNow,
End = DateTimeOffset.UtcNow,
Duration = TimeSpan.Zero,
Exception = ex,
ComputerName = Environment.MachineName,
TestContext = test.Context
};
return test.Result;
}
}
private async Task ExecuteTestWithRetries(Func<Task> testDelegate, TestContext testContext, CancellationToken cancellationToken)
{
var retryLimit = testContext.TestDetails.RetryLimit;
var retryFunc = testContext.RetryFunc!;
for (var i = 0; i < retryLimit + 1; i++)
{
try
{
cancellationToken.ThrowIfCancellationRequested();
await testDelegate();
return;
}
catch (Exception ex) when (i < retryLimit)
{
if (!await retryFunc(testContext, ex, i + 1))
{
throw;
}
await _logger.LogWarningAsync($"Retrying test due to exception: {ex.Message}. Attempt {i} of {retryLimit}.");
}
}
}
private async Task<TestResult> HandleSkippedTestInternalAsync(AbstractExecutableTest test, CancellationToken cancellationToken)
{
test.State = TestState.Skipped;
test.Result = _resultFactory.CreateSkippedResult(
test.StartTime!.Value,
test.Context.SkipReason ?? "Test skipped");
test.EndTime = DateTimeOffset.Now;
await _eventReceiverOrchestrator.InvokeTestSkippedEventReceiversAsync(test.Context, cancellationToken);
return test.Result;
}
private async Task ExecuteTestWithHooksAsync(AbstractExecutableTest test, object instance, CancellationToken cancellationToken)
{
// Context restoration is now handled inside ExecuteBeforeTestHooksAsync
var testClassType = test.Context.TestDetails.ClassType;
var beforeTestHooks = await _hookCollectionService.CollectBeforeTestHooksAsync(testClassType);
var afterTestHooks = await _hookCollectionService.CollectAfterTestHooksAsync(testClassType);
Exception? testException = null;
try
{
await ExecuteBeforeTestHooksAsync(beforeTestHooks, test.Context, cancellationToken);
// RestoreExecutionContext only if needed for the test itself
test.Context.RestoreExecutionContext();
await InvokeTestWithTimeout(test, instance, cancellationToken);
test.State = TestState.Passed;
test.Result = _resultFactory.CreatePassedResult(test.StartTime!.Value);
}
catch (Exception ex)
{
HandleTestFailure(test, ex);
testException = ex;
}
try
{
await ExecuteAfterTestHooksAsync(afterTestHooks, test.Context, cancellationToken);
}
catch (Exception afterHookEx)
{
if (testException != null)
{
throw new AggregateException("Test and after hook both failed", testException, afterHookEx);
}
HandleTestFailure(test, afterHookEx);
throw;
}
finally
{
if (instance is IAsyncDisposable asyncDisposableInstance)
{
await asyncDisposableInstance.DisposeAsync();
}
else if (instance is IDisposable disposableInstance)
{
disposableInstance.Dispose();
}
}
if (testException != null)
{
ExceptionDispatchInfo.Capture(testException).Throw();
}
}
private async Task ExecuteBeforeTestHooksAsync(IReadOnlyList<Func<TestContext, CancellationToken, Task>> hooks, TestContext context, CancellationToken cancellationToken)
{
RestoreHookContexts(context);
context.RestoreExecutionContext();
foreach (var hook in hooks)
{
try
{
await hook(context, cancellationToken);
// RestoreExecutionContext after each hook to ensure AsyncLocal values flow correctly
// when AddAsyncLocalValues() is called in hooks
context.RestoreExecutionContext();
}
catch (Exception ex)
{
await _logger.LogErrorAsync($"Error in before test hook: {ex.Message}");
throw;
}
}
}
private async Task ExecuteAfterTestHooksAsync(IReadOnlyList<Func<TestContext, CancellationToken, Task>> hooks, TestContext context, CancellationToken cancellationToken)
{
var exceptions = new List<Exception>();
// Restore contexts once at the beginning
RestoreHookContexts(context);
foreach (var hook in hooks)
{
try
{
await hook(context, cancellationToken);
}
catch (Exception ex)
{
await _logger.LogErrorAsync($"Error in after test hook: {ex.Message}");
exceptions.Add(ex);
}
}
if (exceptions.Count > 0)
{
if (exceptions.Count == 1)
{
throw new HookFailedException(exceptions[0]);
}
else
{
throw new HookFailedException("Multiple after test hooks failed", new AggregateException(exceptions));
}
}
}
private void HandleTestFailure(AbstractExecutableTest test, Exception ex)
{
if (ex is OperationCanceledException && test.Context.TestDetails.Timeout.HasValue)
{
test.State = TestState.Timeout;
test.Result = _resultFactory.CreateTimeoutResult(
test.StartTime!.Value,
(int)test.Context.TestDetails.Timeout.Value.TotalMilliseconds);
}
else
{
test.State = TestState.Failed;
test.Result = _resultFactory.CreateFailedResult(
test.StartTime!.Value,
ex);
}
}
private void HandleCancellation(AbstractExecutableTest test)
{
test.State = TestState.Cancelled;
test.Result = _resultFactory.CreateCancelledResult(test.StartTime!.Value);
}
private TestNodeUpdateMessage CreateUpdateMessage(AbstractExecutableTest test)
{
var testNode = test.Context.ToTestNode()
.WithProperty(GetTestNodeState(test));
var standardOutput = test.Context.GetStandardOutput();
var errorOutput = test.Context.GetErrorOutput();
if (!string.IsNullOrEmpty(standardOutput))
{
#pragma warning disable TPEXP
testNode = testNode.WithProperty(new StandardOutputProperty(standardOutput));
#pragma warning restore TPEXP
}
if (!string.IsNullOrEmpty(errorOutput))
{
#pragma warning disable TPEXP
testNode = testNode.WithProperty(new StandardErrorProperty(errorOutput));
#pragma warning restore TPEXP
}
return new TestNodeUpdateMessage(
sessionUid: _sessionUid,
testNode: testNode);
}
private IProperty GetTestNodeState(AbstractExecutableTest test)
{
return test.State switch
{
TestState.Passed => PassedTestNodeStateProperty.CachedInstance,
TestState.Failed => new FailedTestNodeStateProperty(test.Result?.Exception ?? new InvalidOperationException($"Test failed but no exception was provided for {test.Context.GetDisplayName()}")),
TestState.Skipped => new SkippedTestNodeStateProperty(test.Result?.OverrideReason ?? test.Context.SkipReason ?? "Test skipped"),
TestState.Timeout => new TimeoutTestNodeStateProperty(test.Result?.OverrideReason ?? "Test timed out"),
TestState.Cancelled => new CancelledTestNodeStateProperty(),
TestState.Running => new FailedTestNodeStateProperty(new InvalidOperationException($"Test is still running: {test.Context.TestDetails.ClassType.FullName}.{test.Context.GetDisplayName()}")),
_ => new FailedTestNodeStateProperty(new InvalidOperationException($"Unknown test state: {test.State}"))
};
}
private async Task InvokeTestWithTimeout(AbstractExecutableTest test, object instance, CancellationToken cancellationToken)
{
var discoveredTest = test.Context.InternalDiscoveredTest;
var testAction = test.Context.TestDetails.Timeout.HasValue
? CreateTimeoutTestAction(test, instance, cancellationToken)
: CreateNormalTestAction(test, instance, cancellationToken);
await InvokeWithTestExecutor(discoveredTest, test.Context, testAction);
}
private Func<ValueTask> CreateTimeoutTestAction(AbstractExecutableTest test, object instance, CancellationToken cancellationToken)
{
return async () =>
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter((int)test.Context.TestDetails.Timeout!.Value.TotalMilliseconds);
var testTask = test.InvokeTestAsync(instance, cts.Token);
var timeoutTask = Task.Delay((int)test.Context.TestDetails.Timeout!.Value.TotalMilliseconds, cancellationToken);
var completedTask = await Task.WhenAny(testTask, timeoutTask);
if (completedTask == timeoutTask)
{
cts.Cancel();
throw new OperationCanceledException($"Test '{test.Context.GetDisplayName()}' exceeded timeout of {(int)test.Context.TestDetails.Timeout!.Value.TotalMilliseconds}ms");
}
await testTask;
};
}
private Func<ValueTask> CreateNormalTestAction(AbstractExecutableTest test, object instance, CancellationToken cancellationToken)
{
return async () =>
{
await test.InvokeTestAsync(instance, cancellationToken);
};
}
private async Task InvokeWithTestExecutor(DiscoveredTest? discoveredTest, TestContext context, Func<ValueTask> testAction)
{
if (discoveredTest?.TestExecutor != null)
{
await discoveredTest.TestExecutor.ExecuteTest(context, testAction);
}
else
{
await testAction();
}
}
private static void RestoreHookContexts(TestContext context)
{
if (context.ClassContext != null)
{
var assemblyContext = context.ClassContext.AssemblyContext;
AssemblyHookContext.Current = assemblyContext;
ClassHookContext.Current = context.ClassContext;
}
}
private void CheckDependenciesAndThrowIfShouldSkip(AbstractExecutableTest test)
{
var failedDependenciesNotAllowingProceed = new List<string>();
foreach (var dependency in test.Dependencies)
{
// Check if the dependency has failed or timed out
if (dependency.Test.State == TestState.Failed || dependency.Test.State == TestState.Timeout)
{
// If this dependency doesn't allow proceeding on failure, add it to the list
if (!dependency.ProceedOnFailure)
{
var dependencyName = GetDependencyDisplayName(dependency.Test);
failedDependenciesNotAllowingProceed.Add(dependencyName);
}
}
}
// Only throw if there are dependencies that don't allow proceeding
if (failedDependenciesNotAllowingProceed.Count > 0)
{
var dependencyNames = string.Join(", ", failedDependenciesNotAllowingProceed);
throw new TestDependencyException(dependencyNames, false);
}
}
private string GetDependencyDisplayName(AbstractExecutableTest dependency)
{
return dependency.Context?.GetDisplayName() ?? $"{dependency.Context?.TestDetails.ClassType.Name}.{dependency.Context?.TestDetails.TestName}" ?? "Unknown";
}
}