Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TestFixtureSource arguments usage in the TestCaseSource method #3593

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
86 changes: 79 additions & 7 deletions src/NUnitFramework/framework/Attributes/TestCaseSourceAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test? suite)
{
int count = 0;

foreach (TestCaseParameters parms in GetTestCasesFor(method))
foreach (TestCaseParameters parms in GetTestCasesFor(method, suite))
{
count++;
yield return _builder.BuildTestMethod(method, suite, parms);
Expand All @@ -158,13 +158,13 @@ public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test? suite)
#region Helper Methods

[SecuritySafeCritical]
private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method)
private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method, Test? suite)
{
List<ITestCaseData> data = new List<ITestCaseData>();

try
{
IEnumerable? source = ContextUtils.DoIsolated(() => GetTestCaseSource(method));
IEnumerable? source = ContextUtils.DoIsolated(() => GetTestCaseSource(method, suite));

if (source != null)
{
Expand Down Expand Up @@ -235,7 +235,7 @@ private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method)
return data;
}

private IEnumerable? GetTestCaseSource(IMethodInfo method)
private IEnumerable? GetTestCaseSource(IMethodInfo method, Test? suite)
{
Type sourceType = SourceType ?? method.TypeInfo.Type;

Expand Down Expand Up @@ -267,15 +267,87 @@ private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method)
var m = member as MethodInfo;
if (m != null)
return m.IsStatic
? (MethodParams == null || m.GetParameters().Length == MethodParams.Length
? (IEnumerable)m.Invoke(null, MethodParams)
: ReturnErrorAsParameter(NumberOfArgsDoesNotMatch))
? InvokeTestCaseSourceMethod(m, suite?.Arguments)
: ReturnErrorAsParameter(SourceMustBeStatic);
}

return null;
}

/// <summary>
/// Ensures that the test case source generator method is called with correct arguments
/// and that exceptions are converted appropriately.
/// </summary>
private IEnumerable InvokeTestCaseSourceMethod(MethodInfo method, object?[]? suiteArguments)
{
try
{
return MethodParams == null || method.GetParameters().Length == MethodParams.Length
? (IEnumerable)method.Invoke(null, UpdateTestCaseSourceParameters(MethodParams, suiteArguments))
: ReturnErrorAsParameter(NumberOfArgsDoesNotMatch);
}
catch (ArgumentException e)
{
return ReturnErrorAsParameter(e.Message);
}
}

/// <summary>
/// Provides functionality of utilizing test fixture source
/// arguments in the test case source initialization method.
/// </summary>
/// <param name="methodParams">Method parameters specified.</param>
/// <param name="suiteArguments">Arguments specified in the test fixture source.</param>
/// <exception cref="ArgumentException">Indicates parameters mismatch.</exception>
private static object?[]? UpdateTestCaseSourceParameters(object?[]? methodParams, object?[]? suiteArguments)
{
// Case #1 : No parameters to call with.
if (null == methodParams)
{
return null;
}

var result = new object? [methodParams.Length];

for (int i = 0; i < methodParams.Length; i++)
{
result[i] = SubstituteFixtureParameterIfNeeded(methodParams[i], suiteArguments);
}

// Integration point ...
return result;
}

/// <summary>
/// Attempts to replace specific parameter with respective fixture
/// argument if necessary.
/// </summary>
/// <param name="methodParam">Parameter to be replaced.</param>
/// <param name="suiteArguments">Arguments of the fixture.</param>
/// <exception cref="ArgumentException">If reference to fixture argument cannot be resolved.</exception>
/// <returns>Actual value to be passed to the test case source.</returns>
private static object? SubstituteFixtureParameterIfNeeded(object? methodParam, object?[]? suiteArguments)
{
if (!(methodParam is TestFixtureArgumentRef))
{
// Not a reference... return original value.
return methodParam;
}

// It is a reference to an argument passed to the fixture.
// Find its index based on the value.
int index = (int)methodParam;


if (index < 0 || null == suiteArguments || suiteArguments.Length <= index)
{
throw new ArgumentException($"Unable to get a reference to fixture attribute at index {index}");
}

// And return corresponding fixture argument.
return suiteArguments[index];
}

private static IEnumerable ReturnErrorAsParameter(string errorMessage)
{
var parms = new TestCaseParameters();
Expand Down
79 changes: 79 additions & 0 deletions src/NUnitFramework/framework/Attributes/TestFixtureArgumentRef.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
// ***********************************************************************
// Copyright (c) 2020 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

namespace NUnit.Framework
{
/// <summary>
/// Represents reference to an argument
/// from the test fixture in form of 0-based
/// index. Used for forwarding values
/// to the test case sources.
///
/// If your fixture contains more than 10 arguments
/// you can always cast any higher index
/// to <see cref="TestFixtureArgumentRef"/>
/// </summary>
public enum TestFixtureArgumentRef
{
/// <summary>
/// Argument at index 0
/// </summary>
Arg0 = 0,
/// <summary>
/// Argument at index 1
/// </summary>
Arg1 = 1,
/// <summary>
/// Argument at index 2
/// </summary>
Arg2 = 2,
/// <summary>
/// Argument at index 3
/// </summary>
Arg3 = 3,
/// <summary>
/// Argument at index 4
/// </summary>
Arg4 = 4,
/// <summary>
/// Argument at index 5
/// </summary>
Arg5 = 5,
/// <summary>
/// Argument at index 6
/// </summary>
Arg6 = 6,
/// <summary>
/// Argument at index 7
/// </summary>
Arg7 = 7,
/// <summary>
/// Argument at index 8
/// </summary>
Arg8 = 8,
/// <summary>
/// Argument at index 9
/// </summary>
Arg9 = 9
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// ***********************************************************************
// Copyright (c) 2020 Charlie Poole, Lukasz Skomial
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace NUnit.Framework.Attributes
{
[TestFixtureSource(nameof(TestFixturesSource))]
public class TestCaseSourceWithTestFixtureArgumentsTests
{
private static string[] FixtureArgumentsSource { get; }
private const int NUMBER_OF_ARGS = 3;

static TestCaseSourceWithTestFixtureArgumentsTests()
{
string uniqueIdentifier = Guid.NewGuid().ToString("N");

FixtureArgumentsSource = new string[NUMBER_OF_ARGS];

for (int i = 0; i < NUMBER_OF_ARGS; i++)
{
FixtureArgumentsSource[i] = $"ARG_{i}_{uniqueIdentifier}";
}
}

public static IEnumerable<TestFixtureData> TestFixturesSource
{
get
{
for (int maxArgs = 0; maxArgs <= NUMBER_OF_ARGS; maxArgs++)
{
string[] args = FixtureArgumentsSource.Take(maxArgs).ToArray();

yield return new TestFixtureData(maxArgs, args).SetArgDisplayNames($"{maxArgs}_arguments_test");

}
}
}

/// <summary>
/// The actual arguments used to create the fixture.
/// </summary>
private string[] FixtureArgs { get; }
private int FixtureNumberOfArgs { get; }

public TestCaseSourceWithTestFixtureArgumentsTests(int numberOfArgs, string[] args)
{
FixtureNumberOfArgs = numberOfArgs;
FixtureArgs = args;
}



/// <summary>
/// Checks that argument from fixture can
/// be passed to
/// </summary>
[Test]
[TestCaseSource(nameof(TestCaseDataWithFixtureContext), new object[]{ TestFixtureArgumentRef.Arg0 })]
public void FixtureArgumentTest(int argumentIndex, int numberOfArguments)
{
Assert.AreEqual(FixtureNumberOfArgs, numberOfArguments);
Assert.AreEqual(FixtureArgs[argumentIndex], FixtureArgumentsSource[argumentIndex]);
}

public static IEnumerable<TestCaseData> TestCaseDataWithFixtureContext(int numberOfArgsFixtureWasCreatedWith)
{
for (int i = 0; i < numberOfArgsFixtureWasCreatedWith; i++)
{
yield return new TestCaseData(i, numberOfArgsFixtureWasCreatedWith)
.SetArgDisplayNames($"Number of args : {i + 1} of {numberOfArgsFixtureWasCreatedWith} ");
}
}



/// <summary>
/// Checks that you can specify index as integer
/// and cast it to the enum and the correct
/// argument will be passed to the test case source method.
/// </summary>
[Test]
[TestCaseSource(nameof(TestCaseDataWithFixtureContext2), new object[] { (TestFixtureArgumentRef) 1 })]
public void FixtureArgumentAsIntegerTest(string argument, int index)
{
Assert.AreEqual(FixtureArgs[index], argument);
}

public static IEnumerable<TestCaseData> TestCaseDataWithFixtureContext2(string[] data)
{
for (int i = 0; i < data.Length; i++)
{
yield return new TestCaseData(data[i], i)
.SetArgDisplayNames($"Argument {i + 1} of {data.Length} validation.");
}
}


/// <summary>
/// Checks that integers are not
/// treated as parameters index.
/// </summary>
[Test]
[TestCaseSource(nameof(PassThroughMethod), new object[]{ 1, 0 })]
public void IntegerSourceArgumentsStillWorkAsExpected(int a, int b)
{
Assert.AreEqual(1, a);
Assert.AreEqual(0, b);
}


public static IEnumerable<TestCaseData> PassThroughMethod(int a, int b)
{
yield return new TestCaseData(a, b);
}

}
}