Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions TUnit.Core.SourceGenerator.Tests/Bugs/5118/Tests5118.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

namespace TUnit.Core.SourceGenerator.Tests.Bugs._5118;

internal class Tests5118 : TestsBase
{
[Test]
public Task Test() => RunTest(Path.Combine(Git.RootDirectory.FullName,
"TUnit.TestProject",
"Bugs",
"5118",
"AsyncClassMethodDataSourceTests.cs"),
async generatedFiles =>
{
await Assert.That(generatedFiles).HasCount().EqualTo(1);
});
}
154 changes: 154 additions & 0 deletions TUnit.Core.SourceGenerator.Tests/Tests5118.Test.verified.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// <auto-generated/>
#pragma warning disable

#nullable enable
namespace TUnit.Generated;
[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
[global::System.CodeDom.Compiler.GeneratedCode("TUnit", "VERSION_SCRUBBED")]
internal static class TUnit_TestProject_Bugs__5118_AsyncClassMethodDataSourceTests__TestSource
{
public static global::System.Collections.Generic.IReadOnlyList<global::TUnit.Core.TestMetadata> GetTests(string testSessionId)
{
var __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests", new global::TUnit.Core.ClassMetadata
{
Type = typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests),
TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests)),
Name = "AsyncClassMethodDataSourceTests",
Namespace = "TUnit.TestProject.Bugs._5118",
Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"),
Parameters = new global::TUnit.Core.ParameterMetadata[]
{
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "Id", new global::TUnit.Core.ConcreteType(typeof(int)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[0]),
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(string), "Name", new global::TUnit.Core.ConcreteType(typeof(string)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[1]),
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(global::System.DateTime), "CreatedAt", new global::TUnit.Core.ConcreteType(typeof(global::System.DateTime)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[2])
},
Properties = global::System.Array.Empty<global::TUnit.Core.PropertyMetadata>(),
Parent = null
});
var __classType = typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests);
var metadata_TestWithAsyncComplexData__CancellationToken = global::TUnit.Core.TestMetadataFactory.Create<global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests>(
"TestWithAsyncComplexData", "TestWithAsyncComplexData", 22,
__InvokeTest_TestWithAsyncComplexData__CancellationToken, __CreateAttributes_0, CreateInstance,
global::TUnit.Core.MethodMetadataFactory.Create("TestWithAsyncComplexData", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: new global::TUnit.Core.ParameterMetadata[]
{
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(global::System.Threading.CancellationToken), "token", new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.CancellationToken)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetMethod("TestWithAsyncComplexData", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0])
}),
classDataSources: new global::TUnit.Core.IDataSourceAttribute[]
{
new global::TUnit.Core.MethodDataSourceAttribute("GetAsyncTestData")
{
Factory = (dataGeneratorMetadata) =>
{
async global::System.Collections.Generic.IAsyncEnumerable<global::System.Func<global::System.Threading.Tasks.Task<object?[]?>>> Factory()
{
var result = global::TUnit.TestProject.Bugs._5118.AsyncTestDataSources.GetAsyncTestData();
await foreach (var item in result)
{
yield return () => global::System.Threading.Tasks.Task.FromResult(global::TUnit.Core.Helpers.DataSourceHelpers.ToObjectArray(item));
}
}
return Factory();
}
},
},
testSessionId: testSessionId
);
return new global::TUnit.Core.TestMetadata[] { metadata_TestWithAsyncComplexData__CancellationToken };
}
public static global::System.Collections.Generic.IEnumerable<global::TUnit.Core.TestDescriptor> EnumerateTestDescriptors()
{
yield return new global::TUnit.Core.TestDescriptor
{
TestId = "TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests.TestWithAsyncComplexData",
ClassName = "AsyncClassMethodDataSourceTests",
MethodName = "TestWithAsyncComplexData",
FullyQualifiedName = "TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests.TestWithAsyncComplexData",
FilePath = @"",
LineNumber = 22,
Categories = global::System.Array.Empty<string>(),
Properties = global::System.Array.Empty<string>(),
HasDataSource = true,
RepeatCount = 0,
DependsOn = global::System.Array.Empty<string>(),
Materializer = __Materialize_TestWithAsyncComplexData__CancellationToken
};
}
private static global::System.Attribute[] __CreateAttributes_0()
{
return
[
new global::TUnit.Core.TestAttribute(),
new global::TUnit.Core.TimeoutAttribute(5000),
new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass),
new global::TUnit.Core.MethodDataSourceAttribute<global::TUnit.TestProject.Bugs._5118.AsyncTestDataSources>("GetAsyncTestData")
];
}
private static global::System.Threading.Tasks.ValueTask __InvokeTest_TestWithAsyncComplexData__CancellationToken(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests instance, object?[] args, global::System.Threading.CancellationToken cancellationToken)
{
try
{
return new global::System.Threading.Tasks.ValueTask(instance.TestWithAsyncComplexData(cancellationToken));
}
catch (global::System.Exception ex)
{
return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex));
}
}
private static global::System.Collections.Generic.IReadOnlyList<global::TUnit.Core.TestMetadata> __Materialize_TestWithAsyncComplexData__CancellationToken(string testSessionId)
{
var __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests", new global::TUnit.Core.ClassMetadata
{
Type = typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests),
TypeInfo = new global::TUnit.Core.ConcreteType(typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests)),
Name = "AsyncClassMethodDataSourceTests",
Namespace = "TUnit.TestProject.Bugs._5118",
Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"),
Parameters = new global::TUnit.Core.ParameterMetadata[]
{
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "Id", new global::TUnit.Core.ConcreteType(typeof(int)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[0]),
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(string), "Name", new global::TUnit.Core.ConcreteType(typeof(string)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[1]),
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(global::System.DateTime), "CreatedAt", new global::TUnit.Core.ConcreteType(typeof(global::System.DateTime)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetConstructor(new global::System.Type[] { typeof(int), typeof(string), typeof(global::System.DateTime) })!.GetParameters()[2])
},
Properties = global::System.Array.Empty<global::TUnit.Core.PropertyMetadata>(),
Parent = null
});
var __classType = typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests);
var metadata = global::TUnit.Core.TestMetadataFactory.Create<global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests>(
"TestWithAsyncComplexData", "TestWithAsyncComplexData", 22,
__InvokeTest_TestWithAsyncComplexData__CancellationToken, __CreateAttributes_0, CreateInstance,
global::TUnit.Core.MethodMetadataFactory.Create("TestWithAsyncComplexData", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: new global::TUnit.Core.ParameterMetadata[]
{
global::TUnit.Core.ParameterMetadataFactory.Create(typeof(global::System.Threading.CancellationToken), "token", new global::TUnit.Core.ConcreteType(typeof(global::System.Threading.CancellationToken)), false, reflectionInfoFactory: static () => typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests).GetMethod("TestWithAsyncComplexData", global::System.Reflection.BindingFlags.Public | global::System.Reflection.BindingFlags.NonPublic | global::System.Reflection.BindingFlags.Instance, null, new global::System.Type[] { typeof(global::System.Threading.CancellationToken) }, null)!.GetParameters()[0])
}),
classDataSources: new global::TUnit.Core.IDataSourceAttribute[]
{
new global::TUnit.Core.MethodDataSourceAttribute("GetAsyncTestData")
{
Factory = (dataGeneratorMetadata) =>
{
async global::System.Collections.Generic.IAsyncEnumerable<global::System.Func<global::System.Threading.Tasks.Task<object?[]?>>> Factory()
{
var result = global::TUnit.TestProject.Bugs._5118.AsyncTestDataSources.GetAsyncTestData();
await foreach (var item in result)
{
yield return () => global::System.Threading.Tasks.Task.FromResult(global::TUnit.Core.Helpers.DataSourceHelpers.ToObjectArray(item));
}
}
return Factory();
}
},
},
testSessionId: testSessionId
);
return new global::TUnit.Core.TestMetadata[] { metadata };
}
internal static global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests CreateInstance(global::System.Type[] typeArgs, object?[] args)
{
return new global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests(global::TUnit.Core.Helpers.CastHelper.Cast<int>(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast<string>(args[1]), global::TUnit.Core.Helpers.CastHelper.Cast<global::System.DateTime>(args[2]));
}
[global::System.Runtime.CompilerServices.ModuleInitializer]
internal static void Initialize()
{
global::TUnit.Core.SourceRegistrar.Register(typeof(global::TUnit.TestProject.Bugs._5118.AsyncClassMethodDataSourceTests), TUnit_TestProject_Bugs__5118_AsyncClassMethodDataSourceTests__TestSource.GetTests, TUnit_TestProject_Bugs__5118_AsyncClassMethodDataSourceTests__TestSource.EnumerateTestDescriptors);
}
}
15 changes: 13 additions & 2 deletions TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,16 @@ private static void GenerateMethodDataSourceAttribute(CodeWriter writer, Attribu
{
// MethodDataSource(string) overload
methodName = attr.ConstructorArguments[0].Value?.ToString();
targetType = typeSymbol;

// Check for MethodDataSource<T> generic variant - extract T from type arguments
if (attr.AttributeClass is { IsGenericType: true })
{
targetType = attr.AttributeClass.TypeArguments[0];
}
else
{
targetType = typeSymbol;
}
}

if (string.IsNullOrEmpty(methodName))
Expand Down Expand Up @@ -894,7 +903,9 @@ private static void GenerateMethodDataSourceAttribute(CodeWriter writer, Attribu
}
else
{
// MethodDataSource(string) constructor
// MethodDataSource(string) constructor — ClassProvidingDataSource is intentionally null here
// because the Factory delegate (set below) already encodes the correct target type directly.
// The runtime attribute only needs ClassProvidingDataSource for reflection-based lookup.
writer.AppendLine($"new {attrTypeName}(\"{methodName}\")");
}
writer.AppendLine("{");
Expand Down
20 changes: 14 additions & 6 deletions TUnit.Core/Attributes/TestData/MethodDataSourceAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,9 @@ public MethodDataSourceAttribute(
}

// Compute paramTypes once to avoid repeated LINQ allocations
var paramTypes = GetParameterTypes(dataGeneratorMetadata.TestInformation?.Parameters);
// Use MembersToGenerate which contains the correct parameters for this data generator type
// (constructor params for class-level, method params for method-level)
var paramTypes = GetMemberTypes(dataGeneratorMetadata.MembersToGenerate);

// If it's IAsyncEnumerable, handle it specially
if (IsAsyncEnumerable(methodResult.GetType()))
Expand Down Expand Up @@ -310,17 +312,23 @@ public MethodDataSourceAttribute(
}
}

private static Type[]? GetParameterTypes(ParameterMetadata[]? parameters)
private static Type[]? GetMemberTypes(IMemberMetadata[]? members)
{
if (parameters == null || parameters.Length == 0)
if (members == null || members.Length == 0)
{
return null;
}

var types = new Type[parameters.Length];
for (var i = 0; i < parameters.Length; i++)
var types = new Type[members.Length];
for (var i = 0; i < members.Length; i++)
{
types[i] = parameters[i].Type;
types[i] = members[i] switch
{
ParameterMetadata param => param.Type,
PropertyMetadata prop => prop.Type,
_ => throw new InvalidOperationException(
$"Unexpected member metadata type {members[i].GetType().Name} in GetMemberTypes")
};
}
return types;
}
Expand Down
29 changes: 29 additions & 0 deletions TUnit.TestProject/Bugs/5118/AsyncClassMethodDataSourceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using TUnit.TestProject.Attributes;

namespace TUnit.TestProject.Bugs._5118;

public class AsyncTestDataSources
{
public static async IAsyncEnumerable<(int Id, string Name, DateTime CreatedAt)> GetAsyncTestData()
{
for (var i = 1; i <= 3; i++)
{
await Task.Delay(10).ConfigureAwait(false);

yield return (Id: i, Name: $"Item_{i}", CreatedAt: DateTime.UtcNow.AddDays(-i));
}
}
}

[EngineTest(ExpectedResult.Pass)]
[MethodDataSource<AsyncTestDataSources>(nameof(AsyncTestDataSources.GetAsyncTestData))]
public class AsyncClassMethodDataSourceTests(int Id, string Name, DateTime CreatedAt)
{
[Test, Timeout(5000)]
public async Task TestWithAsyncComplexData(CancellationToken token)
{
await Assert.That(Id).IsGreaterThan(0);
await Assert.That(Name).StartsWith("Item_");
await Assert.That(CreatedAt).IsLessThan(DateTime.UtcNow);
}
}
Loading