From fdc2edb5703f7ddf396379e329041ede83c3f8a8 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 16:47:18 +0000 Subject: [PATCH 01/15] fix(generic): a class [Arguments] row that infers no type argument lets method rows infer it (#7209) A class row whose values go only to constructor parameters that do not use a class type parameter (e.g. [Arguments(42)] on C(int number)) now supplies no class type argument in either mode. Method rows infer T as without a class row (C for [Arguments(1)], C for [Arguments(null)]), and the instance is built from the class row. - Source gen: such a row no longer suppresses the [Arguments(null)] -> object inference, and it supplies the constructor arguments of method-row-inferred instantiations instead of the NoClassRow failure. - Reflection: such rows are no longer grouped by their values' types; they supply the constructor arguments of the instantiations method rows infer. --- .../Generators/TestMetadataGenerator.cs | 78 ++++++- .../Discovery/ReflectionTestDataCollector.cs | 112 ++++++++- .../Bugs/7209/Tests7209.cs | 18 ++ .../Tests7209.Test.verified.txt | 215 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 29 +++ .../ClassRowInfersNoTypeArgumentTests.cs | 38 ++++ 6 files changed, 479 insertions(+), 11 deletions(-) create mode 100644 tests/TUnit.Core.SourceGenerator.Tests/Bugs/7209/Tests7209.cs create mode 100644 tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt create mode 100644 tests/TUnit.Engine.Tests/Issue7209Tests.cs create mode 100644 tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs diff --git a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs index 8e300101d7f..27a1dd51665 100644 --- a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs +++ b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs @@ -1255,10 +1255,19 @@ a.AttributeClass is { } attributeClass && (attributeClass.IsOrInherits("global::TUnit.Core.GenerateGenericTestAttribute") || DataSourceAttributeHelper.IsDataSourceAttribute(attributeClass))); + // A class row whose values go to no type parameter supplies no class type argument, so an + // [Arguments(null)] row still infers object beside it, as without a class row (#7209). + // Reflection mode applies the same rule. + var nullArgumentsArrayInfersObject = !testMethod.TypeSymbol.GetAttributes().Any(a => + a.AttributeClass is { } attributeClass + && (attributeClass.IsOrInherits("global::TUnit.Core.GenerateGenericTestAttribute") + || (DataSourceAttributeHelper.IsDataSourceAttribute(attributeClass) + && !(attributeClass.Name == "ArgumentsAttribute" && ClassRowSuppliesNoTypeArguments(testMethod.TypeSymbol, a))))); + foreach (var methodArgAttr in methodArgumentsAttributes) { var inferredTypes = InferClassTypesFromMethodArguments(testMethod.TypeSymbol, testMethod.MethodSymbol, methodArgAttr, compilation, - nullArgumentsArrayInfersObject: !classTypeArgumentsSupplied); + nullArgumentsArrayInfersObject: nullArgumentsArrayInfersObject); if (inferredTypes is { Length: > 0 }) { (inferringRows ??= []).Add(methodArgAttr); @@ -1558,11 +1567,29 @@ a.AttributeClass is { } attributeClass var addUninferredMethodDataSources = uninferredMethodDataSources is not null && MethodParametersReferenceTypeParameters(testMethod); + // Class rows whose values go to no type parameter infer no instantiation of their own, so they + // supply the constructor arguments of every instantiation that the method rows infer (#7209). + // Reflection mode builds those instances from the same rows. + List? typeFreeClassRows = null; + foreach (var classAttr in classArgumentsAttributes) + { + if (ClassRowSuppliesNoTypeArguments(testMethod.TypeSymbol, classAttr)) + { + (typeFreeClassRows ??= []).Add(classAttr); + } + } + foreach (var instantiation in rowInstantiations.Values) { if (instantiation.HasMethodRows && !instantiation.HasClassRows) { var hasClassDataSource = false; + foreach (var typeFreeClassRow in typeFreeClassRows ?? []) + { + instantiation.AddRow(typeFreeClassRow, isClassRow: true); + hasClassDataSource = true; + } + foreach (var (attribute, classTypes) in otherClassDataSources ?? []) { if (classTypes is null || InferredTypesMatch(classTypes, instantiation.ClassTypeArgs)) @@ -6755,9 +6782,56 @@ private static bool HasArgumentsArray(AttributeData argAttr) => /// private static bool IsNullArgumentsArray(AttributeData argAttr) => argAttr.ConstructorArguments[0].IsNull; + /// + /// True for a class-level [Arguments] row whose values all bind to constructor parameters that do not + /// use the class's type parameters, as [Arguments(42)] on C<T>(int number). Such a + /// row supplies no class type argument, so the method rows infer them, and the row only supplies the + /// constructor arguments (#7209). Mirrors ReflectionTestDataCollector.ClassRowSuppliesNoTypeArguments. + /// + private static bool ClassRowSuppliesNoTypeArguments(INamedTypeSymbol classSymbol, AttributeData argAttr) + { + int valueCount; + if (argAttr.AttributeClass is { IsGenericType: true, TypeArguments.Length: 1 }) + { + valueCount = 1; + } + else if (!HasArgumentsArray(argAttr)) + { + return false; + } + else + { + // [Arguments(null)] passes one null value + valueCount = IsNullArgumentsArray(argAttr) ? 1 : argAttr.ConstructorArguments[0].Values.Length; + } + + var primaryConstructor = classSymbol.Constructors + .FirstOrDefault(c => c.DeclaringSyntaxReferences.Any(sr => + sr.GetSyntax() is ConstructorDeclarationSyntax cds && + cds.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)))) + ?? classSymbol.Constructors.FirstOrDefault(); + + var boundCount = Math.Min(valueCount, primaryConstructor?.Parameters.Length ?? 0); + if (boundCount == 0) + { + return false; + } + + for (var i = 0; i < boundCount; i++) + { + if (ContainsClassTypeParameter(primaryConstructor!.Parameters[i].Type, classSymbol)) + { + return false; + } + } + + return true; + } + /// /// False when [GenerateGenericTest] or a class-level data source supplies the class type arguments: an - /// [Arguments(null)] row then infers no type and runs on those instantiations. True otherwise, so the + /// [Arguments(null)] row then infers no type and runs on those instantiations. A class row whose values go + /// to no type parameter supplies none (#7209). True otherwise, so the /// row's one null value infers object like any other null value instead of being dropped (#7141). /// private static ITypeSymbol[]? InferClassTypesFromMethodArguments(INamedTypeSymbol classSymbol, IMethodSymbol methodSymbol, AttributeData argAttr, Compilation compilation, bool nullArgumentsArrayInfersObject) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 690e9e6f32c..b046fb58b68 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -523,17 +523,26 @@ private static async Task> DiscoverGenericTests(Type genericT ? BuildTestsFromMethodRows(genericTypeDefinition, testMethods, generateGenericTestAttributes, out methodRowTypeArguments) : null; + // Class rows whose values go to no type parameter infer no instantiation, so they are not grouped + // by type. They supply the constructor arguments of the instantiations that method rows infer, and + // alone they supply no class type argument, so an [Arguments(null)] method row infers object, as in + // the source generator (#7209). + var typeFreeClassRows = methodRowTests == null + ? SplitTypeFreeClassRows(genericTypeDefinition, ref classDataSources) + : null; + // With class-level [Arguments] rows, method rows run only on the class instantiation their own values // infer (#7118) var methodRowClassTypeArguments = methodRowTests == null - ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources) + ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources.Length + (typeFreeClassRows?.Length ?? 0), + nullValuesArrayInfersObject: classDataSources.Length == 0 && generateGenericTestAttributes.Length == 0) : null; // [GenerateGenericTest] types' class constraint violations are reported before the class rows' var generateGenericTestTypeArguments = GetValidGenerateGenericTestTypeArguments(generateGenericTestAttributes, constraintViolations); // Method rows that infer types no class row infers build their instance from every class row, so keep // them all as discovery read them rather than reading the sources again (#7161) - var allClassRows = methodRowClassTypeArguments != null && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; + var allClassRows = methodRowClassTypeArguments != null && typeFreeClassRows == null && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; var classRowGroups = methodRowTests == null ? await GroupClassRowsByTypeArgumentsAsync(genericTypeDefinition, classDataSources, constraintViolations, allClassRows).ConfigureAwait(false) : null; @@ -592,7 +601,7 @@ private static async Task> DiscoverGenericTests(Type genericT if (methodRowClassTypeArguments != null) { - discoveredTests.AddRange(BuildTestsForMethodRowsWithoutClassRow(genericTypeDefinition, testMethods, methodRowClassTypeArguments, classRowGroups!, allClassRows, generateGenericTestAttributes)); + discoveredTests.AddRange(BuildTestsForMethodRowsWithoutClassRow(genericTypeDefinition, testMethods, methodRowClassTypeArguments, classRowGroups!, allClassRows, typeFreeClassRows, generateGenericTestAttributes)); } AddConstraintViolationTests(discoveredTests, constraintViolations); @@ -1089,9 +1098,9 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// whatever the class data sources are, since it cannot know the types a [MethodDataSource] or other /// run-time source yields (#7161). /// - private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, IDataSourceAttribute[] classDataSources) + private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool nullValuesArrayInfersObject) { - if (classDataSources.Length == 0) + if (classDataSourceCount == 0) { return null; } @@ -1119,9 +1128,10 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin for (var i = 0; i < methodDataSources.Length; i++) { - // Class rows supply the instantiations, so [Arguments(null)] infers none and runs on each (#7141) + // Class rows supply the instantiations, so [Arguments(null)] infers none and runs on each (#7141), + // unless every class row goes to no type parameter (#7209) if (methodDataSources[i] is ArgumentsAttribute arguments - && InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject: false) is { } typeArguments) + && InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject) is { } typeArguments) { // A plain local, not `(rowTypeArguments ??= ...)[i] = ...`: the .NET 8 trim analyzer // crashes (AD0001) on an array element write through a null-coalescing assignment. @@ -1201,7 +1211,9 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// class data sources are known only at run time, and the source generator builds the instance from all /// of them, so this does too, from : the rows discovery already read, so a /// source is never read twice (#7161). is null when the class has - /// class-level [Arguments] rows. A class-level [GenerateGenericTest] listing those type arguments runs + /// class-level [Arguments] rows. Class rows whose values go to no type parameter + /// () supply the constructor arguments of every such instantiation, as in + /// the source generator (#7209). A class-level [GenerateGenericTest] listing those type arguments runs /// the rows instead. Rows whose type arguments break the class's constraints are skipped, as the source /// generator skips them. /// @@ -1211,10 +1223,11 @@ private static List BuildTestsForMethodRowsWithoutClassRow( Type[]?[]?[] methodRowClassTypeArguments, List classRowGroups, List? allClassRows, + IDataSourceAttribute[]? typeFreeClassRows, GenerateGenericTestAttribute[] generateGenericTestAttributes) { List? tests = null; - var allClassRowSources = allClassRows?.ToArray(); + var allClassRowSources = allClassRows?.ToArray() ?? typeFreeClassRows; for (var methodIndex = 0; methodIndex < testMethods.Length; methodIndex++) { @@ -1289,6 +1302,87 @@ private static List BuildTestsForMethodRowsWithoutClassRow( return tests ?? []; } + /// + /// Removes from the class-level [Arguments] rows whose values all bind to + /// constructor parameters that do not use the class's type parameters, as [Arguments(42)] on + /// C<T>(int number), and returns them, or null when there are none. Such a row supplies no class + /// type argument (#7209). Mirrors TestMetadataGenerator.ClassRowSuppliesNoTypeArguments. + /// + private static IDataSourceAttribute[]? SplitTypeFreeClassRows(Type genericTypeDefinition, ref IDataSourceAttribute[] classDataSources) + { + List? typeFree = null; + List? rest = null; + for (var i = 0; i < classDataSources.Length; i++) + { + var source = classDataSources[i]; + if (ClassRowSuppliesNoTypeArguments(genericTypeDefinition, source)) + { + if (rest == null) + { + // First type-free row: copy the sources kept so far + rest = new List(classDataSources.Length); + for (var j = 0; j < i; j++) + { + rest.Add(classDataSources[j]); + } + } + + (typeFree ??= []).Add(source); + } + else + { + rest?.Add(source); + } + } + + if (typeFree == null) + { + return null; + } + + classDataSources = rest!.ToArray(); + return typeFree.ToArray(); + } + + private static bool ClassRowSuppliesNoTypeArguments(Type genericTypeDefinition, IDataSourceAttribute dataSource) + { + int valueCount; + if (dataSource is ArgumentsAttribute arguments) + { + valueCount = arguments.Values.Length; + } + else if (dataSource.GetType() is { IsGenericType: true } type && type.GetGenericTypeDefinition() == typeof(ArgumentsAttribute<>)) + { + valueCount = 1; + } + else + { + return false; + } + + if (genericTypeDefinition.GetConstructors() is not [var constructor, ..]) + { + return false; + } + + var parameters = constructor.GetParameters(); + var boundCount = Math.Min(valueCount, parameters.Length); + if (boundCount == 0) + { + return false; + } + + for (var i = 0; i < boundCount; i++) + { + if (parameters[i].ParameterType.ContainsGenericParameters) + { + return false; + } + } + + return true; + } + /// /// Whether the class has class-level [Arguments] rows, in either the or /// the form. The source generator treats both forms as class rows. diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Bugs/7209/Tests7209.cs b/tests/TUnit.Core.SourceGenerator.Tests/Bugs/7209/Tests7209.cs new file mode 100644 index 00000000000..e2e0649a0f4 --- /dev/null +++ b/tests/TUnit.Core.SourceGenerator.Tests/Bugs/7209/Tests7209.cs @@ -0,0 +1,18 @@ +namespace TUnit.Core.SourceGenerator.Tests; + +internal class Tests7209 : TestsBase +{ + [Test] + public Task Test() => RunTest(Path.Combine( + Git.TestsDirectory.FullName, + "TUnit.TestProject", + "Bugs", + "_7209", + "ClassRowInfersNoTypeArgumentTests.cs"), + async generatedFiles => + { + // The null method row's C instantiation is emitted beside C, not dropped + await Assert.That(string.Join("\n", generatedFiles)).Contains("ClassRowInfersNoTypeArgument"); + await Assert.That(string.Join("\n", generatedFiles)).Contains("ClassRowInfersNoTypeArgument"); + }); +} diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt new file mode 100644 index 00000000000..accbd21f4c7 --- /dev/null +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -0,0 +1,215 @@ +// +#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__7209_ClassRowInfersNoTypeArgument_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "ClassRowInfersNoTypeArgument", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument.Run", + filePath: "", + lineNumber: 13, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(null), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.ClassRowInfersNoTypeArgument.Run", + filePath: "", + lineNumber: 13, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_ClassRowInfersNoTypeArgument_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_ClassRowInfersNoTypeArgument_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_ClassRowInfersNoTypeArgument_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_ClassRowInfersNoTypeArgument_T_Run__T_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_ClassRowInfersTypeArgument_T_Run__T__TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "ClassRowInfersTypeArgument", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>), true, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "classValue", new global::TUnit.Core.GenericParameter(0, false, "T"), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), true) +})); + private static global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument), new object[] { "class" })!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute("class") + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.ClassRowInfersTypeArgument.Run", + filePath: "", + lineNumber: 30, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(null), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute("class"), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_ClassRowInfersTypeArgument_T_Run__T__TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_ClassRowInfersTypeArgument_T_Run__T__TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs new file mode 100644 index 00000000000..07fe462f6f6 --- /dev/null +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -0,0 +1,29 @@ +using Shouldly; +using TUnit.Engine.Tests.Enums; + +namespace TUnit.Engine.Tests; + +/// +/// A class [Arguments] row whose values go to no type parameter supplies no class type argument, so the +/// method rows infer it, and the instance is still built from the class row, in both modes (#7209). +/// +public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) +{ + private const string Namespace = "/*/TUnit.TestProject.Bugs._7209"; + + [Test] + [Arguments("ClassRowInfersNoTypeArgument", 2)] + [Arguments("ClassRowInfersTypeArgument", 1)] + public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests) + { + await RunTestsWithFilter( + // Trailing '*': generic class nodes carry the arity + $"{Namespace}/{className}*/*", + [ + result => result.ResultSummary.Outcome.ShouldBe("Completed"), + result => result.ResultSummary.Counters.Total.ShouldBe(expectedTests), + result => result.ResultSummary.Counters.Passed.ShouldBe(expectedTests), + result => result.ResultSummary.Counters.Failed.ShouldBe(0) + ]); + } +} diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs new file mode 100644 index 00000000000..8c05c89c33a --- /dev/null +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -0,0 +1,38 @@ +using TUnit.TestProject.Attributes; + +namespace TUnit.TestProject.Bugs._7209; + +// The class row's value goes to an int constructor parameter, not to T, so it supplies no class type +// argument. T comes from the method rows, as it does without a class row: C for [Arguments(1)] +// and C for [Arguments(null)] (#7141). Each instance is constructed from the class row +// (number = 42), never from a method row. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class ClassRowInfersNoTypeArgument(int number) +{ + [Test] + [Arguments(null)] + [Arguments(1)] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(value is null ? typeof(object) : typeof(int)); + await Assert.That((object?)value is null or 1).IsTrue(); + } +} + +// A class row that does infer T keeps supplying it: the method rows run on C, and the null row +// infers nothing of its own. +[EngineTest(ExpectedResult.Pass)] +[Arguments("class")] +public class ClassRowInfersTypeArgument(T classValue) +{ + [Test] + [Arguments(null)] + public async Task Run(T? value) + { + await Assert.That(typeof(T)).IsEqualTo(typeof(string)); + await Assert.That((object?)classValue).IsEqualTo("class"); + await Assert.That(value).IsNull(); + } +} From 78e0a1df1eb2f6f5c0156ecd16f728573c1f858b Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:09:33 +0000 Subject: [PATCH 02/15] fix(reflection): keep type-free class rows beside other class sources and uninferred method sources (#7209) Reflection dropped a type-free class [Arguments] row from class-row groups that another class data source inferred, and dropped method sources that infer no class type argument from the method-row instantiations the type-free rows build. Both now match the source generator. --- .../Discovery/ReflectionTestDataCollector.cs | 64 ++++++- .../Tests7209.Test.verified.txt | 178 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 2 + .../ClassRowInfersNoTypeArgumentTests.cs | 41 ++++ 4 files changed, 277 insertions(+), 8 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index b046fb58b68..c59cbc82315 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -524,9 +524,9 @@ private static async Task> DiscoverGenericTests(Type genericT : null; // Class rows whose values go to no type parameter infer no instantiation, so they are not grouped - // by type. They supply the constructor arguments of the instantiations that method rows infer, and - // alone they supply no class type argument, so an [Arguments(null)] method row infers object, as in - // the source generator (#7209). + // by type. They supply the constructor arguments of the instantiations that method rows infer, beside + // the rows of any other class data source. Alone they supply no class type argument, so an + // [Arguments(null)] method row infers object, as in the source generator (#7209). var typeFreeClassRows = methodRowTests == null ? SplitTypeFreeClassRows(genericTypeDefinition, ref classDataSources) : null; @@ -542,11 +542,16 @@ private static async Task> DiscoverGenericTests(Type genericT var generateGenericTestTypeArguments = GetValidGenerateGenericTestTypeArguments(generateGenericTestAttributes, constraintViolations); // Method rows that infer types no class row infers build their instance from every class row, so keep // them all as discovery read them rather than reading the sources again (#7161) - var allClassRows = methodRowClassTypeArguments != null && typeFreeClassRows == null && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; + var allClassRows = methodRowClassTypeArguments != null && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; var classRowGroups = methodRowTests == null ? await GroupClassRowsByTypeArgumentsAsync(genericTypeDefinition, classDataSources, constraintViolations, allClassRows).ConfigureAwait(false) : null; + if (typeFreeClassRows != null) + { + AddTypeFreeClassRowsToGroups(classRowGroups!, typeFreeClassRows); + } + foreach (var typeArguments in generateGenericTestTypeArguments) { if (methodRowClassTypeArguments != null && IsInferredByClassRows(classRowGroups!, typeArguments)) @@ -1227,7 +1232,9 @@ private static List BuildTestsForMethodRowsWithoutClassRow( GenerateGenericTestAttribute[] generateGenericTestAttributes) { List? tests = null; - var allClassRowSources = allClassRows?.ToArray() ?? typeFreeClassRows; + var allClassRowSources = typeFreeClassRows == null + ? allClassRows?.ToArray() + : allClassRows is null or { Count: 0 } ? typeFreeClassRows : [.. typeFreeClassRows, .. allClassRows]; for (var methodIndex = 0; methodIndex < testMethods.Length; methodIndex++) { @@ -1282,7 +1289,9 @@ private static List BuildTestsForMethodRowsWithoutClassRow( continue; } - var methodRows = ScopeMethodRowsToClassTypeArguments(concreteType, concreteMethod, rowTypeArguments, typeArguments, onlyInferringRows: true); + // Type-free class rows make this a class row instantiation, so the method sources that infer + // no type run on it too, as in the source generator (#7209) + var methodRows = ScopeMethodRowsToClassTypeArguments(concreteType, concreteMethod, rowTypeArguments, typeArguments, onlyInferringRows: typeFreeClassRows == null); (tests ??= []).Add(allClassRowSources == null ? BuildTestMetadata( concreteType, @@ -1344,6 +1353,42 @@ private static List BuildTestsForMethodRowsWithoutClassRow( return typeFree.ToArray(); } + /// + /// Adds the type-free class rows to every class row group that no class-level [Arguments] row inferred, ahead + /// of the group's own sources. Such a group holds the rows of other class data sources (a [MethodDataSource] + /// or a data source generator), and the source generator builds a method-row instantiation from the type-free + /// rows and those sources together (#7209). + /// + private static void AddTypeFreeClassRowsToGroups(List classRowGroups, IDataSourceAttribute[] typeFreeClassRows) + { + for (var i = 0; i < classRowGroups.Count; i++) + { + var group = classRowGroups[i]; + if (GroupHasClassArgumentsRows(group)) + { + continue; + } + + var sources = new IDataSourceAttribute[typeFreeClassRows.Length + group.ClassDataSources.Length]; + typeFreeClassRows.CopyTo(sources, 0); + group.ClassDataSources.CopyTo(sources, typeFreeClassRows.Length); + classRowGroups[i] = group with { ClassDataSources = sources, RowCount = group.RowCount + typeFreeClassRows.Length }; + } + } + + private static bool GroupHasClassArgumentsRows(ClassRowGroup group) + { + foreach (var source in group.ClassDataSources) + { + if (IsClassArgumentsRow(source is StaticDataSourceAttribute { PartitionOf: { } partitionOf } ? partitionOf : source)) + { + return true; + } + } + + return false; + } + private static bool ClassRowSuppliesNoTypeArguments(Type genericTypeDefinition, IDataSourceAttribute dataSource) { int valueCount; @@ -1391,8 +1436,7 @@ private static bool HasClassArgumentsRows(IDataSourceAttribute[] classDataSource { foreach (var source in classDataSources) { - if (source is ArgumentsAttribute - || (source.GetType() is { IsGenericType: true } type && type.GetGenericTypeDefinition() == typeof(ArgumentsAttribute<>))) + if (IsClassArgumentsRow(source)) { return true; } @@ -1401,6 +1445,10 @@ private static bool HasClassArgumentsRows(IDataSourceAttribute[] classDataSource return false; } + private static bool IsClassArgumentsRow(IDataSourceAttribute source) => + source is ArgumentsAttribute + || (source.GetType() is { IsGenericType: true } type && type.GetGenericTypeDefinition() == typeof(ArgumentsAttribute<>)); + private static List GetValidGenerateGenericTestTypeArguments(GenerateGenericTestAttribute[] generateGenericTestAttributes, ReflectionGenericConstraintViolations constraintViolations) { var result = new List(generateGenericTestAttributes.Length); diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index accbd21f4c7..4008103bf1b 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -213,3 +213,181 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_ClassRowInfersTypeArgument_T_Run__T__TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_ClassRowInfersTypeArgument_T_Run__T__TestSource.Entries_0); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowBesideOtherSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowBesideOtherSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "FortyThree") + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideOtherSource.Run", + filePath: "", + lineNumber: 47, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "FortyThree") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources.FortyThree()), + }, +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideOtherSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideOtherSource_T_Run__T_TestSource.Entries_0); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithUninferredMethodSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithUninferredMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "Two"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithUninferredMethodSource.Run", + filePath: "", + lineNumber: 63, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "Two") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources.Two()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithUninferredMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithUninferredMethodSource_T_Run__T_TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 07fe462f6f6..bbeaeb84491 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -14,6 +14,8 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Test] [Arguments("ClassRowInfersNoTypeArgument", 2)] [Arguments("ClassRowInfersTypeArgument", 1)] + [Arguments("TypeFreeClassRowBesideOtherSource", 2)] + [Arguments("TypeFreeClassRowWithUninferredMethodSource", 2)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 8c05c89c33a..5e3ddf0a034 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -36,3 +36,44 @@ public async Task Run(T? value) await Assert.That(value).IsNull(); } } + +// A type-free class row beside another class data source: the method row infers C, and the instance +// comes from both class sources (number = 42, then 43), not from the other source alone. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +[MethodDataSource(typeof(TypeFreeClassRowSources), nameof(TypeFreeClassRowSources.FortyThree))] +public class TypeFreeClassRowBesideOtherSource(int number) +{ + [Test] + [Arguments(1)] + public async Task Run(T value) + { + await Assert.That(number is 42 or 43).IsTrue(); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(1); + } +} + +// A method source that infers no class type argument runs on the instantiation the method row infers, as +// it does with any other class row: C runs Run(1) and Run(2). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithUninferredMethodSource(int number) +{ + [Test] + [Arguments(1)] + [MethodDataSource(typeof(TypeFreeClassRowSources), nameof(TypeFreeClassRowSources.Two))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value is 1 or 2).IsTrue(); + } +} + +public static class TypeFreeClassRowSources +{ + public static IEnumerable FortyThree() => [43]; + + public static IEnumerable Two() => [2]; +} From a98ad71f7e5929f6713525a4541fba0fb4a04943 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Sun, 1 Nov 2026 23:37:51 +0000 Subject: [PATCH 03/15] fix(generic): type-free class rows let method sources infer and report class types (#7209) Beside only class [Arguments] rows whose values go to no type parameter: - reflection infers the class type arguments from a test-class [MethodDataSource] member's declared type, as the source generator does, instead of discovering no test - a method row inferring types that break the class's constraints fails in both modes instead of disappearing The generator's two class-type-supplied predicates become one. --- .../Generators/TestMetadataGenerator.cs | 13 +- .../ReflectionGenericConstraintViolations.cs | 8 +- .../Discovery/ReflectionTestDataCollector.cs | 132 ++++++++++++- .../Tests7209.Test.verified.txt | 186 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 30 ++- .../ClassRowInfersNoTypeArgumentTests.cs | 34 ++++ 6 files changed, 376 insertions(+), 27 deletions(-) diff --git a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs index 27a1dd51665..eea12d5a770 100644 --- a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs +++ b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs @@ -1250,15 +1250,10 @@ void JoinDeferredDataSources(ITypeSymbol[] typeArguments) // arguments, a method row's values need not infer them: [GenerateGenericTest(typeof(object))] // with [Arguments(1)] runs C, so the C inferred here is not reported as a // violation. Reflection mode applies the same rule. + // A class row whose values go to no type parameter supplies no class type argument (#7209). Beside + // only such rows, an [Arguments(null)] row still infers object, and a row inferring types that + // break the class's constraints fails, as without a class row. var classTypeArgumentsSupplied = testMethod.TypeSymbol.GetAttributes().Any(a => - a.AttributeClass is { } attributeClass - && (attributeClass.IsOrInherits("global::TUnit.Core.GenerateGenericTestAttribute") - || DataSourceAttributeHelper.IsDataSourceAttribute(attributeClass))); - - // A class row whose values go to no type parameter supplies no class type argument, so an - // [Arguments(null)] row still infers object beside it, as without a class row (#7209). - // Reflection mode applies the same rule. - var nullArgumentsArrayInfersObject = !testMethod.TypeSymbol.GetAttributes().Any(a => a.AttributeClass is { } attributeClass && (attributeClass.IsOrInherits("global::TUnit.Core.GenerateGenericTestAttribute") || (DataSourceAttributeHelper.IsDataSourceAttribute(attributeClass) @@ -1267,7 +1262,7 @@ a.AttributeClass is { } attributeClass foreach (var methodArgAttr in methodArgumentsAttributes) { var inferredTypes = InferClassTypesFromMethodArguments(testMethod.TypeSymbol, testMethod.MethodSymbol, methodArgAttr, compilation, - nullArgumentsArrayInfersObject: nullArgumentsArrayInfersObject); + nullArgumentsArrayInfersObject: !classTypeArgumentsSupplied); if (inferredTypes is { Length: > 0 }) { (inferringRows ??= []).Add(methodArgAttr); diff --git a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs index a948c9b359f..091d6a7ed3e 100644 --- a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs +++ b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs @@ -55,12 +55,12 @@ public bool TryAddClassViolation(Type[] typeArguments) /// /// Only invalid rows are reported here. Running the valid rows of such methods is tracked by #7106. /// When or a class-level data source already supplies the - /// class type arguments, method rows do not infer them, so nothing is reported. + /// class type arguments (), method rows do not infer them, so + /// nothing is reported. Class-level [Arguments] rows whose values go to no type parameter supply none (#7209). /// - public void AddMethodRowViolations() + public void AddMethodRowViolations(bool classTypeArgumentsSupplied) { - if (genericTypeDefinition.IsDefined(typeof(GenerateGenericTestAttribute), inherit: false) - || ReflectionAttributeExtractor.ExtractDataSources(genericTypeDefinition).Length > 0) + if (classTypeArgumentsSupplied) { return; } diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index c59cbc82315..ad599191fcf 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -535,7 +535,7 @@ private static async Task> DiscoverGenericTests(Type genericT // infer (#7118) var methodRowClassTypeArguments = methodRowTests == null ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources.Length + (typeFreeClassRows?.Length ?? 0), - nullValuesArrayInfersObject: classDataSources.Length == 0 && generateGenericTestAttributes.Length == 0) + classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0) : null; // [GenerateGenericTest] types' class constraint violations are reported before the class rows' @@ -580,7 +580,7 @@ private static async Task> DiscoverGenericTests(Type genericT discoveredTests.AddRange(methodRowTests); // Return any tests discovered from method rows and GenerateGenericTest attributes - AddConstraintViolationTests(discoveredTests, constraintViolations); + AddConstraintViolationTests(discoveredTests, constraintViolations, classTypeArgumentsSupplied: generateGenericTestAttributes.Length > 0); return discoveredTests; } @@ -609,7 +609,10 @@ private static async Task> DiscoverGenericTests(Type genericT discoveredTests.AddRange(BuildTestsForMethodRowsWithoutClassRow(genericTypeDefinition, testMethods, methodRowClassTypeArguments, classRowGroups!, allClassRows, typeFreeClassRows, generateGenericTestAttributes)); } - AddConstraintViolationTests(discoveredTests, constraintViolations); + // Type-free class rows were split out of classDataSources, so beside only those, method rows infer the + // class type arguments and report the ones that break the class's constraints (#7209) + AddConstraintViolationTests(discoveredTests, constraintViolations, + classTypeArgumentsSupplied: generateGenericTestAttributes.Length > 0 || classDataSources.Length > 0); return discoveredTests; } @@ -697,9 +700,9 @@ private static void AddTestsForInstantiation( } } - private static void AddConstraintViolationTests(List discoveredTests, ReflectionGenericConstraintViolations constraintViolations) + private static void AddConstraintViolationTests(List discoveredTests, ReflectionGenericConstraintViolations constraintViolations, bool classTypeArgumentsSupplied) { - constraintViolations.AddMethodRowViolations(); + constraintViolations.AddMethodRowViolations(classTypeArgumentsSupplied); discoveredTests.AddRange(constraintViolations.CreateMetadata()); } @@ -1103,7 +1106,13 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// whatever the class data sources are, since it cannot know the types a [MethodDataSource] or other /// run-time source yields (#7161). /// - private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool nullValuesArrayInfersObject) + /// + /// False when every class data source is a class row whose values go to no type parameter (#7209). The + /// method sources then infer the class type arguments as without a class row: [Arguments(null)] infers + /// object, and a [MethodDataSource] member of the test class infers them from its declared type, as in the + /// source generator. + /// + private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied) { if (classDataSourceCount == 0) { @@ -1135,8 +1144,14 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin { // Class rows supply the instantiations, so [Arguments(null)] infers none and runs on each (#7141), // unless every class row goes to no type parameter (#7209) - if (methodDataSources[i] is ArgumentsAttribute arguments - && InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject) is { } typeArguments) + var typeArguments = methodDataSources[i] switch + { + ArgumentsAttribute arguments => InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject: !classTypeArgumentsSupplied), + MethodDataSourceAttribute methodDataSource when !classTypeArgumentsSupplied => InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters), + _ => null + }; + + if (typeArguments != null) { // A plain local, not `(rowTypeArguments ??= ...)[i] = ...`: the .NET 8 trim analyzer // crashes (AD0001) on an array element write through a null-coalescing assignment. @@ -1151,6 +1166,107 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin return result; } + /// + /// The class type arguments that a method-level [MethodDataSource] infers from the declared return type of + /// its member, or null. Mirrors the generator's InferClassTypesFromMethodDataSource: only + /// [MethodDataSource("Rows")] naming a static parameterless member of the test class that returns + /// IEnumerable<T> or IEnumerable<Func<T>>. A tuple T is matched + /// element by element against the data parameters, any other T only against a single data parameter. + /// + [UnconditionalSuppressMessage("Trimming", "IL2070", Justification = "Reflection mode requires dynamic access to data source methods")] + private static Type[]? InferClassTypeArgumentsFromMethodDataSource(Type genericTypeDefinition, MethodDataSourceAttribute methodDataSource, ParameterInfo[] parameters) + { + if (methodDataSource.GetType() != typeof(MethodDataSourceAttribute) || methodDataSource.ClassProvidingDataSource is not null) + { + return null; + } + + var dataMethod = genericTypeDefinition.GetMethod( + methodDataSource.MethodNameProvidingDataSource, + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly, + binder: null, + Type.EmptyTypes, + modifiers: null); + + if (dataMethod?.ReturnType is not { IsGenericType: true } returnType + || returnType.GetGenericTypeDefinition() != typeof(IEnumerable<>)) + { + return null; + } + + var dataType = returnType.GetGenericArguments()[0]; + if (dataType.IsGenericType && dataType.GetGenericTypeDefinition() == typeof(Func<>)) + { + dataType = dataType.GetGenericArguments()[0]; + } + + // The generator reads only named types: not arrays, pointers or type parameters + if (dataType.HasElementType || dataType.IsGenericParameter) + { + return null; + } + + // Row values bind to the data parameters only; the engine supplies any CancellationToken + var dataParameters = Array.Exists(parameters, static parameter => parameter.ParameterType == typeof(CancellationToken)) + ? Array.FindAll(parameters, static parameter => parameter.ParameterType != typeof(CancellationToken)) + : parameters; + var typeArguments = new Type?[genericTypeDefinition.GetGenericArguments().Length]; + + if (GetValueTupleElementTypes(dataType) is { } tupleElements) + { + for (var i = 0; i < dataParameters.Length && i < tupleElements.Length; i++) + { + MapClassGenericParameters(dataParameters[i].ParameterType, tupleElements[i], typeArguments); + } + } + else if (dataParameters.Length == 1) + { + MapClassGenericParameters(dataParameters[0].ParameterType, dataType, typeArguments); + } + + foreach (var typeArgument in typeArguments) + { + if (typeArgument is null || typeArgument.ContainsGenericParameters) + { + return null; + } + } + + return typeArguments!; + } + + /// Mirrors the generator's ProcessTypeForGenerics for the class's type parameters. + private static void MapClassGenericParameters(Type parameterType, Type actualType, Type?[] typeArguments) + { + if (parameterType.IsGenericParameter) + { + if (parameterType.DeclaringMethod is null) + { + typeArguments[parameterType.GenericParameterPosition] = actualType; + } + + return; + } + + if (parameterType.IsArray && actualType.IsArray && parameterType.GetArrayRank() == actualType.GetArrayRank()) + { + MapClassGenericParameters(parameterType.GetElementType()!, actualType.GetElementType()!, typeArguments); + return; + } + + if (parameterType.IsGenericType + && actualType.IsGenericType + && parameterType.GetGenericTypeDefinition() == actualType.GetGenericTypeDefinition()) + { + var parameterArguments = parameterType.GetGenericArguments(); + var actualArguments = actualType.GetGenericArguments(); + for (var i = 0; i < parameterArguments.Length && i < actualArguments.Length; i++) + { + MapClassGenericParameters(parameterArguments[i], actualArguments[i], typeArguments); + } + } + } + /// /// The method data sources that run on the class instantiation : the /// [Arguments] rows that infer those type arguments and, unless , every diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 4008103bf1b..36e74afc8c7 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -391,3 +391,189 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithUninferredMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithUninferredMethodSource_T_Run__T_TestSource.Entries_0); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithInferringMethodSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithInferringMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Rows"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource.Run", + filePath: "", + lineNumber: 82, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Rows") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringMethodSource.Rows()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringMethodSource_T_Run__T_TestSource.Entries_0); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowConstraintViolation", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation.Run", + filePath: "", + lineNumber: 98, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + public static readonly global::TUnit.Core.GenericConstraintViolationEntry[] ConstraintViolations = new global::TUnit.Core.GenericConstraintViolationEntry[] + { + new global::TUnit.Core.GenericConstraintViolationEntry + { + MethodName = "Run", + FilePath = "", + LineNumber = 98, + MethodMetadata = __mm_0, + Messages = new string[] { "Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'" }, + }, + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource_ConstraintViolations = global::TUnit.Core.SourceRegistrar.RegisterGenericConstraintViolations(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource.ConstraintViolations); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index bbeaeb84491..f5e4bac4620 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -12,11 +12,12 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) private const string Namespace = "/*/TUnit.TestProject.Bugs._7209"; [Test] - [Arguments("ClassRowInfersNoTypeArgument", 2)] - [Arguments("ClassRowInfersTypeArgument", 1)] - [Arguments("TypeFreeClassRowBesideOtherSource", 2)] - [Arguments("TypeFreeClassRowWithUninferredMethodSource", 2)] - public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests) + [Arguments("ClassRowInfersNoTypeArgument", 2, 2)] + [Arguments("ClassRowInfersTypeArgument", 1, 1)] + [Arguments("TypeFreeClassRowBesideOtherSource", 2, 1)] + [Arguments("TypeFreeClassRowWithUninferredMethodSource", 2, 2)] + [Arguments("TypeFreeClassRowWithInferringMethodSource", 1, 1)] + public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( // Trailing '*': generic class nodes carry the arity @@ -25,7 +26,24 @@ await RunTestsWithFilter( result => result.ResultSummary.Outcome.ShouldBe("Completed"), result => result.ResultSummary.Counters.Total.ShouldBe(expectedTests), result => result.ResultSummary.Counters.Passed.ShouldBe(expectedTests), - result => result.ResultSummary.Counters.Failed.ShouldBe(0) + result => result.ResultSummary.Counters.Failed.ShouldBe(0), + // Distinct method rows keep distinct names, so a row running twice in place of another fails + result => result.Results.Select(x => x.TestName).Distinct(StringComparer.Ordinal).Count().ShouldBe(expectedDistinctNames) + ]); + } + + [Test] + public async Task Method_Row_Inferring_An_Invalid_Class_Type_Beside_A_Type_Free_Class_Row_Fails() + { + await RunTestsWithFilter( + $"{Namespace}/TypeFreeClassRowConstraintViolation*/*", + [ + result => result.ResultSummary.Counters.Total.ShouldBe(2), + result => result.ResultSummary.Counters.Passed.ShouldBe(1), + result => result.ResultSummary.Counters.Failed.ShouldBe(1), + result => result.Results.Single(x => x.Outcome == "Failed").TestName.ShouldBe("Run"), + result => result.Results.Single(x => x.Outcome == "Failed").Output?.ErrorInfo?.Message + .ShouldContain("Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'") ]); } } diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 5e3ddf0a034..bb9f9062ea8 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -71,6 +71,40 @@ public async Task Run(T value) } } +// A [MethodDataSource] member of the test class infers T from its declared type, as without a class row: C +// runs Run(5), built from the class row (number = 42). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithInferringMethodSource(int number) +{ + public static IEnumerable Rows() => [5]; + + [Test] + [MethodDataSource(nameof(Rows))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(5); + } +} + +// Beside only a type-free class row, a method row that infers types breaking the class's constraints fails, as +// without a class row: [Arguments(null)] infers object, which is not a struct. [Arguments(1)] runs on C. +// No [EngineTest]: TUnit.Engine.Tests targets it by name, because it has a failing row. +[Arguments(42)] +public class TypeFreeClassRowConstraintViolation(int number) where T : struct +{ + [Test] + [Arguments(1)] + [Arguments(null)] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That((object?)value).IsEqualTo(1); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable FortyThree() => [43]; From dd94cd15e127768152596139055bd03661dee9a7 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:06:47 +0000 Subject: [PATCH 04/15] fix(reflection): skip CancellationToken in method-row constraint checks; method sources follow inferring rows (#7209) - ReflectionGenericConstraintViolations binds method-row values to the data parameters only, so a CancellationToken no longer shifts a value onto T and reports a false constraint violation (Greptile) - beside only type-free class rows, a [MethodDataSource] infers class type arguments only when no [Arguments] row of the method does; otherwise it runs on the rows' instantiations, as in the source generator (Codex) --- .../ReflectionGenericConstraintViolations.cs | 7 + .../Discovery/ReflectionTestDataCollector.cs | 26 ++- .../Tests7209.Test.verified.txt | 175 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 2 + .../ClassRowInfersNoTypeArgumentTests.cs | 36 ++++ 5 files changed, 238 insertions(+), 8 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs index 091d6a7ed3e..91e158f3e25 100644 --- a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs +++ b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs @@ -140,6 +140,13 @@ private void Add(MethodInfo testMethod, string message) { var typeArguments = new Type?[classGenericParameters.Length]; + // Row values bind to the data parameters only; the engine supplies any CancellationToken, wherever it + // is, as in InferClassTypeArgumentsFromMethodRow and the generator's GetDataParameters + if (Array.Exists(parameters, static parameter => parameter.ParameterType == typeof(CancellationToken))) + { + parameters = Array.FindAll(parameters, static parameter => parameter.ParameterType != typeof(CancellationToken)); + } + for (var i = 0; i < parameters.Length && i < values.Length; i++) { var parameterType = parameters[i].ParameterType; diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index ad599191fcf..158a5e8c688 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -1144,14 +1144,8 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin { // Class rows supply the instantiations, so [Arguments(null)] infers none and runs on each (#7141), // unless every class row goes to no type parameter (#7209) - var typeArguments = methodDataSources[i] switch - { - ArgumentsAttribute arguments => InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject: !classTypeArgumentsSupplied), - MethodDataSourceAttribute methodDataSource when !classTypeArgumentsSupplied => InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters), - _ => null - }; - - if (typeArguments != null) + if (methodDataSources[i] is ArgumentsAttribute arguments + && InferClassTypeArgumentsFromMethodRow(classGenericParameters, parameters, arguments, nullValuesArrayInfersObject: !classTypeArgumentsSupplied) is { } typeArguments) { // A plain local, not `(rowTypeArguments ??= ...)[i] = ...`: the .NET 8 trim analyzer // crashes (AD0001) on an array element write through a null-coalescing assignment. @@ -1160,6 +1154,22 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin } } + // Beside only type-free class rows, a [MethodDataSource] infers the class type arguments only when no + // [Arguments] row of the method does. Otherwise it runs on the instantiations those rows infer, as in + // the source generator, which drops the instantiation such a source alone infers (#7209). + if (!classTypeArgumentsSupplied && rowTypeArguments == null) + { + for (var i = 0; i < methodDataSources.Length; i++) + { + if (methodDataSources[i] is MethodDataSourceAttribute methodDataSource + && InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) is { } typeArguments) + { + rowTypeArguments ??= new Type[]?[methodDataSources.Length]; + rowTypeArguments[i] = typeArguments; + } + } + } + result[methodIndex] = rowTypeArguments; } diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 36e74afc8c7..725c918f303 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -577,3 +577,178 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource_ConstraintViolations = global::TUnit.Core.SourceRegistrar.RegisterGenericConstraintViolations(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowConstraintViolation<>), static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowConstraintViolation_T_Run__T_TestSource.ConstraintViolations); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithInferringRowAndMethodSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithInferringRowAndMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Rows"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource.Run", + filePath: "", + lineNumber: 117, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), + new global::TUnit.Core.MethodDataSourceAttribute("Rows") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndMethodSource.Rows()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndMethodSource_T_Run__T_TestSource.Entries_0); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithCancellationToken_T_Run__Cancellation_E3029BAB_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithCancellationToken", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken<>), "Run", false, 0, 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), +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false), +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "other", new global::TUnit.Core.ConcreteType(typeof(object)), true) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(cancellationToken, global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCancellationToken.Run", + filePath: "", + lineNumber: 134, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1, null), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCancellationToken_T_Run__Cancellation_E3029BAB_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCancellationToken_T_Run__Cancellation_E3029BAB_TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index f5e4bac4620..209f29b44d0 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -17,6 +17,8 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowBesideOtherSource", 2, 1)] [Arguments("TypeFreeClassRowWithUninferredMethodSource", 2, 2)] [Arguments("TypeFreeClassRowWithInferringMethodSource", 1, 1)] + [Arguments("TypeFreeClassRowWithInferringRowAndMethodSource", 2, 2)] + [Arguments("TypeFreeClassRowWithCancellationToken", 1, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index bb9f9062ea8..ad84d238b88 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -105,6 +105,42 @@ public async Task Run(T value) } } +// A [MethodDataSource] member of the test class beside a method row that infers T runs on the instantiation the row +// infers, not on one inferred from its own declared type: C runs Run(1) and Run(2), never C. Same in +// both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithInferringRowAndMethodSource(int number) +{ + public static IEnumerable Rows() => [2]; + + [Test] + [Arguments(1)] + [MethodDataSource(nameof(Rows))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value is 1 or 2).IsTrue(); + } +} + +// The engine supplies the CancellationToken, so the row's values bind to the other parameters: T is int, which +// satisfies the struct constraint, and the null goes to object, not to T. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithCancellationToken(int number) where T : struct +{ + [Test] + [Arguments(1, null)] + public async Task Run(CancellationToken token, T value, object? other) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That((object)value).IsEqualTo(1); + await Assert.That(other).IsNull(); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable FortyThree() => [43]; From c8071471278ef33fbfd0c3ef4972d6f5f961f793 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 00:48:43 +0000 Subject: [PATCH 05/15] fix(reflection): typed method sources infer beside type-free class rows; method-row constraint checks use discovery's type mapping (#7209) - InferClassTypeArgumentsOfMethodRows: beside only type-free class rows, a typed data source (ClassDataSource) on a method with no inferring [Arguments] row now infers the class type arguments, as the generator's InferTypesFromDataSourceAttribute does. Reflection ran no test for [Arguments(42)] C(int) with [ClassDataSource] Run(T); source-gen ran C.Run (Codex). - ReflectionGenericConstraintViolations.AddMethodRowViolations now infers through InferClassTypeArgumentsFromMethodRow, the mapping discovery uses, so a row whose parameter contains T (T[]) reports its constraint violation instead of disappearing (Greptile). - TestProject: TypeFreeClassRowWithTypedMethodSource and TypeFreeClassRowArrayConstraintViolation, with Issue7209Tests entries and the Tests7209 snapshot. --- .../ReflectionGenericConstraintViolations.cs | 49 +--- .../Discovery/ReflectionTestDataCollector.cs | 16 +- .../Tests7209.Test.verified.txt | 215 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 9 +- .../ClassRowInfersNoTypeArgumentTests.cs | 33 +++ 5 files changed, 269 insertions(+), 53 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs index 91e158f3e25..4ef00cd72b2 100644 --- a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs +++ b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs @@ -78,9 +78,11 @@ public void AddMethodRowViolations(bool classTypeArgumentsSupplied) foreach (var argumentsAttribute in testMethod.GetCustomAttributes(inherit: false)) { - // [Arguments(null)] (a null params array) stores one null value, which infers object - // here, as in the source generator (#7141) - var typeArguments = InferClassTypeArguments(classGenericParameters, parameters, argumentsAttribute.Values); + // The type mapping discovery uses, so a parameter that contains a type parameter (T[]) reports + // the row it drops. [Arguments(null)] (a null params array) infers object, as in the source + // generator (#7141) + var typeArguments = ReflectionTestDataCollector.InferClassTypeArgumentsFromMethodRow( + classGenericParameters, parameters, argumentsAttribute, nullValuesArrayInfersObject: true); if (typeArguments == null) { continue; @@ -135,45 +137,4 @@ private void Add(MethodInfo testMethod, string message) messages.Add(message); } - - private static Type[]? InferClassTypeArguments(Type[] classGenericParameters, ParameterInfo[] parameters, object?[] values) - { - var typeArguments = new Type?[classGenericParameters.Length]; - - // Row values bind to the data parameters only; the engine supplies any CancellationToken, wherever it - // is, as in InferClassTypeArgumentsFromMethodRow and the generator's GetDataParameters - if (Array.Exists(parameters, static parameter => parameter.ParameterType == typeof(CancellationToken))) - { - parameters = Array.FindAll(parameters, static parameter => parameter.ParameterType != typeof(CancellationToken)); - } - - for (var i = 0; i < parameters.Length && i < values.Length; i++) - { - var parameterType = parameters[i].ParameterType; - if (!parameterType.IsGenericParameter || parameterType.DeclaringMethod != null) - { - continue; - } - - // Match the source generator: Roslyn types a null element of the params object?[] argument - // as object, and a Type value as System.Type rather than its RuntimeType instance. - var position = parameterType.GenericParameterPosition; - typeArguments[position] ??= values[i] switch - { - null => typeof(object), - Type => typeof(Type), - var value => value.GetType() - }; - } - - foreach (var typeArgument in typeArguments) - { - if (typeArgument == null) - { - return null; - } - } - - return typeArguments!; - } } diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 158a5e8c688..a3f4a4cb8cb 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -1154,15 +1154,19 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin } } - // Beside only type-free class rows, a [MethodDataSource] infers the class type arguments only when no - // [Arguments] row of the method does. Otherwise it runs on the instantiations those rows infer, as in - // the source generator, which drops the instantiation such a source alone infers (#7209). + // Beside only type-free class rows, when no [Arguments] row of the method infers the class type arguments, + // a [MethodDataSource] or a typed data source (ClassDataSource, read as the generator's + // InferTypesFromDataSourceAttribute reads it) infers them, as in the source generator. Beside such a row, + // a [MethodDataSource] runs on the instantiations the rows infer, since the generator drops the + // instantiation that source alone infers (#7209). if (!classTypeArgumentsSupplied && rowTypeArguments == null) { for (var i = 0; i < methodDataSources.Length; i++) { - if (methodDataSources[i] is MethodDataSourceAttribute methodDataSource - && InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) is { } typeArguments) + var typeArguments = methodDataSources[i] is MethodDataSourceAttribute methodDataSource + ? InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) + : InferTypesFromTypedDataSource(methodDataSources[i], classGenericParameters.Length, classGenericParameterCount: 0); + if (typeArguments != null) { rowTypeArguments ??= new Type[]?[methodDataSources.Length]; rowTypeArguments[i] = typeArguments; @@ -1644,7 +1648,7 @@ private static bool IsInferredFromMethodRows(Dictionary && methodRowTypeArguments.TryGetValue(genericMethod, out var groups) && IndexOfTypeArguments(groups, typeArguments) >= 0; - private static Type[]? InferClassTypeArgumentsFromMethodRow(Type[] classGenericParameters, ParameterInfo[] parameters, ArgumentsAttribute arguments, bool nullValuesArrayInfersObject) + internal static Type[]? InferClassTypeArgumentsFromMethodRow(Type[] classGenericParameters, ParameterInfo[] parameters, ArgumentsAttribute arguments, bool nullValuesArrayInfersObject) { // [Arguments(null)] (a null params array) infers no type when [GenerateGenericTest] supplies the // instantiations it runs on. Otherwise its one null value infers object, as in the source generator. diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 725c918f303..376c19e09c9 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -752,3 +752,218 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCancellationToken_T_Run__Cancellation_E3029BAB_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCancellationToken_T_Run__Cancellation_E3029BAB_TestSource.Entries_0); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithTypedMethodSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithTypedMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedMethodSource.Run", + filePath: "", + lineNumber: 150, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedMethodSource_T_Run__T_TestSource.Entries_0); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowArrayConstraintViolation", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "values", new global::TUnit.Core.ConcreteType(typeof(object)), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + switch (args.Length) + { + case 0: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::System.Array.Empty())); + } + case 1: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run((args[0] is null ? null : args[0] is string[] arr ? arr : global::TUnit.Core.Helpers.CastHelper.ToTrailingArray(args[0])))); + } + case 2: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(new string[] { global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]) })); + } + case 3: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(new string[] { global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]), global::TUnit.Core.Helpers.CastHelper.Cast(args[2]) })); + } + case 4: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(new string[] { global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]), global::TUnit.Core.Helpers.CastHelper.Cast(args[2]), global::TUnit.Core.Helpers.CastHelper.Cast(args[3]) })); + } + case 5: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(new string[] { global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]), global::TUnit.Core.Helpers.CastHelper.Cast(args[2]), global::TUnit.Core.Helpers.CastHelper.Cast(args[3]), global::TUnit.Core.Helpers.CastHelper.Cast(args[4]) })); + } + case 6: + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(new string[] { global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]), global::TUnit.Core.Helpers.CastHelper.Cast(args[2]), global::TUnit.Core.Helpers.CastHelper.Cast(args[3]), global::TUnit.Core.Helpers.CastHelper.Cast(args[4]), global::TUnit.Core.Helpers.CastHelper.Cast(args[5]) })); + } + default: + return new global::System.Threading.Tasks.ValueTask(instance.Run((args.Length > 0 ? global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(global::System.Linq.Enumerable.Range(0, args.Length), i => global::TUnit.Core.Helpers.CastHelper.Cast(args[i]))) : global::System.Array.Empty()))); + } + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation.Run", + filePath: "", + lineNumber: 166, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(new object[] { new[] { "a" } }), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + public static readonly global::TUnit.Core.GenericConstraintViolationEntry[] ConstraintViolations = new global::TUnit.Core.GenericConstraintViolationEntry[] + { + new global::TUnit.Core.GenericConstraintViolationEntry + { + MethodName = "Run", + FilePath = "", + LineNumber = 166, + MethodMetadata = __mm_0, + Messages = new string[] { "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'" }, + }, + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource_ConstraintViolations = global::TUnit.Core.SourceRegistrar.RegisterGenericConstraintViolations(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource.ConstraintViolations); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 209f29b44d0..25ee7f654d0 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -19,6 +19,7 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithInferringMethodSource", 1, 1)] [Arguments("TypeFreeClassRowWithInferringRowAndMethodSource", 2, 2)] [Arguments("TypeFreeClassRowWithCancellationToken", 1, 1)] + [Arguments("TypeFreeClassRowWithTypedMethodSource", 1, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( @@ -35,17 +36,19 @@ await RunTestsWithFilter( } [Test] - public async Task Method_Row_Inferring_An_Invalid_Class_Type_Beside_A_Type_Free_Class_Row_Fails() + [Arguments("TypeFreeClassRowConstraintViolation", "Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'")] + [Arguments("TypeFreeClassRowArrayConstraintViolation", "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'")] + public async Task Method_Row_Inferring_An_Invalid_Class_Type_Beside_A_Type_Free_Class_Row_Fails(string className, string expectedMessage) { await RunTestsWithFilter( - $"{Namespace}/TypeFreeClassRowConstraintViolation*/*", + $"{Namespace}/{className}*/*", [ result => result.ResultSummary.Counters.Total.ShouldBe(2), result => result.ResultSummary.Counters.Passed.ShouldBe(1), result => result.ResultSummary.Counters.Failed.ShouldBe(1), result => result.Results.Single(x => x.Outcome == "Failed").TestName.ShouldBe("Run"), result => result.Results.Single(x => x.Outcome == "Failed").Output?.ErrorInfo?.Message - .ShouldContain("Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'") + .ShouldContain(expectedMessage) ]); } } diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index ad84d238b88..b34016470f4 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -141,6 +141,39 @@ public async Task Run(CancellationToken token, T value, object? other) } } +// A typed data source infers T from its declared type, as without a class row: ClassDataSource runs on C, +// built from the class row (number = 42). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithTypedMethodSource(int number) +{ + [Test] + [ClassDataSource] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(0); + } +} + +// Beside only a type-free class row, a method row whose parameter contains T, not only T itself, still reports the +// types that break the class's constraints: new int[] { 1 } for T[] infers int, which is not a class. Run(["a"]) +// runs on C. No [EngineTest]: TUnit.Engine.Tests targets it by name, because it has a failing row. +[Arguments(42)] +public class TypeFreeClassRowArrayConstraintViolation(int number) where T : class +{ + [Test] + [Arguments(new object[] { new[] { "a" } })] + [Arguments(new object[] { new[] { 1 } })] + public async Task Run(T[] values) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(string)); + await Assert.That(values.Length).IsEqualTo(1); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable FortyThree() => [43]; From 948d4b126c5385f577db28ba38f6d8aadec3fa88 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 01:41:46 +0000 Subject: [PATCH 06/15] fix(reflection): infer class type arguments from parameter attributes beside type-free class rows (#7209) Beside only type-free class rows, a [MatrixDataSource] method whose T parameter carries [Matrix] lost its only instantiation in reflection mode. Infer the class type arguments from IInfersType (or typed data source generator) parameter attributes, as the generator's InferTypesFromTypedDataSourceForClass does, and run every method data source on that instantiation. --- .../Discovery/ReflectionTestDataCollector.cs | 75 ++++++++++++++++ .../Tests7209.Test.verified.txt | 89 ++++++++++++++++++- tests/TUnit.Engine.Tests/Issue7209Tests.cs | 1 + .../ClassRowInfersNoTypeArgumentTests.cs | 17 ++++ 4 files changed, 180 insertions(+), 2 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index a3f4a4cb8cb..9183bc072c1 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -1172,6 +1172,16 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin rowTypeArguments[i] = typeArguments; } } + + // Failing those, parameter attributes ([Matrix] on a T parameter) infer them, as the generator's + // InferTypesFromTypedDataSourceForClass does. That instantiation runs every method data source. + if (rowTypeArguments == null + && methodDataSources.Length > 0 + && InferClassTypeArgumentsFromParameterAttributes(classGenericParameters.Length, parameters) is { } parameterTypeArguments) + { + rowTypeArguments = new Type[]?[methodDataSources.Length]; + Array.Fill(rowTypeArguments, parameterTypeArguments); + } } result[methodIndex] = rowTypeArguments; @@ -1180,6 +1190,71 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin return result; } + /// + /// The class type arguments that the attributes of parameters typed by a class type parameter infer, or null + /// unless every class type parameter is inferred. Mirrors the generator's + /// InferTypesFromTypedDataSourceForClass: an attribute implementing IInfersType<T> infers + /// T, and failing that, a typed data source generator attribute infers its first type argument. + /// + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Reflection mode requires dynamic access; attribute interfaces are only read, not invoked")] + private static Type[]? InferClassTypeArgumentsFromParameterAttributes(int classGenericParameterCount, ParameterInfo[] parameters) + { + Type[]? typeArguments = null; + + foreach (var parameter in parameters) + { + var parameterType = parameter.ParameterType; + if (!parameterType.IsGenericParameter || parameterType.DeclaringMethod is not null) + { + continue; + } + + foreach (var attribute in parameter.GetCustomAttributes(inherit: false)) + { + var inferred = GetInferredType(attribute.GetType()) ?? GetTypedDataSourceGeneratorTypeArgument(attribute.GetType()); + if (inferred is not null) + { + typeArguments ??= new Type[classGenericParameterCount]; + typeArguments[parameterType.GenericParameterPosition] = inferred; + break; + } + } + } + + return typeArguments is not null && Array.TrueForAll(typeArguments, static typeArgument => typeArgument is not null) + ? typeArguments + : null; + + static Type? GetInferredType(Type attributeType) + { + foreach (var implemented in attributeType.GetInterfaces()) + { + if (implemented.IsGenericType && implemented.GetGenericTypeDefinition() == typeof(TUnit.Core.Interfaces.IInfersType<>)) + { + return implemented.GetGenericArguments()[0]; + } + } + + return null; + } + + static Type? GetTypedDataSourceGeneratorTypeArgument(Type attributeType) + { + for (var baseType = attributeType.BaseType; baseType is not null; baseType = baseType.BaseType) + { + if (baseType.IsGenericType + && baseType.GetGenericTypeDefinition() is { Namespace: "TUnit.Core" } definition + && (definition.Name.StartsWith("DataSourceGeneratorAttribute`", StringComparison.Ordinal) + || definition.Name.StartsWith("AsyncDataSourceGeneratorAttribute`", StringComparison.Ordinal))) + { + return baseType.GetGenericArguments()[0]; + } + } + + return null; + } + } + /// /// The class type arguments that a method-level [MethodDataSource] infers from the declared return type of /// its member, or null. Mirrors the generator's InferClassTypesFromMethodDataSource: only diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 376c19e09c9..07fce252797 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -839,6 +839,91 @@ internal static partial class TUnit_TestRegistration } +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithInferringParameterAttribute_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithInferringParameterAttribute", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MatrixDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute.Run", + filePath: "", + lineNumber: 167, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MatrixDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringParameterAttribute_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringParameterAttribute_T_Run__T_TestSource.Entries_0); +} + + // ===== FILE SEPARATOR ===== // @@ -930,7 +1015,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "values", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation.Run", filePath: "", - lineNumber: 166, + lineNumber: 183, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -953,7 +1038,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "values", new { MethodName = "Run", FilePath = "", - LineNumber = 166, + LineNumber = 183, MethodMetadata = __mm_0, Messages = new string[] { "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'" }, }, diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 25ee7f654d0..9e15365bc0d 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -20,6 +20,7 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithInferringRowAndMethodSource", 2, 2)] [Arguments("TypeFreeClassRowWithCancellationToken", 1, 1)] [Arguments("TypeFreeClassRowWithTypedMethodSource", 1, 1)] + [Arguments("TypeFreeClassRowWithInferringParameterAttribute", 2, 2)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index b34016470f4..1655715471f 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -157,6 +157,23 @@ public async Task Run(T value) } } +// Beside only a type-free class row, a parameter attribute that infers T (Matrix implements IInfersType) +// supplies the instantiation, as in the source generator: both matrix values run on C, each instance built from +// the class row (number = 42). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithInferringParameterAttribute(int number) +{ + [Test] + [MatrixDataSource] + public async Task Run([Matrix(1, 2)] T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsNotNull(); + } +} + // Beside only a type-free class row, a method row whose parameter contains T, not only T itself, still reports the // types that break the class's constraints: new int[] { 1 } for T[] infers int, which is not a class. Run(["a"]) // runs on C. No [EngineTest]: TUnit.Engine.Tests targets it by name, because it has a failing row. From 73e13a00659af7ff6ef219330c32cc0f82618175 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 02:32:58 +0000 Subject: [PATCH 07/15] fix(reflection): typed and method sources beside type-free class rows infer instantiations without being scoped to them (#7209) A typed data source beside an [Arguments] row that infers another type now also infers its own instantiation, and two method data sources that infer different types each run on both instantiations, as in the source generator. --- .../Discovery/ReflectionTestDataCollector.cs | 92 ++++-- .../Tests7209.Test.verified.txt | 291 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 2 + .../ClassRowInfersNoTypeArgumentTests.cs | 39 +++ 4 files changed, 396 insertions(+), 28 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 9183bc072c1..ec21695ee25 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -533,9 +533,10 @@ private static async Task> DiscoverGenericTests(Type genericT // With class-level [Arguments] rows, method rows run only on the class instantiation their own values // infer (#7118) + List?[]? methodSourceInstantiations = null; var methodRowClassTypeArguments = methodRowTests == null ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources.Length + (typeFreeClassRows?.Length ?? 0), - classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0) + classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0, out methodSourceInstantiations) : null; // [GenerateGenericTest] types' class constraint violations are reported before the class rows' @@ -606,7 +607,7 @@ private static async Task> DiscoverGenericTests(Type genericT if (methodRowClassTypeArguments != null) { - discoveredTests.AddRange(BuildTestsForMethodRowsWithoutClassRow(genericTypeDefinition, testMethods, methodRowClassTypeArguments, classRowGroups!, allClassRows, typeFreeClassRows, generateGenericTestAttributes)); + discoveredTests.AddRange(BuildTestsForMethodRowsWithoutClassRow(genericTypeDefinition, testMethods, methodRowClassTypeArguments, methodSourceInstantiations, classRowGroups!, allClassRows, typeFreeClassRows, generateGenericTestAttributes)); } // Type-free class rows were split out of classDataSources, so beside only those, method rows infer the @@ -1112,8 +1113,15 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// object, and a [MethodDataSource] member of the test class infers them from its declared type, as in the /// source generator. /// - private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied) + /// + /// For each test method, the class instantiations that its other data sources infer beside only type-free + /// class rows (#7209): a typed data source, a [MethodDataSource] member of the test class, or a parameter + /// attribute. Unlike an [Arguments] row, such a source is not scoped to the instantiation it infers: every + /// instantiation runs it, as in the source generator. Null when no method has one. + /// + private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied, out List?[]? sourceInstantiations) { + sourceInstantiations = null; if (classDataSourceCount == 0) { return null; @@ -1154,33 +1162,42 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin } } - // Beside only type-free class rows, when no [Arguments] row of the method infers the class type arguments, - // a [MethodDataSource] or a typed data source (ClassDataSource, read as the generator's - // InferTypesFromDataSourceAttribute reads it) infers them, as in the source generator. Beside such a row, - // a [MethodDataSource] runs on the instantiations the rows infer, since the generator drops the - // instantiation that source alone infers (#7209). - if (!classTypeArgumentsSupplied && rowTypeArguments == null) + // Beside only type-free class rows, a typed data source (ClassDataSource, read as the generator's + // InferTypesFromDataSourceAttribute reads it) infers an instantiation, and so does a [MethodDataSource] + // when no [Arguments] row of the method infers one: beside such a row, the generator drops the + // instantiation that a [MethodDataSource] alone infers, so that source runs on the rows' instantiations. + // Neither source is scoped to the instantiation it infers: each instantiation runs every source that + // infers no type, as in the source generator (#7209). + if (!classTypeArgumentsSupplied) { + List? instantiations = null; for (var i = 0; i < methodDataSources.Length; i++) { - var typeArguments = methodDataSources[i] is MethodDataSourceAttribute methodDataSource - ? InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) - : InferTypesFromTypedDataSource(methodDataSources[i], classGenericParameters.Length, classGenericParameterCount: 0); - if (typeArguments != null) + var typeArguments = methodDataSources[i] switch { - rowTypeArguments ??= new Type[]?[methodDataSources.Length]; - rowTypeArguments[i] = typeArguments; - } + ArgumentsAttribute => null, + MethodDataSourceAttribute methodDataSource => rowTypeArguments == null + ? InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) + : null, + var dataSource => InferTypesFromTypedDataSource(dataSource, classGenericParameters.Length, classGenericParameterCount: 0), + }; + AddDistinctTypeArguments(ref instantiations, typeArguments); } // Failing those, parameter attributes ([Matrix] on a T parameter) infer them, as the generator's // InferTypesFromTypedDataSourceForClass does. That instantiation runs every method data source. if (rowTypeArguments == null + && instantiations == null && methodDataSources.Length > 0 && InferClassTypeArgumentsFromParameterAttributes(classGenericParameters.Length, parameters) is { } parameterTypeArguments) { - rowTypeArguments = new Type[]?[methodDataSources.Length]; - Array.Fill(rowTypeArguments, parameterTypeArguments); + instantiations = [parameterTypeArguments]; + } + + if (instantiations != null) + { + sourceInstantiations ??= new List?[testMethods.Length]; + sourceInstantiations[methodIndex] = instantiations; } } @@ -1425,12 +1442,14 @@ private static void MapClassGenericParameters(Type parameterType, Type actualTyp /// () supply the constructor arguments of every such instantiation, as in /// the source generator (#7209). A class-level [GenerateGenericTest] listing those type arguments runs /// the rows instead. Rows whose type arguments break the class's constraints are skipped, as the source - /// generator skips them. + /// generator skips them. The instantiations that other method sources infer beside only type-free class rows + /// () are built the same way, without scoping those sources. /// private static List BuildTestsForMethodRowsWithoutClassRow( Type genericTypeDefinition, MethodInfo[] testMethods, Type[]?[]?[] methodRowClassTypeArguments, + List?[]? methodSourceInstantiations, List classRowGroups, List? allClassRows, IDataSourceAttribute[]? typeFreeClassRows, @@ -1443,24 +1462,29 @@ private static List BuildTestsForMethodRowsWithoutClassRow( for (var methodIndex = 0; methodIndex < testMethods.Length; methodIndex++) { - if (methodRowClassTypeArguments[methodIndex] is not { } rowTypeArguments) + var rowTypeArguments = methodRowClassTypeArguments[methodIndex]; + var sourceInstantiations = methodSourceInstantiations?[methodIndex]; + if (rowTypeArguments == null && sourceInstantiations == null) { continue; } - // Distinct type arguments, in row order, that no class row infers + // Distinct type arguments, in row order and then in source order, that no class row infers List? unmatchedGroups = null; - foreach (var typeArguments in rowTypeArguments) + foreach (var typeArguments in rowTypeArguments ?? []) { - if (typeArguments == null - || IsInferredByClassRows(classRowGroups, typeArguments) - || IsListedByGenerateGenericTest(generateGenericTestAttributes, typeArguments) - || (unmatchedGroups != null && IndexOfTypeArguments(unmatchedGroups, typeArguments) >= 0)) + if (typeArguments != null && !IsSuppliedByClass(typeArguments)) { - continue; + AddDistinctTypeArguments(ref unmatchedGroups, typeArguments); } + } - (unmatchedGroups ??= []).Add(typeArguments); + foreach (var typeArguments in sourceInstantiations ?? []) + { + if (!IsSuppliedByClass(typeArguments)) + { + AddDistinctTypeArguments(ref unmatchedGroups, typeArguments); + } } if (unmatchedGroups == null) @@ -1514,6 +1538,18 @@ private static List BuildTestsForMethodRowsWithoutClassRow( } return tests ?? []; + + bool IsSuppliedByClass(Type[] typeArguments) => + IsInferredByClassRows(classRowGroups, typeArguments) || IsListedByGenerateGenericTest(generateGenericTestAttributes, typeArguments); + } + + /// Adds to unless it is null or already listed. + private static void AddDistinctTypeArguments(ref List? list, Type[]? typeArguments) + { + if (typeArguments != null && (list == null || IndexOfTypeArguments(list, typeArguments) < 0)) + { + (list ??= []).Add(typeArguments); + } } /// diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 07fce252797..c996bcbd07c 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -1052,3 +1052,294 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource_ConstraintViolations = global::TUnit.Core.SourceRegistrar.RegisterGenericConstraintViolations(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation<>), static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowArrayConstraintViolation_T_Run__T___TestSource.ConstraintViolations); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithInferringRowAndTypedSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithInferringRowAndTypedSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource.Run", + filePath: "", + lineNumber: 201, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1L), + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource.Run", + filePath: "", + lineNumber: 201, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndTypedSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndTypedSource_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndTypedSource_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInferringRowAndTypedSource_T_Run__T_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithTwoInferringMethodSources", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Ints"), + new global::TUnit.Core.MethodDataSourceAttribute("Objects"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Run", + filePath: "", + lineNumber: 218, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Ints") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Ints()), + }, + new global::TUnit.Core.MethodDataSourceAttribute("Objects") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Objects()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Ints"), + new global::TUnit.Core.MethodDataSourceAttribute("Objects"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Run", + filePath: "", + lineNumber: 218, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Ints") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Ints()), + }, + new global::TUnit.Core.MethodDataSourceAttribute("Objects") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Objects()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource.Entries_1); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 9e15365bc0d..d9744fa0314 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -21,6 +21,8 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithCancellationToken", 1, 1)] [Arguments("TypeFreeClassRowWithTypedMethodSource", 1, 1)] [Arguments("TypeFreeClassRowWithInferringParameterAttribute", 2, 2)] + [Arguments("TypeFreeClassRowWithInferringRowAndTypedSource", 3, 2)] + [Arguments("TypeFreeClassRowWithTwoInferringMethodSources", 4, 2)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 1655715471f..efc572ffb37 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -191,6 +191,45 @@ public async Task Run(T[] values) } } +// A typed data source infers T beside a method row that infers another type, and is not scoped to it: [Arguments(1L)] +// runs on C, and ClassDataSource runs on C and on C, each built from the class row (number = 42), +// as in the source generator. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithInferringRowAndTypedSource(int number) +{ + [Test] + [Arguments(1L)] + [ClassDataSource] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That((object?)value is 1L or 0L or 0).IsTrue(); + await Assert.That(typeof(T)).IsEqualTo(value is long ? typeof(long) : typeof(int)); + } +} + +// Two method data sources that infer different types: each instantiation they infer runs both sources, as in the +// source generator, so C and C each run Run(1) and Run(2). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithTwoInferringMethodSources(int number) +{ + [Test] + [MethodDataSource(nameof(Ints))] + [MethodDataSource(nameof(Objects))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T) == typeof(int) || typeof(T) == typeof(object)).IsTrue(); + await Assert.That((object?)value is 1 or 2).IsTrue(); + } + + public static IEnumerable Ints() => [1]; + + public static IEnumerable Objects() => [2]; +} + public static class TypeFreeClassRowSources { public static IEnumerable FortyThree() => [43]; From c04450e590dedeb34c6fcdd770aa6078e07d3eb7 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:09:30 +0000 Subject: [PATCH 08/15] fix(reflection): a typed source beside a type-free class row runs only on its instantiation, and parameter attributes infer theirs beside it (#7209) Beside only type-free class rows, a typed method data source's instantiation runs only that source, and a parameter attribute ([Matrix] on a T parameter) infers its instantiation beside the typed source's, as in the source generator. Adds parity fixtures for both cases. --- .../Discovery/ReflectionTestDataCollector.cs | 122 +++++--- .../Tests7209.Test.verified.txt | 279 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 2 + .../ClassRowInfersNoTypeArgumentTests.cs | 35 +++ 4 files changed, 393 insertions(+), 45 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index ec21695ee25..2df2331a1f8 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -533,7 +533,7 @@ private static async Task> DiscoverGenericTests(Type genericT // With class-level [Arguments] rows, method rows run only on the class instantiation their own values // infer (#7118) - List?[]? methodSourceInstantiations = null; + List?[]? methodSourceInstantiations = null; var methodRowClassTypeArguments = methodRowTests == null ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources.Length + (typeFreeClassRows?.Length ?? 0), classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0, out methodSourceInstantiations) @@ -1116,10 +1116,12 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// /// For each test method, the class instantiations that its other data sources infer beside only type-free /// class rows (#7209): a typed data source, a [MethodDataSource] member of the test class, or a parameter - /// attribute. Unlike an [Arguments] row, such a source is not scoped to the instantiation it infers: every - /// instantiation runs it, as in the source generator. Null when no method has one. + /// attribute, in the source generator's order, the first source to infer a type keeping it. A typed data + /// source's instantiation runs only that source; the others run every method data source that infers no + /// type, as in the source generator. Unlike an [Arguments] row, none of these sources is kept off the other + /// instantiations. Null when no method has one. /// - private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied, out List?[]? sourceInstantiations) + private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied, out List?[]? sourceInstantiations) { sourceInstantiations = null; if (classDataSourceCount == 0) @@ -1163,40 +1165,42 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin } // Beside only type-free class rows, a typed data source (ClassDataSource, read as the generator's - // InferTypesFromDataSourceAttribute reads it) infers an instantiation, and so does a [MethodDataSource] - // when no [Arguments] row of the method infers one: beside such a row, the generator drops the - // instantiation that a [MethodDataSource] alone infers, so that source runs on the rows' instantiations. - // Neither source is scoped to the instantiation it infers: each instantiation runs every source that - // infers no type, as in the source generator (#7209). + // InferTypesFromDataSourceAttribute reads it) infers an instantiation that runs only that source. A + // [MethodDataSource] infers one too when no [Arguments] row of the method infers one: beside such a + // row, the generator drops the instantiation that a [MethodDataSource] alone infers, so that source + // runs on the rows' instantiations. A [MethodDataSource]'s instantiation runs every method data source + // that infers no type, and no source is kept off another source's instantiation, as in the source + // generator (#7209). The generator adds typed sources first, then [MethodDataSource]s. if (!classTypeArgumentsSupplied) { - List? instantiations = null; + List? instantiations = null; for (var i = 0; i < methodDataSources.Length; i++) { - var typeArguments = methodDataSources[i] switch + if (methodDataSources[i] is not (ArgumentsAttribute or MethodDataSourceAttribute)) { - ArgumentsAttribute => null, - MethodDataSourceAttribute methodDataSource => rowTypeArguments == null - ? InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters) - : null, - var dataSource => InferTypesFromTypedDataSource(dataSource, classGenericParameters.Length, classGenericParameterCount: 0), - }; - AddDistinctTypeArguments(ref instantiations, typeArguments); + AddSourceInstantiation(ref instantiations, InferTypesFromTypedDataSource(methodDataSources[i], classGenericParameters.Length, classGenericParameterCount: 0), sourceIndex: i); + } } - // Failing those, parameter attributes ([Matrix] on a T parameter) infer them, as the generator's - // InferTypesFromTypedDataSourceForClass does. That instantiation runs every method data source. - if (rowTypeArguments == null - && instantiations == null - && methodDataSources.Length > 0 - && InferClassTypeArgumentsFromParameterAttributes(classGenericParameters.Length, parameters) is { } parameterTypeArguments) + for (var i = 0; rowTypeArguments == null && i < methodDataSources.Length; i++) { - instantiations = [parameterTypeArguments]; + if (methodDataSources[i] is MethodDataSourceAttribute methodDataSource) + { + AddSourceInstantiation(ref instantiations, InferClassTypeArgumentsFromMethodDataSource(genericTypeDefinition, methodDataSource, parameters), sourceIndex: -1); + } + } + + // Parameter attributes ([Matrix] on a T parameter) infer an instantiation too, beside those of + // the sources above, as the generator's InferTypesFromTypedDataSourceForClass does. It runs every + // method data source. + if (rowTypeArguments == null && methodDataSources.Length > 0) + { + AddSourceInstantiation(ref instantiations, InferClassTypeArgumentsFromParameterAttributes(classGenericParameters.Length, parameters), sourceIndex: -1); } if (instantiations != null) { - sourceInstantiations ??= new List?[testMethods.Length]; + sourceInstantiations ??= new List?[testMethods.Length]; sourceInstantiations[methodIndex] = instantiations; } } @@ -1207,6 +1211,35 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin return result; } + /// + /// A class instantiation that a method data source other than an [Arguments] row infers beside only type-free + /// class rows (#7209). is the index, among the method's data sources, of the only + /// source that runs on it (a typed data source), or -1 when every method data source that infers no type does. + /// + private readonly record struct SourceInstantiation(Type[] TypeArguments, int SourceIndex); + + /// Adds to unless its type arguments are already listed. + private static void AddSourceInstantiation(ref List? list, SourceInstantiation instantiation) + { + foreach (var existing in list ?? []) + { + if (AreSameTypeArguments(existing.TypeArguments, instantiation.TypeArguments)) + { + return; + } + } + + (list ??= []).Add(instantiation); + } + + private static void AddSourceInstantiation(ref List? list, Type[]? typeArguments, int sourceIndex) + { + if (typeArguments != null) + { + AddSourceInstantiation(ref list, new SourceInstantiation(typeArguments, sourceIndex)); + } + } + /// /// The class type arguments that the attributes of parameters typed by a class type parameter infer, or null /// unless every class type parameter is inferred. Mirrors the generator's @@ -1443,13 +1476,14 @@ private static void MapClassGenericParameters(Type parameterType, Type actualTyp /// the source generator (#7209). A class-level [GenerateGenericTest] listing those type arguments runs /// the rows instead. Rows whose type arguments break the class's constraints are skipped, as the source /// generator skips them. The instantiations that other method sources infer beside only type-free class rows - /// () are built the same way, without scoping those sources. + /// () are built the same way: one that a typed data source infers + /// runs only that source, as in the source generator. /// private static List BuildTestsForMethodRowsWithoutClassRow( Type genericTypeDefinition, MethodInfo[] testMethods, Type[]?[]?[] methodRowClassTypeArguments, - List?[]? methodSourceInstantiations, + List?[]? methodSourceInstantiations, List classRowGroups, List? allClassRows, IDataSourceAttribute[]? typeFreeClassRows, @@ -1469,21 +1503,22 @@ private static List BuildTestsForMethodRowsWithoutClassRow( continue; } - // Distinct type arguments, in row order and then in source order, that no class row infers - List? unmatchedGroups = null; + // Distinct type arguments, in row order and then in source order, that no class row infers. A row's + // instantiation runs every source that infers no type; a typed data source's runs only that source. + List? unmatchedGroups = null; foreach (var typeArguments in rowTypeArguments ?? []) { if (typeArguments != null && !IsSuppliedByClass(typeArguments)) { - AddDistinctTypeArguments(ref unmatchedGroups, typeArguments); + AddSourceInstantiation(ref unmatchedGroups, typeArguments, sourceIndex: -1); } } - foreach (var typeArguments in sourceInstantiations ?? []) + foreach (var instantiation in sourceInstantiations ?? []) { - if (!IsSuppliedByClass(typeArguments)) + if (!IsSuppliedByClass(instantiation.TypeArguments)) { - AddDistinctTypeArguments(ref unmatchedGroups, typeArguments); + AddSourceInstantiation(ref unmatchedGroups, instantiation); } } @@ -1493,7 +1528,7 @@ private static List BuildTestsForMethodRowsWithoutClassRow( } var genericMethod = testMethods[methodIndex]; - foreach (var typeArguments in unmatchedGroups) + foreach (var (typeArguments, sourceIndex) in unmatchedGroups) { Type concreteType; try @@ -1520,7 +1555,13 @@ private static List BuildTestsForMethodRowsWithoutClassRow( // Type-free class rows make this a class row instantiation, so the method sources that infer // no type run on it too, as in the source generator (#7209) - var methodRows = ScopeMethodRowsToClassTypeArguments(concreteType, concreteMethod, rowTypeArguments, typeArguments, onlyInferringRows: typeFreeClassRows == null); + // A typed data source's instantiation runs only that source. Its index lines up with the closed + // method's sources, as in ScopeMethodRowsToClassTypeArguments, which keeps every source should + // the two lists ever differ. + var closedDataSources = sourceIndex >= 0 ? ReflectionAttributeExtractor.ExtractMethodDataSources(concreteMethod, concreteType) : null; + IDataSourceAttribute[]? methodRows = closedDataSources != null && sourceIndex < closedDataSources.Length + ? [closedDataSources[sourceIndex]] + : ScopeMethodRowsToClassTypeArguments(concreteType, concreteMethod, rowTypeArguments, typeArguments, onlyInferringRows: typeFreeClassRows == null); (tests ??= []).Add(allClassRowSources == null ? BuildTestMetadata( concreteType, @@ -1543,15 +1584,6 @@ bool IsSuppliedByClass(Type[] typeArguments) => IsInferredByClassRows(classRowGroups, typeArguments) || IsListedByGenerateGenericTest(generateGenericTestAttributes, typeArguments); } - /// Adds to unless it is null or already listed. - private static void AddDistinctTypeArguments(ref List? list, Type[]? typeArguments) - { - if (typeArguments != null && (list == null || IndexOfTypeArguments(list, typeArguments) < 0)) - { - (list ??= []).Add(typeArguments); - } - } - /// /// Removes from the class-level [Arguments] rows whose values all bind to /// constructor parameters that do not use the class's type parameters, as [Arguments(42)] on diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index c996bcbd07c..c62af942c5c 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -1343,3 +1343,282 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoInferringMethodSources_T_Run__T_TestSource.Entries_1); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithTypedSourceAndInferringParameterAttri_D4DF1E54_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.MatrixDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute.Run", + filePath: "", + lineNumber: 241, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.MatrixDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute.Run", + filePath: "", + lineNumber: 241, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.MatrixDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndInferringParameterAttri_D4DF1E54_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndInferringParameterAttri_D4DF1E54_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndInferringParameterAttri_D4DF1E54_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndInferringParameterAttri_D4DF1E54_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithTwoTypedSources", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources.Run", + filePath: "", + lineNumber: 258, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources.Run", + filePath: "", + lineNumber: 258, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource.Entries_1); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index d9744fa0314..e3b31e7428e 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -23,6 +23,8 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithInferringParameterAttribute", 2, 2)] [Arguments("TypeFreeClassRowWithInferringRowAndTypedSource", 3, 2)] [Arguments("TypeFreeClassRowWithTwoInferringMethodSources", 4, 2)] + [Arguments("TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute", 4, 3)] + [Arguments("TypeFreeClassRowWithTwoTypedSources", 2, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index efc572ffb37..dafce020750 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -230,6 +230,41 @@ public async Task Run(T value) public static IEnumerable Objects() => [2]; } +// A parameter attribute infers T beside a typed data source that infers another type, and both instantiations run: +// ClassDataSource infers C, which runs only that source (Run(0)), and Matrix infers C, which runs +// every method data source (Run(0), Run(1) and Run(2)), each built from the class row (number = 42), as in the source +// generator. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute(int number) +{ + [Test] + [ClassDataSource] + [MatrixDataSource] + public async Task Run([Matrix(1, 2)] T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(value is long ? typeof(long) : typeof(int)); + await Assert.That((object?)value is 0L or 0 or 1 or 2).IsTrue(); + } +} + +// Two typed data sources that infer different types: each instantiation runs only the source that infers it, as in +// the source generator, so C runs ClassDataSource and C runs ClassDataSource. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithTwoTypedSources(int number) +{ + [Test] + [ClassDataSource] + [ClassDataSource] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(value!.GetType()).IsEqualTo(typeof(T)); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable FortyThree() => [43]; From 6a97bb86615b480986103217b05d6c470893eb3d Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 03:40:03 +0000 Subject: [PATCH 09/15] fix(reflection): method sources still infer beside a type-free class row when another class source yields no instantiation (#7209) A class data source whose rows infer no class type argument (for example an empty [MethodDataSource]) made reflection mode stop inferring from the method's own sources, so it discovered no tests, while the source generator still infers C from them. Reflection now groups the class rows first and lets the method sources infer unless a class [Arguments] row, [GenerateGenericTest], or a run-time source's rows supplied an instantiation. --- .../ReflectionGenericConstraintViolations.cs | 7 ++ .../Discovery/ReflectionTestDataCollector.cs | 42 +++++--- .../Tests7209.Test.verified.txt | 95 +++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 14 +++ .../ClassRowInfersNoTypeArgumentTests.cs | 22 +++++ 5 files changed, 166 insertions(+), 14 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs index 4ef00cd72b2..fe8151e113a 100644 --- a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs +++ b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs @@ -27,6 +27,12 @@ internal sealed class ReflectionGenericConstraintViolations( { private Dictionary>? _messagesByMethod; + /// + /// Whether recorded a violation: some source supplied class type + /// arguments, even though they break the class's constraints. + /// + public bool HasClassViolation { get; private set; } + /// /// Records as a violation for every test method when they break /// the class's constraints. Returns true when they do, so the caller skips the instantiation. @@ -44,6 +50,7 @@ public bool TryAddClassViolation(Type[] typeArguments) Add(testMethod, message); } + HasClassViolation = true; return true; } diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 2df2331a1f8..17d5b8d7d29 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -531,23 +531,34 @@ private static async Task> DiscoverGenericTests(Type genericT ? SplitTypeFreeClassRows(genericTypeDefinition, ref classDataSources) : null; - // With class-level [Arguments] rows, method rows run only on the class instantiation their own values - // infer (#7118) - List?[]? methodSourceInstantiations = null; - var methodRowClassTypeArguments = methodRowTests == null - ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSources.Length + (typeFreeClassRows?.Length ?? 0), - classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0, out methodSourceInstantiations) - : null; + var classDataSourceCount = classDataSources.Length + (typeFreeClassRows?.Length ?? 0); // [GenerateGenericTest] types' class constraint violations are reported before the class rows' var generateGenericTestTypeArguments = GetValidGenerateGenericTestTypeArguments(generateGenericTestAttributes, constraintViolations); // Method rows that infer types no class row infers build their instance from every class row, so keep // them all as discovery read them rather than reading the sources again (#7161) - var allClassRows = methodRowClassTypeArguments != null && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; + var allClassRows = methodRowTests == null && classDataSourceCount > 0 && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; var classRowGroups = methodRowTests == null ? await GroupClassRowsByTypeArgumentsAsync(genericTypeDefinition, classDataSources, constraintViolations, allClassRows).ConfigureAwait(false) : null; + // With class-level [Arguments] rows, method rows run only on the class instantiation their own values + // infer (#7118). Beside type-free class rows, the other method sources infer the class type arguments + // unless another class source supplies them: a class [Arguments] row, [GenerateGenericTest], or a run-time + // source whose rows inferred an instantiation. A run-time source that yields no such row supplies none, so + // the method sources still infer theirs, as in the source generator, which cannot see that source's rows (#7209). + List?[]? methodSourceInstantiations = null; + var methodRowClassTypeArguments = methodRowTests == null + ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSourceCount, + classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0, + methodSourcesInferClassTypeArguments: typeFreeClassRows != null + && generateGenericTestAttributes.Length == 0 + && !HasClassArgumentsRows(classDataSources) + && classRowGroups!.Count == 0 + && !constraintViolations.HasClassViolation, + out methodSourceInstantiations) + : null; + if (typeFreeClassRows != null) { AddTypeFreeClassRowsToGroups(classRowGroups!, typeFreeClassRows); @@ -1108,10 +1119,13 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// run-time source yields (#7161). /// /// - /// False when every class data source is a class row whose values go to no type parameter (#7209). The - /// method sources then infer the class type arguments as without a class row: [Arguments(null)] infers - /// object, and a [MethodDataSource] member of the test class infers them from its declared type, as in the - /// source generator. + /// False when every class data source is a class row whose values go to no type parameter (#7209). An + /// [Arguments(null)] method row then infers object, as without a class row and as in the source generator. + /// + /// + /// True beside type-free class rows when no other class source supplies an instantiation (#7209). A + /// [MethodDataSource] member of the test class then infers the class type arguments from its declared type, + /// as do typed data sources and parameter attributes, as in the source generator. /// /// /// For each test method, the class instantiations that its other data sources infer beside only type-free @@ -1121,7 +1135,7 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// type, as in the source generator. Unlike an [Arguments] row, none of these sources is kept off the other /// instantiations. Null when no method has one. /// - private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied, out List?[]? sourceInstantiations) + private static Type[]?[]?[]? InferClassTypeArgumentsOfMethodRows(Type genericTypeDefinition, MethodInfo[] testMethods, int classDataSourceCount, bool classTypeArgumentsSupplied, bool methodSourcesInferClassTypeArguments, out List?[]? sourceInstantiations) { sourceInstantiations = null; if (classDataSourceCount == 0) @@ -1171,7 +1185,7 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin // runs on the rows' instantiations. A [MethodDataSource]'s instantiation runs every method data source // that infers no type, and no source is kept off another source's instantiation, as in the source // generator (#7209). The generator adds typed sources first, then [MethodDataSource]s. - if (!classTypeArgumentsSupplied) + if (methodSourcesInferClassTypeArguments) { List? instantiations = null; for (var i = 0; i < methodDataSources.Length; i++) diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index c62af942c5c..95b1cce04e9 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -1622,3 +1622,98 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTwoTypedSources_T_Run__T_TestSource.Entries_1); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowBesideEmptySourceWithInferringMethodSourc_E5888A7F_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowBesideEmptySourceWithInferringMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Rows"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "None") +{SkipIfEmpty = true,} + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource.Run", + filePath: "", + lineNumber: 278, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Rows") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource.Rows()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "None") + { + SkipIfEmpty = true, + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources.None()), + }, +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideEmptySourceWithInferringMethodSourc_E5888A7F_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideEmptySourceWithInferringMethodSourc_E5888A7F_TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index e3b31e7428e..ff92155314c 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -40,6 +40,20 @@ await RunTestsWithFilter( ]); } + [Test] + public async Task Method_Source_Infers_Beside_A_Type_Free_Class_Row_And_An_Empty_Class_Source() + { + // C from the method source, built from the class row, plus the empty source's skipped test + await RunTestsWithFilter( + $"{Namespace}/TypeFreeClassRowBesideEmptySourceWithInferringMethodSource*/*", + [ + result => result.ResultSummary.Counters.Total.ShouldBe(2), + result => result.ResultSummary.Counters.Passed.ShouldBe(1), + result => result.ResultSummary.Counters.NotExecuted.ShouldBe(1), + result => result.ResultSummary.Counters.Failed.ShouldBe(0) + ]); + } + [Test] [Arguments("TypeFreeClassRowConstraintViolation", "Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'")] [Arguments("TypeFreeClassRowArrayConstraintViolation", "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'")] diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index dafce020750..bfe36854538 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -265,8 +265,30 @@ public async Task Run(T value) } } +// A class data source that yields no rows supplies no class type argument either, so beside it and a type-free +// class row the method's [MethodDataSource] member still infers T: C runs Run(1), built from the class row +// (number = 42), and the empty source adds a skipped test, as in the source generator. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +[MethodDataSource(typeof(TypeFreeClassRowSources), nameof(TypeFreeClassRowSources.None), SkipIfEmpty = true)] +public class TypeFreeClassRowBesideEmptySourceWithInferringMethodSource(int number) +{ + public static IEnumerable Rows() => [1]; + + [Test] + [MethodDataSource(nameof(Rows))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(1); + } +} + public static class TypeFreeClassRowSources { + public static IEnumerable None() => []; + public static IEnumerable FortyThree() => [43]; public static IEnumerable Two() => [2]; From 0bfe40862cb830cc010cfe8a008f64eaeabbc48f Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 04:01:02 +0000 Subject: [PATCH 10/15] fix(reflection): a run-time class row going to no type parameter infers no instantiation beside type-free class rows Beside a type-free class [Arguments] row, a class [MethodDataSource] row such as 43L bound to a long constructor parameter grouped as C from its value's run-time type. That group stopped the method's own sources inferring C, which the source generator runs from both class rows. Such a row now joins no group; allClassRows still supplies it to the instantiations the method sources infer (#7209). --- .../Discovery/ReflectionTestDataCollector.cs | 33 ++++++++++++++----- tests/TUnit.Engine.Tests/Issue7209Tests.cs | 1 + .../ClassRowInfersNoTypeArgumentTests.cs | 22 +++++++++++++ 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 17d5b8d7d29..25501926c13 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -538,8 +538,13 @@ private static async Task> DiscoverGenericTests(Type genericT // Method rows that infer types no class row infers build their instance from every class row, so keep // them all as discovery read them rather than reading the sources again (#7161) var allClassRows = methodRowTests == null && classDataSourceCount > 0 && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; + // Beside type-free class rows, a run-time class row whose values also go to no type parameter infers no + // instantiation either, rather than one from its values' run-time types. The source generator cannot see + // that row, so it keeps the source on every instantiation the method sources infer; allClassRows supplies + // the row to those instantiations here (#7209). var classRowGroups = methodRowTests == null - ? await GroupClassRowsByTypeArgumentsAsync(genericTypeDefinition, classDataSources, constraintViolations, allClassRows).ConfigureAwait(false) + ? await GroupClassRowsByTypeArgumentsAsync(genericTypeDefinition, classDataSources, constraintViolations, allClassRows, + typeFreeRowsInferNone: typeFreeClassRows != null && allClassRows != null).ConfigureAwait(false) : null; // With class-level [Arguments] rows, method rows run only on the class instantiation their own values @@ -752,13 +757,20 @@ private static TestMetadata CreateGenericTypeCreationFailedMetadata( /// Rows whose type arguments break the class's constraints go to /// instead of a group (#7107). When is given, it also receives one static /// data source per original source holding every row that source yielded, whatever its types (#7161). + /// When is true, a row whose values all go to constructor parameters + /// that do not use the class's type parameters joins no group (#7209). /// private static async Task> GroupClassRowsByTypeArgumentsAsync( Type genericTypeDefinition, IDataSourceAttribute[] classDataSources, ReflectionGenericConstraintViolations constraintViolations, - List? allClassRows) + List? allClassRows, + bool typeFreeRowsInferNone) { + var constructorParameters = typeFreeRowsInferNone && genericTypeDefinition.GetConstructors() is [var constructor, ..] + ? constructor.GetParameters() + : null; + var typeArgumentGroups = new List(); var sourcesByGroup = new List>(); var rowCounts = new List(); @@ -795,7 +807,8 @@ private static async Task> GroupClassRowsByTypeArgumentsAsyn for (var rowIndex = 0; rowIndex < dataItems.Count; rowIndex++) { var dataRow = evaluatedItems?[rowIndex]?.Value ?? dataItems[rowIndex]; - if (dataRow == null || dataRow.Length == 0) + if (dataRow == null || dataRow.Length == 0 + || (constructorParameters != null && ValuesBindNoTypeParameter(constructorParameters, dataRow.Length))) { continue; } @@ -1692,12 +1705,16 @@ private static bool ClassRowSuppliesNoTypeArguments(Type genericTypeDefinition, return false; } - if (genericTypeDefinition.GetConstructors() is not [var constructor, ..]) - { - return false; - } + return genericTypeDefinition.GetConstructors() is [var constructor, ..] + && ValuesBindNoTypeParameter(constructor.GetParameters(), valueCount); + } - var parameters = constructor.GetParameters(); + /// + /// True when constructor arguments, bound in order to , + /// all go to parameters that do not use the class's type parameters, and at least one is bound. + /// + private static bool ValuesBindNoTypeParameter(ParameterInfo[] parameters, int valueCount) + { var boundCount = Math.Min(valueCount, parameters.Length); if (boundCount == 0) { diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index ff92155314c..137a3f57513 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -25,6 +25,7 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithTwoInferringMethodSources", 4, 2)] [Arguments("TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute", 4, 3)] [Arguments("TypeFreeClassRowWithTwoTypedSources", 2, 1)] + [Arguments("TypeFreeClassRowBesideInferringSourceWithInferringMethodSource", 2, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index bfe36854538..8057f50c58a 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -285,6 +285,26 @@ public async Task Run(T value) } } +// A type-free class row beside a class data source whose row also goes to no type parameter: that row's long value +// infers no C, so the method's [MethodDataSource] member still infers T, as in the source generator. C runs +// Run(1), built from both class sources (number = 42, then 43). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +[MethodDataSource(typeof(TypeFreeClassRowSources), nameof(TypeFreeClassRowSources.FortyThreeLong))] +public class TypeFreeClassRowBesideInferringSourceWithInferringMethodSource(long number) +{ + public static IEnumerable Rows() => [1]; + + [Test] + [MethodDataSource(nameof(Rows))] + public async Task Run(T value) + { + await Assert.That(number is 42 or 43).IsTrue(); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(1); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable None() => []; @@ -292,4 +312,6 @@ public static class TypeFreeClassRowSources public static IEnumerable FortyThree() => [43]; public static IEnumerable Two() => [2]; + + public static IEnumerable FortyThreeLong() => [43L]; } From 9d27913945184c6a1a356ef8d0b1a3e9f7fcb5b3 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 04:28:30 +0000 Subject: [PATCH 11/15] fix(sourcegen): bind generic class rows to the first public instance constructor, as reflection does (#7209, #7361) The generator chose the first constructor declared with a public modifier, so it skipped a C# primary constructor and bound a class row to a later explicit constructor. Reflection's GetConstructors() returns the primary constructor first. Both class-row helpers now use InstanceConstructors and DeclaredAccessibility. The Tests7209 snapshot also picks up #7339's GenericClassRowPartition for TypeFreeClassRowBesideOtherSource after the rebase. --- .../Generators/TestMetadataGenerator.cs | 26 +- .../Tests7209.Test.verified.txt | 367 +++++++++++++++++- tests/TUnit.Engine.Tests/Issue7209Tests.cs | 2 + .../ClassRowInfersNoTypeArgumentTests.cs | 46 +++ 4 files changed, 428 insertions(+), 13 deletions(-) diff --git a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs index eea12d5a770..09b272915ef 100644 --- a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs +++ b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs @@ -6777,6 +6777,18 @@ private static bool HasArgumentsArray(AttributeData argAttr) => /// private static bool IsNullArgumentsArray(AttributeData argAttr) => argAttr.ConstructorArguments[0].IsNull; + /// + /// The constructor a class-level data row binds to when inferring the class's type arguments: the first public + /// instance constructor in declaration order, else the first instance constructor. This matches reflection mode's + /// GetConstructors(), which returns the public constructors in metadata (declaration) order, a C# primary + /// constructor included (#7361). + /// + private static IMethodSymbol? GetClassRowConstructor(INamedTypeSymbol classSymbol) + { + return classSymbol.InstanceConstructors.FirstOrDefault(static c => c.DeclaredAccessibility == Accessibility.Public) + ?? classSymbol.InstanceConstructors.FirstOrDefault(); + } + /// /// True for a class-level [Arguments] row whose values all bind to constructor parameters that do not /// use the class's type parameters, as [Arguments(42)] on C<T>(int number). Such a @@ -6800,11 +6812,7 @@ private static bool ClassRowSuppliesNoTypeArguments(INamedTypeSymbol classSymbol valueCount = IsNullArgumentsArray(argAttr) ? 1 : argAttr.ConstructorArguments[0].Values.Length; } - var primaryConstructor = classSymbol.Constructors - .FirstOrDefault(c => c.DeclaringSyntaxReferences.Any(sr => - sr.GetSyntax() is ConstructorDeclarationSyntax cds && - cds.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)))) - ?? classSymbol.Constructors.FirstOrDefault(); + var primaryConstructor = GetClassRowConstructor(classSymbol); var boundCount = Math.Min(valueCount, primaryConstructor?.Parameters.Length ?? 0); if (boundCount == 0) @@ -7041,12 +7049,8 @@ private static void MapGenericTypeArguments(ITypeSymbol paramType, ITypeSymbol a argumentValues = argAttr.ConstructorArguments[0].Values; } - // Find the primary constructor - var primaryConstructor = classSymbol.Constructors - .FirstOrDefault(c => c.DeclaringSyntaxReferences.Any(sr => - sr.GetSyntax() is ConstructorDeclarationSyntax cds && - cds.Modifiers.Any(m => m.IsKind(SyntaxKind.PublicKeyword)))) - ?? classSymbol.Constructors.FirstOrDefault(); + // The constructor the class row binds to, chosen as in reflection mode + var primaryConstructor = GetClassRowConstructor(classSymbol); if (primaryConstructor == null) { diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 95b1cce04e9..c3c35a1e104 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -282,14 +282,14 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new { new global::TUnit.Core.ArgumentsAttribute(1), }, - classDataSources: new global::TUnit.Core.IDataSourceAttribute[] + classDataSources: global::TUnit.Core.GenericClassRowPartition.Create(new global::System.Type[] { typeof(int) }, global::TUnit.Core.GenericClassRowFallback.None, new global::TUnit.Core.IDataSourceAttribute[] { new global::TUnit.Core.ArgumentsAttribute(42), new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "FortyThree") { Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources.FortyThree()), }, -}, +}, 1), methodMetadata: __mm_0, createInstance: __CreateInstance_0, invokeBody: __Invoke_0, @@ -1717,3 +1717,366 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideEmptySourceWithInferringMethodSourc_E5888A7F_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideEmptySourceWithInferringMethodSourc_E5888A7F_TestSource.Entries_0); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowBesideInferringSourceWithInferringMethodS_52762ED8_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowBesideInferringSourceWithInferringMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(long), "number", new global::TUnit.Core.ConcreteType(typeof(long)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Rows"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "FortyThreeLong") + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource.Run", + filePath: "", + lineNumber: 298, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Rows") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource.Rows()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), + new global::TUnit.Core.MethodDataSourceAttribute(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources), "FortyThreeLong") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowSources.FortyThreeLong()), + }, +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideInferringSourceWithInferringMethodS_52762ED8_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowBesideInferringSourceWithInferringMethodS_52762ED8_TestSource.Entries_0); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowOverloadedConstructors_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowOverloadedConstructors", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors.Run", + filePath: "", + lineNumber: 322, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute("s"), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors.Run", + filePath: "", + lineNumber: 322, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowOverloadedConstructors_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowOverloadedConstructors_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowOverloadedConstructors_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowOverloadedConstructors_T_Run__T_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowPrimaryConstructorBesideTypedConstructor", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor.Run", + filePath: "", + lineNumber: 344, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute("s"), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor), args)!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor.Run", + filePath: "", + lineNumber: 344, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(1), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource.Entries_1); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 137a3f57513..719591da2cc 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -26,6 +26,8 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute", 4, 3)] [Arguments("TypeFreeClassRowWithTwoTypedSources", 2, 1)] [Arguments("TypeFreeClassRowBesideInferringSourceWithInferringMethodSource", 2, 1)] + [Arguments("TypeFreeClassRowOverloadedConstructors", 2, 2)] + [Arguments("TypeFreeClassRowPrimaryConstructorBesideTypedConstructor", 2, 2)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 8057f50c58a..d0a90411616 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -305,6 +305,52 @@ public async Task Run(T value) } } +// With several public constructors, both modes bind the class row to the first one, as reflection's GetConstructors() +// does: (int number) takes no T, so the row is type-free and the method rows infer C and C. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowOverloadedConstructors +{ + private readonly int _number; + + public TypeFreeClassRowOverloadedConstructors(int number) => _number = number; + + public TypeFreeClassRowOverloadedConstructors(T value, int number) : this(number) + { + } + + [Test] + [Arguments("s")] + [Arguments(1)] + public async Task Run(T value) + { + await Assert.That(_number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(value!.GetType()); + } +} + +// A primary constructor comes first, before an explicit constructor that takes T. The source generator used to skip +// the primary constructor because it has no constructor declaration, bind the row to (T value, int number) and infer +// C from it, while reflection bound the row to the primary constructor. Both modes now bind to the primary +// constructor, so the row is type-free and the method rows infer C and C. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowPrimaryConstructorBesideTypedConstructor(int number) +{ + public TypeFreeClassRowPrimaryConstructorBesideTypedConstructor(T value, int number) : this(number) + { + } + + [Test] + [Arguments("s")] + [Arguments(1)] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(value!.GetType()); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable None() => []; From bc7255a35ac932f2b2137308b139c47be7819c7d Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 05:15:42 +0000 Subject: [PATCH 12/15] fix(generic): bind class rows to [TestConstructor] and infer method sources beside [GenerateGenericTest] Both modes now classify a class row against the constructor marked [TestConstructor] when there is one, and reflection lets typed and method data sources infer instantiations beside a type-free class row even when [GenerateGenericTest] lists other types, as the source generator does. Refs #7209 --- .../Generators/TestMetadataGenerator.cs | 13 +- .../Discovery/ReflectionTestDataCollector.cs | 39 +- .../Tests7209.Test.verified.txt | 368 ++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 3 + .../ClassRowInfersNoTypeArgumentTests.cs | 61 +++ 5 files changed, 470 insertions(+), 14 deletions(-) diff --git a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs index 3943b8ec145..1e30fb8478c 100644 --- a/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs +++ b/src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs @@ -6809,14 +6809,17 @@ private static bool HasArgumentsArray(AttributeData argAttr) => private static bool IsNullArgumentsArray(AttributeData argAttr) => argAttr.ConstructorArguments[0].IsNull; /// - /// The constructor a class-level data row binds to when inferring the class's type arguments: the first public - /// instance constructor in declaration order, else the first instance constructor. This matches reflection mode's - /// GetConstructors(), which returns the public constructors in metadata (declaration) order, a C# primary - /// constructor included (#7361). + /// The constructor a class-level data row binds to when inferring the class's type arguments: the public one + /// marked [TestConstructor], which the rows are for, else the first public instance constructor in + /// declaration order, else the first instance constructor. This matches reflection mode's + /// GetClassRowConstructor, whose GetConstructors() returns the public constructors in metadata + /// (declaration) order, a C# primary constructor included (#7361, #7209). /// private static IMethodSymbol? GetClassRowConstructor(INamedTypeSymbol classSymbol) { - return classSymbol.InstanceConstructors.FirstOrDefault(static c => c.DeclaredAccessibility == Accessibility.Public) + return classSymbol.InstanceConstructors.FirstOrDefault(static c => c.DeclaredAccessibility == Accessibility.Public + && c.GetAttributes().Any(static a => a.AttributeClass?.ToDisplayString() == WellKnownFullyQualifiedClassNames.TestConstructorAttribute.WithoutGlobalPrefix)) + ?? classSymbol.InstanceConstructors.FirstOrDefault(static c => c.DeclaredAccessibility == Accessibility.Public) ?? classSymbol.InstanceConstructors.FirstOrDefault(); } diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index f375e3d94d0..3077d698172 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -572,15 +572,15 @@ private static async Task DiscoverGenericTestsAsync(List discovere // With class-level [Arguments] rows, method rows run only on the class instantiation their own values // infer (#7118). Beside type-free class rows, the other method sources infer the class type arguments - // unless another class source supplies them: a class [Arguments] row, [GenerateGenericTest], or a run-time - // source whose rows inferred an instantiation. A run-time source that yields no such row supplies none, so - // the method sources still infer theirs, as in the source generator, which cannot see that source's rows (#7209). + // unless another class source supplies them: a class [Arguments] row or a run-time source whose rows + // inferred an instantiation. A run-time source that yields no such row supplies none, so the method sources + // still infer theirs, as in the source generator, which cannot see that source's rows. [GenerateGenericTest] + // does not stop them either: they add their instantiations beside its types, as in the generator (#7209). List?[]? methodSourceInstantiations = null; var methodRowClassTypeArguments = methodRowTests == null ? InferClassTypeArgumentsOfMethodRows(genericTypeDefinition, testMethods, classDataSourceCount, classTypeArgumentsSupplied: classDataSources.Length > 0 || generateGenericTestAttributes.Length > 0, methodSourcesInferClassTypeArguments: typeFreeClassRows != null - && generateGenericTestAttributes.Length == 0 && !HasClassArgumentsRows(classDataSources) && classRowGroups!.Count == 0 && !constraintViolations.HasClassViolation, @@ -792,7 +792,7 @@ private static async Task> GroupClassRowsByTypeArgumentsAsyn List? deferredOwnSources, bool typeFreeRowsInferNone) { - var constructorParameters = typeFreeRowsInferNone && genericTypeDefinition.GetConstructors() is [var constructor, ..] + var constructorParameters = typeFreeRowsInferNone && GetClassRowConstructor(genericTypeDefinition) is { } constructor ? constructor.GetParameters() : null; @@ -973,7 +973,7 @@ private static async Task> GroupClassRowsByTypeArgumentsAsyn /// /// The class type argument that an row with a null value infers, for a class /// with one type parameter, as the source generator infers it. The null value binds to the first parameter of the - /// class's first public constructor, so the declared T is mapped through that parameter's type: + /// class row's constructor (), so the declared T is mapped through that parameter's type: /// [Arguments<string[]>(null)] on C<T>(T[] values) infers string, not /// string[]. Null for any other row, or when the parameter type does not match the declared type. /// @@ -983,7 +983,7 @@ private static async Task> GroupClassRowsByTypeArgumentsAsyn || dataSource.GetType() is not { IsGenericType: true } sourceType || sourceType.GetGenericTypeDefinition() != typeof(ArgumentsAttribute<>) || genericTypeDefinition.GetGenericArguments() is not [var typeParameter] - || genericTypeDefinition.GetConstructors() is not [var constructor, ..] + || GetClassRowConstructor(genericTypeDefinition) is not { } constructor || constructor.GetParameters() is not [var parameter, ..]) { return null; @@ -1227,7 +1227,8 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin /// [Arguments(null)] method row then infers object, as without a class row and as in the source generator. /// /// - /// True beside type-free class rows when no other class source supplies an instantiation (#7209). A + /// True beside type-free class rows when no other class source supplies an instantiation (#7209), whether or + /// not [GenerateGenericTest] lists types: their instantiations are added beside its own. A /// [MethodDataSource] member of the test class then infers the class type arguments from its declared type, /// as do typed data sources and parameter attributes, as in the source generator. /// @@ -1796,10 +1797,30 @@ private static bool ClassRowSuppliesNoTypeArguments(Type genericTypeDefinition, return false; } - return genericTypeDefinition.GetConstructors() is [var constructor, ..] + return GetClassRowConstructor(genericTypeDefinition) is { } constructor && ValuesBindNoTypeParameter(constructor.GetParameters(), valueCount); } + /// + /// The constructor a class-level data row binds to when classifying it or inferring the class's type arguments + /// from it: the public one marked [TestConstructor], which the instance is built with (see + /// ), else the first public one. Null when there is none. Mirrors + /// TestMetadataGenerator.GetClassRowConstructor (#7209). + /// + private static ConstructorInfo? GetClassRowConstructor(Type genericTypeDefinition) + { + var constructors = genericTypeDefinition.GetConstructors(); + foreach (var constructor in constructors) + { + if (constructor.IsDefined(typeof(TestConstructorAttribute), inherit: false)) + { + return constructor; + } + } + + return constructors.Length > 0 ? constructors[0] : null; + } + /// /// True when constructor arguments, bound in order to , /// all go to parameters that do not use the class's type parameters, and at least one is bound. diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index c3c35a1e104..929586fda3d 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -2080,3 +2080,371 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowPrimaryConstructorBesideTypedConstructor_T_Run__T_TestSource.Entries_1); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithGenerateGenericTestAndTypedSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithGenerateGenericTestAndTypedSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.GenerateGenericTestAttribute(typeof(long)), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource.Run", + filePath: "", + lineNumber: 362, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.GenerateGenericTestAttribute(typeof(long)), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource.Run", + filePath: "", + lineNumber: 362, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndTypedSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndTypedSource_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndTypedSource_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndTypedSource_T_Run__T_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithGenerateGenericTestAndMethodSource_T_Run__T_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithGenerateGenericTestAndMethodSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Values"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.GenerateGenericTestAttribute(typeof(long)), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Run", + filePath: "", + lineNumber: 381, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Values") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Values()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource __CreateInstance_1(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_1(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_1(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.MethodDataSourceAttribute("Values"), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.GenerateGenericTestAttribute(typeof(long)), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_1 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Run", + filePath: "", + lineNumber: 381, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.MethodDataSourceAttribute("Values") + { + Factory = static dataGeneratorMetadata => global::TUnit.Core.Helpers.DataSourceFactories.FromEnumerable(static () => global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Values()), + }, +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_1, + invokeBody: __Invoke_1, + methodIndex: 0, + createAttributes: __Attributes_1, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndMethodSource_T_Run__T_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndMethodSource_T_Run__T_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndMethodSource_T_Run__T_TestSource_1 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithGenerateGenericTestAndMethodSource_T_Run__T_TestSource.Entries_1); +} + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowTestConstructorTakesTypeParameter_T_Run__T__TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowTestConstructorTakesTypeParameter", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>), true, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), true) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return (global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter)global::System.Activator.CreateInstance(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter), new object[] { 42 })!; + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter.Run", + filePath: "", + lineNumber: 406, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(null), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowTestConstructorTakesTypeParameter_T_Run__T__TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowTestConstructorTakesTypeParameter_T_Run__T__TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 719591da2cc..607a3da75d3 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -28,6 +28,9 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowBesideInferringSourceWithInferringMethodSource", 2, 1)] [Arguments("TypeFreeClassRowOverloadedConstructors", 2, 2)] [Arguments("TypeFreeClassRowPrimaryConstructorBesideTypedConstructor", 2, 2)] + [Arguments("TypeFreeClassRowWithGenerateGenericTestAndTypedSource", 2, 1)] + [Arguments("TypeFreeClassRowWithGenerateGenericTestAndMethodSource", 2, 1)] + [Arguments("TypeFreeClassRowTestConstructorTakesTypeParameter", 1, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index d0a90411616..b8107a5aa66 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -351,6 +351,67 @@ public async Task Run(T value) } } +// [GenerateGenericTest] does not stop a typed data source from inferring T beside a type-free class row: C comes +// from [GenerateGenericTest] and C from ClassDataSource, each running the source and built from the class row +// (number = 42). Same in both modes; reflection used to run only C. +[EngineTest(ExpectedResult.Pass)] +[GenerateGenericTest(typeof(long))] +[Arguments(42)] +public class TypeFreeClassRowWithGenerateGenericTestAndTypedSource(int number) +{ + [Test] + [ClassDataSource] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T) == typeof(int) || typeof(T) == typeof(long)).IsTrue(); + await Assert.That(Convert.ToInt64(value)).IsEqualTo(0L); + } +} + +// The same with a [MethodDataSource] member of the test class: C from [GenerateGenericTest] and C from the +// member's declared type, each built from the class row (number = 42). Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[GenerateGenericTest(typeof(long))] +[Arguments(42)] +public class TypeFreeClassRowWithGenerateGenericTestAndMethodSource(int number) +{ + public static IEnumerable Values() => [5]; + + [Test] + [MethodDataSource(nameof(Values))] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T) == typeof(int) || typeof(T) == typeof(long)).IsTrue(); + await Assert.That(Convert.ToInt64(value)).IsEqualTo(5L); + } +} + +// A class row binds to the constructor marked [TestConstructor], the one reflection builds the instance with, not to +// the first public constructor: (T value) takes the row, so it infers C, and the method row runs on it. Same in +// both modes. The source generator builds the instance by matching the row's run-time types (#7365), which picks the +// marked constructor here because the other one takes a long. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowTestConstructorTakesTypeParameter +{ + private readonly string _constructor; + + public TypeFreeClassRowTestConstructorTakesTypeParameter(long number) => _constructor = $"long:{number}"; + + [TestConstructor] + public TypeFreeClassRowTestConstructorTakesTypeParameter(T value) => _constructor = $"T:{value}"; + + [Test] + [Arguments(null)] + public async Task Run(T? value) + { + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That(_constructor).IsEqualTo("T:42"); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable None() => []; From 3e48ddde33a12fb9cd97ea986d6562e07f72d393 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 05:43:23 +0000 Subject: [PATCH 13/15] fix(reflection): a rejected [GenerateGenericTest] type does not stop method sources inferring beside a type-free class row (#7209) Only a class row that breaks the class's constraints supplies class type arguments. HasClassViolation also counted [GenerateGenericTest] violations, recorded before the class rows, so reflection dropped the C a typed source infers beside [GenerateGenericTest(typeof(string))] on a struct-constrained class. The source generator keeps it. --- .../ReflectionGenericConstraintViolations.cs | 9 +++++---- .../Discovery/ReflectionTestDataCollector.cs | 5 ++++- tests/TUnit.Engine.Tests/Issue7209Tests.cs | 1 + .../_7209/ClassRowInfersNoTypeArgumentTests.cs | 18 ++++++++++++++++++ 4 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs index fe8151e113a..e8c06b3302a 100644 --- a/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs +++ b/src/TUnit.Engine/Discovery/ReflectionGenericConstraintViolations.cs @@ -28,10 +28,11 @@ internal sealed class ReflectionGenericConstraintViolations( private Dictionary>? _messagesByMethod; /// - /// Whether recorded a violation: some source supplied class type - /// arguments, even though they break the class's constraints. + /// How many class type argument sets recorded: each is a source that supplied + /// class type arguments, even though they break the class's constraints. A caller compares counts to tell the + /// violations of one source (class rows) from those recorded before it ([GenerateGenericTest]). /// - public bool HasClassViolation { get; private set; } + public int ClassViolationCount { get; private set; } /// /// Records as a violation for every test method when they break @@ -50,7 +51,7 @@ public bool TryAddClassViolation(Type[] typeArguments) Add(testMethod, message); } - HasClassViolation = true; + ClassViolationCount++; return true; } diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 3077d698172..4ea40725d19 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -556,6 +556,9 @@ private static async Task DiscoverGenericTestsAsync(List discovere // [GenerateGenericTest] types' class constraint violations are reported before the class rows' var generateGenericTestTypeArguments = GetValidGenerateGenericTestTypeArguments(generateGenericTestAttributes, constraintViolations); + // Only a class row that breaks the constraints supplies class type arguments; a rejected [GenerateGenericTest] + // type does not stop the method sources from inferring theirs, as in the source generator (#7209) + var generateGenericTestViolationCount = constraintViolations.ClassViolationCount; // Method rows that infer types no class row infers build their instance from every class row, so keep // them all as discovery read them rather than reading the sources again (#7161) var allClassRows = methodRowTests == null && classDataSourceCount > 0 && !HasClassArgumentsRows(classDataSources) ? new List(classDataSources.Length) : null; @@ -583,7 +586,7 @@ private static async Task DiscoverGenericTestsAsync(List discovere methodSourcesInferClassTypeArguments: typeFreeClassRows != null && !HasClassArgumentsRows(classDataSources) && classRowGroups!.Count == 0 - && !constraintViolations.HasClassViolation, + && constraintViolations.ClassViolationCount == generateGenericTestViolationCount, out methodSourceInstantiations) : null; diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 607a3da75d3..7deecebc671 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -63,6 +63,7 @@ await RunTestsWithFilter( [Test] [Arguments("TypeFreeClassRowConstraintViolation", "Type 'Object' does not satisfy the 'struct' constraint for generic parameter 'T'")] [Arguments("TypeFreeClassRowArrayConstraintViolation", "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'")] + [Arguments("TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource", "Type 'String' does not satisfy the 'struct' constraint for generic parameter 'T'")] public async Task Method_Row_Inferring_An_Invalid_Class_Type_Beside_A_Type_Free_Class_Row_Fails(string className, string expectedMessage) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index b8107a5aa66..295da58baaa 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -369,6 +369,24 @@ public async Task Run(T value) } } +// A [GenerateGenericTest] type that breaks the class's constraints fails, but does not stop a typed data source from +// inferring T beside a type-free class row: C fails the 'struct' constraint, and ClassDataSource still runs +// on C, built from the class row (number = 42). Same in both modes; reflection used to drop C. +// No [EngineTest]: TUnit.Engine.Tests targets it by name, because it has a failing row. +[GenerateGenericTest(typeof(string))] +[Arguments(42)] +public class TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource(int number) where T : struct +{ + [Test] + [ClassDataSource] + public async Task Run(T value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That((object?)value).IsEqualTo(0); + } +} + // The same with a [MethodDataSource] member of the test class: C from [GenerateGenericTest] and C from the // member's declared type, each built from the class row (number = 42). Same in both modes. [EngineTest(ExpectedResult.Pass)] From 6ec926b6836006826a4700fc6679ba42aedd9f39 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 06:07:39 +0000 Subject: [PATCH 14/15] fix(reflection): a typed source infers class type arguments beside a type-free class row even when no method parameter uses them (#7209) The source generator's InferTypesFromDataSourceAttribute infers C from ClassDataSource whatever the method's parameters are, but reflection skipped methods whose parameters do not use the class's type parameters before reaching typed-source inference, so [Arguments(42)] on C(int number) with [ClassDataSource] Run(int value) ran no test in reflection mode. Also updates the Tests7209 snapshot, which 3e48ddde33 left without its new class. --- .../Discovery/ReflectionTestDataCollector.cs | 12 +- .../Tests7209.Test.verified.txt | 229 ++++++++++++++++-- tests/TUnit.Engine.Tests/Issue7209Tests.cs | 1 + .../ClassRowInfersNoTypeArgumentTests.cs | 16 ++ 4 files changed, 232 insertions(+), 26 deletions(-) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 4ea40725d19..5eb62c923d6 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -1262,8 +1262,12 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin continue; } + // Only a method whose parameters use the class's type parameters has rows, [MethodDataSource]s or + // parameter attributes that infer them. A typed data source infers them from its declared type + // whatever the parameters are, as the generator's InferTypesFromDataSourceAttribute does (#7209). var parameters = testMethod.GetParameters(); - if (!Array.Exists(parameters, static p => p.ParameterType.ContainsGenericParameters)) + var parametersUseClassTypeParameters = Array.Exists(parameters, static p => p.ParameterType.ContainsGenericParameters); + if (!parametersUseClassTypeParameters && !methodSourcesInferClassTypeArguments) { continue; } @@ -1272,7 +1276,7 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin var methodDataSources = ReflectionAttributeExtractor.ExtractDataSources(testMethod); Type[]?[]? rowTypeArguments = null; - for (var i = 0; i < methodDataSources.Length; i++) + for (var i = 0; parametersUseClassTypeParameters && i < methodDataSources.Length; i++) { // Class rows supply the instantiations, so [Arguments(null)] infers none and runs on each (#7141), // unless every class row goes to no type parameter (#7209) @@ -1304,7 +1308,7 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin } } - for (var i = 0; rowTypeArguments == null && i < methodDataSources.Length; i++) + for (var i = 0; parametersUseClassTypeParameters && rowTypeArguments == null && i < methodDataSources.Length; i++) { if (methodDataSources[i] is MethodDataSourceAttribute methodDataSource) { @@ -1315,7 +1319,7 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin // Parameter attributes ([Matrix] on a T parameter) infer an instantiation too, beside those of // the sources above, as the generator's InferTypesFromTypedDataSourceForClass does. It runs every // method data source. - if (rowTypeArguments == null && methodDataSources.Length > 0) + if (parametersUseClassTypeParameters && rowTypeArguments == null && methodDataSources.Length > 0) { AddSourceInstantiation(ref instantiations, InferClassTypeArgumentsFromParameterAttributes(classGenericParameters.Length, parameters), sourceIndex: -1); } diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 929586fda3d..9ce78ba5dda 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -839,6 +839,91 @@ internal static partial class TUnit_TestRegistration } +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithTypedSourceAndNonGenericParameter_T_Run__int_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithTypedSourceAndNonGenericParameter", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter<>), "Run", false, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "value", new global::TUnit.Core.ConcreteType(typeof(int)), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndNonGenericParameter.Run", + filePath: "", + lineNumber: 166, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndNonGenericParameter_T_Run__int_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithTypedSourceAndNonGenericParameter_T_Run__int_TestSource.Entries_0); +} + + // ===== FILE SEPARATOR ===== // @@ -900,7 +985,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringParameterAttribute.Run", filePath: "", - lineNumber: 167, + lineNumber: 183, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1015,7 +1100,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "values", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowArrayConstraintViolation.Run", filePath: "", - lineNumber: 183, + lineNumber: 199, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1038,7 +1123,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "values", new { MethodName = "Run", FilePath = "", - LineNumber = 183, + LineNumber = 199, MethodMetadata = __mm_0, Messages = new string[] { "Type 'Int32' does not satisfy the 'class' constraint for generic parameter 'T'" }, }, @@ -1115,7 +1200,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource.Run", filePath: "", - lineNumber: 201, + lineNumber: 217, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1164,7 +1249,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInferringRowAndTypedSource.Run", filePath: "", - lineNumber: 201, + lineNumber: 217, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1254,7 +1339,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Run", filePath: "", - lineNumber: 218, + lineNumber: 234, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1310,7 +1395,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoInferringMethodSources.Run", filePath: "", - lineNumber: 218, + lineNumber: 234, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1407,7 +1492,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute.Run", filePath: "", - lineNumber: 241, + lineNumber: 257, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1456,7 +1541,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTypedSourceAndInferringParameterAttribute.Run", filePath: "", - lineNumber: 241, + lineNumber: 257, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1547,7 +1632,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources.Run", filePath: "", - lineNumber: 258, + lineNumber: 274, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1596,7 +1681,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithTwoTypedSources.Run", filePath: "", - lineNumber: 258, + lineNumber: 274, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1687,7 +1772,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideEmptySourceWithInferringMethodSource.Run", filePath: "", - lineNumber: 278, + lineNumber: 294, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1781,7 +1866,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowBesideInferringSourceWithInferringMethodSource.Run", filePath: "", - lineNumber: 298, + lineNumber: 314, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1872,7 +1957,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors.Run", filePath: "", - lineNumber: 322, + lineNumber: 338, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -1919,7 +2004,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowOverloadedConstructors.Run", filePath: "", - lineNumber: 322, + lineNumber: 338, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2007,7 +2092,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor.Run", filePath: "", - lineNumber: 344, + lineNumber: 360, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2054,7 +2139,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowPrimaryConstructorBesideTypedConstructor.Run", filePath: "", - lineNumber: 344, + lineNumber: 360, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2144,7 +2229,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource.Run", filePath: "", - lineNumber: 362, + lineNumber: 378, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2193,7 +2278,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndTypedSource.Run", filePath: "", - lineNumber: 362, + lineNumber: 378, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2221,6 +2306,106 @@ internal static partial class TUnit_TestRegistration } +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSou_C93CA686_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>), "Run", false, 0, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.Core.GenerateGenericTestAttribute(typeof(string)), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource.Run", + filePath: "", + lineNumber: 396, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; + public static readonly global::TUnit.Core.GenericConstraintViolationEntry[] ConstraintViolations = new global::TUnit.Core.GenericConstraintViolationEntry[] + { + new global::TUnit.Core.GenericConstraintViolationEntry + { + MethodName = "Run", + FilePath = "", + LineNumber = 396, + MethodMetadata = __mm_0, + Messages = new string[] { "Type 'String' does not satisfy the 'struct' constraint for generic parameter 'T'" }, + }, + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSou_C93CA686_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSou_C93CA686_TestSource.Entries_0); +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSou_C93CA686_TestSource_ConstraintViolations = global::TUnit.Core.SourceRegistrar.RegisterGenericConstraintViolations(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSource<>), static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithInvalidGenerateGenericTestAndTypedSou_C93CA686_TestSource.ConstraintViolations); +} + + // ===== FILE SEPARATOR ===== // @@ -2283,7 +2468,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Run", filePath: "", - lineNumber: 381, + lineNumber: 415, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2335,7 +2520,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithGenerateGenericTestAndMethodSource.Run", filePath: "", - lineNumber: 381, + lineNumber: 415, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { @@ -2426,7 +2611,7 @@ global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new methodName: "Run", fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowTestConstructorTakesTypeParameter.Run", filePath: "", - lineNumber: 406, + lineNumber: 440, hasDataSource: true, testDataSources: new global::TUnit.Core.IDataSourceAttribute[] { diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 7deecebc671..9e1ff281470 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -20,6 +20,7 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithInferringRowAndMethodSource", 2, 2)] [Arguments("TypeFreeClassRowWithCancellationToken", 1, 1)] [Arguments("TypeFreeClassRowWithTypedMethodSource", 1, 1)] + [Arguments("TypeFreeClassRowWithTypedSourceAndNonGenericParameter", 1, 1)] [Arguments("TypeFreeClassRowWithInferringParameterAttribute", 2, 2)] [Arguments("TypeFreeClassRowWithInferringRowAndTypedSource", 3, 2)] [Arguments("TypeFreeClassRowWithTwoInferringMethodSources", 4, 2)] diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 295da58baaa..7466691695a 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -157,6 +157,22 @@ public async Task Run(T value) } } +// A typed data source infers T from its declared type even when no method parameter uses T: ClassDataSource runs +// on C, built from the class row (number = 42), as the source generator infers it. Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithTypedSourceAndNonGenericParameter(int number) +{ + [Test] + [ClassDataSource] + public async Task Run(int value) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That(value).IsEqualTo(0); + } +} + // Beside only a type-free class row, a parameter attribute that infers T (Matrix implements IInfersType) // supplies the instantiation, as in the source generator: both matrix values run on C, each instance built from // the class row (number = 42). Same in both modes. From 332884605e2ad1abf857d631c09534f2a98e1242 Mon Sep 17 00:00:00 2001 From: Tom Longhurst <30480171+thomhurst@users.noreply.github.com> Date: Mon, 2 Nov 2026 07:05:20 +0000 Subject: [PATCH 15/15] fix(reflection): infer the class from a combined typed source on a generic method beside type-free class rows (#7209) A typed data source whose type arguments cover the class and method type parameters (ClassDataSource on Run(T, U)) lost its only discovery path once the type-free class row was split out, so reflection ran no test while source-gen ran C.Run. Infer the class instantiation from the source's leading type arguments, as the generator's combined branch of InferTypesFromDataSourceAttribute does. --- .../Discovery/ReflectionTestDataCollector.cs | 27 ++++++ .../Tests7209.Test.verified.txt | 87 +++++++++++++++++++ tests/TUnit.Engine.Tests/Issue7209Tests.cs | 1 + .../ClassRowInfersNoTypeArgumentTests.cs | 17 ++++ 4 files changed, 132 insertions(+) diff --git a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs index 5eb62c923d6..816b3d2449a 100644 --- a/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs +++ b/src/TUnit.Engine/Discovery/ReflectionTestDataCollector.cs @@ -1259,6 +1259,33 @@ private static List BuildTestsFromMethodRows(Type genericTypeDefin var testMethod = testMethods[methodIndex]; if (testMethod.IsGenericMethodDefinition) { + // Beside only type-free class rows, a typed data source whose type arguments cover the class type + // parameters and the method's (ClassDataSource on Run(T, U)) infers the class + // instantiation from its leading type arguments, as the generator's combined branch of + // InferTypesFromDataSourceAttribute does. That instantiation runs only that source, and the method + // closes over the source's values as it does on any closed class (#7209). + if (methodSourcesInferClassTypeArguments) + { + classGenericParameters ??= genericTypeDefinition.GetGenericArguments(); + var combinedCount = classGenericParameters.Length + testMethod.GetGenericArguments().Length; + var genericMethodDataSources = ReflectionAttributeExtractor.ExtractDataSources(testMethod); + List? combinedInstantiations = null; + for (var i = 0; i < genericMethodDataSources.Length; i++) + { + if (genericMethodDataSources[i] is not (ArgumentsAttribute or MethodDataSourceAttribute) + && InferTypesFromTypedDataSource(genericMethodDataSources[i], combinedCount, classGenericParameterCount: 0) is { } combinedTypes) + { + AddSourceInstantiation(ref combinedInstantiations, combinedTypes[..classGenericParameters.Length], sourceIndex: i); + } + } + + if (combinedInstantiations != null) + { + sourceInstantiations ??= new List?[testMethods.Length]; + sourceInstantiations[methodIndex] = combinedInstantiations; + } + } + continue; } diff --git a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt index 9ce78ba5dda..3efb80bbd15 100644 --- a/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt +++ b/tests/TUnit.Core.SourceGenerator.Tests/Tests7209.Test.verified.txt @@ -2633,3 +2633,90 @@ internal static partial class TUnit_TestRegistration { static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowTestConstructorTakesTypeParameter_T_Run__T__TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowTestConstructorTakesTypeParameter_T_Run__T__TestSource.Entries_0); } + + +// ===== FILE SEPARATOR ===== + +// +#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__7209_TypeFreeClassRowWithCombinedTypedSource_T_Run__T_U_TestSource +{ + private static readonly global::TUnit.Core.ClassMetadata __classMetadata = global::TUnit.Core.ClassMetadata.GetOrAdd("TestsBase`1:global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>", new global::TUnit.Core.ClassMetadata + { + Type = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>), + TypeInfo = new global::TUnit.Core.ConstructedGeneric(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>), [new global::TUnit.Core.GenericParameter(0, false, "T")]), + Name = "TypeFreeClassRowWithCombinedTypedSource", + Namespace = "TUnit.TestProject.Bugs._7209", + Assembly = global::TUnit.Core.AssemblyMetadata.GetOrAdd("TestsBase`1", "TestsBase`1"), + Parameters = global::TUnit.Core.ParameterMetadataFactory.ForConstructor(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>), false, new global::TUnit.Core.ParameterMetadata[] + { + global::TUnit.Core.ParameterMetadataFactory.Create(typeof(int), "number", new global::TUnit.Core.ConcreteType(typeof(int)), false) + }), + Properties = global::System.Array.Empty(), + Parent = null + }); + private static readonly global::System.Type __classType = typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>); + private static readonly global::TUnit.Core.MethodMetadata __mm_0 = global::TUnit.Core.MethodMetadataFactory.Create("Run", __classType, typeof(global::System.Threading.Tasks.Task), __classMetadata, genericTypeCount: 1, parameters: global::TUnit.Core.ParameterMetadataFactory.ForGenericMethod(typeof(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource<>), "Run", false, 1, new global::TUnit.Core.ParameterMetadata[] +{ +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "value", new global::TUnit.Core.GenericParameter(0, false, "T"), false), +global::TUnit.Core.ParameterMetadataFactory.Create(typeof(object), "other", new global::TUnit.Core.GenericParameter(0, true, "U"), false) +})); + private static global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource __CreateInstance_0(global::System.Type[] typeArgs, object?[] args) + { + return new global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource(global::TUnit.Core.Helpers.CastHelper.Cast(args[0])); + } + private static global::System.Threading.Tasks.ValueTask __Invoke_0(global::TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource instance, int methodIndex, object?[] args, global::System.Threading.CancellationToken cancellationToken) + { + try + { + return new global::System.Threading.Tasks.ValueTask(instance.Run(global::TUnit.Core.Helpers.CastHelper.Cast(args[0]), global::TUnit.Core.Helpers.CastHelper.Cast(args[1]))); + } + catch (global::System.Exception ex) + { + return new global::System.Threading.Tasks.ValueTask(global::System.Threading.Tasks.Task.FromException(ex)); + } + } + private static global::System.Attribute[] __Attributes_0(int groupIndex) + { + return new global::System.Attribute[] + { + new global::TUnit.Core.TestAttribute(), + new global::TUnit.Core.ClassDataSourceAttribute(), + new global::TUnit.TestProject.Attributes.EngineTest(global::TUnit.TestProject.Attributes.ExpectedResult.Pass), + new global::TUnit.Core.ArgumentsAttribute(42) + }; + } + public static readonly global::TUnit.Core.TestEntry>[] Entries_0 = new global::TUnit.Core.TestEntry>[] + { + global::TUnit.Core.TestEntryFactory.Create>( + methodName: "Run", + fullyQualifiedName: "TUnit.TestProject.Bugs._7209.TypeFreeClassRowWithCombinedTypedSource.Run", + methodTypeArgumentsIdentity: "", + filePath: "", + lineNumber: 456, + hasDataSource: true, + testDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ClassDataSourceAttribute(), +}, + classDataSources: new global::TUnit.Core.IDataSourceAttribute[] +{ + new global::TUnit.Core.ArgumentsAttribute(42), +}, + methodMetadata: __mm_0, + createInstance: __CreateInstance_0, + invokeBody: __Invoke_0, + methodIndex: 0, + createAttributes: __Attributes_0, + attributeGroupIndex: 0), + }; +} +internal static partial class TUnit_TestRegistration +{ + static readonly int _r_TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCombinedTypedSource_T_Run__T_U_TestSource_0 = global::TUnit.Core.SourceRegistrar.RegisterEntries>(static () => TUnit_TestProject_Bugs__7209_TypeFreeClassRowWithCombinedTypedSource_T_Run__T_U_TestSource.Entries_0); +} diff --git a/tests/TUnit.Engine.Tests/Issue7209Tests.cs b/tests/TUnit.Engine.Tests/Issue7209Tests.cs index 9e1ff281470..8d4d4f1b98f 100644 --- a/tests/TUnit.Engine.Tests/Issue7209Tests.cs +++ b/tests/TUnit.Engine.Tests/Issue7209Tests.cs @@ -32,6 +32,7 @@ public class Issue7209Tests(TestMode testMode) : InvokableTestBase(testMode) [Arguments("TypeFreeClassRowWithGenerateGenericTestAndTypedSource", 2, 1)] [Arguments("TypeFreeClassRowWithGenerateGenericTestAndMethodSource", 2, 1)] [Arguments("TypeFreeClassRowTestConstructorTakesTypeParameter", 1, 1)] + [Arguments("TypeFreeClassRowWithCombinedTypedSource", 1, 1)] public async Task Rows_Run_On_The_Instantiation_They_Infer(string className, int expectedTests, int expectedDistinctNames) { await RunTestsWithFilter( diff --git a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs index 7466691695a..ef8133d998b 100644 --- a/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs +++ b/tests/TUnit.TestProject/Bugs/_7209/ClassRowInfersNoTypeArgumentTests.cs @@ -446,6 +446,23 @@ public async Task Run(T? value) } } +// A typed data source on a generic method whose type arguments cover the class type parameter and the method's +// (ClassDataSource on Run(T, U)) closes both: C.Run, built from the class row (number = 42). +// Same in both modes. +[EngineTest(ExpectedResult.Pass)] +[Arguments(42)] +public class TypeFreeClassRowWithCombinedTypedSource(int number) +{ + [Test] + [ClassDataSource] + public async Task Run(T value, U other) + { + await Assert.That(number).IsEqualTo(42); + await Assert.That(typeof(T)).IsEqualTo(typeof(int)); + await Assert.That(typeof(U)).IsEqualTo(typeof(long)); + } +} + public static class TypeFreeClassRowSources { public static IEnumerable None() => [];