/// <summary>
        /// Executes the code of the delegate and captures any exception.
        /// If a non-null base constraint was provided, it applies that
        /// constraint to the exception.
        /// </summary>
        /// <param name="actual">A delegate representing the code to be tested</param>
        /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            //TestDelegate code = actual as TestDelegate;
            //if (code == null)
            //    throw new ArgumentException(
            //        string.Format("The actual value must be a TestDelegate but was {0}", actual.GetType().Name), "actual");

            //caughtException = null;

            //try
            //{
            //    code();
            //}
            //catch (Exception ex)
            //{
            //    caughtException = ex;
            //}

            caughtException = ExceptionInterceptor.Intercept(actual);

            return(new ThrowsConstraintResult(
                       this,
                       caughtException,
                       caughtException != null
                    ? BaseConstraint.ApplyTo(caughtException)
                    : null));
        }
Exemple #2
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for if the base constraint fails, false if it succeeds</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            long now      = Stopwatch.GetTimestamp();
            long delayEnd = TimestampOffset(now, DelayInterval.AsTimeSpan);

            if (PollingInterval.IsNotZero)
            {
                long nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);
                while ((now = Stopwatch.GetTimestamp()) < delayEnd)
                {
                    if (nextPoll > now)
                    {
                        ThreadUtility.BlockingDelay((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
                    }
                    nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);

                    ConstraintResult result = BaseConstraint.ApplyTo(actual);
                    if (result.IsSuccess)
                    {
                        return(new ConstraintResult(this, actual, true));
                    }
                }
            }
            if ((now = Stopwatch.GetTimestamp()) < delayEnd)
            {
                ThreadUtility.BlockingDelay((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
            }

            return(new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess));
        }
Exemple #3
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for if the base constraint fails, false if it succeeds</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            long now      = Stopwatch.GetTimestamp();
            long delayEnd = TimestampOffset(now, TimeSpan.FromMilliseconds(delayInMilliseconds));

            if (pollingInterval > 0)
            {
                long nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
                while ((now = Stopwatch.GetTimestamp()) < delayEnd)
                {
                    if (nextPoll > now)
                    {
                        Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
                    }
                    nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));

                    ConstraintResult result = BaseConstraint.ApplyTo(actual);
                    if (result.IsSuccess)
                    {
                        return(new ConstraintResult(this, actual, true));
                    }
                }
            }
            if ((now = Stopwatch.GetTimestamp()) < delayEnd)
            {
                Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
            }

            return(new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess));
        }
Exemple #4
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        protected override ConstraintResult ApplyConstraint <T>(T actual)
        {
            // TODO: Use an error result for null
            Guard.ArgumentNotNull(actual, nameof(actual));

            Type actualType = actual as Type;

            if (actualType == null)
            {
                actualType = actual.GetType();
            }

            PropertyInfo property = actualType.GetTypeInfo().GetProperty(name,
                                                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            // TODO: Use an error result here
            if (property == null)
            {
                throw new ArgumentException($"Property {name} was not found on {actualType}.", "name");
            }

            propValue = property.GetValue(actual, null);
            var baseResult = BaseConstraint.ApplyTo(propValue);

            return(new PropertyConstraintResult(this, baseResult));
        }
        /// <inheritdoc/>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            Exception caughtException = null;

            // If actual is Action or Func<T> where T is not a task
            var synchronousCode = actual as TestDelegate;

            // If actual is a Func<Task<T>> or Func<Task>
            var asyncCode = actual as AsyncTestDelegate;

            CancellationTokenSource waitForAsyncCodeTokenSource = new CancellationTokenSource();
            var token = waitForAsyncCodeTokenSource.Token;

            if (asyncCode != null)
            {
                // Async code could be run synchronously and returning something like Task.CompletedTask, so exceptions could either be propagated normally or be stored within the task.
                try
                {
                    asyncCode().ContinueWith(task => {
                        // Actual exception is wrapped in an AggregateException
                        caughtException = task.Exception?.InnerException;
                        waitForAsyncCodeTokenSource.Cancel(true);
                    }, token);
                }
                catch (Exception e)
                {
                    caughtException = e;
                    waitForAsyncCodeTokenSource.Cancel(true);
                }
            }
            else if (synchronousCode != null)
            {
                waitForAsyncCodeTokenSource.Cancel(true);
                try
                {
                    synchronousCode();
                }
                catch (Exception ex)
                {
                    caughtException = ex;
                }
            }
            else
            {
                throw new ArgumentException(
                          $"The actual value must be a TestDelegate or AsyncTestDelegate but was {actual.GetType().Name}", nameof(actual));
            }

            Task.Delay(TimeLimit, token).ContinueWith(task => {
                if (!task.IsCanceled)
                {
                    throw new InvalidOperationException($"Task did not complete within {TimeLimit}ms.");
                }
            }).GetAwaiter().GetResult();

            return(new HurlsConstraintResult(this, caughtException,
                                             caughtException != null
                    ? BaseConstraint.ApplyTo(caughtException)
                    : null));
        }
Exemple #6
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            // TODO: Use an error result for null
            Guard.ArgumentNotNull(actual, "actual");

            Type actualType = actual as Type;

            if (actualType == null)
            {
                actualType = actual.GetType();
            }

            PropertyInfo property = Reflect.GetUltimateShadowingProperty(actualType, name,
                                                                         BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            // TODO: Use an error result here
            if (property == null)
            {
                throw new ArgumentException(string.Format("Property {0} was not found", name), "name");
            }

            propValue = property.GetValue(actual, null);
            var baseResult = BaseConstraint.ApplyTo(propValue);

            return(new ConstraintResult(this, baseResult.ActualValue, baseResult.IsSuccess));
        }
Exemple #7
0
        /// <summary>
        /// Determines whether the Type or other provider has the 
        /// expected attribute and if its value matches the
        /// additional constraint specified.
        /// </summary>
        public override ConstraintResult ApplyTo<TActual>(TActual actual)
        {
            Guard.ArgumentNotNull(actual, "actual");
            Attribute[] attrs = AttributeHelper.GetCustomAttributes(actual, expectedType, true);
            if (attrs.Length == 0)
                throw new ArgumentException(string.Format("Attribute {0} was not found", expectedType), "actual");

            attrFound = attrs[0];
            return BaseConstraint.ApplyTo(attrFound);
        }
Exemple #8
0
        /// <summary>
        /// Executes the code of the delegate and captures any exception.
        /// If a non-null base constraint was provided, it applies that
        /// constraint to the exception.
        /// </summary>
        /// <param name="actual">A delegate representing the code to be tested</param>
        /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            var @delegate = ConstraintUtils.RequireActual <Delegate>(actual, nameof(actual));

            caughtException = ExceptionHelper.RecordException(@delegate, nameof(actual));

            return(new ThrowsConstraintResult(
                       this,
                       caughtException,
                       caughtException != null
                    ? BaseConstraint.ApplyTo(caughtException)
                    : null));
        }
        /// <summary>
        /// Apply the item constraint to each item in the collection,
        /// succeeding if any item succeeds.
        /// </summary>
        /// <param name="actual"></param>
        /// <returns></returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            var enumerable = ConstraintUtils.RequireActual <IEnumerable>(actual, nameof(actual));

            foreach (object item in enumerable)
            {
                if (BaseConstraint.ApplyTo(item).IsSuccess)
                {
                    return(new ConstraintResult(this, actual, ConstraintStatus.Success));
                }
            }

            return(new ConstraintResult(this, actual, ConstraintStatus.Failure));
        }
Exemple #10
0
        /// <summary>
        /// Apply the item constraint to each item in the collection,
        /// succeeding if any item succeeds.
        /// </summary>
        /// <param name="actual"></param>
        /// <returns></returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            if (!(actual is IEnumerable))
            {
                throw new ArgumentException("The actual value must be an IEnumerable", "actual");
            }

            foreach (object item in (IEnumerable)actual)
            {
                if (BaseConstraint.ApplyTo(item).IsSuccess)
                {
                    return(new ConstraintResult(this, actual, ConstraintStatus.Success));
                }
            }

            return(new ConstraintResult(this, actual, ConstraintStatus.Failure));
        }
        /// <summary>
        /// Apply the item constraint to each item in the collection,
        /// failing if any item fails.
        /// </summary>
        /// <param name="actual"></param>
        /// <returns></returns>
        protected override ConstraintResult ApplyConstraint <TActual>(TActual actual)
        {
            var enumerable = ConstraintUtils.RequireActual <IEnumerable>(actual, nameof(actual));

            int index = 0;

            foreach (object item in enumerable)
            {
                if (!BaseConstraint.ApplyTo(item).IsSuccess)
                {
                    return(new EachItemConstraintResult(this, actual, item, index));
                }

                index++;
            }

            return(new ConstraintResult(this, actual, ConstraintStatus.Success));
        }
Exemple #12
0
        /// <summary>
        /// Apply the item constraint to each item in the collection,
        /// succeeding only if the expected number of items pass.
        /// </summary>
        /// <param name="actual"></param>
        /// <returns></returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            if (!(actual is IEnumerable))
            {
                throw new ArgumentException("The actual value must be an IEnumerable", "actual");
            }

            int count = 0;

            foreach (object item in (IEnumerable)actual)
            {
                if (BaseConstraint.ApplyTo(item).IsSuccess)
                {
                    count++;
                }
            }

            return(new ConstraintResult(this, actual, count == expectedCount));
        }
        /// <summary>
        /// Test whether the constraint is satisfied by a delegate
        /// </summary>
        /// <param name="del">The delegate whose value is to be tested</param>
        /// <returns>A ConstraintResult</returns>
        public override ConstraintResult ApplyTo <TActual>(ActualValueDelegate <TActual> del)
        {
            long now      = Stopwatch.GetTimestamp();
            long delayEnd = TimestampOffset(now, DelayInterval.AsTimeSpan);

            object actual;

            if (PollingInterval.IsNotZero)
            {
                long nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);
                while ((now = Stopwatch.GetTimestamp()) < delayEnd)
                {
                    if (nextPoll > now)
                    {
                        ThreadUtility.BlockingDelay((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
                    }
                    nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);

                    actual = InvokeDelegate(del);

                    try
                    {
                        ConstraintResult result = BaseConstraint.ApplyTo(actual);
                        if (result.IsSuccess)
                        {
                            return(new DelegatingConstraintResult(this, result));
                        }
                    }
                    catch (Exception)
                    {
                        // Ignore any exceptions when polling
                    }
                }
            }
            if ((now = Stopwatch.GetTimestamp()) < delayEnd)
            {
                ThreadUtility.BlockingDelay((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
            }

            actual = InvokeDelegate(del);
            return(new DelegatingConstraintResult(this, BaseConstraint.ApplyTo(actual)));
        }
Exemple #14
0
        /// <summary>
        /// Test whether the constraint is satisfied by a delegate
        /// </summary>
        /// <param name="del">The delegate whose value is to be tested</param>
        /// <returns>A ConstraintResult</returns>
        public override ConstraintResult ApplyTo <TActual>(ActualValueDelegate <TActual> del)
        {
            long now      = Stopwatch.GetTimestamp();
            long delayEnd = TimestampOffset(now, TimeSpan.FromMilliseconds(delayInMilliseconds));

            object actual;

            if (pollingInterval > 0)
            {
                long nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));
                while ((now = Stopwatch.GetTimestamp()) < delayEnd)
                {
                    if (nextPoll > now)
                    {
                        Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
                    }
                    nextPoll = TimestampOffset(now, TimeSpan.FromMilliseconds(pollingInterval));

                    actual = InvokeDelegate(del);

                    try
                    {
                        ConstraintResult result = BaseConstraint.ApplyTo(actual);
                        if (result.IsSuccess)
                        {
                            return(new ConstraintResult(this, actual, true));
                        }
                    }
                    catch (Exception)
                    {
                        // Ignore any exceptions when polling
                    }
                }
            }
            if ((now = Stopwatch.GetTimestamp()) < delayEnd)
            {
                Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
            }

            actual = InvokeDelegate(del);
            return(new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess));
        }
Exemple #15
0
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            if (!(actual is RecordedValueDelegate action))
            {
                throw new Exception($"Actual value must be a {nameof(RecordedValueDelegate)}");
            }

            var recordedValue = new RecordedValue();

            using (new TestExecutionContext.IsolatedContext())
            {
                action(recordedValue);
            }

            var(hasValue, value) = recordedValue;

            return(!hasValue
                ? BaseConstraint.ApplyTo(new NoValue())
                : BaseConstraint.ApplyTo(value));
        }
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            Guard.ArgumentNotNull(actual, nameof(actual));

            object indexedValue;
            var    actualType = actual as Type ?? actual.GetType();

            if (actualType.IsArray)
            {
                var array = actual as Array;
                indexedValue = array?.GetValue(_arguments.Cast <int>().ToArray());
            }
            else
            {
                var getMethod = Reflect.GetDefaultIndexer(actualType, _argumentTypes) ?? throw new ArgumentException($"Default indexer accepting arguments {MsgUtils.FormatCollection(_arguments)} was not found on {actualType}.");

                indexedValue = Reflect.InvokeMethod(getMethod, actual, _arguments);
            }

            return(BaseConstraint.ApplyTo(indexedValue));
        }
Exemple #17
0
        /// <summary>
        /// Executes the code of the delegate and captures any exception.
        /// If a non-null base constraint was provided, it applies that
        /// constraint to the exception.
        /// </summary>
        /// <param name="actual">A delegate representing the code to be tested</param>
        /// <returns>True if an exception is thrown and the constraint succeeds, otherwise false</returns>
        protected override ConstraintResult ApplyConstraint <T>(T actual)
        {
            try
            {
                (actual as Delegate).DynamicInvoke();
            }
            catch (TargetInvocationException ex)
            {
                _caughtException = ex.InnerException;
            }
            catch (Exception ex)
            {
                _caughtException = ex;
            }

            return(new ThrowsConstraintResult(
                       this,
                       _caughtException,
                       _caughtException != null
                    ? BaseConstraint.ApplyTo(_caughtException)
                    : null));
        }
Exemple #18
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            // TODO: Use an error result for null
            Guard.ArgumentNotNull(actual, nameof(actual));
            const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

            PropertyInfo property = Reflect.GetUltimateShadowingProperty(typeof(TActual), name, bindingFlags);

            if (property == null && typeof(TActual).IsInterface)
            {
                foreach (var @interface in typeof(TActual).GetInterfaces())
                {
                    property = Reflect.GetUltimateShadowingProperty(@interface, name, bindingFlags);
                    if (property != null)
                    {
                        break;
                    }
                }
            }

            if (property == null)
            {
                Type actualType = actual as Type ?? actual.GetType();

                property = Reflect.GetUltimateShadowingProperty(actualType, name, bindingFlags);

                // TODO: Use an error result here
                if (property == null)
                {
                    throw new ArgumentException($"Property {name} was not found on {actualType}.", nameof(name));
                }
            }

            propValue = property.GetValue(actual, null);
            var baseResult = BaseConstraint.ApplyTo(propValue);

            return(new PropertyConstraintResult(this, baseResult));
        }
Exemple #19
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given reference.
        /// Overridden to wait for the specified delay period before
        /// calling the base constraint with the dereferenced value.
        /// </summary>
        /// <param name="actual">A reference to the value to be tested</param>
        /// <returns>True for success, false for failure</returns>
        public override ConstraintResult ApplyTo <TActual>(ref TActual actual)
        {
            long now      = Stopwatch.GetTimestamp();
            long delayEnd = TimestampOffset(now, DelayInterval.AsTimeSpan);

            if (PollingInterval.IsNotZero)
            {
                long nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);
                while ((now = Stopwatch.GetTimestamp()) < delayEnd)
                {
                    if (nextPoll > now)
                    {
                        Thread.Sleep((int)TimestampDiff(delayEnd < nextPoll ? delayEnd : nextPoll, now).TotalMilliseconds);
                    }
                    nextPoll = TimestampOffset(now, PollingInterval.AsTimeSpan);

                    try
                    {
                        ConstraintResult result = BaseConstraint.ApplyTo(actual);
                        if (result.IsSuccess)
                        {
                            return(new ConstraintResult(this, actual, true));
                        }
                    }
                    catch (Exception)
                    {
                        // Ignore any exceptions when polling
                    }
                }
            }
            if ((now = Stopwatch.GetTimestamp()) < delayEnd)
            {
                Thread.Sleep((int)TimestampDiff(delayEnd, now).TotalMilliseconds);
            }

            return(new ConstraintResult(this, actual, BaseConstraint.ApplyTo(actual).IsSuccess));
        }
Exemple #20
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for if the base constraint fails, false if it succeeds</returns>
        protected override ConstraintResult ApplyConstraint <T>(T actual)
        {
            var baseResult = BaseConstraint.ApplyTo(actual);

            return(new ConstraintResult(this, baseResult.ActualValue, !baseResult.IsSuccess));
        }
Exemple #21
0
        /// <summary>
        /// Test whether the constraint is satisfied by a given value
        /// </summary>
        /// <param name="actual">The value to be tested</param>
        /// <returns>True for if the base constraint fails, false if it succeeds</returns>
        public override ConstraintResult ApplyTo <TActual>(TActual actual)
        {
            var baseResult = BaseConstraint.ApplyTo(actual);

            return(new ConstraintResult(this, baseResult.ActualValue, !baseResult.IsSuccess));
        }