/// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { List<TestMethod> tests = new List<TestMethod>(); IParameterInfo[] parameters = method.GetParameters(); if (parameters.Length > 0) { IEnumerable[] sources = new IEnumerable[parameters.Length]; try { for (int i = 0; i < parameters.Length; i++) sources[i] = _dataProvider.GetDataFor(parameters[i]); } catch (InvalidDataSourceException ex) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, ex.Message); tests.Add(_builder.BuildTestMethod(method, suite, parms)); return tests; } foreach (var parms in _strategy.GetTestCases(sources)) tests.Add(_builder.BuildTestMethod(method, suite, (TestCaseParameters)parms)); } return tests; }
/// <summary> /// Formulates the extended portion of the display name for a test method. For tests with no arguments, this will /// return just the base name; for tests with arguments, attempts to format the arguments and appends the argument /// list to the test name. /// </summary> /// <param name="method">The test method</param> /// <param name="baseDisplayName">The base part of the display name</param> /// <param name="arguments">The test method arguments</param> /// <param name="genericTypes">The test method's generic types</param> /// <returns>The full display name for the test method</returns> public static string GetDisplayNameWithArguments(this IMethodInfo method, string baseDisplayName, object[] arguments, ITypeInfo[] genericTypes) { baseDisplayName += ResolveGenericDisplay(genericTypes); if (arguments == null) { return(baseDisplayName); } var parameterInfos = method.GetParameters().CastOrToArray(); var displayValues = new string[Math.Max(arguments.Length, parameterInfos.Length)]; int idx; for (idx = 0; idx < arguments.Length; idx++) { displayValues[idx] = ParameterToDisplayValue(GetParameterName(parameterInfos, idx), arguments[idx]); } for (; idx < parameterInfos.Length; idx++) { var reflectionParameterInfo = parameterInfos[idx] as IReflectionParameterInfo; var parameterName = GetParameterName(parameterInfos, idx); if (reflectionParameterInfo?.ParameterInfo.IsOptional ?? false) { displayValues[idx] = ParameterToDisplayValue(parameterName, reflectionParameterInfo.ParameterInfo.DefaultValue); } else { displayValues[idx] = parameterName + ": ???"; } } return($"{baseDisplayName}({string.Join(", ", displayValues)})"); }
/// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable <TestMethod> BuildFrom(IMethodInfo method, Test suite) { List <TestMethod> tests = new List <TestMethod>(); IParameterInfo[] parameters = method.GetParameters(); if (parameters.Length > 0) { IEnumerable[] sources = new IEnumerable[parameters.Length]; try { for (int i = 0; i < parameters.Length; i++) { sources[i] = _dataProvider.GetDataFor(parameters[i]); } } catch (InvalidDataSourceException ex) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, ex.Message); tests.Add(_builder.BuildTestMethod(method, suite, parms)); return(tests); } foreach (var parms in _strategy.GetTestCases(sources)) { tests.Add(_builder.BuildTestMethod(method, suite, (TestCaseParameters)parms)); } } return(tests); }
public ScenarioInfo(IMethodInfo testMethod, object[] dataRow, string scenarioOutlineDisplayName) { var parameters = testMethod.GetParameters().ToList(); var typeParameters = testMethod.GetGenericArguments().ToList(); ITypeInfo[] typeArguments; if (testMethod.IsGenericMethodDefinition) { typeArguments = typeParameters .Select(typeParameter => InferTypeArgument(typeParameter.Name, parameters, dataRow)) .ToArray(); this.MethodToRun = testMethod.MakeGenericMethod(typeArguments).ToRuntimeMethod(); } else { typeArguments = new ITypeInfo[0]; this.MethodToRun = testMethod.ToRuntimeMethod(); } var passedArguments = Reflector.ConvertArguments( dataRow, this.MethodToRun.GetParameters().Select(p => p.ParameterType).ToArray()); var generatedArguments = GetGeneratedArguments( typeParameters, typeArguments, parameters, passedArguments.Length); var arguments = passedArguments .Select(value => new Argument(value)) .Concat(generatedArguments) .ToList(); this.ScenarioDisplayName = GetScenarioDisplayName(scenarioOutlineDisplayName, typeArguments, parameters, arguments); this.ConvertedDataRow = arguments.Select(argument => argument.Value).ToList(); }
public Test BuildFrom(IMethodInfo method, Test?parentSuite) { var tests = new List <TestMethod>(); List <ITestBuilder> builders = new List <ITestBuilder>( method.GetCustomAttributes <ITestBuilder>(false)); // See if we need to add a CombinatorialAttribute for parameterized data if (method.MethodInfo.GetParameters().Any(param => param.HasAttribute <IParameterDataSource>(false)) && !builders.Any(builder => builder is CombiningStrategyAttribute)) { builders.Add(new CombinatorialAttribute()); } foreach (var attr in builders) { foreach (var test in attr.BuildFrom(method, parentSuite)) { tests.Add(test); } } return(builders.Count > 0 && method.GetParameters().Length > 0 || tests.Count > 0 ? BuildParameterizedMethodSuite(method, tests) : BuildSingleTestMethod(method, parentSuite)); }
/// <summary> /// Formulates the extended portion of the display name for a test method. For tests with no arguments, this will /// return just the base name; for tests with arguments, attempts to format the arguments and appends the argument /// list to the test name. /// </summary> /// <param name="method">The test method</param> /// <param name="baseDisplayName">The base part of the display name</param> /// <param name="arguments">The test method arguments</param> /// <param name="genericTypes">The test method's generic types</param> /// <returns>The full display name for the test method</returns> public static string GetDisplayNameWithArguments(this IMethodInfo method, string baseDisplayName, object[] arguments, ITypeInfo[] genericTypes) { baseDisplayName += ResolveGenericDisplay(genericTypes); if (arguments == null) { return(baseDisplayName); } var parameterInfos = method.GetParameters().CastOrToArray(); var displayValues = new string[Math.Max(arguments.Length, parameterInfos.Length)]; int idx; for (idx = 0; idx < arguments.Length; idx++) { displayValues[idx] = ParameterToDisplayValue(GetParameterName(parameterInfos, idx), arguments[idx]); } for (; idx < parameterInfos.Length; idx++) // Fill-in any missing parameters with "???" { displayValues[idx] = GetParameterName(parameterInfos, idx) + ": ???"; } return($"{baseDisplayName}({string.Join(", ", displayValues)})"); }
private IEnumerable <Func <Expression, string> > GetArgumentTranslators( IMethodInfo method, IEnumerable <Expression> arguments, Func <Expression, string> defaultArgumentTranslator) { if (method == null) { return(arguments.Select(argument => defaultArgumentTranslator).ToArray()); } var parameters = method.GetParameters(); if (method.IsExtensionMethod) { parameters = parameters.Skip(1).ToArray(); } return(arguments .Select((argument, i) => { var parameter = parameters.ElementAtOrDefault(i); if (IsNotFuncType(parameter, method)) { return defaultArgumentTranslator; } return CanBeConvertedToMethodGroup(argument) ? MethodGroupTranslator : defaultArgumentTranslator; }) .ToArray()); }
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { foreach (var p in GetCombination(method.GetParameters().Select(_ => _.ParameterType).ToArray())) { yield return(new NUnitTestCaseBuilder().BuildTestMethod(method, suite, new TestCaseParameters(p))); } }
protected IEnumerable <TestCaseParameters> GetTestCases(IMethodInfo testMethodInfo) { var parameterType = testMethodInfo.GetParameters().First().ParameterType; var method = Factory.GetProviderMethod(parameterType); var testCases = method.Invoke(Factory.TestCaseProvider, null); return(((IEnumerable <object>)testCases).Select( s => new TestCaseParameters(new[] { s }))); }
public TestMethod BuildFrom(IMethodInfo method, NUnit.Framework.Internal.Test suite) { var defaultParameters = method.GetParameters().Select( parameter => TypeUtils.defaultOf(parameter.ParameterType)).ToArray(); var parameters = new TestCaseParameters(defaultParameters); if (method.ReturnType.Type != typeof(void)) { parameters.ExpectedResult = null; } return(_builder.BuildTestMethod(method, suite, parameters)); }
private static TypeScriptReturnStatement GenerateMethodCallWithBody(IMethodInfo methodInfo, string methodName) { var routeTemplate = methodInfo.GetAttributes(TypeInfo.From <RouteAttribute>()).Single().GetValue("Template", ""); return(new TypeScriptReturnStatement( new TypeScriptMethodCallExpression( new TypeScriptThisReference(), methodName, new TypeScriptTemplateStringLiteral(routeTemplate.Replace("{", "${")), GenerateConstructBody(methodInfo.GetParameters().ToArray(), routeTemplate) ))); }
private static IEnumerable <Func <string, string> > GetParameterModifers(IMethodInfo method) { if (method == null) { return(Enumerable.Empty <Func <string, string> >()); } return(method .GetParameters() .Select(GetParameterModifier) .ToArray()); }
/// <summary> /// Resolves all the generic types for a test method. The test parameters are used to determine /// the best matching generic types for the test method that can be satisfied by all /// the generic parameters and their values. /// </summary> /// <param name="method">The test method</param> /// <param name="parameters">The parameter values being passed to the test method</param> /// <returns>The best matching generic types</returns> public static ITypeInfo[] ResolveGenericTypes(this IMethodInfo method, object[] parameters) { var genericTypes = method.GetGenericArguments().ToArray(); var resolvedTypes = new ITypeInfo[genericTypes.Length]; var parameterInfos = method.GetParameters().CastOrToArray(); for (var idx = 0; idx < genericTypes.Length; ++idx) { resolvedTypes[idx] = ResolveGenericType(genericTypes[idx], parameters, parameterInfos); } return(resolvedTypes); }
private TestCaseParameters GetParametersForMethod(IMethodInfo method) { try { var parameterValues = this.CreateParameterValues(method.GetParameters()); return new TestCaseParameters(parameterValues); } catch (Exception ex) { return new TestCaseParameters(ex); } }
private static TypeScriptInterfaceFunctionMember BuildApiInterfaceMember(IMethodInfo methodInfo, Func <ITypeInfo, TypeScriptType> buildAndImportType) { var result = new TypeScriptInterfaceFunctionMember(methodInfo.Name.ToLowerCamelCase(), GetMethodResult(methodInfo, buildAndImportType)); result.Arguments.AddRange( methodInfo.GetParameters().Select(x => new TypeScriptArgumentDeclaration { Name = x.Name, Type = buildAndImportType(x.ParameterType) }) ); return(result); }
private TestCaseParameters GetParametersForMethod(IMethodInfo method) { try { var parameterValues = this.CreateParameterValues(method.GetParameters()); return(new TestCaseParameters(parameterValues)); } catch (Exception ex) { return(new TestCaseParameters(ex)); } }
/// <summary> /// FOR INTERNAL USE ONLY. /// </summary> protected static ITypeInfo[] ResolveGenericTypes(IMethodInfo method, object[] parameters) { ITypeInfo[] genericTypes = method.GetGenericArguments().ToArray(); ITypeInfo[] resolvedTypes = new ITypeInfo[genericTypes.Length]; IParameterInfo[] parameterInfos = method.GetParameters().ToArray(); for (int idx = 0; idx < genericTypes.Length; ++idx) { resolvedTypes[idx] = ResolveGenericType(genericTypes[idx], parameters, parameterInfos); } return(resolvedTypes); }
IEnumerable <TestMethod> BuildFrom(IMethodInfo method, Test suite, IScenario scenario) { var builder = new NUnitTestCaseBuilder(); var resolvedParameters = method.GetParameters() .Select(p => scenario.DiContainer.TryResolve(p.ParameterType)) .ToArray(); var tcParams = new TestCaseParameters(resolvedParameters); var testMethod = builder.BuildTestMethod(method, suite, tcParams); testMethod.Properties.Add(ScenarioAdapter.ScreenplayScenarioKey, scenario); return(new[] { testMethod }); }
private TestCaseParameters GetParametersForMethod(IMethodInfo method) { try { var parameters = method.GetParameters(); var parameterValues = this.GetParameterValues(parameters); return(new TestCaseParameters(parameterValues.ToArray())); } catch (Exception ex) { return(new TestCaseParameters(ex)); } }
private static TestCaseParameters GetParametersForMethod(IMethodInfo method, object[] args, int autoDataStartIndex) { var result = new TestCaseParameters(args); EnsureOriginalArgumentsArrayIsNotShared(result); var methodParameters = method.GetParameters(); for (int i = autoDataStartIndex; i < result.OriginalArguments.Length; i++) { result.OriginalArguments[i] = new TypeNameRenderer(methodParameters[i].ParameterType); } return(result); }
private static TypeScriptReturnStatement GenerateGetMethodCall(IMethodInfo methodInfo) { var routeTemplate = methodInfo.GetAttributes(TypeInfo.From <RouteAttribute>()).Single().GetValue("Template", ""); return(new TypeScriptReturnStatement( new TypeScriptMethodCallExpression( new TypeScriptThisReference(), "get", new[] { new TypeScriptTemplateStringLiteral(routeTemplate.Replace("{", "${")), GenerateConstructGetParams(methodInfo.GetParameters().ToArray(), routeTemplate) }.Where(x => x != null).ToArray() ))); }
private TestCaseParameters GetParametersForMethod(IMethodInfo method) { try { var specimenBuilder = new SpecimenContext(this._fixture); var parameterValues = method.GetParameters() .Select(p => specimenBuilder.Resolve(p.ParameterInfo)) .ToArray(); return new TestCaseParameters(parameterValues); } catch (Exception ex) { return new TestCaseParameters(ex); } }
private TypeScriptReturnStatement GenerateMethodCallWithBody(IMethodInfo methodInfo, string methodName, ITypeInfo controllerType) { var route = BuildRoute(controllerType, methodInfo); return new TypeScriptReturnStatement( new TypeScriptMethodCallExpression( new TypeScriptThisReference(), methodName, new TypeScriptTemplateStringLiteral(route.Replace("{", "${")), GenerateConstructGetParams( GetQueryParameters(methodInfo.GetParameters(), controllerType), route ), GetBodyExpression(methodInfo, methodName, controllerType) )); }
private TestCaseParameters GetParametersForMethod(IMethodInfo method) { try { var specimenBuilder = new SpecimenContext(this._fixture); var parameterValues = method.GetParameters() .Select(p => specimenBuilder.Resolve(p.ParameterInfo)) .ToArray(); return(new TestCaseParameters(parameterValues)); } catch (Exception ex) { return(new TestCaseParameters(ex)); } }
internal MethodEmitter(AbstractTypeEmitter owner, String name, MethodAttributes attributes, IMethodInfo methodToUseAsATemplate) : this(owner, name, attributes) { var name2GenericType = GenericUtil.GetGenericArgumentsMap(owner); var returnType = GenericUtil.ExtractCorrectType(methodToUseAsATemplate.ReturnType, name2GenericType); var baseMethodParameters = methodToUseAsATemplate.GetParameters(); var parameters = GenericUtil.ExtractParametersTypes(baseMethodParameters, name2GenericType); genericTypeParams = GenericUtil.CopyGenericArguments(methodToUseAsATemplate, builder, name2GenericType); SetParameters(parameters); SetReturnType(returnType); SetSignature(returnType, methodToUseAsATemplate.ReturnParameter, parameters, baseMethodParameters); DefineParameters(baseMethodParameters); }
/// <summary> /// Builds the parameters /// </summary> protected virtual TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { IParameterInfo[] parameters = method.GetParameters(); parms = GetParametersForTestCaseHelper(parameters, method); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return(parms); }
private IEnumerable<TypeScriptInterfaceFunctionMember> BuildApiInterfaceMember(IMethodInfo methodInfo, Func<ITypeInfo, TypeScriptType> buildAndImportType, ITypeInfo controllerType) { var result = new TypeScriptInterfaceFunctionMember( methodInfo.Name.ToLowerCamelCase(), GetMethodResult(methodInfo, buildAndImportType) ); result.Arguments.AddRange( methodInfo.GetParameters() .Where(x => PassParameterToCall(x, controllerType)) .Select(x => new TypeScriptArgumentDeclaration { Name = x.Name, Type = buildAndImportType(x.ParameterType) }) ); yield return result; }
/// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Internal.Test suite) { IParameterInfo[] parameters = method.GetParameters(); List<TestMethod> tests = new List<TestMethod>(); if (parameters.Length > 0) { IEnumerable[] sources = new IEnumerable[parameters.Length]; for (int i = 0; i < parameters.Length; i++) sources[i] = _dataProvider.GetDataFor(parameters[i]); foreach (var parms in new CombinatorialStrategy().GetTestCases(sources)) tests.Add(_builder.BuildTestMethod(method, suite, (TestCaseParameters)parms)); } return tests; }
/// <summary> /// Builds the parameters /// </summary> protected override TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { var parameterlist = method.GetParameters().ToList(); parameterlist.RemoveAt(0); IParameterInfo[] parameters = parameterlist.ToArray(); parms = GetParametersForTestCaseHelper(parameters, method); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return(parms); }
/// <summary> /// Build a Test from the provided MethodInfo. Depending on /// whether the method takes arguments and on the availability /// of test case data, this method may return a single test /// or a group of tests contained in a ParameterizedMethodSuite. /// </summary> /// <param name="method">The method for which a test is to be built</param> /// <param name="parentSuite">The test fixture being populated, or null</param> /// <returns>A Test representing one or more method invocations</returns> public Test BuildFrom(IMethodInfo method, Test parentSuite) { var tests = new List <TestMethod>(); List <ITestBuilder> builders = new List <ITestBuilder>( method.GetCustomAttributes <ITestBuilder>(false)); // See if we need a CombinatorialAttribute added bool needCombinatorial = true; foreach (var attr in builders) { if (attr is CombiningStrategyAttribute) { needCombinatorial = false; } } // This check must be done before CombinatorialAttribute gets added to the builders collection var hasBuildersSpecified = builders.Count > 0; // We could check to see if here are any data attributes specified // on the parameters but that's what CombinatorialAttribute does // and it simply won't return any cases if it finds nothing. // TODO: We need to add some other ITestBuilder than a combinatorial attribute // because we want the attribute to generate an error if it's present on // a generic method. if (needCombinatorial) { builders.Add(new CombinatorialAttribute()); } foreach (var attr in builders) { foreach (var test in attr.BuildFrom(method, parentSuite)) { tests.Add(test); } } return(hasBuildersSpecified && method.GetParameters().Length > 0 || tests.Count > 0 ? BuildParameterizedMethodSuite(method, tests) : BuildSingleTestMethod(method, parentSuite)); }
public static string GetDisplayNameWithArguments(IMethodInfo method, string baseDisplayName, object[] arguments, ITypeInfo[] genericTypes) { baseDisplayName += ResolveGenericDisplay(genericTypes); if (arguments == null) return baseDisplayName; var parameterInfos = method.GetParameters().ToArray(); var displayValues = new string[Math.Max(arguments.Length, parameterInfos.Length)]; int idx; for (idx = 0; idx < arguments.Length; idx++) displayValues[idx] = ParameterToDisplayValue(GetParameterName(parameterInfos, idx), arguments[idx]); for (; idx < parameterInfos.Length; idx++) // Fill-in any missing parameters with "???" displayValues[idx] = GetParameterName(parameterInfos, idx) + ": ???"; return String.Format(CultureInfo.CurrentCulture, "{0}({1})", baseDisplayName, string.Join(", ", displayValues)); }
public ScenarioInfo(IMethodInfo testMethod, object[] actualArgs, string scenarioOutlineDisplayName) { //Guard.AgainstNullArgument(nameof(testMethod), testMethod); #if DEBUG testMethod = testMethod.RequiresNotNull(nameof(testMethod)); #endif // Which, we "do", in DEBUG mode. #pragma warning disable CA1062 // ...validate parameter 'name' is non-null before using it... var parameters = testMethod.GetParameters().ToList(); #pragma warning restore CA1062 // ...validate parameter 'name' is non-null before using it... var typeParams = testMethod.GetGenericArguments().ToList(); ITypeInfo[] typeArgs; if (testMethod.IsGenericMethodDefinition) { typeArgs = typeParams .Select(typeParameter => InferTypeArgument(typeParameter.Name, parameters, actualArgs)) .ToArray(); this.MethodToRun = testMethod.MakeGenericMethod(typeArgs).ToRuntimeMethod(); } else { typeArgs = Array.Empty <ITypeInfo>(); this.MethodToRun = testMethod.ToRuntimeMethod(); } var passedArgs = Reflector.ConvertArguments(actualArgs, this.MethodToRun.GetParameters().Select(p => p.ParameterType).ToArray()); var generatedArguments = GetGeneratedArguments(typeParams, typeArgs, parameters, passedArgs.Length); var args = passedArgs .Select(value => new Argument(value)) .Concat(generatedArguments) .ToList(); this.ScenarioDisplayName = GetScenarioDisplayName(scenarioOutlineDisplayName, typeArgs, parameters, args); this.ConvertedActualArgs = args.Select(arg => arg.Value).ToList(); }
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { // If the system doesn't support exceptions (Unity editor for delegates) we should not test with exceptions bool skipTest = (ExpectCompilerException || ExpectedException != null) && !SupportException; var expectResult = !method.ReturnType.IsType(typeof(void)); var name = method.Name; var arguments = this.Arguments; var permutations = CreatePermutation(0, arguments, method.GetParameters()); // TODO: Workaround for a scalability bug with R# or Rider // Run only one testcase if not running from the commandline if (!IsCommandLine()) { permutations = permutations.Take(1); } foreach (var newArguments in permutations) { var caseParameters = new TestCaseParameters(newArguments); if (expectResult) { caseParameters.ExpectedResult = true; if (OverrideResultOnMono != null && IsMono()) { caseParameters.Properties.Set(nameof(OverrideResultOnMono), OverrideResultOnMono); } } // Transfer FastMath parameter to the compiler caseParameters.Properties.Set(nameof(FastMath), FastMath); var test = _builder.BuildTestMethod(method, suite, caseParameters); if (skipTest) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, "Exceptions are not supported"); } yield return(test); } }
public IEnumerable <TestMethod> BuildFrom(IMethodInfo method, Test?suite) { int count = 0; foreach (TestCaseParameters parms in GetTestCasesFor(method)) { count++; yield return(_builder.BuildTestMethod(method, suite, parms)); } // If count > 0, error messages will be shown for each case // but if it's 0, we need to add an extra "test" to show the message. if (count == 0 && method.GetParameters().Length == 0) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, "TestCaseSourceAttribute may not be used on a method without parameters"); yield return(_builder.BuildTestMethod(method, suite, parms)); } }
public static void CopyOutAndRefParameters(TypeReference[] dereferencedArguments, LocalReference invocation, IMethodInfo method, MethodEmitter emitter) { var parameters = method.GetParameters(); if (!ArgumentsUtil.IsAnyByRef(parameters)) { return; //saving the need to create locals if there is no need } var arguments = StoreInvocationArgumentsInLocal(emitter, invocation); for (var i = 0; i < parameters.Length; i++) { if (!parameters[i].ParameterType.IsByRef) { continue; } emitter.CodeBuilder.AddStatement(AssignArgument(dereferencedArguments, i, arguments)); } }
private static TypeScriptClassMemberDefinition BuildApiImplMember(IMethodInfo methodInfo, Func <ITypeInfo, TypeScriptType> buildAndImportType) { var functionDefinition = new TypeScriptFunctionDefinition { IsAsync = true, Result = GetMethodResult(methodInfo, buildAndImportType), Body = { CreateCall(methodInfo) } }; functionDefinition.Arguments.AddRange( methodInfo.GetParameters().Select(x => new TypeScriptArgumentDeclaration { Name = x.Name, Type = buildAndImportType(x.ParameterType) }) ); return(new TypeScriptClassMemberDefinition { Name = methodInfo.Name.ToLowerCamelCase(), Definition = functionDefinition }); }
/// <inheritdoc/> public virtual IEnumerable<object[]> GetData(IAttributeInfo dataAttribute, IMethodInfo testMethod) { // The data from GetConstructorArguments does not maintain its original form (in particular, collections // end up as generic IEnumerable<T>). So we end up needing to call .ToArray() on the enumerable so that // we can restore the correct argument type from InlineDataAttribute. // // In addition, [InlineData(null)] gets translated into passing a null array, not a single array with a null // value in it, which is why the null coalesce operator is required (this is covered by the acceptance test // in Xunit2TheoryAcceptanceTests.InlineDataTests.SingleNullValuesWork). var count = testMethod.GetParameters().Count(); var arguments = dataAttribute.GetConstructorArguments(); var args = (IEnumerable<object>)arguments.Single() ?? new object[] { null }; var objects = args.ToArray(); var results = objects.Select(x => Enumerable.Empty<object>().Concat(new[] { x })); while (--count > 0) { results = results.Join(objects, o => true, o => true, (enumerable, item) => enumerable.Concat(new[] { item }).ToArray()); } var array = results.Select(x => x.ToArray()).ToArray(); return array; }
private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { #if NETCF var tmethod = method.MakeGenericMethodEx(Arguments); if (tmethod == null) throw new NotSupportedException("Cannot determine generic types from probing"); method = tmethod; #endif IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); parms.Arguments = new object[] { 1, 1, 1 }; if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; }
private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); // Special handling for params arguments if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) { IParameterInfo lastParameter = parameters[argsNeeded - 1]; Type lastParameterType = lastParameter.ParameterType; Type elementType = lastParameterType.GetElementType(); if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false)) { if (argsProvided == argsNeeded) { Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType(); if (!lastParameterType.GetTypeInfo().IsAssignableFrom(lastArgumentType.GetTypeInfo())) { Array array = Array.CreateInstance(elementType, 1); array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } else { object[] newArglist = new object[argsNeeded]; for (int i = 0; i < argsNeeded && i < argsProvided; i++) newArglist[i] = parms.Arguments[i]; int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; argsProvided = argsNeeded; } } } //Special handling for optional parameters if (parms.Arguments.Length < argsNeeded) { object[] newArgList = new object[parameters.Length]; Array.Copy(parms.Arguments, newArgList, parms.Arguments.Length); //Fill with Type.Missing for remaining required parameters where optional for (var i = parms.Arguments.Length; i < parameters.Length; i++) { if (parameters[i].IsOptional) newArgList[i] = Type.Missing; else { if (i < parms.Arguments.Length) newArgList[i] = parms.Arguments[i]; else throw new TargetParameterCountException(string.Format( "Method requires {0} arguments but TestCaseAttribute only supplied {1}", argsNeeded, argsProvided)); } } parms.Arguments = newArgList; } //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) // parms.Arguments = new object[]{parms.Arguments}; // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { if (argsProvided > 1 || argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[])) { parms.Arguments = new object[] { parms.Arguments }; } } if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; }
/// <summary> /// Construct one or more TestMethods from a given MethodInfo, /// using available parameter data. /// </summary> /// <param name="method">The MethodInfo for which tests are to be constructed.</param> /// <param name="suite">The suite to which the tests will be added.</param> /// <returns>One or more TestMethods</returns> public IEnumerable<TestMethod> BuildFrom(IMethodInfo method, Test suite) { List<TestMethod> tests = new List<TestMethod>(); #if NETCF if (method.ContainsGenericParameters) { var genericParams = method.GetGenericArguments(); var numGenericParams = genericParams.Length; var o = new object(); var tryArgs = Enumerable.Repeat(o, numGenericParams).ToArray(); IMethodInfo mi; try { // This fails if the generic method has constraints // that are not met by object. mi = method.MakeGenericMethodEx(tryArgs); if (mi == null) return tests; } catch { return tests; } var par = mi.GetParameters(); if (par.Length == 0) return tests; var sourceData = par.Select(p => _dataProvider.GetDataFor(p)).ToArray(); foreach (var parms in _strategy.GetTestCases(sourceData)) { mi = method.MakeGenericMethodEx(parms.Arguments); if (mi == null) { var tm = new TestMethod(method, suite); tm.RunState = RunState.NotRunnable; tm.Properties.Set(PropertyNames.SkipReason, "Incompatible arguments"); tests.Add(tm); } else tests.Add(_builder.BuildTestMethod(mi, suite, (TestCaseParameters)parms)); } return tests; } #endif IParameterInfo[] parameters = method.GetParameters(); if (parameters.Length > 0) { IEnumerable[] sources = new IEnumerable[parameters.Length]; try { for (int i = 0; i < parameters.Length; i++) sources[i] = _dataProvider.GetDataFor(parameters[i]); } catch (InvalidDataSourceException ex) { var parms = new TestCaseParameters(); parms.RunState = RunState.NotRunnable; parms.Properties.Set(PropertyNames.SkipReason, ex.Message); tests.Add(_builder.BuildTestMethod(method, suite, parms)); return tests; } foreach (var parms in _strategy.GetTestCases(sources)) tests.Add(_builder.BuildTestMethod(method, suite, (TestCaseParameters)parms)); } return tests; }
private TestCaseParameters GetParametersForTestCase(IMethodInfo method) { TestCaseParameters parms; try { #if NETCF var tmethod = method.MakeGenericMethodEx(Arguments); if (tmethod == null) throw new NotSupportedException("Cannot determine generic types from probing"); method = tmethod; #endif IParameterInfo[] parameters = method.GetParameters(); int argsNeeded = parameters.Length; int argsProvided = Arguments.Length; parms = new TestCaseParameters(this); // Special handling for params arguments if (argsNeeded > 0 && argsProvided >= argsNeeded - 1) { IParameterInfo lastParameter = parameters[argsNeeded - 1]; Type lastParameterType = lastParameter.ParameterType; Type elementType = lastParameterType.GetElementType(); if (lastParameterType.IsArray && lastParameter.IsDefined<ParamArrayAttribute>(false)) { if (argsProvided == argsNeeded) { Type lastArgumentType = parms.Arguments[argsProvided - 1].GetType(); if (!lastParameterType.IsAssignableFrom(lastArgumentType)) { Array array = Array.CreateInstance(elementType, 1); array.SetValue(parms.Arguments[argsProvided - 1], 0); parms.Arguments[argsProvided - 1] = array; } } else { object[] newArglist = new object[argsNeeded]; for (int i = 0; i < argsNeeded && i < argsProvided; i++) newArglist[i] = parms.Arguments[i]; int length = argsProvided - argsNeeded + 1; Array array = Array.CreateInstance(elementType, length); for (int i = 0; i < length; i++) array.SetValue(parms.Arguments[argsNeeded + i - 1], i); newArglist[argsNeeded - 1] = array; parms.Arguments = newArglist; argsProvided = argsNeeded; } } } //if (method.GetParameters().Length == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) // parms.Arguments = new object[]{parms.Arguments}; // Special handling when sole argument is an object[] if (argsNeeded == 1 && method.GetParameters()[0].ParameterType == typeof(object[])) { if (argsProvided > 1 || argsProvided == 1 && parms.Arguments[0].GetType() != typeof(object[])) { parms.Arguments = new object[] { parms.Arguments }; } } if (argsProvided == argsNeeded) PerformSpecialConversions(parms.Arguments, parameters); } catch (Exception ex) { parms = new TestCaseParameters(ex); } return parms; }
/// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { foreach (object item in source) { // First handle two easy cases: // 1. Source is null. This is really an error but if we // throw an exception we simply get an invalid fixture // without good info as to what caused it. Passing a // single null argument will cause an error to be // reported at the test level, in most cases. // 2. User provided an ITestCaseData and we just use it. ITestCaseData parms = item == null ? new TestCaseParameters(new object[] { null }) : item as ITestCaseData; if (parms == null) { // 3. An array was passed, it may be an object[] // or possibly some other kind of array, which // TestCaseSource can accept. var args = item as object[]; if (args == null && item is Array) { Array array = item as Array; #if NETCF bool netcfOpenType = method.IsGenericMethodDefinition; #else bool netcfOpenType = false; #endif int numParameters = netcfOpenType ? array.Length : method.GetParameters().Length; if (array != null && array.Rank == 1 && array.Length == numParameters) { // Array is something like int[] - convert it to // an object[] for use as the argument array. args = new object[array.Length]; for (int i = 0; i < array.Length; i++) args[i] = array.GetValue(i); } } // Check again if we have an object[] if (args != null) { #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); if (mi == null) throw new NotSupportedException("Cannot determine generic Type"); method = mi; } #endif var parameters = method.GetParameters(); var argsNeeded = parameters.Length; var argsProvided = args.Length; // If only one argument is needed, our array may actually // be the bare argument. If it is, we should wrap it in // an outer object[] representing the list of arguments. if (argsNeeded == 1) { var singleParmType = parameters[0].ParameterType; if (argsProvided == 0 || typeof(object[]).IsAssignableFrom(singleParmType)) { if (argsProvided > 1 || singleParmType.IsAssignableFrom(args.GetType())) { args = new object[] { item }; } } } } else // It may be a scalar or a multi-dimensioned array. Wrap it in object[] { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; }
/// <summary> /// FOR INTERNAL USE ONLY. /// </summary> protected static ITypeInfo[] ResolveGenericTypes(IMethodInfo method, object[] parameters) { ITypeInfo[] genericTypes = method.GetGenericArguments().ToArray(); ITypeInfo[] resolvedTypes = new ITypeInfo[genericTypes.Length]; IParameterInfo[] parameterInfos = method.GetParameters().ToArray(); for (int idx = 0; idx < genericTypes.Length; ++idx) resolvedTypes[idx] = ResolveGenericType(genericTypes[idx], parameters, parameterInfos); return resolvedTypes; }
private FuzzyMethod(FuzzyType target, IMethodInfo runtimeMethod) { _method = runtimeMethod; var genericArgs = new List<FuzzyType>(); foreach (var genericArg in _method.GetMethodGenericArguments()) genericArgs.Add(FuzzyType.FromRuntimeType(genericArg)); GenericArguments = genericArgs.AsReadOnly(); Target = target; ReturnValue = FuzzyType.FromRuntimeType(_method.ReturnType); Args = _method.GetParameters() .Select(param => FuzzyType.FromRuntimeType(param.ParameterType)) .ToArray(); // establishing links between typedef generic args and method's generic args // read more comments at FuzzyType.GetFieldOrProperty // see also comments to ReflectionHelper.GetGenericArgsMapping foreach (var pair in _method.GetGenericArgsMapping()) { var typeDefArg = SelectGenericArg(pair.Value); var publicTypePointArgs = SelectGenericArg(pair.Key); publicTypePointArgs.IsIdenticalTo(typeDefArg); } // SomeMoreStuffInferred handlers for children just escalate the event // no need to process it since everything necessary is already done by links // // upd. currently noone cares about this event from this very class, // but imo it's still important to comply to FuzzyMetadata contract Target.SomeMoreStuffInferred += (o, e) => FireSomeMoreStuffInferred(); ReturnValue.SomeMoreStuffInferred += (o, e) => FireSomeMoreStuffInferred(); Args.ForEach(arg => arg.SomeMoreStuffInferred += (o, e) => FireSomeMoreStuffInferred()); // Register typepoints for debug -> 0 downtime in release, but immensely useful in debug mode var methodBinding = target.DebuggableParents.OfType<FuzzyMethodBinding>().SingleOrDefault(); if (methodBinding != null) { this.RegDebuggableParent(methodBinding).SetDesc("alt"); ReturnValue.RegDebuggableParent(this).SetDesc("ret"); Args.ForEach((arg, i) => arg.RegDebuggableParent(this).SetDesc("arg" + i)); } }
/// <summary> /// Returns a set of ITestCaseDataItems for use as arguments /// to a parameterized test method. /// </summary> /// <param name="method">The method for which data is needed.</param> /// <returns></returns> private IEnumerable<ITestCaseData> GetTestCasesFor(IMethodInfo method) { List<ITestCaseData> data = new List<ITestCaseData>(); try { IEnumerable source = GetTestCaseSource(method); if (source != null) { #if NETCF int numParameters = method.IsGenericMethodDefinition ? 0 : method.GetParameters().Length; #else int numParameters = method.GetParameters().Length; #endif foreach (object item in source) { var parms = item as ITestCaseData; if (parms == null) { object[] args = item as object[]; if (args != null) { #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); numParameters = mi == null ? 0 : mi.GetParameters().Length; } #endif if (args.Length != numParameters)//parameters.Length) args = new object[] { item }; } else if (item is Array) { Array array = item as Array; #if NETCF if (array.Rank == 1 && (method.IsGenericMethodDefinition || array.Length == numParameters))//parameters.Length)) #else if (array.Rank == 1 && array.Length == numParameters)//parameters.Length) #endif { args = new object[array.Length]; for (int i = 0; i < array.Length; i++) args[i] = array.GetValue(i); #if NETCF if (method.IsGenericMethodDefinition) { var mi = method.MakeGenericMethodEx(args); if (mi == null || array.Length != mi.GetParameters().Length) args = new object[] {item}; } #endif } else { args = new object[] { item }; } } else { args = new object[] { item }; } parms = new TestCaseParameters(args); } if (this.Category != null) foreach (string cat in this.Category.Split(new char[] { ',' })) parms.Properties.Add(PropertyNames.Category, cat); data.Add(parms); } } } catch (Exception ex) { data.Clear(); data.Add(new TestCaseParameters(ex)); } return data; }