Skip to content

Commit ef4ea6d

Browse files
EvangelinkCopilotgithub-code-quality[bot]Copilot
authored
Allow trailing CancellationToken parameters in MSTest tests (#11991)
Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <223894421+github-code-quality[bot]@users.noreply.github.com> Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Copilot-Session: e91db52f-30be-43f0-bd01-b8069a1068e7
1 parent e46ed0f commit ef4ea6d

18 files changed

Lines changed: 2611 additions & 70 deletions

File tree

‎docs/decisions/test-method-cancellation-token.md‎

Lines changed: 514 additions & 0 deletions
Large diffs are not rendered by default.

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.ArgumentResolution.cs‎

Lines changed: 46 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
33

4+
using Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
5+
46
namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution;
57

68
#pragma warning disable CA1852 // Seal internal types - This class is inherited in tests.
@@ -20,28 +22,38 @@ internal partial class TestMethodInfo
2022
// reused across all data rows regardless of whether they share a TestMethodInfo instance.
2123
ParameterMetadata metadata = GetParameterMetadata();
2224
int requiredParameterCount = metadata.RequiredParameterCount;
25+
int parameterCount = parametersInfo.Length;
26+
if (arguments.Length < parameterCount && TestDataSourceHelpers.GetDataParameterCount(parametersInfo) < parameterCount)
27+
{
28+
parameterCount--;
29+
if (!parametersInfo[^1].IsOptional)
30+
{
31+
requiredParameterCount--;
32+
}
33+
}
34+
2335
bool hasParamsValue = metadata.HasParams;
2436
object? paramsValues = null;
2537

2638
// If all the parameters are required, we have fewer arguments
2739
// supplied than required, or more arguments than the method takes
2840
// and it doesn't have a params parameter don't try and resolve anything
29-
if (requiredParameterCount == parametersInfo.Length ||
41+
if (requiredParameterCount == parameterCount ||
3042
arguments.Length < requiredParameterCount ||
31-
(!hasParamsValue && arguments.Length > parametersInfo.Length))
43+
(!hasParamsValue && arguments.Length > parameterCount))
3244
{
3345
return arguments;
3446
}
3547

36-
object?[] newParameters = new object[parametersInfo.Length];
48+
object?[] newParameters = new object[parameterCount];
3749
for (int argumentIndex = 0; argumentIndex < arguments.Length; argumentIndex++)
3850
{
3951
// We have reached the end of the regular parameters and any additional
4052
// values will go in a params array
41-
if (argumentIndex >= parametersInfo.Length - 1 && hasParamsValue)
53+
if (argumentIndex >= parameterCount - 1 && hasParamsValue)
4254
{
4355
// If this is the params parameter, instantiate a new object of that type
44-
if (argumentIndex == parametersInfo.Length - 1)
56+
if (argumentIndex == parameterCount - 1)
4557
{
4658
paramsValues = PlatformServiceProvider.Instance.ReflectionOperations.CreateInstance(parametersInfo[argumentIndex].ParameterType, [arguments.Length - argumentIndex]);
4759
newParameters[argumentIndex] = paramsValues;
@@ -51,7 +63,7 @@ internal partial class TestMethodInfo
5163
// set the values as a generic array
5264
if (paramsValues is Array paramsArray)
5365
{
54-
paramsArray.SetValue(arguments[argumentIndex], argumentIndex - (parametersInfo.Length - 1));
66+
paramsArray.SetValue(arguments[argumentIndex], argumentIndex - (parameterCount - 1));
5567
}
5668
}
5769
else
@@ -62,15 +74,41 @@ internal partial class TestMethodInfo
6274

6375
// If arguments supplied are less than total possible arguments set
6476
// the values supplied to the default values for those parameters
65-
for (int parameterNotProvidedIndex = arguments.Length; parameterNotProvidedIndex < parametersInfo.Length; parameterNotProvidedIndex++)
77+
for (int parameterNotProvidedIndex = arguments.Length; parameterNotProvidedIndex < parameterCount; parameterNotProvidedIndex++)
6678
{
6779
// If this is the params parameters, set it to an empty
6880
// array of that type as DefaultValue is DBNull
69-
newParameters[parameterNotProvidedIndex] = hasParamsValue && parameterNotProvidedIndex == parametersInfo.Length - 1
81+
newParameters[parameterNotProvidedIndex] = hasParamsValue && parameterNotProvidedIndex == parameterCount - 1
7082
? PlatformServiceProvider.Instance.ReflectionOperations.CreateInstance(parametersInfo[parameterNotProvidedIndex].ParameterType, [0])
7183
: parametersInfo[parameterNotProvidedIndex].DefaultValue;
7284
}
7385

7486
return newParameters;
7587
}
88+
89+
private object?[]? GetArgumentsWithCancellationToken(object?[]? arguments)
90+
{
91+
ParameterInfo[] parameters = ParameterTypes;
92+
int dataParameterCount = TestDataSourceHelpers.GetDataParameterCount(parameters);
93+
if (dataParameterCount == parameters.Length)
94+
{
95+
return arguments;
96+
}
97+
98+
if (arguments is not [object[]]
99+
&& TestDataSourceHelpers.IsDataConsideredSingleArgumentValue(arguments, parameters))
100+
{
101+
arguments = [arguments];
102+
}
103+
104+
if (arguments is not null)
105+
{
106+
arguments = ResolveArguments(arguments);
107+
}
108+
109+
// Bind after initialization and timeout setup, without adding the token to the stored test data.
110+
return (arguments?.Length ?? 0) == dataParameterCount
111+
? [.. arguments ?? [], TestContext.Context.CancellationToken]
112+
: arguments;
113+
}
76114
}

‎src/Adapter/MSTestAdapter.PlatformServices/Execution/TestMethodInfo.Execution.cs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ private async Task<TestResult> ExecuteInternalAsync(
165165
// In case of WinUI's default synchronization context, this will ensure that the test method runs on the UI thread.
166166
if (await RunTestInitializeMethodAsync(classInstance, result, timeoutTokenSource).ConfigureAwait(true))
167167
{
168+
arguments = GetArgumentsWithCancellationToken(arguments);
168169
if (_executionContext is null)
169170
{
170171
Task? invokeResult = MethodInfo.GetInvokeResultWithParametersAsync(classInstance, ParameterTypes, arguments);

‎src/Adapter/MSTestAdapter.PlatformServices/Extensions/MethodInfoExtensions.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ internal static bool HasCorrectTestMethodSignature(this MethodInfo method, bool
8383
!method.IsAbstract &&
8484
(method.IsStatic == method.DeclaringType!.IsFSharpModule()) &&
8585
(method.IsPublic || (discoverInternals && method.IsAssembly)) &&
86-
(method.GetParameters().Length == 0 || ignoreParameterLength) &&
86+
(ignoreParameterLength || TestDataSourceHelpers.GetDataParameterCount(method.GetParameters()) == 0) &&
8787
method.IsValidReturnType(); // Match return type Task for async methods only. Else return type void.
8888
}
8989

‎src/Adapter/MSTestAdapter.PlatformServices/Helpers/TestDataSourceHelpers.cs‎

Lines changed: 38 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,20 @@ namespace Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers;
77

88
internal static class TestDataSourceHelpers
99
{
10+
internal static int GetDataParameterCount(ParameterInfo[] parameters)
11+
=> parameters.Length > 0 && parameters[^1].ParameterType == typeof(CancellationToken)
12+
? parameters.Length - 1
13+
: parameters.Length;
14+
1015
public static bool IsDataConsideredSingleArgumentValue(object?[]? data, ParameterInfo[] parameters)
1116
=> data is not null
1217
&& (data.Length != 1 || data[0] is not null)
13-
&& parameters.Length == 1
14-
&& parameters[0].ParameterType == typeof(object[]);
18+
&& GetDataParameterCount(parameters) == 1
19+
&& parameters[0].ParameterType == typeof(object[])
20+
&& !IsDataWithExplicitCancellationToken(data, parameters)
21+
&& !(parameters.Length == 2 && data.Length == 1
22+
&& TryHandleTupleDataSource(data[0], parameters, out object?[] tupleArguments)
23+
&& IsDataWithExplicitCancellationToken(tupleArguments, parameters));
1524

1625
public static bool TryHandleITestDataRow(
1726
object?[] d,
@@ -64,13 +73,38 @@ public static bool TryHandleITestDataRow(
6473

6574
public static bool TryHandleTupleDataSource(object? data, ParameterInfo[] testMethodParameters, out object?[] array)
6675
{
67-
if (testMethodParameters.Length == 1 &&
68-
testMethodParameters[0].ParameterType?.IsAssignableFrom(data?.GetType()) == true)
76+
bool isSingleDataArgument = GetDataParameterCount(testMethodParameters) == 1
77+
&& testMethodParameters[0].ParameterType?.IsAssignableFrom(data?.GetType()) is true;
78+
if (isSingleDataArgument && testMethodParameters.Length == 1)
79+
{
80+
array = [];
81+
return false;
82+
}
83+
84+
if (!TryExpandTupleDataSource(data, out array))
85+
{
86+
return false;
87+
}
88+
89+
// A valid full-arity row supplies its own token, even when the tuple itself fits the data parameter.
90+
if (isSingleDataArgument && !IsDataWithExplicitCancellationToken(array, testMethodParameters))
6991
{
7092
array = [];
7193
return false;
7294
}
7395

96+
return true;
97+
}
98+
99+
private static bool IsDataWithExplicitCancellationToken(object?[] data, ParameterInfo[] parameters)
100+
=> parameters.Length == 2
101+
&& parameters[1].ParameterType == typeof(CancellationToken)
102+
&& data.Length == 2
103+
&& (data[0] is null || parameters[0].ParameterType.IsInstanceOfType(data[0]))
104+
&& (data[1] is null or CancellationToken || data[1] == Type.Missing);
105+
106+
private static bool TryExpandTupleDataSource(object? data, out object?[] array)
107+
{
74108
#if NET471_OR_GREATER || NETCOREAPP
75109
if (data is ITuple tuple)
76110
{

‎src/Adapter/MSTestAdapter.PlatformServices/InternalAPI/InternalAPI.Unshipped.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
#nullable enable
2+
static Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Helpers.TestDataSourceHelpers.GetDataParameterCount(System.Reflection.ParameterInfo![]! parameters) -> int
23
Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery.AssemblyEnumerator.EnumerateAssembly(string! assemblyFileName, bool mustSerialize, bool useGeneratedDescriptors, System.Type![]? types, System.Action<System.Type!, System.Collections.Generic.IReadOnlyList<Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.ObjectModel.UnitTestElement!>?>? typeObserver) -> Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Discovery.AssemblyEnumerationResult!
34
Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.UnitTestDiscovererFactory.get -> System.Func<Microsoft.VisualStudio.TestPlatform.MSTestAdapter.PlatformServices.Interface.ITestSourceHandler!, Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.UnitTestDiscoverer!>?
45
Microsoft.VisualStudio.TestPlatform.MSTest.TestAdapter.Execution.TestExecutionManager.UnitTestDiscovererFactory.set -> void

0 commit comments

Comments
 (0)