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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 64 additions & 12 deletions src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@

private static readonly DiagnosticDescriptor GenerationErrorDescriptor = new(
"TUNIT0999",
"Source Generation Error",

Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Activer le suivi de version d'analyseur pour le projet d'analyseur contenant la règle 'TUNIT0999' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Enable analyzer release tracking for the analyzer project containing rule 'TUNIT0999' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (sv-SE)

Enable analyzer release tracking for the analyzer project containing rule 'TUNIT0999' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Enable analyzer release tracking for the analyzer project containing rule 'TUNIT0999' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)

Check warning on line 29 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Enable analyzer release tracking for the analyzer project containing rule 'TUNIT0999' (https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md)
"Failed to generate test metadata for {0}.{1}: {2}",
"TUnit",
DiagnosticSeverity.Error,
Expand Down Expand Up @@ -2471,7 +2471,24 @@
writer.AppendLine($"dependencies: {depsExpr},");
}

writer.AppendLine($"methodMetadata: __mm_0,");
if (TryGetClosedParametersForSharedBinder(testMethod, entry) is { } closedParameters
&& HasSingleElementTupleParameter(closedParameters))
{
// The factories and engine bind using ParameterMetadata.Type, so close that metadata
// as well as the invoker. Keep attributes and lazy reflection access from the original.
var parameters = testMethod.MethodSymbol.Parameters.Select(parameter =>
{
var closed = closedParameters.FirstOrDefault(p => p.Ordinal == parameter.Ordinal);
var original = $"__mm_0.Parameters[{parameter.Ordinal.ToString(CultureInfo.InvariantCulture)}]";
return closed is null ? original
: $"{original} with {{ Type = typeof({closed.Type.GloballyQualified()}), TypeInfo = new global::TUnit.Core.ConcreteType(typeof({closed.Type.GloballyQualified()})) }}";
});
writer.AppendLine($"methodMetadata: __mm_0 with {{ Parameters = new global::TUnit.Core.ParameterMetadata[] {{ {string.Join(", ", parameters)} }} }},");
}
else
{
writer.AppendLine($"methodMetadata: __mm_0,");
}
writer.AppendLine($"createInstance: __CreateInstance_{groupIndex.ToString(CultureInfo.InvariantCulture)},");
writer.AppendLine($"invokeBody: __Invoke_{groupIndex.ToString(CultureInfo.InvariantCulture)},");
writer.AppendLine($"methodIndex: {entryIndex.ToString(CultureInfo.InvariantCulture)},");
Expand Down Expand Up @@ -2534,6 +2551,11 @@
}
}

// Match the concrete invoker: an open T may close to a one-element tuple.
var keepSingleElementTupleWhole = TryGetClosedParametersForSharedBinder(testMethod, entry) is { } closedParameters
? HasSingleElementTupleParameter(closedParameters)
: HasSingleElementTupleParameter(methodSymbol.Parameters);

// Method data sources
List<AttributeData> methodDataSources;
AttributeData[] classDataSources;
Expand Down Expand Up @@ -2623,7 +2645,7 @@
foreach (var rowSourceAttribute in rowSources)
{
var rowWriter = new CodeWriter(includeHeader: false);
GenerateDataSourceAttribute(rowWriter, testMethod.CompilationContext, rowSourceAttribute, methodSymbol, concreteTypeSymbol);
GenerateDataSourceAttribute(rowWriter, testMethod.CompilationContext, rowSourceAttribute, methodSymbol, concreteTypeSymbol, keepSingleElementTupleWhole);
dsWriter.AppendLine($"global::TUnit.Core.GenericConstraintViolationDataSource.Create({message}, {rowWriter.ToString().Trim().TrimEnd(',')}),");
}
}
Expand Down Expand Up @@ -2653,7 +2675,7 @@
dsWriter.Indent();
foreach (var attr in methodDataSources)
{
GenerateDataSourceAttribute(dsWriter, testMethod.CompilationContext, attr, methodSymbol, concreteTypeSymbol);
GenerateDataSourceAttribute(dsWriter, testMethod.CompilationContext, attr, methodSymbol, concreteTypeSymbol, keepSingleElementTupleWhole);
}
dsWriter.Unindent();
dsWriter.Append("}");
Expand Down Expand Up @@ -3014,7 +3036,7 @@
GeneratePropertyDataSources(writer, testMethod);
}

private static void GenerateDataSourceAttribute(CodeWriter writer, CompilationContext compilationContext, AttributeData attr, IMethodSymbol methodSymbol, INamedTypeSymbol typeSymbol)
private static void GenerateDataSourceAttribute(CodeWriter writer, CompilationContext compilationContext, AttributeData attr, IMethodSymbol methodSymbol, INamedTypeSymbol typeSymbol, bool? keepSingleElementTupleWhole = null)
{
var attrClass = attr.AttributeClass;
if (attrClass == null)
Expand All @@ -3029,7 +3051,7 @@
// finds no trimmed field or property metadata (#7225).
if (attrName is "global::TUnit.Core.MethodDataSourceAttribute" or InstanceMethodDataSourceAttributeName)
{
GenerateMethodDataSourceAttribute(writer, attr, typeSymbol, compilationContext.Compilation);
GenerateMethodDataSourceAttribute(writer, attr, typeSymbol, methodSymbol, compilationContext.Compilation, keepSingleElementTupleWhole);
}
else if (attrName == "global::TUnit.Core.ArgumentsAttribute")
{
Expand Down Expand Up @@ -3318,7 +3340,7 @@
return true;
}

private static void GenerateMethodDataSourceAttribute(CodeWriter writer, AttributeData attr, INamedTypeSymbol typeSymbol, Compilation compilation)
private static void GenerateMethodDataSourceAttribute(CodeWriter writer, AttributeData attr, INamedTypeSymbol typeSymbol, IMethodSymbol methodSymbol, Compilation compilation, bool? keepSingleElementTupleWhole)
{
// Extract method name and target type
string? methodName = null;
Expand Down Expand Up @@ -3463,20 +3485,42 @@
// a per-data-source compiler-generated state machine class (#6227). Only the per-test-unique
// invocation is emitted, as a static lambda.
writer.Append("Factory = static dataGeneratorMetadata => ");
EmitDataSourceFactoryInvocation(writer, dataSourceMember, targetType, usesTestClassInstance, hasArguments ? argumentsProperty.Value : (TypedConstant?)null, compilation, isDeclaredInstanceAttribute);
keepSingleElementTupleWhole ??= HasSingleElementTupleParameter(methodSymbol.Parameters);
EmitDataSourceFactoryInvocation(writer, dataSourceMember, targetType, usesTestClassInstance, hasArguments ? argumentsProperty.Value : (TypedConstant?)null, compilation, isDeclaredInstanceAttribute, keepSingleElementTupleWhole.Value);
writer.AppendLine(",");

writer.Unindent();
writer.AppendLine("},");
}

private static bool HasSingleElementTupleParameter(IEnumerable<IParameterSymbol> parameters)
{
ITypeSymbol? dataType = null;
foreach (var parameter in parameters)
{
if (parameter.Type.IsCancellationToken())
{
continue;
}

if (dataType is not null)
{
return false;
}

dataType = parameter.Type;
}

return dataType is INamedTypeSymbol { IsTupleType: true, TupleElements.Length: 1 };
}

/// <summary>
/// Emits a call to a <c>TUnit.Core.Helpers.DataSourceFactories</c> helper, passing the
/// data source member invocation as a static lambda. The helper is selected from the
/// member's declared return type (mirroring the previous inline-iterator branch order)
/// and whether the member is static or instance-based.
/// </summary>
private static void EmitDataSourceFactoryInvocation(CodeWriter writer, ISymbol dataSourceMember, ITypeSymbol targetType, bool usesTestClassInstance, TypedConstant? arguments, Compilation compilation, bool decidesRowsFromRuntimeValue)
private static void EmitDataSourceFactoryInvocation(CodeWriter writer, ISymbol dataSourceMember, ITypeSymbol targetType, bool usesTestClassInstance, TypedConstant? arguments, Compilation compilation, bool decidesRowsFromRuntimeValue, bool keepSingleElementTupleWhole)
{
var dataSourceMethod = dataSourceMember as IMethodSymbol;

Expand Down Expand Up @@ -3561,7 +3605,8 @@
// The instance helpers take the metadata anyway. [InstanceMethodDataSource] read its member by reflection before
// #7225, and that path keeps a tuple row whole when the test takes a single tuple, so its static helpers get the
// metadata too: without the parameter types, a one-element tuple holding null would reach the test as null.
var metadataArgument = usesTestClassInstance || decidesRowsFromRuntimeValue ? "dataGeneratorMetadata, " : "";
// Preserve one-element rows before unwrapping: their element can itself have the expected tuple type.
var metadataArgument = usesTestClassInstance || decidesRowsFromRuntimeValue || keepSingleElementTupleWhole ? "dataGeneratorMetadata, " : "";

// A declared type such as object does not say whether the value is one row or many. Reflection mode, and the
// attribute's reflection fallback that read every field and every private or protected property before the
Expand Down Expand Up @@ -4413,22 +4458,29 @@

// Special case: Single tuple parameter (same as in TestInvoker)
// If we have exactly one parameter that's a tuple type, we need to handle it specially
// In source-generated mode, tuples are always unwrapped into their elements
// Generated factories unwrap tuples; instance sources can preserve the whole tuple.
if (parametersFromArgs is
[
{ Type: INamedTypeSymbol { IsTupleType: true } singleTupleParam }
])
{
writer.AppendLine("// Special handling for single tuple parameter");
writer.AppendLine($"if (args.Length == {singleTupleParam.TupleElements.Length.ToString(CultureInfo.InvariantCulture)})");
// Factories preserve one-element tuple rows, so a matching tuple is the whole row,
// even when its element is another tuple of the same type.
var unwrappedCheck = singleTupleParam.TupleElements.Length == 1
? $" && args[0] is not {singleTupleParam.GloballyQualified()}"
: "";
writer.AppendLine($"if (args.Length == {singleTupleParam.TupleElements.Length.ToString(CultureInfo.InvariantCulture)}{unwrappedCheck})");
Comment thread
thomhurst marked this conversation as resolved.
Resolved
writer.AppendLine("{");
writer.Indent();
writer.AppendLine("// Arguments are unwrapped tuple elements, reconstruct the tuple");

// Build tuple reconstruction with proper casting
var tupleElements = singleTupleParam.TupleElements.Select((elem, i) =>
$"global::TUnit.Core.Helpers.CastHelper.Cast<{elem.Type.GloballyQualified()}>(args[{i.ToString(CultureInfo.InvariantCulture)}])");
var tupleConstruction = $"({string.Join(", ", tupleElements)})";
var tupleConstruction = singleTupleParam.TupleElements.Length == 1
? $"new {singleTupleParam.GloballyQualified()}({string.Join(", ", tupleElements)})"
: $"({string.Join(", ", tupleElements)})";
Comment thread
thomhurst marked this conversation as resolved.
Resolved

var methodCallReconstructed = $"instance.{methodName}({FormatSingleArgumentCall(tupleConstruction, hasCancellationToken, parametersFromArgs)})";
GenerateReturnHandling(writer, methodCallReconstructed, returnPattern);
Expand Down Expand Up @@ -7598,7 +7650,7 @@
if (inferredTypes.Count == typeParameters.Length)
{
var result = new ITypeSymbol[typeParameters.Length];
for (var i = 0; i < typeParameters.Length; i++)

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / AOT (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (fr-FR)

Déréférencement d'une éventuelle référence null.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (windows-latest)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (sv-SE)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (sv-SE)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 7653 in src/TUnit.Core.SourceGenerator/Generators/TestMetadataGenerator.cs

View workflow job for this annotation

GitHub Actions / modularpipeline (macos-latest)

Dereference of a possibly null reference.
{
if (inferredTypes.TryGetValue(typeParameters[i].Name, out var type))
{
Expand Down
5 changes: 3 additions & 2 deletions src/TUnit.Core/Helpers/TestDataRowUnwrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,9 @@ public static bool IsTestDataRowType(Type? type)
/// Unwraps an array of values, extracting TestDataRow metadata from single-element arrays.
/// </summary>
/// <param name="values">The array of values to unwrap.</param>
/// <param name="expectedTupleType">Preserve tuple payloads assignable to this parameter type.</param>
/// <returns>A tuple of the unwrapped data array and any extracted metadata.</returns>
public static (object?[] Data, TestDataRowMetadata? Metadata) UnwrapArray(object?[] values)
public static (object?[] Data, TestDataRowMetadata? Metadata) UnwrapArray(object?[] values, Type? expectedTupleType = null)
{
if (values.Length == 1 && TryUnwrap(values[0], out var data, out var metadata))
{
Expand All @@ -82,7 +83,7 @@ public static (object?[] Data, TestDataRowMetadata? Metadata) UnwrapArray(object
}

// Check if the data is a tuple that should be expanded
if (DataSourceHelpers.IsTuple(data))
if (DataSourceHelpers.IsTuple(data) && (expectedTupleType is null || !expectedTupleType.IsInstanceOfType(data)))
{
return (data.ToObjectArray(), metadata);
}
Expand Down
32 changes: 30 additions & 2 deletions src/TUnit.Engine/Helpers/DataUnwrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ public static (object?[] Data, TestDataRowMetadata? Metadata) UnwrapWithTypesAnd
ParameterMetadata[]? expectedParameters)
{
// First check for TestDataRow wrapper
var (unwrapped, metadata) = TestDataRowUnwrapper.UnwrapArray(values);
var (unwrapped, metadata) = TestDataRowUnwrapper.UnwrapArray(values,
values is [ITestDataRow] ? GetSingleTupleDataParameterType(expectedParameters) : null);

// Then apply type-aware unwrapping
var data = UnwrapWithTypesInternal(unwrapped, expectedParameters);
Expand All @@ -58,10 +59,37 @@ public static (object?[] Data, TestDataRowMetadata? Metadata) UnwrapWithTypesAnd
public static object?[] UnwrapWithTypes(object?[] values, ParameterMetadata[]? expectedParameters)
{
// First handle TestDataRow unwrapping
var (unwrapped, _) = TestDataRowUnwrapper.UnwrapArray(values);
var (unwrapped, _) = TestDataRowUnwrapper.UnwrapArray(values,
values is [ITestDataRow] ? GetSingleTupleDataParameterType(expectedParameters) : null);
return UnwrapWithTypesInternal(unwrapped, expectedParameters);
}

private static Type? GetSingleTupleDataParameterType(ParameterMetadata[]? parameters)
{
Type? dataType = null;
if (parameters is null)
{
return null;
}

foreach (var parameter in parameters)
{
if (parameter.Type == typeof(CancellationToken))
{
continue;
}

if (dataType is not null)
{
return null;
}

dataType = parameter.Type;
}

return TupleHelper.IsTupleType(dataType) ? dataType : null;
}

private static object?[] UnwrapWithTypesInternal(object?[] values, ParameterMetadata[]? expectedParameters)
{
// If no parameter information, fall back to default behavior
Expand Down
Loading
Loading