public MethodTokenExpression(IMethodInfo method) { this.method = method; #if !MONO declaringType = method.DeclaringType; #endif }
protected override void SetTestSemantics(PatternTest test, IMethodInfo method) { base.SetTestSemantics(test, method); test.TestInstanceActions.ExecuteTestInstanceChain.Around( delegate(PatternTestInstanceState state, Action<PatternTestInstanceState> action) { Specify.ThrownBy(delegate { action(state); }).ShouldBeNull(); bool failed = false; foreach (ISpecificationConstraint constraint in Specify.GetConstraints()) { SpecificationResult result = constraint.Evaluate(); if (!result.Success) { failed = true; using (Log.BeginSection(constraint.Description)) { Log.Failures.WriteLine(result.Message); if (result.StackTrace != null) Log.Failures.WriteLine(result.StackTrace); } } } if (failed) throw new SilentTestException(TestOutcome.Failed); }); }
void Initialize(ITestCollection testCollection, IAssemblyInfo assembly, ITypeInfo type, IMethodInfo method, IAttributeInfo factAttribute, object[] arguments) { string displayNameBase = factAttribute.GetNamedArgument<string>("DisplayName") ?? type.Name + "." + method.Name; ITypeInfo[] resolvedTypes = null; if (arguments != null && method.IsGenericMethodDefinition) { resolvedTypes = ResolveGenericTypes(method, arguments); method = method.MakeGenericMethod(resolvedTypes); } Assembly = assembly; Class = type; Method = method; Arguments = arguments; DisplayName = GetDisplayNameWithArguments(displayNameBase, arguments, resolvedTypes); SkipReason = factAttribute.GetNamedArgument<string>("Skip"); Traits = new Dictionary<string, List<string>>(StringComparer.OrdinalIgnoreCase); TestCollection = testCollection; foreach (IAttributeInfo traitAttribute in Method.GetCustomAttributes(typeof(TraitAttribute)) .Concat(Class.GetCustomAttributes(typeof(TraitAttribute)))) { var ctorArgs = traitAttribute.GetConstructorArguments().ToList(); Traits.Add((string)ctorArgs[0], (string)ctorArgs[1]); } uniqueID = new Lazy<string>(GetUniqueID, true); }
public CulturedXunitTestCase(ITestCollection testCollection, IAssemblyInfo assembly, ITypeInfo type, IMethodInfo method, IAttributeInfo factAttribute, string culture) : base(testCollection, assembly, type, method, factAttribute) { this.culture = culture; Traits.Add("Culture", culture); }
/// <inheritdoc /> protected override void DecorateContainingScope(IPatternScope containingScope, IMethodInfo methodInfo) { Type formattableType = methodInfo.Parameters[0].Resolve(true).ParameterType; var extensionPoints = (IExtensionPoints)RuntimeAccessor.ServiceLocator.ResolveByComponentId("Gallio.ExtensionPoints"); CustomTestEnvironment.SetUpThreadChain.Before(() => extensionPoints.CustomFormatters.Register(formattableType, x => (string)methodInfo.Resolve(true).Invoke(this, new[] { x }))); CustomTestEnvironment.TeardownThreadChain.After(() => extensionPoints.CustomFormatters.Unregister(formattableType)); }
public static string GetSkipReason(IMethodInfo method) { foreach (IAttributeInfo attribute in method.GetCustomAttributes(typeof(FactAttribute))) return attribute.GetPropertyValue<string>("Skip"); return null; }
/// <summary> /// Initializes a new instance of the <see cref="TestMethod"/> class. /// </summary> /// <param name="method">The method to be used as a test.</param> /// <param name="parentSuite">The suite or fixture to which the new test will be added</param> public TestMethod(IMethodInfo method, Test parentSuite) : base(method ) { // Needed to give proper fullname to test in a parameterized fixture. // Without this, the arguments to the fixture are not included. if (parentSuite != null) FullName = parentSuite.FullName + "." + Name; }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { var commands = base.EnumerateTestCommands(method); var attrs = method.MethodInfo.GetCustomAttributes(typeof(DataAttribute), false); if (commands.Count() != attrs.Count()) { throw new InvalidOperationException("Some data attribute doesn't generate test command"); } var filteredCommands = new List<ITestCommand>(); int index = 0; foreach (var command in commands) { var theoryCmd = command as TheoryCommand; var skippableData = attrs.ElementAt(index++) as ISkippable; if (skippableData != null && !string.IsNullOrEmpty(skippableData.SkipReason)) { SkipCommand cmd = new SkipCommand(method, theoryCmd.DisplayName, skippableData.SkipReason); filteredCommands.Add(cmd); } else { filteredCommands.Add(command); } } return filteredCommands; }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo testMethod) { if (Helper.Credentials == null) yield return new SkipCommand(testMethod, MethodUtility.GetDisplayName(testMethod), "Automation settings not configured. Please set the OCTOKIT_GITHUBUSERNAME and OCTOKIT_GITHUBPASSWORD environment variables to a GitHub test account (i.e, DO NOT USE A \"REAL\" ACCOUNT)."); else yield return new FactCommand(testMethod); }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { // prepare specification invocations var theoryTestCommands = base.EnumerateTestCommands(method); var commands = new List<ITestCommand>(); foreach (var item in theoryTestCommands) { if (item is TheoryCommand) { commands.AddRange(SubSpec.Core.SpecificationContext.SafelyEnumerateTestCommands(method, m => { // Create a new test class instance object obj = item.ShouldCreateInstance ? Activator.CreateInstance(method.MethodInfo.ReflectedType) : null; // create method item.Execute(obj); })); } else { commands.Clear(); commands.Add(item); break; } } return commands; }
protected MethodResult(IMethodInfo method, string displayName) : this(method.Name, method.TypeName, displayName, MethodUtility.GetTraits(method)) { }
private static IMethodInfo EnsureIsNotNull(IMethodInfo method) { if (method == null) throw new ArgumentNullException("method"); return method; }
/// <summary> /// Creates a new instance of the <see cref="TestMethodCommand"/> class. /// </summary> /// <param name="method">The <see cref="IMethodInfo"/> describing the test case method.</param> public TestMethodCommand(IMethodInfo method) : base(method) { this.Namespace = method.Class.Type.Namespace; this.Class = method.Class.Type.Name; this.Method = method.Name; }
public IEnumerable<ITestCommand> CreateTestCommands(IMethodInfo testMethod, IFixtureSet fixtureSet) { foreach (var command in MethodUtility.GetTestCommands(testMethod)) { yield return new ParadigmTestCommand(testMethod, fixtureSet.ApplyFixturesToCommand(command), GetNameFor(command), new ConstructorInvokingObjectFactory(_testClassType.Type, _parameters.Select(x => x.Value).ToArray())); } }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { if (DateTime.Today < SkipUntil) return Enumerable.Empty<ITestCommand>(); throw new InvalidOperationException("Time bombed fact expired"); //return base.EnumerateTestCommands(method); }
/// <inheritdoc /> protected override void Validate(IPatternScope containingScope, IMethodInfo method) { base.Validate(containingScope, method); if (method.Parameters.Count != 0) ThrowUsageErrorException("A fixture set-up method must not have any parameters."); }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { if (method == null) { return new[] { new ExceptionCommand(new MethodCall(method), new ArgumentNullException("method")) }; } IEnumerable<ITestCommand> backgroundCommands; IEnumerable<ICommand> scenarioCommands; // NOTE: any exception must be wrapped in a command, otherwise the test runner will retry this method infinitely try { backgroundCommands = this.EnumerateBackgroundCommands(method).ToArray(); scenarioCommands = this.EnumerateScenarioCommands(method).ToArray(); } catch (Exception ex) { return new[] { new ExceptionCommand(new MethodCall(method), ex) }; } // NOTE: this is not in the try catch since we are yielding internally // TODO: address this - see http://stackoverflow.com/a/346772/49241 return scenarioCommands.SelectMany( scenarioCommand => CurrentScenario.ExtractCommands(scenarioCommand.MethodCall, backgroundCommands.Concat(new[] { scenarioCommand }))); }
/// <summary> /// Creates all the test command for the method specified by <paramref name="method"/>. /// </summary> /// <param name="method">The method to create command for.</param> /// <returns> /// All test commands which should be executed for the particular test method. /// </returns> protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { foreach (var command in base.EnumerateTestCommands(method)) { yield return new SpecificationCommand(command, method); } }
public static string GetDisplayName(IMethodInfo method) { foreach (IAttributeInfo attribute in method.GetCustomAttributes(typeof(FactAttribute))) return attribute.GetPropertyValue<string>("Name"); return null; }
/// <summary> /// Finds the tests on a test method. /// </summary> /// <param name="testCollection">The test collection that the test method belongs to.</param> /// <param name="type">The test class that the test method belongs to.</param> /// <param name="method">The test method.</param> /// <param name="includeSourceInformation">Set to <c>true</c> to indicate that source information should be included.</param> /// <param name="messageBus">The message bus to report discovery messages to.</param> /// <returns>Return <c>true</c> to continue test discovery, <c>false</c>, otherwise.</returns> protected virtual bool FindTestsForMethod(ITestCollection testCollection, ITypeInfo type, IMethodInfo method, bool includeSourceInformation, IMessageBus messageBus) { var factAttribute = method.GetCustomAttributes(typeof(FactAttribute)).FirstOrDefault(); if (factAttribute == null) return true; var testCaseDiscovererAttribute = factAttribute.GetCustomAttributes(typeof(XunitTestCaseDiscovererAttribute)).FirstOrDefault(); if (testCaseDiscovererAttribute == null) return true; var args = testCaseDiscovererAttribute.GetConstructorArguments().Cast<string>().ToList(); var discovererType = Reflector.GetType(args[1], args[0]); if (discovererType == null) return true; var discoverer = GetDiscoverer(discovererType); if (discoverer == null) return true; foreach (var testCase in discoverer.Discover(testCollection, AssemblyInfo, type, method, factAttribute)) if (!ReportDiscoveredTestCase(testCase, includeSourceInformation, messageBus)) return false; return true; }
internal UnresolvedMethodInfo(IMethodInfo adapter) { if (adapter == null) throw new ArgumentNullException("adapter"); this.adapter = adapter; }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { var displayName = method.TypeName + "." + method.Name; if (File.Exists(@"C:\Windows\System32\InetSrv\Microsoft.Web.Administration.dll") == false) { yield return new SkipCommand(method, displayName, "Could not execute " + displayName + " because it requires IIS7 and could not find Microsoft.Web.Administration"); yield break; } var windowsIdentity = WindowsIdentity.GetCurrent(); if (windowsIdentity != null) { if (new WindowsPrincipal(windowsIdentity).IsInRole(WindowsBuiltInRole.Administrator) == false) { yield return new SkipCommand(method, displayName, "Could not execute " + displayName + " because it requires Admin privileges"); yield break; } } foreach (var command in base.EnumerateTestCommands(method)) { yield return command; } }
public IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo testMethod) { EnumerateTestCommands__Called = true; EnumerateTestCommands_TestMethod = testMethod; return EnumerateTestCommands__Result ?? testClassCommand.EnumerateTestCommands(testMethod); }
public RepositoryTheoryCommand(IMethodInfo method, RepositoryProvider provider) :base(method) { _provider = provider; DisplayName = string.Format( "{0} - DatabaseProvider: {1}", DisplayName, _provider); }
public static int GetTimeoutParameter(IMethodInfo method) { foreach (IAttributeInfo attribute in method.GetCustomAttributes(typeof(FactAttribute))) return attribute.GetPropertyValue<int>("Timeout"); return -1; }
public IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo testMethod) { var commands = command.EnumerateTestCommands(testMethod).ToList(); if (!commands.Any()) commands.Add(new FactCommand(testMethod)); return commands; }
/// <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; }
protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { foreach (ITestCommand command in EnumerateTestCommandsInternal(method)) { yield return new ObservationCommand(command); } }
/// <summary> /// Creates a new instance of <see cref="TheoryCommand"/> based on a generic theory. /// </summary> /// <param name="testMethod">The method under test</param> /// <param name="parameters">The parameters to be passed to the test method</param> /// <param name="genericTypes">The generic types that were used to resolved the generic method.</param> public TheoryCommand(IMethodInfo testMethod, object[] parameters, Type[] genericTypes) : base(testMethod, MethodUtility.GetDisplayName(testMethod), MethodUtility.GetTimeoutParameter(testMethod)) { Guard.ArgumentNotNull("testMethod", testMethod); int idx; Parameters = parameters ?? new object[0]; if (genericTypes != null && genericTypes.Length > 0) { string[] typeNames = new string[genericTypes.Length]; for (idx = 0; idx < genericTypes.Length; idx++) typeNames[idx] = ConvertToSimpleTypeName(genericTypes[idx]); DisplayName = String.Format(CultureInfo.CurrentCulture, "{0}<{1}>", DisplayName, string.Join(", ", typeNames)); } ParameterInfo[] parameterInfos = testMethod.MethodInfo.GetParameters(); string[] displayValues = new string[Math.Max(Parameters.Length, parameterInfos.Length)]; for (idx = 0; idx < Parameters.Length; idx++) displayValues[idx] = ParameterToDisplayValue(GetParameterName(parameterInfos, idx), Parameters[idx]); for (; idx < parameterInfos.Length; idx++) // Fill-in any missing parameters with "???" displayValues[idx] = parameterInfos[idx].Name + ": ???"; DisplayName = String.Format(CultureInfo.CurrentCulture, "{0}({1})", DisplayName, string.Join(", ", displayValues)); }
public FailedResult(IMethodInfo method, Exception exception, string displayName) : base(method, displayName) { ExceptionType = exception.GetType().FullName; Message = ExceptionUtility.GetMessage(exception); StackTrace = ExceptionUtility.GetStackTrace(exception); }
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { if (!method.IsGenericMethodDefinition) { return(base.BuildFrom(method, suite)); } if (TypeArguments == null || TypeArguments.Length != method.GetGenericArguments().Length) { var parms = new TestCaseParameters { RunState = RunState.NotRunnable }; parms.Properties.Set(PropertyNames.SkipReason, $"{nameof(TypeArguments)} should have {method.GetGenericArguments().Length} elements"); return(new[] { new NUnitTestCaseBuilder().BuildTestMethod(method, suite, parms) }); } var genMethod = method.MakeGenericMethod(TypeArguments); return(base.BuildFrom(genMethod, suite)); }
/// <summary> /// Creates a new method specification. /// </summary> /// <param name="resolvedType">The non-generic type or generic type instantiation /// that declares the method to be invoked or is a subtype of the declaring type. /// This parameter is used to resolve the method to its declaring type.</param> /// <param name="method">The method or generic method definition to be instantiated.</param> /// <param name="slotValues">The slot values.</param> /// <param name="converter">The converter to use for converting slot values /// to the required types.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="resolvedType"/>, /// <paramref name="method"/>, <paramref name="slotValues"/> or <paramref name="converter"/> is null.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="slotValues" /> contains /// slots that are declared by different methods or have incompatible values.</exception> public MethodInvocationSpec(Type resolvedType, IMethodInfo method, IEnumerable <KeyValuePair <ISlotInfo, object> > slotValues, IConverter converter) : base(slotValues, converter) { if (resolvedType == null) { throw new ArgumentNullException("resolvedType"); } if (method == null) { throw new ArgumentNullException("method"); } ValidateSlots(method, slotValues); this.resolvedType = resolvedType; this.method = method; ResolveMethod(); ResolveArguments(); }
/// <inheritdoc /> public override void Consume(IPatternScope containingScope, ICodeElementInfo codeElement, bool skipChildren) { //TODO: Review: Issue 762: Shouldn't the base method be invoked here? //base.Consume(containingScope, codeElement, skipChildren); IMethodInfo method = codeElement as IMethodInfo; Validate(containingScope, method); IPatternScope methodScope = containingScope.CreateChildTestScope(method.Name, method); methodScope.TestBuilder.Kind = TestKinds.Test; methodScope.TestBuilder.IsTestCase = true; methodScope.TestBuilder.Order = Order; methodScope.TestBuilder.TimeoutFunc = () => TestAssemblyExecutionParameters.DefaultTestCaseTimeout; InitializeTest(methodScope, method); SetTestSemantics(methodScope.TestBuilder, method); methodScope.TestBuilder.ApplyDeferredActions(); }
/// <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) { TestMethod test = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, GetParametersForTestCase(method)); #if PLATFORM_DETECTION if (test.RunState != RunState.NotRunnable && test.RunState != RunState.Ignored) { PlatformHelper platformHelper = new PlatformHelper(); if (!platformHelper.IsPlatformSupported(this)) { test.RunState = RunState.Skipped; test.Properties.Add(PropertyNames.SkipReason, platformHelper.Reason); } } #endif yield return(test); }
public ProxySyntaxFactory( ITypeInfo interfaceType, ITypeInfo interceptorType, string?containingAssembly, OutputType outputType, ReferenceCollector?referenceCollector) : base(outputType, containingAssembly ?? $"Proxy_{interceptorType.GetMD5HashCode()}", referenceCollector) { if (!interfaceType.IsInterface) { throw new ArgumentException(Resources.NOT_AN_INTERFACE, nameof(interfaceType)); } if (interfaceType is IGenericTypeInfo genericIface && genericIface.IsGenericDefinition) { throw new ArgumentException(Resources.GENERIC_IFACE, nameof(interfaceType)); } string baseInterceptorName = typeof(InterfaceInterceptor <>).FullName; IGenericTypeInfo?baseInterceptor = (IGenericTypeInfo?) ( interceptorType.QualifiedName == baseInterceptorName ? interceptorType : interceptorType.GetBaseTypes().Single(ic => ic.QualifiedName == baseInterceptorName, throwOnEmpty: false) ); if (baseInterceptor?.GenericArguments?.Single()?.EqualsTo(interfaceType) is not true) { throw new ArgumentException(Resources.NOT_AN_INTERCEPTOR, nameof(interceptorType)); } if (interceptorType is IGenericTypeInfo genericInterceptor && genericInterceptor.IsGenericDefinition) { throw new ArgumentException(Resources.GENERIC_INTERCEPTOR, nameof(interceptorType)); } InterfaceType = interfaceType; InterceptorType = interceptorType; Invoke = InterceptorType.Methods.Single (
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { List <TestMethod> results = new List <TestMethod>(); IGraphicsTestCaseProvider provider = Provider; try { foreach (var testCase in provider.GetTestCases()) { TestCaseData data = new TestCaseData(new object[] { testCase }); data.SetName(System.IO.Path.GetFileNameWithoutExtension(testCase.ScenePath)); data.ExpectedResult = new Object(); data.HasExpectedResult = true; TestMethod test = this._builder.BuildTestMethod(method, suite, data); if (test.parms != null) { test.parms.HasExpectedResult = false; } test.Name = System.IO.Path.GetFileNameWithoutExtension(testCase.ScenePath); results.Add(test); } } catch (Exception ex) { Console.WriteLine("Failed to generate graphics testcases!"); Debug.LogException(ex); throw; } suite.Properties.Set("ColorSpace", ColorSpace); suite.Properties.Set("RuntimePlatform", Platform); suite.Properties.Set("GraphicsDevice", GraphicsDevice); Console.WriteLine("Generated {0} graphics test cases.", results.Count); return(results); }
public CodeSnippetWriter Build(IMethodInfo method) { return(writer => { if (_useArrows) { writer.Write($"export const {method.Name} = "); } else { writer.Write($"export function {method.Name}"); } if (method.GenericTypeParams.Any()) { writer.Write("<"); writer.Write(string.Join(", ", method.GenericTypeParams)); writer.Write(">"); } writer.Write("("); writer.WriteDelimited(method.Params, (p, w) => { w.Write($"{p.Name}{(p.Type.Optional ? "?": "")}: "); w.WriteTypeRef(p.Type); }, ", "); writer.Write("): "); writer.WriteTypeRef(method.ReturnType); writer.Write(_useArrows ? " =>" : ""); writer.OpenBlock(); method.WriteBody(writer); writer.CloseBlock(_useArrows ? "};" : "}"); }); }
IEnumerable <ExpressionStatementSyntax> AssignByRefParameters(IMethodInfo method, LocalDeclarationStatementSyntax argsArray) { int i = 0; foreach (IParameterInfo param in method.Parameters) { if (ByRefs.Some(x => x == param.Kind)) { yield return(ExpressionStatement ( expression: AssignmentExpression ( kind: SyntaxKind.SimpleAssignmentExpression, left: IdentifierName(param.Name), right: CastExpression ( type: ResolveType(param.Type), expression: ElementAccessExpression(ResolveIdentifierName(argsArray)).WithArgumentList ( argumentList: BracketedArgumentList ( SingletonSeparatedList ( Argument ( LiteralExpression ( SyntaxKind.NumericLiteralExpression, Literal(i) ) ) ) ) ) ) ) )); } i++; } }
void Initialize(ITestCollection testCollection, IAssemblyInfo assembly, ITypeInfo type, IMethodInfo method, IAttributeInfo factAttribute, object[] arguments) { string displayNameBase = factAttribute.GetNamedArgument <string>("DisplayName") ?? type.Name + "." + method.Name; ITypeInfo[] resolvedTypes = null; if (arguments != null && method.IsGenericMethodDefinition) { resolvedTypes = ResolveGenericTypes(method, arguments); method = method.MakeGenericMethod(resolvedTypes); } Assembly = assembly; Class = type; Method = method; Arguments = arguments; DisplayName = GetDisplayNameWithArguments(displayNameBase, arguments, resolvedTypes); SkipReason = factAttribute.GetNamedArgument <string>("Skip"); Traits = new Dictionary <string, List <string> >(StringComparer.OrdinalIgnoreCase); TestCollection = testCollection; foreach (var traitAttribute in Method.GetCustomAttributes(typeof(ITraitAttribute)) .Concat(Class.GetCustomAttributes(typeof(ITraitAttribute)))) { var discovererAttribute = traitAttribute.GetCustomAttributes(typeof(TraitDiscovererAttribute)).First(); var args = discovererAttribute.GetConstructorArguments().Cast <string>().ToList(); var discovererType = Reflector.GetType(args[1], args[0]); if (discovererType != null) { var discoverer = ExtensibilityPointFactory.GetTraitDiscoverer(discovererType); foreach (var keyValuePair in discoverer.GetTraits(traitAttribute)) { Traits.Add(keyValuePair.Key, keyValuePair.Value); } } } uniqueID = new Lazy <string>(GetUniqueID, true); }
/// <summary> /// The .Net framework handles several built-in types in a special way. Basically, /// to inheritors, certain 'extern' private methods appear to vanish. We deal /// with those cases uniformly here. There may yet be others! /// </summary> private static bool IsSpecialNonInheritedMethod(IMethodInfo method) { if (!method.IsPrivate) { return(false); } switch (method.DeclaringType.FullName + ":" + method.Name) { case "System.Object:FieldGetter": case "System.Object:FieldSetter": case "System.Object:GetFieldInfo": case "System.ValueType:CanCompareBits": case "System.ValueType:FastEqualsCheck": case "System.Enum:InternalGetValue": case "System.Enum:GetValue": case "System.Array:InternalGetReference": case "System.Delegate:BindToMethodName": case "System.Delegate:BindToMethodInfo": case "System.Delegate:DelegateConstruct": case "System.MulticastDelegate:InvocationListEquals": case "System.MulticastDelegate:TrySetSlot": case "System.MulticastDelegate:DeleteFromInvocationList": case "System.MulticastDelegate:EqualInvocationLists": case "System.MulticastDelegate:ThrowNullThisInDelegateToInstance": case "System.MulticastDelegate:CtorClosed": case "System.MulticastDelegate:CtorClosedStatic": case "System.MulticastDelegate:CtorRTClosed": case "System.MulticastDelegate:CtorOpened": case "System.MulticastDelegate:CtorSecureClosed": case "System.MulticastDelegate:CtorSecureClosedStatic": case "System.MulticastDelegate:CtorSecureRTClosed": case "System.MulticastDelegate:CtorSecureOpened": case "System.MulticastDelegate:CtorVirtualDispatch": case "System.MulticastDelegate:CtorSecureVirtualDispatch": return(true); default: return(false); } }
/// <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; } } // 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(tests.Count > 0 ? BuildParameterizedMethodSuite(method, tests) : BuildSingleTestMethod(method, parentSuite)); }
private MetaMethod AddMethod(IMethodInfo method, IProxyGenerationHook hook, bool isStandalone) { if (checkedMethods.Contains(method.Key)) { return(null); } checkedMethods.Add(method.Key); if (methods.ContainsKey(method)) { return(null); } var methodToGenerate = GetMethodToGenerate(method, hook, isStandalone); if (methodToGenerate != null) { methods[method] = methodToGenerate; } return(methodToGenerate); }
protected MemberAccessExpressionSyntax MethodAccess(ExpressionSyntax?target, IMethodInfo method, ITypeInfo?castTargetTo = null) { SimpleNameSyntax identifier = IdentifierName(method.Name); if (method is IGenericMethodInfo genericMethod) { identifier = GenericName(identifier.Identifier).WithTypeArgumentList ( typeArgumentList: TypeArgumentList ( arguments: genericMethod.GenericArguments.ToSyntaxList(ResolveType) ) ); } return(SimpleMemberAccess ( AmendTarget(target, method, castTargetTo), identifier )); }
private TypeScriptReturnStatement CreateCall(IMethodInfo methodInfo, ITypeInfo controllerType) { var verb = ResolveBaseApiMethod(methodInfo); switch (verb) { case BaseApiMethod.Get: return GenerateMethodCallWithBody(methodInfo, "get", controllerType); case BaseApiMethod.Post: return GenerateMethodCallWithBody(methodInfo, "post", controllerType); case BaseApiMethod.Put: return GenerateMethodCallWithBody(methodInfo, "put", controllerType); case BaseApiMethod.Delete: return GenerateMethodCallWithBody(methodInfo, "delete", controllerType); case BaseApiMethod.Download: return GenerateMethodCallWithBody(methodInfo, "download", controllerType); case BaseApiMethod.Upload: return GenerateMethodCallWithBody(methodInfo, "upload", controllerType); default: throw new ArgumentOutOfRangeException(); } }
IEnumerable <TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) { if (!method.IsGenericMethodDefinition) { return(base.BuildFrom(method, suite)); } var numberOfGenericArguments = method.GetGenericArguments().Length; var typeArguments = Arguments.Take(numberOfGenericArguments).OfType <Type>().ToArray(); if (typeArguments.Length != numberOfGenericArguments) { var parms = new TestCaseParameters { RunState = RunState.NotRunnable }; parms.Properties.Set("_SKIPREASON", $"Arguments should have {typeArguments} type elements"); return(new[] { new NUnitTestCaseBuilder().BuildTestMethod(method, suite, parms) }); } var genMethod = method.MakeGenericMethod(typeArguments); return(new TestCaseAttribute(Arguments.Skip(numberOfGenericArguments).ToArray()).BuildFrom(genMethod, suite)); }
protected override IEnumerable <ITestCommand> EnumerateTestCommands(IMethodInfo method) { var result = (List <ITestCommand>)base.EnumerateTestCommands(method); try { return(TransferToSupportOptional(result, method)); } catch (Exception ex) { result.Clear(); result.Add(new LambdaTestCommand(method, () => { throw new InvalidOperationException( String.Format("An exception was thrown while getting data for theory {0}.{1}:\r\n{2}", method.TypeName, method.Name, ex) ); })); } return(result); }
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 IEnumerable <TestMethod> BuildFrom(IMethodInfo method, Test suite) { InheritAttributes(method); var arguments = new List <object>(); foreach (var parameter in method.MethodInfo.GetParameters()) { var argument = Resolver.GetService(method, parameter.ParameterType); if (argument != null) { arguments.Add(argument); } } var testMethod = new NUnitTestCaseBuilder().BuildTestMethod(method, suite, new TestCaseParameters(arguments.ToArray())); CheckApplyExecuteInSetup(testMethod); yield return(testMethod); }
public ProxyMemberSyntaxFactory(IProxyContext context) : base(context.InterfaceType) { Context = context; TARGET = Context.InterceptorType.Properties.Single ( prop => prop.Name == nameof(InterfaceInterceptor <object> .Target) ); INVOKE_TARGET = Context.InterceptorType.Properties.Single ( prop => prop.Name == nameof(InterfaceInterceptor <object> .InvokeTarget) ); INVOKE = Context.InterceptorType.Methods.Single ( met => met.SignatureEquals ( MetadataMethodInfo.CreateFrom ( (MethodInfo)MemberInfoExtensions.ExtractFrom <InterfaceInterceptor <object> >(ic => ic.Invoke(default !, default !, default !))
public StressTestCaseBase( string testApplicationName, ServerType serverType, IMethodInfo warmupMethod, IMessageSink diagnosticMessageSink, ITestMethod testMethod) : base(diagnosticMessageSink, TestMethodDisplay.Method, testMethod) { // Override display name to avoid getting info about TestMethodArguments in the name; Fact has no arguments. var name = TestMethod.Method.GetCustomAttributes(typeof(FactAttribute)) .First() .GetNamedArgument <string>("DisplayName") ?? BaseDisplayName; TestApplicationName = testApplicationName; TestMethodName = name; WarmupMethod = warmupMethod; DisplayName = name; DiagnosticMessageSink = diagnosticMessageSink; ServerType = serverType; }
/// <inheritdoc /> protected override void Validate(IPatternScope containingScope, IMethodInfo method) { base.Validate(containingScope, method); if (!method.IsStatic) { ThrowUsageErrorException("A static test factory method must be static."); } if (method.Parameters.Count != 0) { ThrowUsageErrorException("A static test factory method must not have any parameters."); } if (method.ContainsGenericParameters) { ThrowUsageErrorException("A static test factory method must not be generic."); } if (method.DeclaringType.ContainsGenericParameters) { ThrowUsageErrorException("A static test factory method must not be declared on a generic type."); } }
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 }); }
/// <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); }
private IEnumerable<TypeScriptClassMemberDefinition> BuildApiImplMember(IMethodInfo methodInfo, Func<ITypeInfo, TypeScriptType> buildAndImportType, ITypeInfo controllerType) { var functionDefinition = new TypeScriptFunctionDefinition { IsAsync = true, Result = GetMethodResult(methodInfo, buildAndImportType), Body = {WrapCall(methodInfo, CreateCall(methodInfo, controllerType))} }; functionDefinition.Arguments.AddRange( methodInfo.GetParameters().Where(x => PassParameterToCall(x, controllerType)).Select(x => new TypeScriptArgumentDeclaration { Name = x.Name, Type = buildAndImportType(x.ParameterType) }) ); yield return new TypeScriptClassMemberDefinition { Name = methodInfo.Name.ToLowerCamelCase(), Definition = functionDefinition }; }
public IEnumerable <ITestCommand> EnumerateTestCommands(IMethodInfo testMethod) { foreach (var attr in testMethod.GetCustomAttributes(typeof(FactAttribute))) { if (!String.IsNullOrEmpty(attr.GetPropertyValue <String>("Skip"))) { yield break; } } foreach (var testCommand in _cmd.EnumerateTestCommands(testMethod)) { if (testCommand is MediumTrustTestCommand) { yield return(testCommand); continue; } yield return(new MediumTrustTestCommand(testCommand, null)); } }
private static bool CompareSignatures(IMethodInfo a, IMethodInfo b) { IList <IParameterInfo> aParameters = a.Parameters; IList <IParameterInfo> bParameters = b.Parameters; int parameterCount = aParameters.Count; if (parameterCount != bParameters.Count) { return(false); } for (int i = 0; i < parameterCount; i++) { if (!aParameters[i].ValueType.Equals(bParameters[i].ValueType)) { return(false); } } return(true); }
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); }
public StressTestCase( string testApplicationName, long iterations, int clients, string variation, ServerType serverType, IMethodInfo warmupMethod, IMessageSink diagnosticMessageSink, ITestMethod testMethod, object[] testMethodArguments) : base( testApplicationName, variation, serverType, warmupMethod, diagnosticMessageSink, testMethod, testMethodArguments) { Clients = clients; Iterations = iterations; }
private static void BuildRowTest(Test parent, IMethodInfo method, string namePrefix, string nameSuffix, RowTestAttribute2 attrib) { foreach (RowAttribute2 rowAttrib in AttributeUtils.GetAttributes <RowAttribute2>(method, true)) { // Note: The way the name is formatted must be identical to that which MbUnit v2 natively produces. object[] row = rowAttrib.GetRow(); StringWriter rowName = new StringWriter(CultureInfo.InvariantCulture); rowName.Write('('); for (int i = 0; i < row.Length; i++) { if (i != 0) { rowName.Write(','); } rowName.Write(row[i]); } rowName.Write(')'); AddChildTest(parent, method, namePrefix, rowName + nameSuffix); } }
static void SetName(TestMethod test, IMethodInfo method, string provider, bool isLinqService, int caseNumber, string baseName) { var name = (baseName ?? method.Name) + "." + provider; if (isLinqService) { name += ".LinqService"; } // numerate cases starting from second case to preserve naming for most of tests if (caseNumber > 0) { if (baseName == null) { name += "." + caseNumber; } test.FullName += "." + caseNumber; } test.Name = method.TypeInfo.FullName.Replace("Tests.", "") + "." + name; }