public object Create(object request, ISpecimenContext context)
        {
            var pi = request as PropertyInfo;

            if (pi != null)
            {
                var isIEnumerable = pi.PropertyType
                    .GetInterfaces()
                    .Any(t => t.IsGenericType
                              && t.GetGenericTypeDefinition() == typeof(IList<>));

                if (isIEnumerable)
                {
                    if (pi.PropertyType.IsArray)
                    {
                        return Array.CreateInstance(pi.PropertyType.GetElementType(), 0);
                    }

                    var genericArguments = pi.PropertyType.GetGenericArguments();
                    var concreteType = typeof(List<>).MakeGenericType(genericArguments);
                    var instance = Activator.CreateInstance(concreteType);
                    return instance;
                }
            }

            return new NoSpecimen(request);
        }
        public object Create(object request, ISpecimenContext context)
        {
            var pr = request as ParameterInfo;
            if (pr == null)
            {
                return new NoSpecimen(request);
            }

            if (pr.ParameterType == typeof (IEnumerable<Address>))
            {
                var count = random.Next(0, Cities.Length - 1);
                var cities = new List<Address>();

                for (int i = 0; i < count; i++)
                {
                    var index = random.Next(0, Cities.Length - 1);
                    cities.Add(new Address()
                    {
                        City = Cities[index]
                    });
                }
                return cities.ToArray();
            }

            return new NoSpecimen(request);
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
            {
                return new NoSpecimen();
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var customAttributeProvider = request as ICustomAttributeProvider;
            if (customAttributeProvider == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var regularExpressionAttribute = customAttributeProvider.GetCustomAttributes(typeof(RegularExpressionAttribute), inherit: true).Cast<RegularExpressionAttribute>().SingleOrDefault();
            if (regularExpressionAttribute == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return context.Resolve(new RegularExpressionRequest(regularExpressionAttribute.Pattern));
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A mock instance created by FakeItEasy if appropriate; otherwise a
        /// <see cref="NoSpecimen"/> instance.
        /// </returns>
        /// <remarks>
        /// <para>
        /// The Create method checks whether a request is for an interface or abstract class. If so
        /// it delegates the call to the decorated <see cref="Builder"/>. When the specimen is
        /// returned from the decorated <see cref="ISpecimenBuilder"/> the method checks whether
        /// the returned instance is a FakeItEasy instance.
        /// </para>
        /// <para>
        /// If all pre- and post-conditions are satisfied, the mock instance is returned; otherwise
        /// a <see cref="NoSpecimen" /> instance.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            var type = request as Type;
            if (!type.IsFake())
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var fake = this.builder.Create(request, context) as FakeItEasy.Configuration.IHideObjectMembers;
            if (fake == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var fakeType = type.GetFakedType();
            if (fake.GetType().GetFakedType() != fakeType)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return fake;
        }
        public static void AddMany(object specimen, ISpecimenContext context)
        {
            if (specimen == null)
            {
                throw new ArgumentNullException("specimen");
            }
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var typeArguments = specimen.GetType().GetGenericArguments();
            if (typeArguments.Length != 2)
            {
                throw new ArgumentException("The specimen must be an instance of IDictionary<TKey, TValue>.", "specimen");
            }

            if (!typeof(IDictionary<,>).MakeGenericType(typeArguments).IsAssignableFrom(specimen.GetType()))
            {
                throw new ArgumentException("The specimen must be an instance of IDictionary<TKey, TValue>.", "specimen");
            }

            var kvpType = typeof(KeyValuePair<,>).MakeGenericType(typeArguments);
            var enumerable = context.Resolve(new MultipleRequest(kvpType)) as IEnumerable;
            foreach (var item in enumerable)
            {
                var addMethod = typeof(ICollection<>).MakeGenericType(kvpType).GetMethod("Add", new[] { kvpType });
                addMethod.Invoke(specimen, new[] { item });
            }
        }
        /// <summary>
        /// Creates a relayed request based on the <see cref="SubstituteAttribute"/> applied to a code element and 
        /// resolves it from the given <paramref name="context"/>.
        /// </summary>
        /// <returns>
        /// A specimen resolved from the <paramref name="context"/> based on a relayed request.
        /// If the <paramref name="request"/> code element does not have <see cref="SubstituteAttribute"/> applied, 
        /// returns <see cref="NoSpecimen"/>.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var customAttributeProvider = request as ICustomAttributeProvider;
            if (customAttributeProvider == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var attribute = customAttributeProvider.GetCustomAttributes(typeof(SubstituteAttribute), true)
                    .OfType<SubstituteAttribute>().FirstOrDefault();
            if (attribute == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            object substituteRequest = CreateSubstituteRequest(customAttributeProvider, attribute);
            return context.Resolve(substituteRequest);
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (!typeof(Uri).Equals(request))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var scheme = context.Resolve(typeof(UriScheme)) as UriScheme;
            if (scheme == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var authority = context.Resolve(typeof(string)) as string;
            if (authority == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return UriGenerator.CreateAnonymous(scheme, authority);
        }
        /// <summary>
        /// Creates a new specimen based on a request and raises events tracing the progress.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        /// <remarks>
        /// <para>
        /// The <paramref name="request"/> can be any object, but will often be a
        /// <see cref="Type"/> or other <see cref="System.Reflection.MemberInfo"/> instances.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            var isFilterSatisfied = this.filter.IsSatisfiedBy(request);
            if (isFilterSatisfied)
            {
                this.OnSpecimenRequested(new RequestTraceEventArgs(request, ++this.depth));
            }

            bool specimenWasCreated = false;
            object specimen = null;
            try
            {
                specimen = this.Builder.Create(request, context);
                specimenWasCreated = true;
                return specimen;
            }
            finally
            {
                if (isFilterSatisfied)
                {
                    if (specimenWasCreated)
                    {
                        this.OnSpecimenCreated(new SpecimenCreatedEventArgs(request, specimen, this.depth));
                    }
                    this.depth--;
                }
            }
        }
 private long GetRandomNumberOfTicks(ISpecimenContext context)
 {
     var randomNumberOfTicks = (long)_randomizer.Create(typeof(long), context);
     if (_noFractions)
         randomNumberOfTicks = randomNumberOfTicks - (randomNumberOfTicks % TimeSpan.TicksPerSecond);
     return randomNumberOfTicks;
 }
    public object Create(object request, ISpecimenContext context)
    {
      var customAttributeProvider = request as ICustomAttributeProvider;
      if (customAttributeProvider == null)
      {
        return new NoSpecimen(request);
      }

      var attribute =
        customAttributeProvider.GetCustomAttributes(typeof(ContentAttribute), true)
          .OfType<ContentAttribute>()
          .FirstOrDefault();
      if (attribute == null)
      {
        return new NoSpecimen(request);
      }

      var parameterInfo = request as ParameterInfo;
      if (parameterInfo == null)
      {
        return new NoSpecimen(request);
      }

      return context.Resolve(parameterInfo.ParameterType);
    }
 /// <summary>
 /// Creates a new specimen by delegating to <see cref="Builders"/>.
 /// </summary>
 /// <param name="request">The request that describes what to create.</param>
 /// <param name="context">A container that can be used to create other specimens.</param>
 /// <returns>The first result created by <see cref="Builders"/>.</returns>
 public object Create(object request, ISpecimenContext context)
 {
     return (from b in this.Builders
             let result = b.Create(request, context)
             where !(result is NoSpecimen)
             select result).DefaultIfEmpty(new NoSpecimen(request)).FirstOrDefault();
 }
        /// <summary>
        /// Sets up a mocked object's methods so that the return values will be retrieved from a fixture,
        /// instead of being created directly by Moq.
        /// </summary>
        /// <param name="specimen">The mock to setup.</param>
        /// <param name="context">The context of the mock.</param>
        public void Execute(object specimen, ISpecimenContext context)
        {
            if (specimen == null) throw new ArgumentNullException("specimen");
            if (context == null) throw new ArgumentNullException("context");

            var mock = specimen as Mock;
            if (mock == null)
                return;

            var mockType = mock.GetType();
            var mockedType = mockType.GetMockedType();
            var methods = GetConfigurableMethods(mockedType);

            foreach (var method in methods)
            {
                var returnType = method.ReturnType;
                var methodInvocationLambda = MakeMethodInvocationLambda(mockedType, method, context);

                if (method.IsVoid())
                {
                    //call `Setup`
                    mock.Setup(methodInvocationLambda);
                }
                else
                {
                    //call `Setup`
                    var setup = mock.Setup(returnType, methodInvocationLambda);

                    //call `Returns`
                    setup.ReturnsUsingContext(context, mockedType, returnType);
                }
            }
        }
Exemple #13
0
		public object Create(object request, ISpecimenContext context)
		{
			var specimen = _postprocessor.Create(request, context);
			if (specimen.GetType() == typeof (NoSpecimen))
			{
				return specimen;
			}
			var mockedType = GetMockedType(specimen);
			var methodsWithTasks = GetMethodsWithTasks(mockedType);
			var isAny = typeof (It).GetMethod("IsAny");
			foreach (var method in methodsWithTasks)
			{
				var mockSetupMethod = GetMockSetupMethod(mockedType, method.ReturnType);
				var mockReturnMethod = GetMockReturnsMethod(mockedType, method.ReturnType);
				var returnTaskType = GetReturnType(method.ReturnType);
				var returnValue = context.Resolve(returnTaskType);
				var returnTask = typeof (Task).GetMethod("FromResult")
				                              .MakeGenericMethod(returnTaskType)
				                              .Invoke(null, new object[] {returnValue});
				var parameters = method.GetParameters()
				                       .Select(info =>(Expression) Expression.Constant(isAny.MakeGenericMethod(info.ParameterType).Invoke(null, new object[] {})))
				                       .ToArray();
				var parameter = Expression.Parameter(mockedType);
				var body = Expression.Call(parameter, method, parameters);
				var lambda = Expression.Lambda(body, parameter);
				var setup = mockSetupMethod.Invoke(specimen, new object[] {lambda});
				mockReturnMethod.Invoke(setup, new object[] {returnTask});
			}
			return specimen;
		}
        /// <summary>
        /// Creates a random number within the request range.
        /// </summary>
        /// <param name="request">The request that describes what to create. Other requests for same type and limits 
        /// denote the same set. </param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The next random number in a range <paramref name="request"/> is a request
        /// for a numeric value; otherwise, a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
                return new NoSpecimen();

            if (context == null)
                throw new ArgumentNullException("context");

            var rangedNumberRequest = request as RangedNumberRequest;
            
            if (rangedNumberRequest == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            try
            {
                return SelectGenerator(rangedNumberRequest).Create(rangedNumberRequest.OperandType, context);
            }
            catch (ArgumentException)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A dynamic mock instance of the requested interface or abstract class if possible;
        /// otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (!this.fakeableSpecification.IsSatisfiedBy(request))
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            var type = request as Type;
            if (type == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            var fakeType = typeof(Fake<>).MakeGenericType(type);

            var fake = context.Resolve(fakeType);
            if (!fakeType.IsInstanceOfType(fake))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return fake.GetType().GetProperty("FakedObject").GetValue(fake, null);
        }
        /// <summary>
        /// Creates a new MailAddress.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        /// <remarks>>
        /// The generated MailAddress will have one of the reserved domains,
        /// so as to avoid any possibility of tests bothering real email addresses
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (!typeof(MailAddress).Equals(request))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            try
            {
                return TryCreateMailAddress(request, context);
            }                    
            catch (FormatException)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }
        }
Exemple #17
0
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A dynamic mock instance of the requested interface or abstract class if possible;
        /// otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
                throw new ArgumentNullException("context");

            if (!this.mockableSpecification.IsSatisfiedBy(request))
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            var t = request as Type;
            if (t == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            var result = MockRelay.ResolveMock(t, context);
            // Note: null is a valid specimen (e.g., returned by NullRecursionHandler)
            if (result is NoSpecimen || result is OmitSpecimen || result == null)
                return result;

            var m = result as Mock;
            if (m == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            return m.Object;
        }
        /// <summary>
        /// Creates an anonymous string based on a seed.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A string with the seed prefixed to a string created by <paramref name="context"/> if
        /// possible; otherwise, <see langword="null"/>.
        /// </returns>
        /// <remarks>
        /// <para>
        /// This method only returns an instance if a number of conditions are satisfied.
        /// <paramref name="request"/> must represent a request for a seed string, and
        /// <paramref name="context"/> must be able to create a string.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var seededRequest = request as SeededRequest;
            if (seededRequest == null ||
                (!seededRequest.Request.Equals(typeof(string))))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var seed = seededRequest.Seed as string;
            if (seed == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var containerResult = context.Resolve(typeof(string));
            if (containerResult is NoSpecimen)
            {
                return containerResult;
            }

            return seed + containerResult;
        }
        /// <summary>
        /// Creates a new specimen based on a specified length of characters that are allowed.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A container that can be used to create other specimens.</param>
        /// <returns>
        /// A specimen created from a <see cref="RangedNumberRequest"/> encapsulating the operand
        /// type, the minimum and the maximum of the requested number, if possible; otherwise,
        /// a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
            {
                return new NoSpecimen();
            }

            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var customAttributeProvider = request as ICustomAttributeProvider;
            if (customAttributeProvider == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var stringLengthAttribute = customAttributeProvider.GetCustomAttributes(typeof(StringLengthAttribute), inherit: true).Cast<StringLengthAttribute>().SingleOrDefault();
            if (stringLengthAttribute == null)
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return context.Resolve(new ConstrainedStringRequest(stringLengthAttribute.MinimumLength, stringLengthAttribute.MaximumLength));
        }
        /// <summary>
        /// Creates an anonymous string based on a seed.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A string with the seed prefixed to a string created by <paramref name="context"/> if
        /// possible; otherwise, <see langword="null"/>.
        /// </returns>
        /// <remarks>
        /// <para>
        /// This method only returns an instance if a number of conditions are satisfied.
        /// <paramref name="request"/> must represent a request for a seed string, and
        /// <paramref name="context"/> must be able to create a string.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var seededRequest = request as SeededRequest;
            if (seededRequest == null ||
                seededRequest.Request != typeof(string))
            {
                return new NoSpecimen(request);
            }

            var seed = seededRequest.Seed as string;
            if (seed == null)
            {
                return new NoSpecimen(request);
            }

            var containerResult = context.Resolve(typeof(string));
            if (containerResult is NoSpecimen)
            {
                return containerResult;
            }

            return seed + containerResult;
        }
        /// <summary>
        /// Creates a substitute when request is an abstract type.
        /// </summary>
        /// <returns>
        /// A substitute resolved from the <paramref name="context"/> when <paramref name="request"/> is an abstract
        /// type or <see cref="NoSpecimen"/> for all other requests.
        /// </returns>
        /// <exception cref="InvalidOperationException">
        /// An attempt to resolve a substitute from the <paramref name="context"/> returned an object that was not 
        /// created by NSubstitute.
        /// </exception>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var requestedType = request as Type;
            if (requestedType == null || !requestedType.IsAbstract)
            {
                return new NoSpecimen(request);
            }

            object substitute = context.Resolve(new SubstituteRequest(requestedType));

            try
            {
                SubstitutionContext.Current.GetCallRouterFor(substitute);
            }
            catch (NotASubstituteException e)
            {
                throw new InvalidOperationException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        "Object resolved by request for substitute of {0} was not created by NSubstitute. " +
                        "Ensure that {1} was added to Fixture.Customizations.",
                        requestedType.FullName, typeof(SubstituteRequestHandler).FullName),
                    e);
            }

            return substitute;
        }
        /// <summary>
        /// Creates a specimen based on a requested enumerable parameter.
        /// </summary>
        /// <param name="request">
        /// The request that describes what to create.
        /// </param>
        /// <param name="context">
        /// A context that can be used to create other specimens.
        /// </param>
        /// <returns>
        /// A specimen created from a <see cref="SeededRequest"/> encapsulating
        /// the parameter type and name of the requested parameter, if
        /// possible; otherwise, a <see cref="NoSpecimen" />.
        /// </returns>
        /// <remarks>
        /// <para>
        /// This method only handles <see cref="ParameterInfo" /> instances
        /// where <see cref="ParameterInfo.ParameterType" /> is
        /// <see cref="IEnumerable{T}" />.  If <paramref name="context" />
        /// returns an <see cref="OmitSpecimen" /> instance, an empty array of
        /// the correct type is returned instead.
        /// </para>
        /// </remarks>
        /// <exception cref="System.ArgumentNullException">
        /// <paramref name="context" /> is <see langword="null"/>
        /// </exception>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
                throw new ArgumentNullException(nameof(context));

            var pi = request as ParameterInfo;
            if (pi == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            if (!pi.ParameterType.IsGenericType)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            if (IsNotEnumerable(pi))
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618

            var returnValue = context.Resolve(
                new SeededRequest(
                    pi.ParameterType,
                    pi.Name));

            if (returnValue is OmitSpecimen)
                return Array.CreateInstance(
                    pi.ParameterType.GetGenericArguments().Single(),
                    0);

            return returnValue;
        }
        /// <summary>
        /// Creates a new <see cref="Delegate"/> instance.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <exception cref="ArgumentNullException"><paramref name="context"/> is null.</exception>
        /// <returns>
        /// A new <see cref="Delegate"/> instance, if <paramref name="request"/> is a request for a
        /// <see cref="Delegate"/>; otherwise, a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var delegateType = request as Type;

            if (delegateType == null)
            {
                return new NoSpecimen(request);
            }

            if (!typeof(Delegate).IsAssignableFrom(delegateType))
            {
                return new NoSpecimen(request);
            }

            var delegateMethod = delegateType.GetMethod("Invoke");
            var methodSpecimenParams = DelegateGenerator.CreateMethodSpecimenParameters(delegateMethod);
            var methodSpecimenBody = DelegateGenerator.CreateMethodSpecimenBody(delegateMethod, context);

            var delegateSpecimen = Expression.Lambda(delegateType, methodSpecimenBody, methodSpecimenParams).Compile();

            return delegateSpecimen;
        }
        /// <summary>
        /// Creates a new number based on a RangedNumberRequest.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested number if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
            {
                return new NoSpecimen();
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var range = request as RangedNumberRequest;
            if (range == null)
            {
                return new NoSpecimen(request);
            }

            var value = context.Resolve(range.OperandType) as IComparable;
            if (value == null)
            {
                return new NoSpecimen(request);
            }

            try
            {
                this.CreateAnonymous(range, value);
            }
            catch (InvalidOperationException)
            {
                return new NoSpecimen(request);
            }

            return this.rangedValue;
        }
Exemple #25
0
        /// <summary>
        /// Creates a new array based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// An array of the requested type if possible; otherwise a <see cref="NoSpecimen"/>
        /// instance.
        /// </returns>
        /// <remarks>
        /// <para>
        /// If <paramref name="request"/> is a request for an array and <paramref name="context"/>
        /// can satisfy a <see cref="MultipleRequest"/> for the element type, the return value is a
        /// populated array of the requested type. If not, the return value is a
        /// <see cref="NoSpecimen"/> instance.
        /// </para>
        /// </remarks>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            // This is performance-sensitive code when used repeatedly over many requests.
            // See discussion at https://github.com/AutoFixture/AutoFixture/pull/218
            var type = request as Type;
            if (type == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            if (!type.IsArray)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            var elementType = type.GetElementType();
            var specimen = context.Resolve(new MultipleRequest(elementType));
            if (specimen is OmitSpecimen)
                return specimen;
            var elements = specimen as IEnumerable;
            if (elements == null)
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            return ArrayRelay.ToArray(elements, elementType);
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// A valid specimen for the requested member if possible; otherwise a <see cref="T:Ploeh.AutoFixture.Kernel.NoSpecimen" /> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (_mappings == null || !_mappings.Any())
            {
                return new NoSpecimen(request);
            }

            var mi = request as MemberInfo;
            if (mi == null || mi.DeclaringType != _sourceType)
            {
                return new NoSpecimen(request);
            }

            var mapping = _mappings
                            .Where(p => p.SourceMember == mi)
                            .FirstOrDefault();

            if (mapping == null)
            {
                return new NoSpecimen(request);
            }

            //Since AutoFixture registers an Omitter when a Member is
            //customized via fixture.Customize<T>(c => c.With(x => x.<Member>, <value>))
            //then if a call to context.Resolve is made using that member an
            //OmitSpecimen is returned
            //return context.Resolve(mapping.DestinationMember); -> OmitSpecimen
            if (_destination == null)
                //fetch an instance of destinationType, for performance
                //we will always use the same instance to provide the
                //values for the requested members
                _destination = context.Resolve(_destinationType);

            return mapping.DestinationMember.GetValue(_destination);            
        }
        /// <summary>
        /// Creates a new specimen based on a request.
        /// </summary>
        /// <param name="request">The request that describes what to create</param>
        /// <param name="context">A context that can be used to create other specimens.</param>
        /// <returns>
        /// The requested specimen if possible; otherwise a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (request == null || !typeof(EmailAddressLocalPart).Equals(request))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            var localPart = context.Resolve(typeof(string)) as string;

            if (string.IsNullOrEmpty(localPart))
            {
#pragma warning disable 618
                return new NoSpecimen(request);
#pragma warning restore 618
            }

            return new EmailAddressLocalPart(localPart);
        }       
        private long GetRandomNumberOfTicks(ISpecimenContext context)
        {
            long randomValue = (long)this.randomizer.Create(typeof(long), context);
            long correctValue = randomValue / this.accuracy * this.accuracy;

            return correctValue;
        }
        /// <summary>
        /// Creates a new specimen based on a requested range.
        /// </summary>
        /// <param name="request">The request that describes what to create.</param>
        /// <param name="context">A container that can be used to create other specimens.</param>
        /// <returns>
        /// A specimen created from a <see cref="RangedNumberRequest"/> encapsulating the operand
        /// type, the minimum and the maximum of the requested number, if possible; otherwise,
        /// a <see cref="NoSpecimen"/> instance.
        /// </returns>
        public object Create(object request, ISpecimenContext context)
        {
            if (request == null)
            {
                return new NoSpecimen();
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            var customAttributeProvider = request as ICustomAttributeProvider;
            if (customAttributeProvider == null)
            {
                return new NoSpecimen(request);
            }

            var rangeAttribute = customAttributeProvider.GetCustomAttributes(typeof(RangeAttribute), inherit: true).Cast<RangeAttribute>().SingleOrDefault();
            if (rangeAttribute == null)
            {
                return new NoSpecimen(request);
            }

            return context.Resolve(RangeAttributeRelay.Create(rangeAttribute, request));
        }
		public object Create(object request, ISpecimenContext context)
		{
			var requestAsParameter = request as ParameterInfo;
			if (requestAsParameter == null || !requestAsParameter.Equals(this.parameter))
				return new NoSpecimen();

			return this.typeFilteredBuilder.Create(this.parameter.ParameterType, context);
		}
Exemple #31
0
        private static object CreateGenericTask(Type resultType, ISpecimenContext context)
        {
            var result = context.Resolve(resultType);

            return(CreateTask(resultType, result));
        }
 /// <summary>Creates a new specimen based on a request.</summary>
 /// <param name="request">
 /// The request that describes what to create.
 /// </param>
 /// <param name="context">
 /// A context that can be used to create other specimens.
 /// </param>
 /// <returns>
 /// The requested specimen if possible; otherwise a
 /// <see cref="NoSpecimen" /> instance.
 /// </returns>
 /// <remarks>
 /// <para>
 /// The <paramref name="request" /> can be any object, but will often be a
 /// <see cref="Type" /> or other <see cref="System.Reflection.MemberInfo" /> instances.
 /// </para>
 /// </remarks>
 public object Create(object request, ISpecimenContext context)
 {
     return(new CompositeSpecimenBuilder(this.Composers)
            .Create(request, context));
 }
 public object Create(object request, ISpecimenContext context)
 {
     throw new System.NotImplementedException();
 }
Exemple #34
0
 IEnumerable <Expression> GetAnyAccedptableParameterExpressions(MethodInfo dlgtMethod, ISpecimenContext context)
 {
     return(dlgtMethod.GetParameters().Select(_ => ToAnyAccedptableParameterExpression(_, context)));
 }
 /// <summary>
 /// Creates a new specimen based on a request.
 /// </summary>
 /// <param name="request">The request that describes what to create.</param>
 /// <param name="context">A context that can be used to create other specimens.</param>
 /// <returns>
 /// The specimen created by the Func contained by this instance.
 /// </returns>
 /// <remarks>
 /// <para>
 /// <paramref name="request"/> is ignored. Instead, the Func contained by this instance is
 /// used to create a specimen.
 /// </para>
 /// </remarks>
 public object Create(object request, ISpecimenContext context)
 {
     return(this.create());
 }
 Reportable CreateFailurePerformance(ISpecimenContext context)
 {
     return(CreateReportable(context,
                             ReportableType.FailureWithError,
                             exception: (Exception)context.Resolve(typeof(Exception))));
 }
Exemple #37
0
 public MethodRule(ISpecimenContext context, CallResultCache resultSource)
 {
     this.context      = context;
     this.resultSource = resultSource;
 }
Exemple #38
0
 public virtual object Create(object request, ISpecimenContext context) => _builder.Create(request, context);
Exemple #39
0
 /// <inheritdoc/>
 protected override YearMonth CreateFromDateTimeOffset(DateTimeOffset dateTimeOffset, ISpecimenContext context)
 => new YearMonth(dateTimeOffset.Year, dateTimeOffset.Month);
Exemple #40
0
 private static void SetupMethod <TMock, TResult>(Mock <TMock> mock, Expression <Func <TMock, TResult> > methodCallExpression, ISpecimenContext context) where TMock : class
 {
     if (mock == null)
     {
         throw new ArgumentNullException("mock");
     }
     ReturnsUsingContext(mock.Setup(methodCallExpression), context);
 }
 private static IEnumerable <T> SequenceWithExactlyOneElement(ISpecimenContext context)
 {
     return(new[] { (T)context.Resolve(typeof(T)) });
 }
        public void MakeExist(ModKey modKey, ISpecimenContext context)
        {
            var dataDir = context.Create <IDataDirectoryProvider>();

            MakeFileExist.MakeExist(Path.Combine(dataDir.Path, modKey.FileName), context);
        }
 public SubstituteValueFactory(object substitute, ISpecimenContext context)
 {
     this.substitute = substitute ?? throw new ArgumentNullException(nameof(substitute));
     this.context    = context ?? throw new ArgumentNullException(nameof(context));
 }
Exemple #44
0
 private object CreateRandomTimeSpan(ISpecimenContext context)
 {
     return(new TimeSpan(GetRandomNumberOfTicks(context)));
 }
 Reportable CreateSuccessPerformance(ISpecimenContext context)
 {
     return(CreateReportable(context,
                             ReportableType.Success));
 }
 /// <inheritdoc/>
 protected override LocalTime CreateFromDateTimeOffset(DateTimeOffset dateTimeOffset, ISpecimenContext context)
 => LocalTime.FromTicksSinceMidnight(dateTimeOffset.TimeOfDay.Ticks);
 Reportable CreateSuccessPerformanceWithResult(ISpecimenContext context)
 {
     return(CreateReportable(context,
                             ReportableType.SuccessWithResult,
                             context.Resolve(typeof(Guid))));
 }
 private object CreateRandomDate(ISpecimenContext context)
 {
     return(new DateTime(GetRandomNumberOfTicks(context)).Date);
 }
 Reportable CreateGainAbility(ISpecimenContext context)
 {
     return(CreateReportable(context, ReportableType.GainAbility));
 }
 private long GetRandomNumberOfTicks(ISpecimenContext context)
 {
     return((long)_randomizer.Create(typeof(long), context));
 }
Exemple #51
0
 /// <summary>Creates a new specimen based on a request.</summary>
 /// <param name="request">
 /// The request that describes what to create.
 /// </param>
 /// <param name="context">
 /// A context that can be used to create other specimens.
 /// </param>
 /// <returns>
 /// The requested specimen if possible; otherwise a
 /// <see cref="NoSpecimen" /> instance.
 /// </returns>
 /// <remarks>
 /// <para>
 /// The <paramref name="request" /> can be any object, but will often
 /// be a <see cref="Type" /> or other
 /// <see cref="System.Reflection.MemberInfo" /> instances.
 /// </para>
 /// </remarks>
 public object Create(object request, ISpecimenContext context)
 {
     return(this.Builder.Create(request, context));
 }
Exemple #52
0
 protected override object CreateSpecimen(object request, ISpecimenContext context) =>
 Duration.FromTimeSpan(context.Create <TimeSpan>());
Exemple #53
0
 /// <summary>
 /// Does nothing.
 /// </summary>
 /// <param name="specimen">A specimen.</param>
 /// <param name="context">An <see cref="ISpecimenContext"/>.</param>
 public void Execute(T specimen, ISpecimenContext context)
 {
 }
 /// <inheritdoc/>
 protected override ZonedDateTime CreateFromDateTimeOffset(DateTimeOffset dateTimeOffset, ISpecimenContext context)
 => OffsetDateTime.FromDateTimeOffset(dateTimeOffset)
 .InZone((DateTimeZone) new DateTimeZoneGenerator().Create(typeof(DateTimeZone), context));
 public static ConfiguredCall MockToReturn<T>(this ISpecimenContext context)
     where T : class
 {
     return context.Resolve(Arg.Is<SeededRequest>(o => (Type)o.Request == typeof(T)))
         .Returns(Substitute.For<T>());
 }
Exemple #56
0
 /// <summary>
 /// Creates a new instance of <see cref="CallResultResolver"/>.
 /// </summary>
 public CallResultResolver(ISpecimenContext specimenContext)
 {
     this.SpecimenContext = specimenContext ?? throw new ArgumentNullException(nameof(specimenContext));
 }
Exemple #57
0
 /// <summary>
 /// Executes <see cref="Action"/> on the supplied specimen.
 /// </summary>
 /// <param name="specimen">The specimen on which the command is executed.</param>
 /// <param name="context">
 /// An <see cref="ISpecimenContext"/> that can be used to resolve other requests. Not
 /// used.
 /// </param>
 public void Execute(T specimen, ISpecimenContext context)
 {
     this.Action(specimen);
 }
 public static void ShouldHaveCreated<T>(this ISpecimenContext context)
 {
     context.Received(1).Resolve(Arg.Is<SeededRequest>(o => (Type) o.Request == typeof(T)));
 }
Exemple #59
0
 public object Create(object request, ISpecimenContext context)
 {
     return(_instances.GetOrAdd(request, r => _builder.Create(r, context)));
 }
 public static ConfiguredCall MockToReturn<T>(this ISpecimenContext context, T item)
 {
     return context.Resolve(Arg.Is<SeededRequest>(o => (Type)o.Request == typeof(T)))
         .Returns(item!);
 }