-
-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathAotTestDataCollector.cs
More file actions
367 lines (331 loc) · 15.2 KB
/
AotTestDataCollector.cs
File metadata and controls
367 lines (331 loc) · 15.2 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
using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using TUnit.Core;
using TUnit.Engine.Building.Interfaces;
namespace TUnit.Engine.Building.Collectors;
/// <summary>
/// AOT-compatible test data collector that uses source-generated test metadata.
/// Operates without reflection by leveraging pre-compiled test sources.
/// </summary>
internal sealed class AotTestDataCollector : ITestDataCollector, IStreamingTestDataCollector
{
private readonly HashSet<Type>? _filterTypes;
public AotTestDataCollector(HashSet<Type>? filterTypes)
{
_filterTypes = filterTypes;
}
public async Task<IEnumerable<TestMetadata>> CollectTestsAsync(string testSessionId)
{
// Compatibility method - collects all from streaming
var tests = new List<TestMetadata>();
await foreach (var test in CollectTestsStreamingAsync(testSessionId, CancellationToken.None))
{
tests.Add(test);
}
return tests;
}
public async IAsyncEnumerable<TestMetadata> CollectTestsStreamingAsync(
string testSessionId,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
// Stream from all test sources
var testSources = Sources.TestSources
.Where(kvp => _filterTypes == null || _filterTypes.Contains(kvp.Key))
.SelectMany(kvp => kvp.Value);
// Stream tests from each source
foreach (var testSource in testSources)
{
cancellationToken.ThrowIfCancellationRequested();
await foreach (var metadata in testSource.GetTestsAsync(testSessionId, cancellationToken))
{
yield return metadata;
}
}
// Also stream dynamic tests
await foreach (var metadata in CollectDynamicTestsStreaming(testSessionId, cancellationToken))
{
yield return metadata;
}
}
private async IAsyncEnumerable<TestMetadata> CollectDynamicTestsStreaming(
string testSessionId,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
if (Sources.DynamicTestSources.Count == 0)
{
yield break;
}
// Stream from each dynamic test source
foreach (var source in Sources.DynamicTestSources)
{
cancellationToken.ThrowIfCancellationRequested();
IEnumerable<DynamicTest> dynamicTests;
try
{
dynamicTests = source.CollectDynamicTests(testSessionId);
}
catch (Exception ex)
{
// Create a failed test metadata for this dynamic test source
yield return CreateFailedTestMetadataForDynamicSource(source, ex);
continue;
}
foreach (var dynamicTest in dynamicTests)
{
// Convert each dynamic test to test metadata and stream
await foreach (var metadata in ConvertDynamicTestToMetadataStreaming(dynamicTest, cancellationToken))
{
yield return metadata;
}
}
}
}
private async IAsyncEnumerable<TestMetadata> ConvertDynamicTestToMetadataStreaming(
DynamicTest dynamicTest,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
foreach (var discoveryResult in dynamicTest.GetTests())
{
cancellationToken.ThrowIfCancellationRequested();
if (discoveryResult is DynamicDiscoveryResult { TestMethod: not null } dynamicResult)
{
var testMetadata = await CreateMetadataFromDynamicDiscoveryResult(dynamicResult);
yield return testMetadata;
}
}
}
private Task<TestMetadata> CreateMetadataFromDynamicDiscoveryResult(DynamicDiscoveryResult result)
{
if (result.TestClassType == null || result.TestMethod == null)
{
throw new InvalidOperationException("Dynamic test discovery result must have a test class type and method");
}
// Extract method info from the expression
System.Reflection.MethodInfo? methodInfo = null;
var lambdaExpression = result.TestMethod as LambdaExpression;
if (lambdaExpression?.Body is MethodCallExpression methodCall)
{
methodInfo = methodCall.Method;
}
else if (lambdaExpression?.Body is UnaryExpression { Operand: MethodCallExpression unaryMethodCall })
{
methodInfo = unaryMethodCall.Method;
}
if (methodInfo == null)
{
throw new InvalidOperationException("Could not extract method info from dynamic test expression");
}
var testName = methodInfo.Name;
return Task.FromResult<TestMetadata>(new AotDynamicTestMetadata(result)
{
TestName = testName,
#pragma warning disable IL2072
TestClassType = result.TestClassType,
#pragma warning restore IL2072
TestMethodName = methodInfo.Name,
Dependencies = result.Attributes.OfType<DependsOnAttribute>().Select(a => a.ToTestDependency()).ToArray(),
DataSources = [], // Dynamic tests don't use data sources in the same way
ClassDataSources = [],
PropertyDataSources = [],
InstanceFactory = CreateAotDynamicInstanceFactory(result.TestClassType, result.TestClassArguments)!,
TestInvoker = CreateAotDynamicTestInvoker(result),
ParameterCount = result.TestMethodArguments?.Length ?? 0,
ParameterTypes = methodInfo.GetParameters().Select(p => p.ParameterType).ToArray(),
TestMethodParameterTypes = methodInfo.GetParameters().Select(p => p.ParameterType.FullName ?? p.ParameterType.Name).ToArray(),
FilePath = null,
LineNumber = null,
MethodMetadata = ReflectionMetadataBuilder.CreateMethodMetadata(result.TestClassType, methodInfo),
GenericTypeInfo = null,
GenericMethodInfo = null,
GenericMethodTypeArguments = null,
AttributeFactory = () => result.Attributes.ToArray(),
#pragma warning disable IL2072
PropertyInjections = PropertyInjectionService.DiscoverInjectableProperties(result.TestClassType)
#pragma warning restore IL2072
});
}
[UnconditionalSuppressMessage("Trimming",
"IL2070:'this' argument does not satisfy 'DynamicallyAccessedMemberTypes.PublicConstructors' in call to 'System.Type.GetConstructors()'",
Justification = "AOT mode uses source-generated factories")]
[UnconditionalSuppressMessage("Trimming",
"IL2067:Target parameter does not satisfy annotation requirements",
Justification = "AOT mode uses source-generated factories")]
[UnconditionalSuppressMessage("Trimming",
"IL2072:Target method return value does not have matching annotations",
Justification = "AOT mode uses source-generated factories")]
[UnconditionalSuppressMessage("Trimming",
"IL2055:Call to 'MakeGenericType' can not be statically analyzed",
Justification = "Dynamic tests may use generic types")]
[UnconditionalSuppressMessage("AOT",
"IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling",
Justification = "Dynamic tests require dynamic code generation")]
private static Func<Type[], object?[], object>? CreateAotDynamicInstanceFactory(Type testClass, object?[]? predefinedClassArgs)
{
// For dynamic tests, we always use the predefined args (or empty array if null)
var classArgs = predefinedClassArgs ?? [];
return (typeArgs, args) =>
{
// Always use the predefined class args, ignoring the args parameter
if (testClass.IsGenericTypeDefinition && typeArgs.Length > 0)
{
var closedType = testClass.MakeGenericType(typeArgs);
if (classArgs.Length == 0)
{
return Activator.CreateInstance(closedType)!;
}
return Activator.CreateInstance(closedType, classArgs)!;
}
if (classArgs.Length == 0)
{
return Activator.CreateInstance(testClass)!;
}
return Activator.CreateInstance(testClass, classArgs)!;
};
}
private static Func<object, object?[], Task> CreateAotDynamicTestInvoker(DynamicDiscoveryResult result)
{
return async (instance, args) =>
{
try
{
if (result.TestMethod == null)
{
throw new InvalidOperationException("Dynamic test method expression is null");
}
// Since we're in AOT mode, we need to handle this differently
// The expression should already be compiled in source generation
var lambdaExpression = result.TestMethod as LambdaExpression;
if (lambdaExpression == null)
{
throw new InvalidOperationException("Dynamic test method must be a lambda expression");
}
var compiledExpression = lambdaExpression.Compile();
var testInstance = instance ?? throw new InvalidOperationException("Test instance is null");
// The expression is already bound to the correct method with arguments
// so we just need to invoke it with the instance
var invokeMethod = compiledExpression.GetType().GetMethod("Invoke")!;
var invokeResult = invokeMethod.Invoke(compiledExpression, new[] { testInstance });
if (invokeResult is Task task)
{
await task;
}
else if (invokeResult is ValueTask valueTask)
{
await valueTask;
}
}
catch (System.Reflection.TargetInvocationException tie)
{
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Capture(tie.InnerException ?? tie).Throw();
throw;
}
};
}
[UnconditionalSuppressMessage("Trimming", "IL2072:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttribute\' in call to target method. The return value of the source method does not have matching annotations.",
Justification = "We won't instantiate this since it failed")]
private static TestMetadata CreateFailedTestMetadataForDynamicSource(IDynamicTestSource source, Exception ex)
{
var testName = $"[DYNAMIC SOURCE FAILED] {source.GetType().Name}";
return new FailedDynamicTestMetadata(ex)
{
TestName = testName,
TestClassType = source.GetType(),
TestMethodName = "CollectDynamicTests",
MethodMetadata = CreateDummyMethodMetadata(source.GetType(), "CollectDynamicTests"),
AttributeFactory = () => [],
DataSources = [],
ClassDataSources = [],
PropertyDataSources = []
};
}
[UnconditionalSuppressMessage("Trimming",
"IL2067:Target parameter does not satisfy annotation requirements",
Justification = "Dynamic test metadata creation")]
[UnconditionalSuppressMessage("Trimming",
"IL2072:Target method return value does not have matching annotations",
Justification = "Dynamic test metadata creation")]
private static MethodMetadata CreateDummyMethodMetadata(Type type, string methodName)
{
return new MethodMetadata
{
Name = methodName,
Type = type,
Class = new ClassMetadata
{
Name = type.Name,
Type = type,
TypeReference = TypeReference.CreateConcrete(type.AssemblyQualifiedName!),
Namespace = type.Namespace ?? string.Empty,
Assembly = new AssemblyMetadata
{
Name = type.Assembly.GetName().Name ?? "Unknown"
},
Parameters = [],
Properties = [],
Parent = null
},
Parameters = [],
GenericTypeCount = 0,
ReturnTypeReference = TypeReference.CreateConcrete(typeof(void).AssemblyQualifiedName!),
ReturnType = typeof(void),
TypeReference = TypeReference.CreateConcrete(type.AssemblyQualifiedName!)
};
}
private sealed class AotDynamicTestMetadata(DynamicDiscoveryResult dynamicResult) : TestMetadata, IDynamicTestMetadata
{
public override Func<ExecutableTestCreationContext, TestMetadata, AbstractExecutableTest> CreateExecutableTestFactory
{
get => (context, metadata) =>
{
// For dynamic tests, we need to use the specific arguments from the dynamic result
var modifiedContext = new ExecutableTestCreationContext
{
TestId = context.TestId,
DisplayName = context.DisplayName,
Arguments = dynamicResult.TestMethodArguments ?? context.Arguments,
ClassArguments = dynamicResult.TestClassArguments ?? context.ClassArguments,
Context = context.Context
};
// Create instance and test invoker for the dynamic test
Func<TestContext, Task<object>> createInstance = (TestContext testContext) =>
{
var instance = metadata.InstanceFactory(Type.EmptyTypes, modifiedContext.ClassArguments);
// Handle property injections
foreach (var propertyInjection in metadata.PropertyInjections)
{
var value = propertyInjection.ValueFactory();
propertyInjection.Setter(instance, value);
}
return Task.FromResult(instance);
};
var invokeTest = metadata.TestInvoker ?? throw new InvalidOperationException("Test invoker is null");
return new ExecutableTest(createInstance,
async (instance, args, context, ct) => await invokeTest(instance, args))
{
TestId = modifiedContext.TestId,
Metadata = metadata,
Arguments = modifiedContext.Arguments,
ClassArguments = modifiedContext.ClassArguments,
Context = modifiedContext.Context
};
};
}
}
private sealed class FailedDynamicTestMetadata(Exception exception) : TestMetadata
{
public override Func<ExecutableTestCreationContext, TestMetadata, AbstractExecutableTest> CreateExecutableTestFactory
{
get => (context, metadata) => new FailedExecutableTest(exception)
{
TestId = context.TestId,
Metadata = metadata,
Arguments = context.Arguments,
ClassArguments = context.ClassArguments,
Context = context.Context
};
}
}
}