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
37 changes: 26 additions & 11 deletions TUnit.Core/Helpers/CastHelper.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
using System.Collections;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
using System.Runtime.CompilerServices;
using TUnit.Core.Converters;

namespace TUnit.Core.Helpers;

[UnconditionalSuppressMessage("AOT", "IL3050:Calling members annotated with 'RequiresDynamicCodeAttribute' may break functionality when AOT compiling.")]
[UnconditionalSuppressMessage("Trimming", "IL2072:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttribute\' in call to target method. The return value of the source method does not have matching annotations.")]
public static class CastHelper
{
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Type conversion uses reflection for custom conversions")]
[RequiresDynamicCode("Dynamic type conversion may require runtime code generation")]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static T? Cast<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] T>(object? value)
{
if (value is null)
Expand Down Expand Up @@ -69,6 +69,7 @@ public static class CastHelper
// Handle null -> empty array
if (value is null)
{
ThrowOnAot(value, underlyingType);
return (T?)(object)Array.CreateInstance(targetElementType, 0);
}

Expand All @@ -77,6 +78,8 @@ public static class CastHelper
{
if (value is IConvertible)
{
ThrowOnAot(value, underlyingType);

try
{
var convertedValue = Convert.ChangeType(value, targetElementType);
Expand Down Expand Up @@ -104,6 +107,7 @@ public static class CastHelper
// Otherwise, convert each element
try
{
ThrowOnAot(value, underlyingType);
var targetArray = Array.CreateInstance(targetElementType, sourceArray.Length);
for (var i = 0; i < sourceArray.Length; i++)
{
Expand Down Expand Up @@ -175,10 +179,7 @@ public static class CastHelper
}
}

#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Type conversion uses reflection for custom conversions")]
[RequiresDynamicCode("Dynamic type conversion may require runtime code generation")]
#endif
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static object? Cast([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] Type type, object? value)
{
if (value is null)
Expand Down Expand Up @@ -217,6 +218,7 @@ public static class CastHelper
var firstItem = enumerable.Cast<object>().FirstOrDefault();
if (firstItem != null)
{
ThrowOnAot(value, underlyingType);
// Use reflection to get the Value property
var valueProperty = GetValuePropertySafe(firstItem.GetType());
if (valueProperty != null)
Expand Down Expand Up @@ -252,6 +254,7 @@ public static class CastHelper
// Handle null -> empty array
if (value is null)
{
ThrowOnAot(value, underlyingType);
return Array.CreateInstance(targetElementType, 0);
}

Expand All @@ -260,6 +263,7 @@ public static class CastHelper
{
if (value is IConvertible)
{
ThrowOnAot(value, underlyingType);
try
{
var convertedValue = Convert.ChangeType(value, targetElementType);
Expand Down Expand Up @@ -287,6 +291,7 @@ public static class CastHelper
// Otherwise, convert each element
try
{
ThrowOnAot(value, underlyingType);
var targetArray = Array.CreateInstance(targetElementType, sourceArray.Length);
for (var i = 0; i < sourceArray.Length; i++)
{
Expand Down Expand Up @@ -363,6 +368,19 @@ public static class CastHelper
mi.Name == "op_Explicit" && mi.ReturnType == targetType && HasCorrectInputType(baseType, mi));
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ThrowOnAot(object? value, Type? targetType)
{
#if NET
if (!RuntimeFeature.IsDynamicCodeSupported)
{
throw new InvalidOperationException(
$"Cannot cast {value?.GetType()?.Name ?? "null"} to {targetType?.Name} in AOT mode. " +
"Consider using AotConverterRegistry.Register() for custom type conversions.");
}
#endif
}

private static bool HasCorrectInputType(Type baseType, MethodInfo mi)
{
var pi = mi.GetParameters().FirstOrDefault();
Expand All @@ -372,9 +390,6 @@ private static bool HasCorrectInputType(Type baseType, MethodInfo mi)
/// <summary>
/// Gets the "Value" property from a type in an AOT-safer manner.
/// </summary>
#if NET6_0_OR_GREATER
[RequiresUnreferencedCode("Property access for CustomAttributeTypedArgument unwrapping")]
#endif
private static PropertyInfo? GetValuePropertySafe([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type)
{
return type.GetProperty("Value");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1949,13 +1949,14 @@ namespace .Helpers
public static string FormatArguments(.<object?> arguments) { }
public static string GetConstantValue(.TestContext testContext, object? o) { }
}
[.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" +
"nctionality when AOT compiling.")]
[.("Trimming", "IL2072:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttr" +
"ibute\' in call to target method. The return value of the source method does not " +
"have matching annotations.")]
public static class CastHelper
{
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static object? Cast([.(..None | ..PublicMethods | ..NonPublicMethods)] type, object? value) { }
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static T? Cast<[.(..None | ..PublicMethods | ..NonPublicMethods)] T>(object? value) { }
public static .MethodInfo? GetConversionMethod([.(..None | ..PublicMethods | ..NonPublicMethods)] baseType, [.(..None | ..PublicMethods | ..NonPublicMethods)] targetType) { }
}
Expand Down Expand Up @@ -2006,20 +2007,17 @@ namespace .Helpers
public static class DataSourceHelpers
{
public static <.<object?>>[] HandleTupleValue(object? value, bool shouldUnwrap) { }
public static . InitializeDataSourcePropertiesAsync(object? instance, .MethodMetadata testInformation, string testSessionId) { }
public static object? InvokeIfFunc(object? value) { }
public static T InvokeIfFunc<T>(object? value) { }
public static bool IsTuple(object? obj) { }
public static .<object?> ProcessDataSourceResult<T>(T data) { }
public static .<object?> ProcessDataSourceResultGeneric<T>(T data) { }
public static .<object?> ProcessEnumerableDataSource<T>(.<T> enumerable) { }
public static <.<object?>>[] ProcessTestDataSource<T>(T data, int expectedParameterCount = -1) { }
public static void RegisterPropertyInitializer<T>(<T, .MethodMetadata, string, .> initializer) { }
public static void RegisterTypeCreator<T>(<.MethodMetadata, string, .<T>> creator) { }
[.("Data source resolution may require dynamic code generation")]
[.("Property types are resolved through reflection")]
public static .<object?> ResolveDataSourceForPropertyAsync([.(..None | ..PublicParameterlessConstructor | ..PublicFields | ..NonPublicFields | ..PublicProperties)] containingType, string propertyName, .MethodMetadata testInformation, string testSessionId) { }
public static .<object?> ResolveDataSourcePropertyAsync(object instance, string propertyName, .MethodMetadata testInformation, string testSessionId) { }
public static object?[] ToObjectArray(this object? item) { }
public static object?[] ToObjectArrayWithTypes(this object? item, []? expectedTypes) { }
[return: .(new string[] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1949,13 +1949,14 @@ namespace .Helpers
public static string FormatArguments(.<object?> arguments) { }
public static string GetConstantValue(.TestContext testContext, object? o) { }
}
[.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" +
"nctionality when AOT compiling.")]
[.("Trimming", "IL2072:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttr" +
"ibute\' in call to target method. The return value of the source method does not " +
"have matching annotations.")]
public static class CastHelper
{
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static object? Cast([.(..None | ..PublicMethods | ..NonPublicMethods)] type, object? value) { }
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static T? Cast<[.(..None | ..PublicMethods | ..NonPublicMethods)] T>(object? value) { }
public static .MethodInfo? GetConversionMethod([.(..None | ..PublicMethods | ..NonPublicMethods)] baseType, [.(..None | ..PublicMethods | ..NonPublicMethods)] targetType) { }
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1949,13 +1949,14 @@ namespace .Helpers
public static string FormatArguments(.<object?> arguments) { }
public static string GetConstantValue(.TestContext testContext, object? o) { }
}
[.("AOT", "IL3050:Calling members annotated with \'RequiresDynamicCodeAttribute\' may break fu" +
"nctionality when AOT compiling.")]
[.("Trimming", "IL2072:Target parameter argument does not satisfy \'DynamicallyAccessedMembersAttr" +
"ibute\' in call to target method. The return value of the source method does not " +
"have matching annotations.")]
public static class CastHelper
{
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static object? Cast([.(..None | ..PublicMethods | ..NonPublicMethods)] type, object? value) { }
[.("Dynamic type conversion may require runtime code generation")]
[.("Type conversion uses reflection for custom conversions")]
public static T? Cast<[.(..None | ..PublicMethods | ..NonPublicMethods)] T>(object? value) { }
public static .MethodInfo? GetConversionMethod([.(..None | ..PublicMethods | ..NonPublicMethods)] baseType, [.(..None | ..PublicMethods | ..NonPublicMethods)] targetType) { }
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,5 @@
[assembly: .(".NETCoreApp,Version=v10.0", FrameworkDisplayName=".NET 10.0")]
namespace
{
public static class AotMethodInvokers
{
public static string GetMethodKey(string typeName, string methodName, int parameterCount = 0) { }
public static .<object?> InvokeMethodAsync(string methodKey, object? instance, params object?[]? parameters) { }
}
}
namespace
{
public class BrowserTest : .PlaywrightTest
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,12 @@ public void Test()
{
TestContext.Current!.GetDefaultLogger().LogInformation("Blah");
}
}

[Test]
[Arguments(1)]
[Arguments(2)]
public void DataTest(int value)
{
TestContext.Current!.GetDefaultLogger().LogInformation(value.ToString());
}
}
Loading