-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestCase.cs
More file actions
487 lines (443 loc) · 20.5 KB
/
TestCase.cs
File metadata and controls
487 lines (443 loc) · 20.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
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace IntelliTect.TestTools.TestFramework
{
public class TestCase
{
public TestCase(string testCaseName, string testMethodName, int testCaseId, IServiceCollection services)
{
TestCaseName = testCaseName;
TestMethodName = testMethodName;
TestCaseId = testCaseId;
ServiceCollection = services;
}
// Switch to get; init; when this can be updated to .net5
// Maybe target .net5 support for v3?
/// <summary>
/// The friendly name for the test case.
/// </summary>
public string TestCaseName { get; }
/// <summary>
/// The unit test method name. Defaults to the calling member for new TestBuilder().
/// </summary>
public string TestMethodName { get; }
/// <summary>
/// Any ID associated with the test case, otherwise 0.
/// </summary>
public int TestCaseId { get; }
/// <summary>
/// If this test case should throw if a finally block has an exception. Defaults to true.
/// <br />
/// If a finally block fails and this property is true, the test case is still considered passed internally, but most unit test frameworks will mark the test failed.
/// </summary>
public bool ThrowOnFinallyBlockException { get; set; } = true;
/// <summary>
/// If any test block throws an exception, it will be stored here. Finally block exceptions are stored separately in FinallyBlockExceptions. If this is not null at the end of the test case execution, the test case is considered failed.
/// </summary>
public Exception? TestBlockException { get; private set; }
/// <summary>
/// Gets the list of exceptions that were thrown during the execution of finally blocks.
/// </summary>
/// <remarks>This collection contains all exceptions that occurred in finally blocks, allowing
/// callers to inspect or handle them after execution. The list is empty if no exceptions were thrown in any
/// finally block.</remarks>
//public readonly List<Exception> FinallBlockExceptions { get; } = [];
public IReadOnlyList<Exception> CurrentFinallyBlockExceptions => FinallyBlockExceptions;
/// <summary>
/// Did the test case pass? This is determined by whether any test block threw an exception.
/// </summary>
/// <remarks>
/// Finally block exceptions do not cause the test case to be marked as failed, but they are still captured and can cause the test case to throw after execution if ThrowOnFinallyBlockException is true.
/// </remarks>
public bool Passed { get; set; }
// May make sense to make some of the below public if it's needed for debugging.
// If so, definitely need to change them to internal or private sets.
internal List<Block> TestBlocks { get; set; } = [];
internal List<Block> FinallyBlocks { get; set; } = [];
internal bool HasLogger { get; set; } = true;
private ITestCaseLogger? Log { get; set; }
private IServiceCollection ServiceCollection { get; }
private Dictionary<Type, object> BlockOutput { get; } = [];
private List<Exception> FinallyBlockExceptions { get; } = [];
/// <summary>
/// Legacy method signature. Executes the test case. NOTE: Prefer to use ExecuteAsync, even if you have no awaitable test blocks.
/// </summary>
/// <exception cref="TestCaseException">The exception describing a test failure.</exception>
/// <exception cref="AggregateException">Occurs when finally blocks fail, or the test fails and at least one finally block fails.</exception>
public void Execute()
{
Task.Run(ExecuteAsync).Wait();
}
/// <summary>
/// Executes the test case.
/// </summary>
/// <exception cref="TestCaseException">The exception describing a test failure.</exception>
/// <exception cref="AggregateException">Occurs when finally blocks fail, or the test fails and at least one finally block fails.</exception>
public async Task ExecuteAsync()
{
ServiceProvider services = ServiceCollection.BuildServiceProvider();
using (var testCaseScope = services.CreateScope())
{
Log = testCaseScope.ServiceProvider.GetService<ITestCaseLogger>();
if (Log is not null)
{
Log.CurrentTestBlock = "N/A";
}
Log?.Info($"Starting test case: {TestCaseName}");
foreach (var tb in TestBlocks)
{
if (Log is not null) Log.CurrentTestBlock = tb.Type.ToString();
Log?.Debug($"Starting test block: {tb.Type}");
if (!TryGetBlock(testCaseScope, tb, out object testBlockInstance)) break;
if (!TrySetBlockProperties(testCaseScope, tb, testBlockInstance)) break;
if (!TryGetExecuteArguments(testCaseScope, tb, out List<object?> executeArgs)) break;
bool runSuccess = await TryRunBlock(tb, testBlockInstance, executeArgs);
if (!runSuccess)
{
TestBlockException ??= new(
$"Unknown error occurred while running test block {tb}. " +
"Please file an issue: https://github.com/IntelliTect/TestTools.TestFramework/issues");
break;
}
}
if (TestBlockException is null)
{
Passed = true;
Log?.Info("Test case finished successfully.");
}
else
{
Log?.Critical($"Test case failed and will continue to executing Finally blocks. Exception: {TestBlockException}");
}
foreach (var fb in FinallyBlocks)
{
if (Log is not null) Log.CurrentTestBlock = fb.Type.ToString();
Log?.Debug($"Starting finally block: {fb.Type}");
if (!TryGetBlock(testCaseScope, fb, out var finallyBlockInstance)) continue;
if (!TrySetBlockProperties(testCaseScope, fb, finallyBlockInstance)) continue;
if (!TryGetExecuteArguments(testCaseScope, fb, out List<object?> executeArgs)) continue;
bool runSuccess = await TryRunBlock(fb, finallyBlockInstance, executeArgs);
if (!runSuccess)
{
Log?.Critical($"Finally block failed: {FinallyBlockExceptions.LastOrDefault()}");
}
}
}
services.Dispose();
// This seems... gross. Revisit after sleeping.
// Maybe call out in a code review.
if (TestBlockException is not null
&& (!ThrowOnFinallyBlockException
|| !FinallyBlockExceptions.Any()))
{
throw new TestCaseException("Test case failed.", TestBlockException);
}
else if (TestBlockException is not null
&& ThrowOnFinallyBlockException
&& FinallyBlockExceptions.Any())
{
FinallyBlockExceptions.Insert(0, TestBlockException);
throw new AggregateException("Test case failed and finally blocks failed.",
FinallyBlockExceptions);
}
else if (TestBlockException is null
&& ThrowOnFinallyBlockException
&& FinallyBlockExceptions.Any())
{
throw new AggregateException("Test case succeeded, but one or more finally blocks failed.",
FinallyBlockExceptions);
}
//if (tce is not null) throw tce;
}
// Does it make sense for testBlock to be nullable?
// On one hand, a return of 'true' implies it will never be null.
// On the other hand, if we modify this code and accidentaly remove/forgot a 'false' check,
// it would be nice to be forced to null check.
// Might be worth setting testBlock to be non-nullable and use temp vars as the nullable type?
private bool TryGetBlock(IServiceScope scope, Block block, out object blockInstance)
{
HandleFinallyBlock(
block,
() => Log?.Debug($"Attempting to activate test block: {block.Type}"),
() => Log?.Debug($"Attempting to activate finally block: {block.Type}")
);
bool result = false;
object? foundBlock = null;
try
{
foundBlock = scope.ServiceProvider.GetService(block.Type);
// What happens in the below scenario?
//blockInstance = scope.ServiceProvider.GetService(block.Type);
if (foundBlock is null)
{
HandleFinallyBlock(
block,
() => TestBlockException = new InvalidOperationException($"Unable to find test block: {block.Type}"),
() => FinallyBlockExceptions.Add(new InvalidOperationException($"Unable to find finally block: {block.Type}"))
);
}
}
catch (InvalidOperationException e)
{
// Only try to re-build the test block if we get an InvalidOperationException.
// That implies the block was found but could not be activated.
// Also... can this message be clearer? Not sure what will make sense to people.
Log?.Debug($"Unable to activate from DI service, attempting to re-build block: {block.Type}. Original error: {e}");
_ = TryBuildBlock(scope, block, out foundBlock);
}
if (foundBlock is not null)
{
blockInstance = foundBlock;
result = true;
}
else
{
// Is this the best way to do this?
// Or should blockInstance be nullable?
blockInstance = new object();
}
return result;
}
// Notes for documentation:
// ... First level dependencies should be validated at build time.
// ... Second level dependencies are not and can fail.
// ... This mainly affects objects returned by test blocks.
// ... Best practice is to add as much as possible via AddDependency methods and *only* return items from test blocks that *have* to be.
// ... E.G. this is fine:
// ... ... TestBlock1 - returns bool
// ... ... TestBlock2 - needs bool
// ... This starts to get problematic and requires extra attention to ensure it's absolutely necesssary:
// ... ... TestBlock1 - returns bool
// ... ... TestBlock2 - needs ObjectA which needs bool
private bool TryBuildBlock(IServiceScope scope, Block block, out object? blockInstance)
{
List<object?> blockParams = new();
foreach (ParameterInfo? c in block.ConstructorParams)
{
object? obj = ActivateObject(scope, block, c.ParameterType, "constructor argument");
if (obj is null)
{
if (!CheckForITestLogger(c.ParameterType))
{
blockInstance = null;
return false;
}
}
blockParams.Add(obj);
}
blockInstance = Activator.CreateInstance(block.Type,
BindingFlags.CreateInstance |
BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.OptionalParamBinding,
null,
blockParams.ToArray(),
CultureInfo.CurrentCulture);
return true;
}
private bool TrySetBlockProperties(IServiceScope scope, Block block, object blockInstance)
{
foreach (PropertyInfo? prop in block.PropertyParams)
{
if (!prop.CanWrite)
{
Log?.Debug($"Skipping property {prop}. No setter found.");
continue;
}
object? obj = ActivateObject(scope, block, prop.PropertyType, "property");
if (obj is null)
{
if (CheckForITestLogger(prop.PropertyType))
{
continue;
}
return false;
}
prop.SetValue(blockInstance, obj);
Log?.TestBlockInput(obj);
}
return true;
}
private bool TryGetExecuteArguments(IServiceScope scope, Block block, out List<object?> executeArgs)
{
executeArgs = new List<object?>();
foreach (ParameterInfo? ep in block.ExecuteParams)
{
object? obj = null;
if (block.ExecuteArgumentOverrides.Count > 0)
{
block.ExecuteArgumentOverrides.TryGetValue(ep.ParameterType, out obj);
}
if (obj is null)
{
obj = ActivateObject(scope, block, ep.ParameterType, "execute method argument");
if (obj is null)
{
if (CheckForITestLogger(ep.ParameterType))
{
executeArgs.Add(null);
continue;
}
return false;
}
}
executeArgs.Add(obj);
Log?.TestBlockInput(obj);
}
return true;
}
private object? ActivateObject(IServiceScope scope, Block block, Type objectType, string targetMember) // Probably need to come up with a better name than 'targetMember'.
{
if (!BlockOutput.TryGetValue(objectType, out object? obj))
{
try
{
obj = scope.ServiceProvider.GetService(objectType);
// Is the below check worth it?
// It is avoided if the test block asks for an interface if the dependency is implementing an interface.
// HOWEVER, this would facilitate injecting multiple different implementations in a test.
if (obj is null)
{
foreach (var i in objectType.GetInterfaces())
{
IEnumerable<object?> objs = scope.ServiceProvider.GetServices(i);
obj = objs.FirstOrDefault(o => o?.GetType() == objectType);
if (obj is not null) break;
}
}
}
catch (InvalidOperationException e)
{
HandleFinallyBlock(
block,
() => TestBlockException = new InvalidOperationException(
$"Test Block - {block.Type} - Error attempting to activate {targetMember}: {objectType}: {e}"),
() => FinallyBlockExceptions.Add(new InvalidOperationException(
$"Finally Block = {block.Type} - Error attempting to activate {targetMember}: {objectType}: {e}"))
);
}
}
// If we've already set an exception, i.e. the GetService call above failed, don't override it.
// This is to account for two different scenarios: a dependency is not present (below) vs. a dependency is present but failed to activate (above).
if (obj is null && TestBlockException is null)
{
HandleFinallyBlock(
block,
() => TestBlockException = new InvalidOperationException(
$"Test Block - {block.Type} - Unable to find {targetMember}: {objectType}"),
() => FinallyBlockExceptions.Add(new InvalidOperationException(
$"Finally Block = {block.Type} - Unable to find {targetMember}: {objectType}"))
);
}
return obj;
}
private async Task<bool> TryRunBlock(Block block, object blockInstance, List<object?> executeArgs)
{
bool result = false;
HandleFinallyBlock(
block,
() => Log?.Debug($"Executing test block: {block.Type}"),
() => Log?.Debug($"Executing finally block: {block.Type}")
);
try
{
object? output = null;
if (block.IsAsync)
{
dynamic asyncOutput = block.ExecuteMethod.Invoke(blockInstance, executeArgs.ToArray());
await asyncOutput;
if (block.AsyncReturnType != typeof(void))
{
output = asyncOutput.GetAwaiter().GetResult();
}
}
else
{
output = block.ExecuteMethod.Invoke(blockInstance, executeArgs.ToArray());
}
if (output is not null)
{
if (output is IBlockData blockData)
{
foreach (KeyValuePair<Type, object?> dataPoint in blockData.Data)
{
if (dataPoint.Value is not null)
{
Log?.TestBlockOutput(dataPoint.Value);
BlockOutput.Remove(dataPoint.Key);
BlockOutput.Add(dataPoint.Key, dataPoint.Value);
}
}
}
else
{
Log?.TestBlockOutput(output);
Type outputType = output.GetType();
BlockOutput.Remove(outputType);
BlockOutput.Add(outputType, output);
}
}
result = true;
}
catch (TargetInvocationException ex)
{
HandleFinallyBlock(
block,
() => TestBlockException = ex.InnerException,
() => FinallyBlockExceptions.Add(ex.InnerException)
);
}
catch (TargetParameterCountException ex)
{
ex.Data.Add("AdditionalInfo", "Test block failed: Mismatched count between Execute method arguments and supplied dependencies.");
HandleFinallyBlock(
block,
() => TestBlockException = ex,
() => FinallyBlockExceptions.Add(ex)
);
}
catch (Exception ex)
{
HandleFinallyBlock(
block,
() => TestBlockException = ex,
() => FinallyBlockExceptions.Add(ex)
);
}
if (result) Log?.Debug($"Test block completed successfully.");
return result;
}
private static void HandleFinallyBlock(Block block, Action testBlockAction, Action finallyBlockAction)
{
if (block.IsFinallyBlock)
{
finallyBlockAction();
}
else
{
testBlockAction();
}
}
// Type checking every single time we find no dependency seems a bit inefficient.
// Call this out specifically in a code review.
private bool CheckForITestLogger(Type type)
{
bool isLogger = false;
if (!HasLogger && type == typeof(ITestCaseLogger))
{
TestBlockException = null;
if (FinallyBlockExceptions.Count > 0)
{
FinallyBlockExceptions.Remove(FinallyBlockExceptions.Last());
}
isLogger = true;
}
return isLogger;
}
}
}