public IEnumerable GetData(IParameterInfo parameter) { return(DeviceFixture.GetDevices() .OfType <PcapDevice>() .Select(d => new DeviceFixture(d)) .ToArray()); }
public override Task <AutocompletionResult> GenerateSuggestionsAsync( IInteractionContext context, IAutocompleteInteraction autocompleteInteraction, IParameterInfo parameter, IServiceProvider services ) { var input = autocompleteInteraction.Data.Current.Value as string; var matches = _cmdHelpService.GetCmdsStartsWithInput(context.User, input) .Select(cmd => { if (cmd is CommandInfo regCmdInfo) { return(regCmdInfo.Name); } else { return((cmd as IApplicationCommandInfo)?.Name); } }) .Distinct() .PartialSort(25); var results = AutocompletionResult.FromSuccess(matches.Select(cmdName => new AutocompleteResult(cmdName, cmdName))); return(Task.FromResult(results)); }
public void TestInitialize( ) { _fixture = new Fixture( ); _sutCreator = new SutCreator(new SutInstanceCreator(new ArgumentNullExceptionFinder( )), new SutLazyInstanceCreator(new ArgumentNullExceptionFinder( ), new CustomAttributeFinder( ))); _freezeAttribute = Substitute.For <ICustomAttributeData> ( ); _freezeAttribute.AttributeType.Returns(typeof(FreezeAttribute)); _customAttributesWithFreeze = new [] { _freezeAttribute }; _infoInt = CreateParameterInfo(typeof(int)); _infoLazyString = CreateParameterInfo(typeof(Lazy <string>)); _infoString = CreateParameterInfo(typeof(string)); _infoClass = CreateParameterInfo(typeof(SomethingElse)); _infoSut = CreateParameterInfo(typeof(Something)); _infoLazyClass = CreateParameterInfo(typeof(Lazy <Something>)); _infoSomething = CreateParameterInfo(typeof(ISomething)); _infoSomethingElseWithFreeze = CreateParameterInfo(typeof(ISomethingElse)); _infoSomethingElseWithFreeze.CustomAttributes.Returns(_customAttributesWithFreeze); _infoStringFreeze = CreateParameterInfo(typeof(string)); _infoStringFreeze.CustomAttributes.Returns(_customAttributesWithFreeze); }
public IArgumentSpecification Create(object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { // Next specificaion is for the whole params array. if (suppliedArgumentSpecifications.IsNextFor(argument, parameterInfo.ParameterType)) { return(suppliedArgumentSpecifications.Dequeue()); } // Check whether the specification ambiguity could happen. bool isAmbiguousSpecificationPresent = suppliedArgumentSpecifications.AnyFor(argument, parameterInfo.ParameterType); if (isAmbiguousSpecificationPresent) { throw new AmbiguousArgumentsException(suppliedArgumentSpecifications.AllSpecifications); } // User passed "null" as the params array value. if (argument == null) { return(_argumentEqualsSpecificationFactory.Create(null, parameterInfo.ParameterType)); } // User specified arguments using the native params syntax. var paramterInfosFromParamsArray = _parameterInfosFromParamsArrayFactory.Create(argument, parameterInfo.ParameterType); var arrayArgumentSpecifications = _arrayArgumentSpecificationsFactory.Create(argument, paramterInfosFromParamsArray, suppliedArgumentSpecifications); return(_arrayContentsArgumentSpecificationFactory.Create(arrayArgumentSpecifications, parameterInfo.ParameterType)); }
public bool HasDataFor(IParameterInfo parameter) { var method = parameter.Method; if (!method.IsDefined <TheoryAttribute>(true)) { return(false); } Type parameterType = parameter.ParameterType; if (parameterType == typeof(bool) || parameterType.GetTypeInfo().IsEnum) { return(true); } Type containingType = method.TypeInfo.Type; foreach (MemberInfo member in containingType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) { if (member.IsDefined(typeof(DatapointAttribute), true) && GetTypeFromMemberInfo(member) == parameterType) { return(true); } else if (member.IsDefined(typeof(DatapointSourceAttribute), true) && GetElementTypeFromMemberInfo(member) == parameterType) { return(true); } } return(false); }
public IEnumerable GetData(IParameterInfo parameter) { for (var i = 0; i < _count; i++) { yield return(GenerateRandomString()); } }
public IEnumerable GetData(IParameterInfo parameter) { for (var i = 0; i < Count; i++) { yield return(i.ToString()); } }
private IArgumentSpecification CreateSpecFromParamsArg(object?argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { // Next specification is for the whole params array. if (suppliedArgumentSpecifications.IsNextFor(argument, parameterInfo.ParameterType)) { return(suppliedArgumentSpecifications.Dequeue()); } // Check whether the specification ambiguity could happen. bool isAmbiguousSpecificationPresent = suppliedArgumentSpecifications.AnyFor(argument, parameterInfo.ParameterType); if (isAmbiguousSpecificationPresent) { throw new AmbiguousArgumentsException(); } // User passed "null" as the params array value. if (argument == null) { return(new ArgumentSpecification(parameterInfo.ParameterType, new EqualsArgumentMatcher(null))); } // User specified arguments using the native params syntax. var arrayArg = argument as Array; if (arrayArg == null) { throw new SubstituteInternalException($"Expected to get array argument, but got argument of '{argument.GetType().FullName}' type."); } var arrayArgumentSpecifications = UnwrapParamsArguments(arrayArg.Cast <object?>(), parameterInfo.ParameterType.GetElementType() !, suppliedArgumentSpecifications); return(new ArgumentSpecification(parameterInfo.ParameterType, new ArrayContentsArgumentMatcher(arrayArgumentSpecifications))); }
public IEnumerable GetData(IParameterInfo parameter) { var skipAttrs = new HashSet <string>( from a in parameter.Method.GetCustomAttributes <SkipCategoryAttribute>(true) where a.ProviderName != null && TestBase.SkipCategories.Contains(a.Category) select a.ProviderName); var methodName = parameter.Method.Name; var typeMethodName = $"{parameter.Method.MethodInfo.DeclaringType.Name}.{methodName}"; var fullMethodName = $"{parameter.Method.MethodInfo.DeclaringType.FullName}.{methodName}"; var skipTests = TestBase.SkipTests; var providers = skipAttrs.Count == 0 ? GetProviders() : GetProviders().Where(a => !skipAttrs.Contains(a)); providers = providers.Where(_ => !skipTests[_].Contains(methodName) && !skipTests[_].Contains(typeMethodName) && !skipTests[_].Contains(fullMethodName)); if (NoLinqService || !IncludeLinqService) { return(providers); } return(providers.Concat(providers.Select(p => p + ".LinqService"))); }
public bool HasDataFor(IParameterInfo parameter) { var method = parameter.Method; if (!method.IsDefined <TheoryAttribute>(true)) { return(false); } Type parameterType = parameter.ParameterType; if (parameterType == typeof(bool) || parameterType.GetTypeInfo().IsEnum) { return(true); } Type containingType = method.TypeInfo.Type; foreach (MemberInfo member in GetMembersFromType(containingType)) { if (member.IsDefined(typeof(DatapointAttribute), true) && GetTypeFromMemberInfo(member) == parameterType) { return(true); } else if (member.IsDefined(typeof(DatapointSourceAttribute), true) && GetElementTypeFromMemberInfo(member) == parameterType) { return(true); } } return(false); }
private IDbDataParameter CreateParameter(IParameterInfo parameterInfo) { var parameter = _command.CreateParameter(); parameter.ParameterName = parameterInfo.ParameterName; parameter.DbType = parameterInfo.DbType; if (parameterInfo.Size.HasValue) { parameter.Size = parameterInfo.Size.Value; } if (parameterInfo.Precision.HasValue) { parameter.Precision = (byte)parameterInfo.Precision.Value; } if (parameterInfo.Scale.HasValue) { parameter.Scale = (byte)parameterInfo.Scale.Value; } _command.Parameters.Add(parameter); return(parameter); }
public override void Context() { base.Context(); _parameterInfo = mock <IParameterInfo>(); _argumentEqualsSpecificationFactory = mock <IArgumentEqualsSpecificationFactory>(); _suppliedArgumentSpecifications = mock <ISuppliedArgumentSpecifications>(); }
public IEnumerable GetData(IParameterInfo parameter) { return(DeviceFixture.GetDevices() .Cast <LibPcapLiveDevice>() .Select(d => new DeviceFixture(d)) .ToArray()); }
/// <summary> /// Retrieves a list of arguments which can be passed to the specified parameter. /// </summary> /// <param name="parameter">The parameter of a parameterized test.</param> public IEnumerable GetData(IParameterInfo parameter) { var from = ParamAttributeTypeConversions.Convert(_from, parameter.ParameterType); var to = ParamAttributeTypeConversions.Convert(_to, parameter.ParameterType); var valueGenerator = ValueGenerator.Create(parameter.ParameterType); if (!valueGenerator.TryCreateStep(_step, out var step)) { // ValueGenerator.CreateStep has the responsibility to enable Byte values to be incremented // by the Int32 value -1. Or perhaps in the future, DateTime values to be incremented by a TimeSpan. // It handles scenarios where the incrementing type is fundamentally different in its most natural form. // However, ParamAttributeTypeConversions has the responsibility to convert attribute arguments // that are only of a different type due to IL limitations or NUnit smoothing over overload differences. // See the XML docs for the ParamAttributeTypeConversions class. if (!ParamAttributeTypeConversions.TryConvert(_step, parameter.ParameterType, out var stepValueToRequire)) { // This will cause CreateStep to throw the same exception as it would throw if TryConvert // succeeded but the value generator still didn’t recognize the step value. stepValueToRequire = _step; } step = valueGenerator.CreateStep(stepValueToRequire); } return(valueGenerator.GenerateRange(from, to, step)); }
public override IEnumerable GetData(IParameterInfo parameter) { Guard.ArgumentValid(parameter.ParameterType.GetTypeInfo().IsEnum, "EnumDataSource requires an enum parameter", "parameter"); Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); DataType = parameter.ParameterType; int valueCount = Enum.GetValues(DataType).Cast <int>().Distinct().Count(); Guard.OperationValid(!(Distinct && _count > valueCount), $"The enum \"{DataType.Name}\" has {valueCount} values and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { object next; do { next = randomizer.NextEnum(parameter.ParameterType); } while (previousValues.Contains(next)); previousValues.Add(next); yield return(next); } else { yield return(randomizer.NextEnum(parameter.ParameterType)); } } }
public override IEnumerable GetData(IParameterInfo parameter) { //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter"); var randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); Guard.OperationValid(CanUseRange() || !_inRange, $"The value type {parameter.ParameterType} does not support range of values."); Guard.OperationValid(!(Distinct && _inRange && !CanBeDistinct(_min !, _max !, _count)), $"The range of values is [{_min}, {_max}[ and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { T next; do { next = _inRange ? GetNext(randomizer, _min !, _max !) : GetNext(randomizer); } while (previousValues.Contains(next)); previousValues.Add(next); yield return(next); } else { yield return(_inRange ? GetNext(randomizer, _min !, _max !) : GetNext(randomizer)); } } }
public IArgumentSpecification Create(object?argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { return(parameterInfo.IsParams ? CreateSpecFromParamsArg(argument, parameterInfo, suppliedArgumentSpecifications) : CreateSpecFromNonParamsArg(argument, parameterInfo, suppliedArgumentSpecifications)); }
public IEnumerable GetData(IParameterInfo parameter) { foreach (var item in _configuration) { yield return(item.Value <string>(_parameter)); } }
private object Resolve(IParameterInfo parameterInfo) { CustomizeFixtureByParameter(parameterInfo); return new SpecimenContext(this._fixture) .Resolve(parameterInfo.ParameterInfo); }
private static void ValidateSlots(IMethodInfo method, IEnumerable <KeyValuePair <ISlotInfo, object> > slotValues) { foreach (KeyValuePair <ISlotInfo, object> slotValue in slotValues) { ISlotInfo slot = slotValue.Key; switch (slot.Kind) { case CodeElementKind.GenericParameter: IGenericParameterInfo genericParameter = (IGenericParameterInfo)slot; if (method.Equals(genericParameter.DeclaringMethod)) { continue; } break; case CodeElementKind.Parameter: IParameterInfo parameter = (IParameterInfo)slot; if (method.Equals(parameter.Member)) { continue; } break; } throw new ArgumentException(String.Format("Slot '{0}' is not valid for invoking method '{1}'.", slot, method), "slotValues"); } }
public IEnumerable GetData(IParameterInfo parameter) { if (!IncludeLinqService) return GetProviders(); var providers = GetProviders().ToArray(); return providers.Concat(providers.Select(p => p + ".LinqService")); }
public IArgumentSpecification Create(object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { if (_defaultChecker.IsDefault(argument, parameterInfo.ParameterType)) { if (suppliedArgumentSpecifications.IsNextFor(argument, parameterInfo.ParameterType)) { var argumentSpecification = suppliedArgumentSpecifications.Dequeue(); if (suppliedArgumentSpecifications.DequeueRemaining().Count() == 0) { return(argumentSpecification); } } else if (!suppliedArgumentSpecifications.AnyFor(argument, parameterInfo.ParameterType)) { if (suppliedArgumentSpecifications.DequeueRemaining().Count() == 0) { return(_argumentEqualsSpecificationFactory.Create(argument, parameterInfo.ParameterType)); } } } else { var paramterInfosFromParamsArray = _parameterInfosFromParamsArrayFactory.Create(argument, parameterInfo.ParameterType); var suppliedArgumentSpecificationsFromParamsArray = _suppliedArgumentSpecificationsFactory.Create(suppliedArgumentSpecifications.DequeueRemaining()); var arrayArgumentSpecifications = _arrayArgumentSpecificationsFactory.Create(argument, paramterInfosFromParamsArray, suppliedArgumentSpecificationsFromParamsArray); return(_arrayContentsArgumentSpecificationFactory.Create(arrayArgumentSpecifications, parameterInfo.ParameterType)); } throw new AmbiguousArgumentsException(); }
public static ITypeInfo ResolveGenericType(ITypeInfo genericType, object[] parameters, IParameterInfo[] parameterInfos) { bool sawNullValue = false; ITypeInfo matchedType = null; for (int idx = 0; idx < parameterInfos.Length; ++idx) { var parameterType = parameterInfos[idx].ParameterType; if (parameterType.IsGenericParameter && parameterType.Name == genericType.Name) { object parameterValue = parameters[idx]; if (parameterValue == null) sawNullValue = true; else if (matchedType == null) matchedType = Reflector.Wrap(parameterValue.GetType()); else if (matchedType.Name != parameterValue.GetType().FullName) return ObjectTypeInfo; } } if (matchedType == null) return ObjectTypeInfo; return sawNullValue && matchedType.IsValueType ? ObjectTypeInfo : matchedType; }
bool TryGetValue_NameValueCollection(int p1, IParameterInfo p2, object p3, out object value) { var p10 = (System.Collections.Specialized.NameValueCollection)p3; if (p2.Type.IsArray || (p2.Type != typeof(string) && TypeExtensions.IsInheritFrom(p2.Type, typeof(System.Collections.IEnumerable)))) { string[] values = p10.GetValues(p2.Name); if (values != null && values.Length > 0) { value = values; return(true); } } else { string values = p10[p2.Name]; if (!string.IsNullOrEmpty(values)) { value = values; return(true); } } return(TryGetValue_As(p1, p2, p3, out value)); }
public override void Write(ApplicationCommandOptionProperties properties, IParameterInfo parameter) { if (_channelTypes is not null) { properties.ChannelTypes = _channelTypes; } }
private IEnumerable GetDataSource(IParameterInfo parameter, Test suite) { var fixtureDataObject = LocateArgumentByElementType(suite.Arguments, SourceType); if (fixtureDataObject == null) { throw new InvalidDataSourceException( $"The {nameof(SourceType)} specified on a " + $"{nameof(FixtureValueSourceAttribute)} must refer to an argument of that " + "type that exists in the argument list of the containing Test Fixture."); } var argumentType = fixtureDataObject.GetType(); MemberInfo[] members = argumentType.GetMember(SourceName, ALL_BINDINGS); var dataSource = GetDataSourceValue(parameter, members, fixtureDataObject); if (dataSource == null) { throw new InvalidDataSourceException( $"Could not retrieve a value from {argumentType}.{SourceName}. " + $"{SourceName} is inaccessible via reflection or does not exist."); } return(dataSource); }
static string GetParameterName(IParameterInfo[] parameters, int index) { if (index >= parameters.Length) return "???"; return parameters[index].Name; }
public IArgumentSpecification Create(object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { if (_defaultChecker.IsDefault(argument, parameterInfo.ParameterType)) { if (suppliedArgumentSpecifications.IsNextFor(argument, parameterInfo.ParameterType)) { var argumentSpecification = suppliedArgumentSpecifications.Dequeue(); if (suppliedArgumentSpecifications.DequeueRemaining().Count() == 0) { return argumentSpecification; } } else if (!suppliedArgumentSpecifications.AnyFor(argument, parameterInfo.ParameterType)) { if (suppliedArgumentSpecifications.DequeueRemaining().Count() == 0) { return _argumentEqualsSpecificationFactory.Create(argument, parameterInfo.ParameterType); } } } else { var paramterInfosFromParamsArray = _parameterInfosFromParamsArrayFactory.Create(argument, parameterInfo.ParameterType); var suppliedArgumentSpecificationsFromParamsArray = _suppliedArgumentSpecificationsFactory.Create(suppliedArgumentSpecifications.DequeueRemaining()); var arrayArgumentSpecifications = _arrayArgumentSpecificationsFactory.Create(argument, paramterInfosFromParamsArray, suppliedArgumentSpecificationsFromParamsArray); return _arrayContentsArgumentSpecificationFactory.Create(arrayArgumentSpecifications, parameterInfo.ParameterType); } throw new AmbiguousArgumentsException(); }
private object Resolve(IParameterInfo parameterInfo) { CustomizeFixtureByParameter(parameterInfo); return(new SpecimenContext(this._fixture) .Resolve(parameterInfo.ParameterInfo)); }
internal UnresolvedParameterInfo(IParameterInfo adapter) { if (adapter == null) throw new ArgumentNullException("adapter"); this.adapter = adapter; }
public void ParameterWrapper(int position) { MethodInfo method = typeof(ReflectionPolicySample.Interface1).GetMethod("Method1"); ParameterInfo target = position == -1 ? method.ReturnParameter : method.GetParameters()[position]; IParameterInfo info = GetMethodParameter(target); WrapperAssert.AreEquivalent(target, info, false); }
/// <summary> /// Determine whether any data is available for a parameter. /// </summary> /// <param name="parameter">An IParameterInfo representing one /// argument to a parameterized test</param> /// <returns>True if any data is available, otherwise false.</returns> public bool HasDataFor(IParameterInfo parameter) { foreach (var provider in _providers) if (provider.HasDataFor(parameter)) return true; return false; }
public Call(MethodInfo methodInfo, object[] arguments, object target, IParameterInfo[] parameterInfos) { _methodInfo = methodInfo; _arguments = arguments; _target = target; _parameterInfos = parameterInfos ?? GetParameterInfosFrom(_methodInfo); _argumentSpecifications = SubstitutionContext.Current.DequeueAllArgumentSpecifications(); }
public IEnumerable<IArgumentSpecification> Create(IList<IArgumentSpecification> argumentSpecs, object[] arguments, IParameterInfo[] parameterInfos, MatchArgs matchArgs) { var argumentSpecifications = _mixedArgumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos); return (matchArgs == MatchArgs.Any) ? argumentSpecifications.Select(x => x.CreateCopyMatchingAnyArgOfType(x.ForType)) : argumentSpecifications; }
public override DbParameter BuildParameter(IParameterInfo c) { object value = c.Value; OleDbParameter p = new OleDbParameter(string.Format("@{0}{1}", c.ColumnName, c.Number), value ?? DBNull.Value); SetOleDbTypeForDateTime(value, p); return(p); }
public IEnumerable<IArgumentSpecification> Create(IList<IArgumentSpecification> argumentSpecs, object[] arguments, IParameterInfo[] parameterInfos, MatchArgs matchArgs) { if (matchArgs == MatchArgs.Any) return parameterInfos.Select(x => (IArgumentSpecification) new ArgumentIsAnythingSpecification(x.ParameterType)); if (argumentSpecs.Count == arguments.Length) return argumentSpecs; return MixedArgumentSpecificationsFactory.Create(argumentSpecs, arguments, parameterInfos); }
protected override bool PassParameterToCall(IParameterInfo parameterInfo, ITypeInfo controllerType) { if (IsUserScopedApi(controllerType) && parameterInfo.Name == "userId") { return(false); } return(true); }
internal UnresolvedParameterInfo(IParameterInfo adapter) { if (adapter == null) { throw new ArgumentNullException("adapter"); } this.adapter = adapter; }
public object CreateOtherArgument(IParameterInfo info) { Guard.ArgumentNotNull(info, nameof(info)); return(CreateArgument(info.ParameterType, IsPopulateProperties(info), // toto test IsFreezeParameter(info), IsBeNullParameter(info))); }
public Call(MethodInfo methodInfo, object[] arguments, object target, IParameterInfo[] parameterInfos, Func<object> originalMethodCall) { _methodInfo = methodInfo; _arguments = arguments; _target = target; _originalMethodCall = originalMethodCall; _parameterInfos = parameterInfos ?? GetParameterInfosFrom(_methodInfo); _argumentSpecifications = (_parameterInfos.Length == 0) ? EmptyList() : SubstitutionContext.Current.DequeueAllArgumentSpecifications(); }
public IEnumerable<IArgumentSpecification> Create(IList<IArgumentSpecification> argumentSpecs, object[] arguments, IParameterInfo[] parameterInfos) { var suppliedArgumentSpecifications = _suppliedArgumentSpecificationsFactory.Create(argumentSpecs); return new List<IArgumentSpecification>( arguments.Select( (argument, i) => _argumentSpecificationFactory.Create( argument, parameterInfos[i], suppliedArgumentSpecifications) ) ); }
public IArgumentSpecification Create(object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { if (parameterInfo.IsParams) { return _paramsArgumentSpecificationFactory.Create(argument, parameterInfo, suppliedArgumentSpecifications); } else { return _nonParamsArgumentSpecificationFactory.Create(argument, parameterInfo, suppliedArgumentSpecifications); } }
public IArgumentSpecification Create(object argument, IParameterInfo parameterInfo, ISuppliedArgumentSpecifications suppliedArgumentSpecifications) { if (suppliedArgumentSpecifications.IsNextFor(argument, parameterInfo.ParameterType)) { return suppliedArgumentSpecifications.Dequeue(); } if (!suppliedArgumentSpecifications.AnyFor(argument, parameterInfo.ParameterType) || parameterInfo.IsOptional || parameterInfo.IsOut) { return _argumentEqualsSpecificationFactory.Create(argument, parameterInfo.ParameterType); } throw new AmbiguousArgumentsException(); }
public ParameterView(IModuleContext context, IParameterInfo parameter) { _context = context; _parameter = parameter; _types = new Lazy<IEnumerable<IAnalysisItemView>>(CalculateTypes); Name = _parameter.Name; if (_parameter.IsParamArray) { Name = "*" + Name; } else if (_parameter.IsKeywordDict) { Name = "**" + Name; } }
/// <summary> /// Return an IEnumerable providing data for use with the /// supplied parameter. /// </summary> /// <param name="parameter">An IParameterInfo representing one /// argument to a parameterized test</param> /// <returns> /// An IEnumerable providing the required data /// </returns> public IEnumerable GetDataFor(IParameterInfo parameter) { var data = new List<object>(); foreach (IParameterDataSource source in parameter.GetCustomAttributes<IParameterDataSource>(false)) { foreach (object item in source.GetData(parameter)) data.Add(item); } return data; }
public IEnumerable GetData(IParameterInfo parameter) { // use randomizer instead of random so that the consistant seed is used Randomizer rand = Randomizer.GetRandomizer(parameter.ParameterInfo); for (int i = 0; i < count; i++) { double x = rand.NextDouble(minComp, maxComp); double y = rand.NextDouble(minComp, maxComp); double z = rand.NextDouble(minComp, maxComp); yield return new Vector3(x, y, z); } }
/// <summary> /// Determine whether any data is available for a parameter. /// </summary> /// <param name="parameter">A ParameterInfo representing one /// argument to a parameterized test</param> /// <returns> /// True if any data is available, otherwise false. /// </returns> public bool HasDataFor(IParameterInfo parameter) { var method = parameter.Method; if (!method.IsDefined<TheoryAttribute>(true)) return false; Type parameterType = parameter.ParameterType; if (parameterType == typeof(bool) || parameterType.GetTypeInfo().IsEnum) return true; Type containingType = method.TypeInfo.Type; foreach (MemberInfo member in containingType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) { if (member.IsDefined(typeof(DatapointAttribute), true) && GetTypeFromMemberInfo(member) == parameterType) return true; else if (member.IsDefined(typeof(DatapointSourceAttribute), true) && GetElementTypeFromMemberInfo(member) == parameterType) return true; } return false; }
/// <summary> /// Creates a <see cref="ParameterInfo" /> wrapper for <see cref="IParameterInfo" />. /// </summary> /// <param name="adapter">The adapter.</param> /// <returns>The unresolved parameter.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="adapter"/> is null.</exception> public abstract ParameterInfo Wrap(IParameterInfo adapter);
/// <summary> /// Return an IEnumerable providing data for use with the /// supplied parameter. /// </summary> /// <param name="parameter">A ParameterInfo representing one /// argument to a parameterized test</param> /// <returns> /// An IEnumerable providing the required data /// </returns> public System.Collections.IEnumerable GetDataFor(IParameterInfo parameter) { var datapoints = new List<object>(); Type parameterType = parameter.ParameterType; Type fixtureType = parameter.Method.TypeInfo.Type; foreach (MemberInfo member in fixtureType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy)) { if (member.IsDefined(typeof(DatapointAttribute), true)) { var field = member as FieldInfo; if (GetTypeFromMemberInfo(member) == parameterType && field != null) { if (field.IsStatic) datapoints.Add(field.GetValue(null)); else datapoints.Add(field.GetValue(ProviderCache.GetInstanceOf(fixtureType))); } } else if (member.IsDefined(typeof(DatapointSourceAttribute), true)) { if (GetElementTypeFromMemberInfo(member) == parameterType) { object instance; FieldInfo field = member as FieldInfo; PropertyInfo property = member as PropertyInfo; MethodInfo method = member as MethodInfo; if (field != null) { instance = field.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)field.GetValue(instance)) datapoints.Add(data); } else if (property != null) { MethodInfo getMethod = property.GetGetMethod(true); instance = getMethod.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)property.GetValue(instance, null)) datapoints.Add(data); } else if (method != null) { instance = method.IsStatic ? null : ProviderCache.GetInstanceOf(fixtureType); foreach (object data in (IEnumerable)method.Invoke(instance, new Type[0])) datapoints.Add(data); } } } } if (datapoints.Count == 0) { var underlyingParameterType = Nullable.GetUnderlyingType(parameterType); if (underlyingParameterType != null) { parameterType = underlyingParameterType; } if (parameterType == typeof(bool)) { datapoints.Add(true); datapoints.Add(false); } else if (parameterType.GetTypeInfo().IsEnum) { foreach (object o in TypeHelper.GetEnumValues(parameterType)) { datapoints.Add(o); } } if (datapoints.Count > 0 && underlyingParameterType != null) { datapoints.Add(null); } } return datapoints; }
private void CustomizeFixtureByParameter(IParameterInfo parameter) { var customizeAttributes = parameter.GetCustomAttributes<CustomizeAttribute>(false); foreach (var ca in customizeAttributes) { var customization = ca.GetCustomization(parameter.ParameterInfo); this._fixture.Customize(customization); } }
// Returns False if no more parameters can be updated for this unit. private bool UpdateSingleDefaultParameter(AnalysisUnit unit, InterpreterScope scope, int index, IParameterInfo info) { if (index >= FunctionDefinition.Parameters.Count) { return false; } VariableDef param; var name = FunctionDefinition.Parameters[index].Name; if (scope.Variables.TryGetValue(name, out param)) { var ns = ProjectState.GetNamespaceFromObjects(info.ParameterType); if ((info.IsParamArray && !(param is ListParameterVariableDef)) || (info.IsKeywordDict && !(param is DictParameterVariableDef))) { return false; } param.AddTypes(unit, ns); } return true; }
/// <summary> /// Resolves a generic type for a test method. The test parameters (and associated parameter infos) are /// used to determine the best matching generic type for the test method that can be satisfied by all /// the generic parameters and their values. /// </summary> /// <param name="genericType">The generic type to be resolved</param> /// <param name="parameters">The parameter values being passed to the test method</param> /// <param name="parameterInfos">The parameter infos for the test method</param> /// <returns>The best matching generic type</returns> public static ITypeInfo ResolveGenericType(this ITypeInfo genericType, object[] parameters, IParameterInfo[] parameterInfos) { for (var idx = 0; idx < parameterInfos.Length; ++idx) { var methodParameterType = parameterInfos[idx].ParameterType; var passedParameterType = parameters[idx]?.GetType(); Type matchedType = null; if (ResolveGenericParameter(genericType, methodParameterType, passedParameterType, ref matchedType)) return Reflector.Wrap(matchedType); } return ObjectTypeInfo; }
/// <summary> /// Convert an argument list to the required parameter types. /// Currently, only widening numeric conversions are performed. /// </summary> /// <param name="arglist">An array of args to be converted</param> /// <param name="parameters">A ParameterInfo[] whose types will be used as targets</param> public static void ConvertArgumentList(object[] arglist, IParameterInfo[] parameters) { System.Diagnostics.Debug.Assert(arglist.Length <= parameters.Length); for (int i = 0; i < arglist.Length; i++) { object arg = arglist[i]; #if PORTABLE if (arg != null) #else if (arg != null && arg is IConvertible) #endif { Type argType = arg.GetType(); Type targetType = parameters[i].ParameterType; bool convert = false; if (argType != targetType && !argType.IsAssignableFrom(targetType)) { if (IsNumeric(argType) && IsNumeric(targetType)) { if (targetType == typeof(double) || targetType == typeof(float)) convert = arg is int || arg is long || arg is short || arg is byte || arg is sbyte; else if (targetType == typeof(long)) convert = arg is int || arg is short || arg is byte || arg is sbyte; else if (targetType == typeof(short)) convert = arg is byte || arg is sbyte; } } if (convert) arglist[i] = Convert.ChangeType(arg, targetType, System.Globalization.CultureInfo.InvariantCulture); } } }
/// <summary> /// Gets an enumeration of data items for use as arguments /// for a test method parameter. /// </summary> /// <param name="parameter">The parameter for which data is needed</param> /// <returns> /// An enumeration containing individual data items /// </returns> public IEnumerable GetData(IParameterInfo parameter) { return GetDataSource(parameter); }
/// <summary> /// Determine whether any data is available for a parameter. /// </summary> /// <param name="parameter">A ParameterInfo representing one /// argument to a parameterized test</param> /// <returns> /// True if any data is available, otherwise false. /// </returns> public bool HasDataFor(IParameterInfo parameter) { return parameter.IsDefined<IParameterDataSource>(false); }
private IEnumerable GetDataSource(IParameterInfo parameter) { Type sourceType = SourceType ?? parameter.Method.TypeInfo.Type; // TODO: Test this if (SourceName == null) return Reflect.Construct(sourceType) as IEnumerable; MemberInfo[] members = sourceType.GetMember(SourceName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance); if (members.Length == 1) { MemberInfo member = members[0]; var field = member as FieldInfo; if (field != null) { if (field.IsStatic) return (IEnumerable)field.GetValue(null); ThrowInvalidDataSourceException(); } var property = member as PropertyInfo; if (property != null) { if (property.GetGetMethod(true).IsStatic) return (IEnumerable)property.GetValue(null, null); ThrowInvalidDataSourceException(); } var m = member as MethodInfo; if (m != null) { if (m.IsStatic) return (IEnumerable)m.Invoke(null, null); ThrowInvalidDataSourceException(); } } return null; }
/// <summary> /// Helper method that checks the signature of a TestMethod and /// any supplied parameters to determine if the test is valid. /// /// Currently, NUnitTestMethods are required to be public, /// non-abstract methods, either static or instance, /// returning void. They may take arguments but the _values must /// be provided or the TestMethod is not considered runnable. /// /// Methods not meeting these criteria will be marked as /// non-runnable and the method will return false in that case. /// </summary> /// <param name="testMethod">The TestMethod to be checked. If it /// is found to be non-runnable, it will be modified.</param> /// <param name="parms">Parameters to be used for this test, or null</param> /// <returns>True if the method signature is valid, false if not</returns> /// <remarks> /// The return value is no longer used internally, but is retained /// for testing purposes. /// </remarks> private static bool CheckTestMethodSignature(TestMethod testMethod, TestCaseParameters parms) { if (testMethod.Method.IsAbstract) return MarkAsNotRunnable(testMethod, "Method is abstract"); if (!testMethod.Method.IsPublic) return MarkAsNotRunnable(testMethod, "Method is not public"); IParameterInfo[] parameters; #if NETCF if (testMethod.Method.IsGenericMethodDefinition) { if (parms != null && parms.Arguments != null) { var mi = testMethod.Method.MakeGenericMethodEx(parms.Arguments); if (mi == null) return MarkAsNotRunnable(testMethod, "Cannot determine generic types by probing"); testMethod.Method = mi; parameters = testMethod.Method.GetParameters(); } else parameters = new IParameterInfo[0]; } else parameters = testMethod.Method.GetParameters(); int minArgsNeeded = parameters.Length; #else parameters = testMethod.Method.GetParameters(); int minArgsNeeded = 0; foreach (var parameter in parameters) { // IsOptional is supported since .NET 1.1 if (!parameter.IsOptional) minArgsNeeded++; } #endif int maxArgsNeeded = parameters.Length; object[] arglist = null; int argsProvided = 0; if (parms != null) { testMethod.parms = parms; testMethod.RunState = parms.RunState; arglist = parms.Arguments; if (arglist != null) argsProvided = arglist.Length; if (testMethod.RunState != RunState.Runnable) return false; } #if NETCF ITypeInfo returnType = testMethod.Method.IsGenericMethodDefinition && (parms == null || parms.Arguments == null) ? new TypeWrapper(typeof(void)) : testMethod.Method.ReturnType; #else ITypeInfo returnType = testMethod.Method.ReturnType; #endif #if NET_4_0 || NET_4_5 || PORTABLE if (AsyncInvocationRegion.IsAsyncOperation(testMethod.Method.MethodInfo)) { if (returnType.IsType(typeof(void))) return MarkAsNotRunnable(testMethod, "Async test method must have non-void return type"); var returnsGenericTask = returnType.IsGenericType && returnType.GetGenericTypeDefinition() == typeof(System.Threading.Tasks.Task<>); if (returnsGenericTask && (parms == null || !parms.HasExpectedResult)) return MarkAsNotRunnable(testMethod, "Async test method must have non-generic Task return type when no result is expected"); if (!returnsGenericTask && parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Async test method must have Task<T> return type when a result is expected"); } else #endif if (returnType.IsType(typeof(void))) { if (parms != null && parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method returning void cannot have an expected result"); } else if (parms == null || !parms.HasExpectedResult) return MarkAsNotRunnable(testMethod, "Method has non-void return value, but no result is expected"); if (argsProvided > 0 && maxArgsNeeded == 0) return MarkAsNotRunnable(testMethod, "Arguments provided for method not taking any"); if (argsProvided == 0 && minArgsNeeded > 0) return MarkAsNotRunnable(testMethod, "No arguments were provided"); if (argsProvided < minArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Not enough arguments provided, provide at least {0} arguments.", minArgsNeeded)); if (argsProvided > maxArgsNeeded) return MarkAsNotRunnable(testMethod, string.Format("Too many arguments provided, provide at most {0} arguments.", maxArgsNeeded)); if (testMethod.Method.IsGenericMethodDefinition && arglist != null) { var typeArguments = new GenericMethodHelper(testMethod.Method.MethodInfo).GetTypeArguments(arglist); foreach (Type o in typeArguments) if (o == null || o == TypeHelper.NonmatchingType) return MarkAsNotRunnable(testMethod, "Unable to determine type arguments for method"); testMethod.Method = testMethod.Method.MakeGenericMethod(typeArguments); parameters = testMethod.Method.GetParameters(); } if (arglist != null && parameters != null) TypeHelper.ConvertArgumentList(arglist, parameters); return true; }
/// <summary> /// Performs several special conversions allowed by NUnit in order to /// permit arguments with types that cannot be used in the constructor /// of an Attribute such as TestCaseAttribute or to simplify their use. /// </summary> /// <param name="arglist">The arguments to be converted</param> /// <param name="parameters">The ParameterInfo array for the method</param> private static void PerformSpecialConversions(object[] arglist, IParameterInfo[] parameters) { for (int i = 0; i < arglist.Length; i++) { object arg = arglist[i]; Type targetType = parameters[i].ParameterType; if (arg == null) continue; if (arg is SpecialValue && (SpecialValue)arg == SpecialValue.Null) { arglist[i] = null; continue; } if (targetType.IsAssignableFrom(arg.GetType())) continue; #if !PORTABLE if (arg is DBNull) { arglist[i] = null; continue; } #endif bool convert = false; if (targetType == typeof(short) || targetType == typeof(byte) || targetType == typeof(sbyte) || targetType == typeof(short?) || targetType == typeof(byte?) || targetType == typeof(sbyte?) || targetType == typeof(double?)) { convert = arg is int; } else if (targetType == typeof(decimal) || targetType == typeof(decimal?)) { convert = arg is double || arg is string || arg is int; } else if (targetType == typeof(DateTime) || targetType == typeof(DateTime?)) { convert = arg is string; } if (convert) { Type convertTo = targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(Nullable<>) ? targetType.GetGenericArguments()[0] : targetType; arglist[i] = Convert.ChangeType(arg, convertTo, System.Globalization.CultureInfo.InvariantCulture); } else // Convert.ChangeType doesn't work for TimeSpan from string if ((targetType == typeof(TimeSpan) || targetType == typeof(TimeSpan?)) && arg is string) { arglist[i] = TimeSpan.Parse((string)arg); } } }
public DelegateCall(ICallRouter callRouter, IParameterInfo[] parameterInfos) { _callRouter = callRouter; _parameterInfos = parameterInfos; }
/// <summary> /// Get the collection of _values to be used as arguments /// </summary> public IEnumerable GetData(IParameterInfo parameter) { Type targetType = parameter.ParameterType; if (targetType.GetTypeInfo().IsEnum && data.Length == 0) { return TypeHelper.GetEnumValues(targetType); } if (targetType == typeof(bool) && data.Length == 0) { return new object[] {true, false}; } return GetData(targetType); }