diff --git a/src/TUnit.Analyzers/TestDataAnalyzer.cs b/src/TUnit.Analyzers/TestDataAnalyzer.cs index 30f4b15c4dd..ecf54f943a6 100644 --- a/src/TUnit.Analyzers/TestDataAnalyzer.cs +++ b/src/TUnit.Analyzers/TestDataAnalyzer.cs @@ -446,6 +446,7 @@ private void CheckMethodDataSource(SymbolAnalysisContext context, methodSymbol.Name == methodName && !methodSymbol.IsGenericMethod && ArgumentsMatchParameterTypes(context, argumentsForMethodCall, methodSymbol.Parameters.WithoutCancellationTokenParameter().Select(p => p.Type))) + ?? FindOptionalDataSource(context, argumentsForMethodCall, methodSymbols, methodName!, type!) ?? methodSymbols.FirstOrDefault(x => x.Name == methodName && !x.IsGenericMethod) ?? methodSymbols.FirstOrDefault(x => x.Name == methodName); @@ -669,7 +670,9 @@ private void CheckMethodDataSource(SymbolAnalysisContext context, return; } - if (!ArgumentsMatchParameterTypes(context, argumentsForMethodCall, dataSourceMethodParameterTypes)) + if (!(argumentsForMethodCall.Length == dataSourceMethod.Parameters.Length + ? ArgumentsMatchParameterTypes(context, argumentsForMethodCall, dataSourceMethod.Parameters.Select(p => p.Type)) + : ScoreOptionalDataSource(context, argumentsForMethodCall, dataSourceMethod) >= 0)) { context.ReportDiagnostic( Diagnostic.Create( @@ -745,6 +748,134 @@ private void CheckMethodDataSource(SymbolAnalysisContext context, } } + private static IMethodSymbol? FindOptionalDataSource(SymbolAnalysisContext context, TypedConstant[] arguments, + IMethodSymbol[] methods, string name, ITypeSymbol targetType) + { + // Inaccessible declarations cannot hide an otherwise available base source. + var availableMethods = methods.Where(method => method.Name == name && !method.IsGenericMethod + && (SymbolEqualityComparer.Default.Equals(method.ContainingType, targetType) + || (method.DeclaredAccessibility != Accessibility.Private + && context.Compilation.IsSymbolAccessibleWithin(method, context.Compilation.Assembly)))) + .ToArray(); + IMethodSymbol? best = null; + var bestScore = -1; + foreach (var method in availableMethods) + { + if (availableMethods.Any(derived => HidesBaseSignature(derived, method))) + { + continue; + } + + var score = ScoreOptionalDataSource(context, arguments, method); + var moreSpecific = best is not null && score == bestScore && score >= 0 + && IsMoreSpecificOptionalDataSource(context.Compilation, method, best, arguments.Length); + if (score > bestScore || moreSpecific) + { + best = method; + bestScore = score; + } + } + + return best; + } + + // Specificity compares parameter conversions, including lifted nullable conversions, rather than + // boxed argument conversions. Mirrors IsMoreSpecificDataSourceOverload and reflection's IsMoreSpecific. + private static bool IsMoreSpecificOptionalDataSource(Compilation compilation, IMethodSymbol candidate, + IMethodSymbol other, int argumentCount) + { + var anyDifferent = false; + for (var i = 0; i < argumentCount; i++) + { + var candidateType = candidate.Parameters[i].Type; + var otherType = other.Parameters[i].Type; + if (SymbolEqualityComparer.Default.Equals(candidateType, otherType)) + { + continue; + } + + if (compilation.ClassifyCommonConversion(candidateType, otherType) is not { IsImplicit: true, IsUserDefined: false }) + { + return false; + } + + anyDifferent = true; + } + + return anyDifferent; + } + + private static bool HidesBaseSignature(IMethodSymbol derived, IMethodSymbol candidate) + { + if (derived.Name != candidate.Name || derived.Arity != candidate.Arity + || derived.Parameters.Length != candidate.Parameters.Length) + { + return false; + } + + var isDerived = derived.ContainingType.BaseType?.GetSelfAndBaseTypes() + .Any(type => SymbolEqualityComparer.Default.Equals(type, candidate.ContainingType)) == true; + return isDerived && derived.Parameters.Zip(candidate.Parameters, (left, right) => + left.RefKind == right.RefKind && SymbolEqualityComparer.Default.Equals(left.Type, right.Type)).All(equal => equal); + } + + // Mirrors the invocation conversions accepted by both MethodDataSource execution paths. + private static bool IsOptionalInvocationConversion(Compilation compilation, ITypeSymbol? argumentType, ITypeSymbol parameterType) + { + var conversion = compilation.ClassifyCommonConversion(argumentType!, parameterType); + if (conversion is not { IsImplicit: true, IsUserDefined: false }) + { + return false; + } + + if (conversion.IsNullable) + { + return parameterType is INamedTypeSymbol { TypeArguments: [var underlying] } + && SymbolEqualityComparer.Default.Equals(underlying, argumentType); + } + + return !conversion.IsNumeric || parameterType.SpecialType != SpecialType.System_Decimal; + } + + // Defaults belong to the selected declaration: an override does not inherit its base method's defaults. + // Supplied arguments bind positionally; only omitted token parameters are injected. + private static int ScoreOptionalDataSource(SymbolAnalysisContext context, TypedConstant[] arguments, IMethodSymbol method) + { + if (arguments.Length > method.Parameters.Length) + { + return -1; + } + + var score = 0; + for (var i = 0; i < method.Parameters.Length; i++) + { + var parameter = method.Parameters[i]; + if (i >= arguments.Length) + { + if (!parameter.HasExplicitDefaultValue + && parameter.Type.ToDisplayString() != "System.Threading.CancellationToken") + { + return -1; + } + + continue; + } + + var argument = arguments[i]; + if (!DataSourceArgumentMatches(context.Compilation, argument, parameter.Type, invocationOnly: true)) + { + return -1; + } + + if (!argument.IsNull) + { + score += SymbolEqualityComparer.Default.Equals(argument.Type, parameter.Type) ? 2 : 1; + } + } + + return score; + } + private static bool ArgumentsMatchParameterTypes(SymbolAnalysisContext context, TypedConstant[] argumentsForMethodCall, IEnumerable parameterTypes) { @@ -760,9 +891,7 @@ private static bool ArgumentsMatchParameterTypes(SymbolAnalysisContext context, for (var i = 0; i < argumentsForMethodCall.Length; i++) { var argument = argumentsForMethodCall[i]; - var matches = argument.IsNull - ? CanAcceptNull(parameterTypeArray[i]) - : context.Compilation.HasImplicitConversionOrGenericParameter(argument.Type, parameterTypeArray[i]); + var matches = DataSourceArgumentMatches(context.Compilation, argument, parameterTypeArray[i], invocationOnly: false); if (!matches) { @@ -773,6 +902,18 @@ private static bool ArgumentsMatchParameterTypes(SymbolAnalysisContext context, return true; } + // Exact-count matching retains its existing generic/conversion behavior; optional overload selection + // is restricted to conversions supported by invocation in both execution modes. + private static bool DataSourceArgumentMatches(Compilation compilation, TypedConstant argument, + ITypeSymbol parameterType, bool invocationOnly) + { + return argument.IsNull + ? CanAcceptNull(parameterType) + : invocationOnly + ? IsOptionalInvocationConversion(compilation, argument.Type, parameterType) + : compilation.HasImplicitConversionOrGenericParameter(argument.Type, parameterType); + } + // Mirrors the null-argument overload selection in both execution modes (added in #7143): a null argument binds to // any parameter that can hold null, i.e. anything other than a non-nullable value type. private static bool CanAcceptNull(ITypeSymbol parameterType) @@ -1592,7 +1733,7 @@ private static bool IsIAsyncEnumerable(ITypeSymbol type, Compilation compilation // Mirrors DefaultBinder.FindMostSpecificMethod: an overload wins when it is more specific for at least one // parameter and less specific for none. Overloads with the same parameter types (a member hidden with `new`) // are resolved by the binder in favour of the most derived declaration, so they never tie. - private static bool IsAtLeastAsSpecific(Compilation compilation, IMethodSymbol candidate, IMethodSymbol other, ITypeSymbol[] argumentTypes) + private static bool IsAtLeastAsSpecific(Compilation compilation, IMethodSymbol candidate, IMethodSymbol other, ITypeSymbol?[] argumentTypes) { var otherWins = false; @@ -1622,7 +1763,7 @@ private static bool IsAtLeastAsSpecific(Compilation compilation, IMethodSymbol c } // Mirrors DefaultBinder.FindMostSpecificType: 1 when the first type is more specific, 2 when the second is, 0 for a tie. - private static int FindMostSpecificType(Compilation compilation, ITypeSymbol first, ITypeSymbol second, ITypeSymbol argumentType) + private static int FindMostSpecificType(Compilation compilation, ITypeSymbol first, ITypeSymbol second, ITypeSymbol? argumentType) { if (SymbolEqualityComparer.Default.Equals(first, argumentType)) { diff --git a/tests/TUnit.Analyzers.Tests/MethodDataSourceAnalyzerTests.cs b/tests/TUnit.Analyzers.Tests/MethodDataSourceAnalyzerTests.cs index 291aae8f52b..68a69869e03 100644 --- a/tests/TUnit.Analyzers.Tests/MethodDataSourceAnalyzerTests.cs +++ b/tests/TUnit.Analyzers.Tests/MethodDataSourceAnalyzerTests.cs @@ -4,6 +4,230 @@ namespace TUnit.Analyzers.Tests; public class MethodDataSourceAnalyzerTests : BaseAnalyzerTests { + [Test] + public async Task Private_Intermediate_Source_Does_Not_Hide_Public_Base_Overload() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Base + { + public static IEnumerable Rows(int value, int count = 1) => [value]; + } + public class Middle : Base + { + private new static IEnumerable Rows(int value, int count = 1) => [value]; + } + public class Tests : Middle + { + public static IEnumerable Rows(object value, int count = 1) => ["broad"]; + [Test, MethodDataSource(nameof(Rows), Arguments = new object[] { 1 })] + public void Specific(int value) { } + } + """); + } + + [Test] + public async Task Optional_Metadata_Without_Default_Is_Rejected() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using System.Runtime.InteropServices; + using TUnit.Core; + public class Tests + { + public static IEnumerable Rows([Optional] int value) => [value]; + [Test, {|#0:MethodDataSource(nameof(Rows))|}] + public void Missing(int value) { } + } + """, + Verifier.Diagnostic(Rules.WrongArgumentTypeTestData) + .WithLocation(0).WithArguments("", "int")); + } + + [Test] + public async Task Null_Optional_Overloads_Compare_Lifted_Parameter_Conversions() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Tests + { + public static IEnumerable Rows(long? value, int count = 1) => ["broad"]; + public static IEnumerable Rows(int? value, int count = 1) => [count]; + public static IEnumerable Reversed(int? value, int count = 1) => [count]; + public static IEnumerable Reversed(long? value, int count = 1) => ["broad"]; + [Test, MethodDataSource(nameof(Rows), Arguments = new object?[] { null })] + public void Specific(int value) { } + [Test, MethodDataSource(nameof(Reversed), Arguments = new object?[] { null })] + public void SpecificReversed(int value) { } + } + """); + } + + [Test] + public async Task Equally_Specific_Optional_Overloads_Keep_Declaration_Order() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Tests + { + public static IEnumerable Rows(int value, int count = 1) => ["first"]; + public static IEnumerable Rows(int value, string suffix = "") => [value]; + [Test, MethodDataSource(nameof(Rows), Arguments = new object[] { 1 })] + public void First(string value) { } + } + """); + } + + [Test] + public async Task Optional_Overloads_Use_Invocation_Conversions() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Tests + { + public static IEnumerable Decimal(object value, int count = 1) => ["ok"]; + public static IEnumerable Decimal(decimal value, int count = 1) => [count]; + public static IEnumerable Nullable(object value, int count = 1) => ["ok"]; + public static IEnumerable Nullable(long? value, int count = 1) => [count]; + public static IEnumerable UserDefined(object value, int count = 1) => ["ok"]; + public static IEnumerable UserDefined(Converted value, int count = 1) => [count]; + [Test, MethodDataSource(nameof(Decimal), Arguments = new object[] { 1 })] + public void DecimalTest(string value) { } + [Test, MethodDataSource(nameof(Nullable), Arguments = new object[] { 1 })] + public void NullableTest(string value) { } + [Test, MethodDataSource(nameof(UserDefined), Arguments = new object[] { 1 })] + public void UserDefinedTest(string value) { } + } + public class Converted + { + public static implicit operator Converted(int value) => new(); + } + """); + } + + [Test] + public async Task Optional_Overloads_Exclude_Unavailable_Base_Methods() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Base + { + private static IEnumerable Private(int value, int count = 1) => [count]; + public static IEnumerable Hidden(int value, int count = 1) => [count]; + } + public class Tests : Base + { + public static IEnumerable Private(object value, int count = 1) => ["ok"]; + public new static IEnumerable Hidden(int value, int count) => [count]; + public static IEnumerable Hidden(object value, int count = 1) => ["ok"]; + [Test, MethodDataSource(nameof(Private), Arguments = new object[] { 1 })] + public void PrivateTest(string value) { } + [Test, MethodDataSource(nameof(Hidden), Arguments = new object[] { 1 })] + public void HiddenTest(string value) { } + } + """); + } + + [Test] + public async Task Null_Argument_Selects_More_Specific_Optional_Overload() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Tests + { + public static IEnumerable Rows(object value, int count = 1) => ["broad"]; + public static IEnumerable Rows(string value, int count = 1) => [count]; + public static IEnumerable Reversed(string value, int count = 1) => [count]; + public static IEnumerable Reversed(object value, int count = 1) => ["broad"]; + + [Test, MethodDataSource(nameof(Rows), Arguments = new object?[] { null })] + public void Specific(int value) { } + [Test, MethodDataSource(nameof(Reversed), Arguments = new object?[] { null })] + public void SpecificReversed(int value) { } + [Test, {|#0:MethodDataSource(nameof(Rows), Arguments = new object?[] { null })|}] + public void Incompatible(string value) { } + } + """, + Verifier.Diagnostic(Rules.WrongArgumentTypeTestData) + .WithLocation(0) + .WithArguments("int", "string")); + } + + [Test] + public async Task Override_Does_Not_Inherit_Optional_Default() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using TUnit.Core; + public class Base + { + public virtual IEnumerable Rows(int value = 1) => [value]; + } + public class Tests : Base + { + public override IEnumerable Rows(int value) => [value]; + [Test, {|#0:MethodDataSource(nameof(Rows))|}] + public void Required(int value) { } + } + """, + Verifier.Diagnostic(Rules.WrongArgumentTypeTestData) + .WithLocation(0) + .WithArguments("", "int")); + } + + [Test] + public async Task Omitted_Optional_Data_Method_Parameters_Are_Accepted() + { + await Verifier.VerifyAnalyzerAsync( + """ + using System.Collections.Generic; + using System.Threading; + using TUnit.Core; + + public class Base + { + public virtual IEnumerable Inherited(int value = 1) => [value]; + } + + public class Tests : Base + { + public override IEnumerable Inherited(int value = 2) => [value]; + public static IEnumerable Rows(string value) => [value]; + public static IEnumerable Rows(int value, int count = 1) => [value]; + public static IEnumerable Specific(object value, int count = 1) => ["broad"]; + public static IEnumerable Specific(long value, int count = 1) => [1]; + public static IEnumerable Exact(int value, int count = 1) => ["optional"]; + public static IEnumerable Exact(int value) => [value]; + public static IEnumerable Tokens(int value, int count = 1, CancellationToken token = default) => [value]; + + [Test, MethodDataSource(nameof(Rows), Arguments = new object[] { 1 })] + public void Optional(int value) { } + [Test, MethodDataSource(nameof(Specific), Arguments = new object[] { 1 })] + public void MoreSpecific(int value) { } + [Test, MethodDataSource(nameof(Exact), Arguments = new object[] { 1 })] + public void ExactMatch(int value) { } + [Test, MethodDataSource(nameof(Inherited))] + public void OverrideDefault(int value) { } + [Test, MethodDataSource(nameof(Tokens), Arguments = new object[] { 1 })] + public void InjectedToken(int value) { } + } + """); + } + [Test] public async Task DataSourceDriven_Argument_Is_Flagged_When_Does_Not_Match_Parameter_Type() {