-
-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathReflectionTestDataCollector.cs
More file actions
2173 lines (1926 loc) · 85.6 KB
/
ReflectionTestDataCollector.cs
File metadata and controls
2173 lines (1926 loc) · 85.6 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
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Buffers;
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using TUnit.Core;
using TUnit.Core.Helpers;
using TUnit.Engine.Building;
using TUnit.Engine.Building.Interfaces;
using TUnit.Engine.Helpers;
namespace TUnit.Engine.Discovery;
/// Discovers tests at runtime using reflection with assembly scanning and caching
[UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2062", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2065", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2067:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttribute\' in call to target method. The parameter of method does not have matching annotations.")]
[UnconditionalSuppressMessage("Trimming", "IL2070", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2072", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2111:Method with parameters or return value with `DynamicallyAccessedMembersAttribute` is accessed via reflection. Trimmer can\'t guarantee availability of the requirements of the method.")]
[UnconditionalSuppressMessage("AOT", "IL3000", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("AOT", "IL3050", Justification = "Reflection mode isn't used in AOT scenarios")]
[UnconditionalSuppressMessage("Trimming", "IL2055:Either the type on which the MakeGenericType is called can\'t be statically determined, or the type parameters to be used for generic arguments can\'t be statically determined.")]
[UnconditionalSuppressMessage("Trimming", "IL2060:Call to \'System.Reflection.MethodInfo.MakeGenericMethod\' can not be statically analyzed. It\'s not possible to guarantee the availability of requirements of the generic method.")]
internal sealed class ReflectionTestDataCollector : ITestDataCollector
{
private static readonly ConcurrentDictionary<Assembly, bool> _scannedAssemblies = new();
private static readonly List<TestMetadata> _discoveredTests = new(capacity: 1000); // Pre-sized for typical test suites
private static readonly Lock _discoveredTestsLock = new(); // Lock for thread-safe access to _discoveredTests
private static readonly ConcurrentDictionary<Assembly, Type[]> _assemblyTypesCache = new();
private static readonly ConcurrentDictionary<Type, MethodInfo[]> _typeMethodsCache = new();
private static Assembly[]? _cachedAssemblies;
private static readonly Lock _assemblyCacheLock = new();
private static Assembly[] GetCachedAssemblies()
{
lock (_assemblyCacheLock)
{
return _cachedAssemblies ??= AppDomain.CurrentDomain.GetAssemblies();
}
}
public static void ClearCaches()
{
_scannedAssemblies.Clear();
lock (_discoveredTestsLock)
{
_discoveredTests.Clear();
}
_assemblyTypesCache.Clear();
_typeMethodsCache.Clear();
lock (_assemblyCacheLock)
{
_cachedAssemblies = null;
}
}
private async Task<List<TestMetadata>> ProcessAssemblyAsync(Assembly assembly, SemaphoreSlim semaphore)
{
await semaphore.WaitAsync().ConfigureAwait(false);
try
{
if (!_scannedAssemblies.TryAdd(assembly, true))
{
return [];
}
try
{
return await DiscoverTestsInAssembly(assembly).ConfigureAwait(false);
}
catch (Exception ex)
{
// Create a failed test metadata for the assembly that couldn't be scanned
var failedTest = CreateFailedTestMetadataForAssembly(assembly, ex);
return [failedTest];
}
}
finally
{
semaphore.Release();
}
}
public async Task<IEnumerable<TestMetadata>> CollectTestsAsync(string testSessionId)
{
#if NET
if (!RuntimeFeature.IsDynamicCodeSupported)
{
throw new Exception("Using TUnit Reflection mechanisms isn't supported in AOT mode");
}
#endif
var allAssemblies = GetCachedAssemblies();
var assembliesList = new List<Assembly>(allAssemblies.Length);
foreach (var assembly in allAssemblies)
{
if (ShouldScanAssembly(assembly))
{
assembliesList.Add(assembly);
}
}
var assemblies = assembliesList;
var maxConcurrency = Math.Min(assemblies.Count, Environment.ProcessorCount * 2);
var semaphore = new SemaphoreSlim(maxConcurrency, maxConcurrency);
var tasks = new Task<List<TestMetadata>>[assemblies.Count];
for (var i = 0; i < assemblies.Count; i++)
{
var assembly = assemblies[i];
var index = i;
tasks[index] = ProcessAssemblyAsync(assembly, semaphore);
}
// Wait for all tasks to complete
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
var totalCount = results.Sum(r => r.Count);
var newTests = new List<TestMetadata>(totalCount);
foreach (var tests in results)
{
newTests.AddRange(tests);
}
// Discover dynamic tests from DynamicTestBuilderAttribute methods
var dynamicTests = await DiscoverDynamicTests(testSessionId).ConfigureAwait(false);
newTests.AddRange(dynamicTests);
// Add to discovered tests with lock (better enumeration performance than ConcurrentBag)
lock (_discoveredTestsLock)
{
_discoveredTests.AddRange(newTests);
return new List<TestMetadata>(_discoveredTests);
}
}
public async IAsyncEnumerable<TestMetadata> CollectTestsStreamingAsync(
string testSessionId,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Get assemblies to scan
var allAssemblies = GetCachedAssemblies();
var assemblies = new List<Assembly>(allAssemblies.Length);
foreach (var assembly in allAssemblies)
{
if (ShouldScanAssembly(assembly))
{
assemblies.Add(assembly);
}
}
// Stream tests from each assembly
foreach (var assembly in assemblies)
{
cancellationToken.ThrowIfCancellationRequested();
// Use lock-free ConcurrentDictionary for assembly tracking
if (!_scannedAssemblies.TryAdd(assembly, true))
{
continue;
}
// Stream tests from this assembly
await foreach (var test in DiscoverTestsInAssemblyStreamingAsync(assembly, cancellationToken))
{
lock (_discoveredTestsLock)
{
_discoveredTests.Add(test);
}
yield return test;
}
}
// Stream dynamic tests
await foreach (var dynamicTest in DiscoverDynamicTestsStreamingAsync(testSessionId, cancellationToken))
{
lock (_discoveredTestsLock)
{
_discoveredTests.Add(dynamicTest);
}
yield return dynamicTest;
}
}
private static IEnumerable<MethodInfo> GetAllTestMethods([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods)] Type type)
{
return _typeMethodsCache.GetOrAdd(type, static t =>
{
var methods = new List<MethodInfo>(20);
var currentType = t;
while (currentType != null && currentType != typeof(object))
{
methods.AddRange(currentType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly));
currentType = currentType.BaseType;
}
return methods.ToArray();
});
}
private static readonly HashSet<string> ExcludedAssemblyNames =
[
"mscorlib",
"System",
"System.Core",
"System.Runtime",
"System.Private.CoreLib",
"System.Collections",
"System.Linq",
"System.Threading",
"System.Text.RegularExpressions",
"System.Diagnostics.Debug",
"System.Runtime.Extensions",
"System.Collections.Concurrent",
"System.Text.Json",
"System.Memory",
"System.Net.Http",
"System.IO.FileSystem",
"System.Console",
"System.Diagnostics.Process",
"System.ComponentModel.TypeConverter",
"System.ComponentModel.Primitives",
"System.ObjectModel",
"System.Private.Uri",
"System.Private.Xml",
"netstandard",
// Microsoft platform assemblies
"Microsoft.CSharp",
"Microsoft.Win32.Primitives",
"Microsoft.Win32.Registry",
"Microsoft.VisualBasic.Core",
"Microsoft.VisualBasic",
// TUnit framework assemblies (except test projects)
"TUnit",
"TUnit.Core",
"TUnit.Engine",
"TUnit.Assertions",
// Test platform assemblies
"testhost",
"Microsoft.TestPlatform.CoreUtilities",
"Microsoft.TestPlatform.CommunicationUtilities",
"Microsoft.TestPlatform.CrossPlatEngine",
"Microsoft.TestPlatform.Common",
"Microsoft.TestPlatform.PlatformAbstractions",
"Microsoft.Testing.Platform",
// Common third-party assemblies
"Newtonsoft.Json",
"Castle.Core",
"Moq",
"xunit.core",
"xunit.assert",
"xunit.execution.desktop",
"nunit.framework",
"FluentAssertions",
"AutoFixture",
"FakeItEasy",
"Shouldly",
"NSubstitute",
"Rhino.Mocks"
];
private static bool ShouldScanAssembly(Assembly assembly)
{
var name = assembly.GetName().Name;
if (name == null)
{
return false;
}
if (ExcludedAssemblyNames.Contains(name))
{
return false;
}
if (name.EndsWith(".resources") || name.EndsWith(".XmlSerializers"))
{
return false;
}
if (assembly.IsDynamic)
{
return false;
}
try
{
var location = assembly.Location;
if (!string.IsNullOrEmpty(location) &&
(location.Contains("ref") ||
location.Contains("runtimes") ||
location.Contains("Microsoft.NETCore.App") ||
location.Contains("Microsoft.AspNetCore.App") ||
location.Contains("Microsoft.WindowsDesktop.App")))
{
return false;
}
}
catch
{
// In single-file mode, assembly.Location might throw - but we should still scan the assembly
// Don't return false here, continue with other checks
}
var referencedAssemblies = AssemblyReferenceCache.GetReferencedAssemblies(assembly);
var hasTUnitReference = false;
foreach (var reference in referencedAssemblies)
{
if (reference.Name != null && (reference.Name.StartsWith("TUnit") || reference.Name == "TUnit"))
{
hasTUnitReference = true;
break;
}
}
if (!hasTUnitReference)
{
return false;
}
return true;
}
private static async Task<List<TestMetadata>> DiscoverTestsInAssembly(Assembly assembly)
{
var discoveredTests = new List<TestMetadata>(100);
var types = _assemblyTypesCache.GetOrAdd(assembly, asm =>
{
try
{
return asm.GetTypes();
}
catch (ReflectionTypeLoadException reflectionTypeLoadException)
{
return reflectionTypeLoadException.Types.Where(static x => x != null).ToArray()!;
}
catch (Exception)
{
return [];
}
});
if (types.Length == 0)
{
return discoveredTests;
}
var filteredTypes = types.Where(static t => t.IsClass && !IsCompilerGenerated(t));
foreach (var type in filteredTypes)
{
if (type.IsAbstract)
{
continue;
}
if (type.IsGenericTypeDefinition)
{
var genericTests = await DiscoverGenericTests(type).ConfigureAwait(false);
discoveredTests.AddRange(genericTests);
continue;
}
MethodInfo[] testMethods;
try
{
// Check if this class inherits tests from base classes
var inheritsTests = type.IsDefined(typeof(InheritsTestsAttribute), inherit: false);
if (inheritsTests)
{
// Get all methods including inherited ones
// Optimize: Manual filtering instead of LINQ Where().ToArray()
var allMethods = GetAllTestMethods(type);
var testMethodsList = new List<MethodInfo>();
foreach (var method in allMethods)
{
if (method.IsDefined(typeof(TestAttribute), inherit: false) && !method.IsAbstract)
{
testMethodsList.Add(method);
}
}
testMethods = testMethodsList.ToArray();
}
else
{
var declaredMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
var testMethodsList = new List<MethodInfo>(declaredMethods.Length);
foreach (var method in declaredMethods)
{
if (method.IsDefined(typeof(TestAttribute), inherit: false) && !method.IsAbstract)
{
testMethodsList.Add(method);
}
}
testMethods = testMethodsList.ToArray();
}
}
catch (Exception)
{
continue;
}
foreach (var method in testMethods)
{
try
{
discoveredTests.Add(await BuildTestMetadata(type, method).ConfigureAwait(false));
}
catch (Exception ex)
{
var failedTest = CreateFailedTestMetadata(type, method, ex);
discoveredTests.Add(failedTest);
}
}
}
return discoveredTests;
}
private static async IAsyncEnumerable<TestMetadata> DiscoverTestsInAssemblyStreamingAsync(
Assembly assembly,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var types = _assemblyTypesCache.GetOrAdd(assembly, asm =>
{
try
{
// In single file mode, GetExportedTypes might miss some types
// Use GetTypes() instead which gets all types including nested ones
return asm.GetTypes();
}
catch (ReflectionTypeLoadException rtle)
{
// Some types might fail to load, but we can still use the ones that loaded successfully
// Optimize: Manual filtering with ArrayPool for better memory efficiency
var loadedTypes = rtle.Types;
if (loadedTypes == null)
{
return [];
}
// Use ArrayPool for temporary storage to reduce allocations
var tempArray = ArrayPool<Type>.Shared.Rent(loadedTypes.Length);
try
{
var validCount = 0;
foreach (var type in loadedTypes)
{
if (type != null)
{
tempArray[validCount++] = type;
}
}
var result = new Type[validCount];
Array.Copy(tempArray, result, validCount);
return result;
}
finally
{
ArrayPool<Type>.Shared.Return(tempArray);
}
}
catch (Exception)
{
return [];
}
});
if (types.Length == 0)
{
yield break;
}
var filteredTypes = types.Where(static t => t.IsClass && !IsCompilerGenerated(t));
foreach (var type in filteredTypes)
{
cancellationToken.ThrowIfCancellationRequested();
// Skip abstract types - they can't be instantiated
if (type.IsAbstract)
{
continue;
}
// Handle generic type definitions specially
if (type.IsGenericTypeDefinition)
{
await foreach (var genericTest in DiscoverGenericTestsStreamingAsync(type, cancellationToken))
{
yield return genericTest;
}
continue;
}
MethodInfo[] testMethods;
try
{
// Check if this class inherits tests from base classes
var inheritsTests = type.IsDefined(typeof(InheritsTestsAttribute), inherit: false);
if (inheritsTests)
{
// Get all test methods including inherited ones
testMethods = GetAllTestMethods(type)
.Where(static m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract)
.ToArray();
}
else
{
// Only get declared test methods
testMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly)
.Where(static m => m.IsDefined(typeof(TestAttribute), inherit: false) && !m.IsAbstract)
.ToArray();
}
}
catch (Exception)
{
continue;
}
foreach (var method in testMethods)
{
cancellationToken.ThrowIfCancellationRequested();
TestMetadata? testMetadata = null;
TestMetadata? failedMetadata = null;
try
{
// Prevent duplicate test metadata for inherited tests
if (method.DeclaringType != type && !type.IsDefined(typeof(InheritsTestsAttribute), inherit: false))
{
continue;
}
testMetadata = await BuildTestMetadata(type, method).ConfigureAwait(false);
}
catch (Exception ex)
{
// Create a failed test metadata for discovery failures
failedMetadata = CreateFailedTestMetadata(type, method, ex);
}
if (testMetadata != null)
{
yield return testMetadata;
}
else if (failedMetadata != null)
{
yield return failedMetadata;
}
}
}
}
private static async Task<List<TestMetadata>> DiscoverGenericTests(Type genericTypeDefinition)
{
var discoveredTests = new List<TestMetadata>(100);
// Extract class-level data sources that will determine the generic type arguments
var classDataSources = ReflectionAttributeExtractor.ExtractDataSources(genericTypeDefinition);
if (classDataSources.Length == 0)
{
// This is expected for generic test classes in reflection mode
// They need data sources to determine concrete types
return discoveredTests;
}
// Get test methods from the generic type definition
// Optimize: Manual filtering instead of LINQ Where().ToArray()
var declaredMethods = genericTypeDefinition.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
var testMethodsList = new List<MethodInfo>(declaredMethods.Length);
foreach (var method in declaredMethods)
{
if (method.IsDefined(typeof(TestAttribute), inherit: false) && !method.IsAbstract)
{
testMethodsList.Add(method);
}
}
var testMethods = testMethodsList.ToArray();
if (testMethods.Length == 0)
{
return discoveredTests;
}
// For each data source combination, create a concrete generic type
foreach (var dataSource in classDataSources)
{
var dataItems = await GetDataFromSourceAsync(dataSource, null!).ConfigureAwait(false);
foreach (var dataRow in dataItems)
{
if (dataRow == null || dataRow.Length == 0)
{
continue;
}
// Determine generic type arguments from the data
var typeArguments = ReflectionGenericTypeResolver.DetermineGenericTypeArguments(genericTypeDefinition, dataRow);
if (typeArguments == null || typeArguments.Length == 0)
{
continue;
}
try
{
// Create concrete type with validation
var concreteType = ReflectionGenericTypeResolver.CreateConcreteType(genericTypeDefinition, typeArguments);
// Build tests for each method in the concrete type
foreach (var genericMethod in testMethods)
{
var concreteMethod = concreteType.GetMethod(genericMethod.Name,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
if (concreteMethod != null)
{
// Build test metadata for the concrete type
// The concrete type already has its generic arguments resolved
// For generic types with primary constructors that were resolved from class-level data sources,
// we need to ensure the class data sources contain the specific data for this instantiation
var testMetadata = await BuildTestMetadata(concreteType, concreteMethod, dataRow).ConfigureAwait(false);
discoveredTests.Add(testMetadata);
}
}
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to create concrete type for {genericTypeDefinition.FullName ?? genericTypeDefinition.Name}. " +
$"Error: {ex.Message}. " +
$"Generic parameter count: {genericTypeDefinition.GetGenericArguments().Length}, " +
$"Type arguments provided: {typeArguments?.Length ?? 0}, " +
$"Data row length: {dataRow?.Length ?? 0}", ex);
}
}
}
return discoveredTests;
}
private static async IAsyncEnumerable<TestMetadata> DiscoverGenericTestsStreamingAsync(
Type genericTypeDefinition,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Extract class-level data sources that will determine the generic type arguments
var classDataSources = ReflectionAttributeExtractor.ExtractDataSources(genericTypeDefinition);
if (classDataSources.Length == 0)
{
// This is expected for generic test classes in reflection mode
// They need data sources to determine concrete types
yield break;
}
// Get test methods from the generic type definition
// Optimize: Manual filtering instead of LINQ Where().ToArray()
var declaredMethods = genericTypeDefinition.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
var testMethodsList = new List<MethodInfo>(declaredMethods.Length);
foreach (var method in declaredMethods)
{
if (method.IsDefined(typeof(TestAttribute), inherit: false) && !method.IsAbstract)
{
testMethodsList.Add(method);
}
}
var testMethods = testMethodsList.ToArray();
if (testMethods.Length == 0)
{
yield break;
}
// For each data source combination, create a concrete generic type
foreach (var dataSource in classDataSources)
{
cancellationToken.ThrowIfCancellationRequested();
var dataItems = await GetDataFromSourceAsync(dataSource, null!).ConfigureAwait(false);
foreach (var dataRow in dataItems)
{
cancellationToken.ThrowIfCancellationRequested();
if (dataRow == null || dataRow.Length == 0)
{
continue;
}
// Determine generic type arguments from the data
var typeArguments = ReflectionGenericTypeResolver.DetermineGenericTypeArguments(genericTypeDefinition, dataRow);
if (typeArguments == null || typeArguments.Length == 0)
{
continue;
}
TestMetadata? failedMetadata = null;
List<TestMetadata>? successfulTests = null;
try
{
// Create concrete type with validation
var concreteType = ReflectionGenericTypeResolver.CreateConcreteType(genericTypeDefinition, typeArguments);
// Build tests for each method in the concrete type
foreach (var genericMethod in testMethods)
{
var concreteMethod = concreteType.GetMethod(genericMethod.Name,
BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly);
if (concreteMethod != null)
{
// Build test metadata for the concrete type
// The concrete type already has its generic arguments resolved
// For generic types with primary constructors that were resolved from class-level data sources,
// we need to ensure the class data sources contain the specific data for this instantiation
var testMetadata = await BuildTestMetadata(concreteType, concreteMethod, dataRow).ConfigureAwait(false);
if (successfulTests == null)
{
successfulTests =
[
];
}
successfulTests.Add(testMetadata);
}
}
}
catch (Exception ex)
{
failedMetadata = new FailedTestMetadata(
new InvalidOperationException(
$"Failed to create concrete type for {genericTypeDefinition.FullName ?? genericTypeDefinition.Name}. " +
$"Error: {ex.Message}. " +
$"Generic parameter count: {genericTypeDefinition.GetGenericArguments().Length}, " +
$"Type arguments: {string.Join(", ", typeArguments?.Select(static t => t.Name) ?? [
])}", ex),
$"[GENERIC TYPE CREATION FAILED] {genericTypeDefinition.Name}")
{
TestName = $"[GENERIC TYPE CREATION FAILED] {genericTypeDefinition.Name}",
TestClassType = genericTypeDefinition,
TestMethodName = "GenericTypeCreationFailed",
FilePath = "Unknown",
LineNumber = 0,
MethodMetadata = CreateDummyMethodMetadata(genericTypeDefinition, "GenericTypeCreationFailed"),
AttributeFactory = () => [],
DataSources = [],
ClassDataSources = [],
PropertyDataSources = []
};
}
// Yield successful tests first
if (successfulTests != null)
{
foreach (var test in successfulTests)
{
yield return test;
}
}
// Then yield failed metadata if any
if (failedMetadata != null)
{
yield return failedMetadata;
}
}
}
}
private static async Task<List<object?[]>> GetDataFromSourceAsync(IDataSourceAttribute dataSource, MethodMetadata methodMetadata)
{
var data = new List<object?[]>(16);
try
{
// Use the centralized factory for generic type discovery
var metadata = DataGeneratorMetadataCreator.CreateForGenericTypeDiscovery(dataSource, methodMetadata);
// Get data rows from the source
await foreach (var rowFactory in dataSource.GetDataRowsAsync(metadata))
{
var dataArray = await rowFactory().ConfigureAwait(false);
if (dataArray != null)
{
data.Add(dataArray);
}
}
}
catch (Exception ex)
{
throw new InvalidOperationException(
$"Failed to get data from source: {ex.Message}", ex);
}
return await Task.FromResult(data).ConfigureAwait(false);
}
private static int CalculateInheritanceDepth(Type testClass, MethodInfo testMethod)
{
// If the method is declared directly in the test class, depth is 0
if (testMethod.DeclaringType == testClass)
{
return 0;
}
// Count how many levels up the inheritance chain the method is declared
var depth = 0;
var currentType = testClass.BaseType;
while (currentType != null && currentType != typeof(object))
{
depth++;
if (testMethod.DeclaringType == currentType)
{
return depth;
}
currentType = currentType.BaseType;
}
// This shouldn't happen in normal cases, but return the depth anyway
return depth;
}
private static Task<TestMetadata> BuildTestMetadata(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields | DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)]
Type testClass,
MethodInfo testMethod,
object?[]? classData = null)
{
var testName = GenerateTestName(testClass, testMethod);
var inheritanceDepth = CalculateInheritanceDepth(testClass, testMethod);
// Determine the actual class type for generic type resolution
// If the method is declared in a generic base class, use the constructed version from the inheritance hierarchy
var typeForGenericResolution = testClass;
if (testMethod.DeclaringType != null &&
testMethod.DeclaringType != testClass &&
testMethod.DeclaringType.IsGenericTypeDefinition)
{
// Find the constructed generic type in the inheritance chain
var baseType = testClass.BaseType;
while (baseType != null)
{
if (baseType.IsGenericType &&
baseType.GetGenericTypeDefinition() == testMethod.DeclaringType)
{
typeForGenericResolution = baseType;
break;
}
baseType = baseType.BaseType;
}
}
try
{
return Task.FromResult<TestMetadata>(new ReflectionTestMetadata(testClass, testMethod)
{
TestName = testName,
TestClassType = typeForGenericResolution, // Use resolved type for generic resolution (may be constructed generic base)
TestMethodName = testMethod.Name,
Dependencies = ReflectionAttributeExtractor.ExtractDependencies(testClass, testMethod),
DataSources = ReflectionAttributeExtractor.ExtractDataSources(testMethod),
ClassDataSources = classData != null
? [new StaticDataSourceAttribute(new[] { classData })]
: ReflectionAttributeExtractor.ExtractDataSources(testClass),
PropertyDataSources = ReflectionAttributeExtractor.ExtractPropertyDataSources(testClass),
InstanceFactory = CreateInstanceFactory(testClass)!,
TestInvoker = CreateTestInvoker(testClass, testMethod),
FilePath = ExtractFilePath(testMethod) ?? "Unknown",
LineNumber = ExtractLineNumber(testMethod) ?? 0,
MethodMetadata = ReflectionMetadataBuilder.CreateMethodMetadata(testClass, testMethod),
GenericTypeInfo = ReflectionGenericTypeResolver.ExtractGenericTypeInfo(typeForGenericResolution),
GenericMethodInfo = ReflectionGenericTypeResolver.ExtractGenericMethodInfo(testMethod),
GenericMethodTypeArguments = testMethod.IsGenericMethodDefinition ? null : testMethod.GetGenericArguments(),
AttributeFactory = () => ReflectionAttributeExtractor.GetAllAttributes(testClass, testMethod),
RepeatCount = testMethod.GetCustomAttribute<RepeatAttribute>()?.Times
?? testClass.GetCustomAttribute<RepeatAttribute>()?.Times,
PropertyInjections = PropertySourceRegistry.DiscoverInjectableProperties(testClass),
InheritanceDepth = inheritanceDepth
});
}
catch (Exception ex)
{
return Task.FromResult(CreateFailedTestMetadata(testClass, testMethod, ex));
}
}
private static string GenerateTestName(Type testClass, MethodInfo testMethod)
{
// Check for DisplayNameAttribute and extract the template
var displayNameAttr = testMethod.GetCustomAttribute<DisplayNameAttribute>();
if (displayNameAttr != null)
{
// Extract the display name template from the attribute
// We can't fully process it here because we don't have parameter values yet
// But we can at least show the template for tests without parameters
var displayNameField = typeof(DisplayNameAttribute).GetField("displayName",
BindingFlags.NonPublic | BindingFlags.Instance);
if (displayNameField != null)
{
var displayNameValue = displayNameField.GetValue(displayNameAttr) as string;
if (!string.IsNullOrEmpty(displayNameValue) && !displayNameValue!.Contains("$"))
{
// If the display name doesn't have parameter placeholders, use it directly
return displayNameValue;
}
}
}
// Default format - just method name to match source generation
return testMethod.Name;
}
private static Func<Type[], object?[], object> CreateInstanceFactory([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type testClass)
{
// For generic types, we need to handle MakeGenericType
if (testClass.IsGenericTypeDefinition)
{
return (typeArgs, args) =>
{
if (typeArgs == null || typeArgs.Length == 0)
{
throw new InvalidOperationException(
$"Cannot create instance of generic type definition {testClass.FullName} without type arguments.");
}
if (typeArgs.Length != testClass.GetGenericArguments().Length)
{
throw new InvalidOperationException(
$"Type argument count mismatch for {testClass.FullName}: expected {testClass.GetGenericArguments().Length}, got {typeArgs.Length}");
}
var closedType = testClass.MakeGenericType(typeArgs);
if (args.Length == 0)
{
return Activator.CreateInstance(closedType)!;
}
return Activator.CreateInstance(closedType, args)!;
};
}
// For already-constructed generic types (e.g., from DiscoverGenericTests)
// we don't need type arguments - the type is already closed
if (testClass.IsConstructedGenericType)
{
var constructedTypeConstructors = testClass.GetConstructors();
if (constructedTypeConstructors.Length == 0)
{
return (_, _) => Activator.CreateInstance(testClass)!;
}
var constructedTypeCtor = constructedTypeConstructors.FirstOrDefault(static c => c.GetParameters().Length == 0) ?? constructedTypeConstructors.First();
var constructedTypeFactory = CreateReflectionInstanceFactory(constructedTypeCtor);
// Return a factory that ignores type arguments since the type is already closed
return (_, args) => constructedTypeFactory(args);
}
var constructors = testClass.GetConstructors();
if (constructors.Length == 0)
{
return (_, _) => Activator.CreateInstance(testClass)!;
}
var ctor = constructors.FirstOrDefault(static c => c.GetParameters().Length == 0) ?? constructors.First();
var factory = CreateReflectionInstanceFactory(ctor);
return (_, args) => factory(args);
}
private static Func<object, object?[], Task> CreateTestInvoker(Type testClass, MethodInfo testMethod)
{
return CreateReflectionTestInvoker(testClass, testMethod);
}