Пример #1
0
        public void Verify_WhenAssertionFuncReturnsNull_DoesNotSubmitAnyFailures()
        {
            var failures = AssertionHelper.Eval(() =>
            {
                AssertionHelper.Verify(() => null);
            });

            Assert.IsEmpty(failures);
        }
Пример #2
0
        public void Fail_WhenFailureIsNull_DoesNothing()
        {
            var failures = AssertionHelper.Eval(() =>
            {
                AssertionHelper.Fail(null);
            });

            Assert.IsEmpty(failures);
        }
Пример #3
0
 public override void OnSave()
 {
     if (Validatable.IsAlreadyPersisted())
     {
         AssertionHelper
         .AssertAny(ADORepository.Entities <T>().Is(Validatable))
         .Return("Сохранение невозможно. Вы пытаетесь сохранить сущность, которая уже была удалена");
     }
 }
Пример #4
0
        public void Fail_WhenFailureIsNotNull_SubmitsTheFailure()
        {
            var failure  = new AssertionFailureBuilder("Boom").ToAssertionFailure();
            var failures = AssertionHelper.Eval(() =>
            {
                AssertionHelper.Fail(failure);
            });

            Assert.AreElementsEqual(new[] { failure }, failures);
        }
Пример #5
0
 /// <summary>
 /// Asserts that the collection of distinct instances specified by the user is not empty.
 /// </summary>
 protected void AssertDistinctIntancesNotEmpty()
 {
     AssertionHelper.Explain(() =>
                             Assert.GreaterThan(DistinctInstances.Instances.Count, 0),
                             innerFailures => new AssertionFailureBuilder("Expected the collection of distinct instances to be not empty.\n" +
                                                                          "Please feed the 'DistinctInstances' property of your collection contract with some valid objects.")
                             .SetStackTrace(Context.GetStackTraceData())
                             .AddInnerFailures(innerFailures)
                             .ToAssertionFailure());
 }
        public async Task Sync_LoadTest_TwoWay()
        {
            CreateRandomHobbies(out var sourceDictionary, out var destinationDictionary);

            await CreateSyncAgent(sourceDictionary, destinationDictionary)
            .Configure((c) => c.SyncMode.SyncModePreset = SyncModePreset.TwoWay)
            .SyncAsync(CancellationToken.None).ConfigureAwait(false);

            AssertionHelper.VerifyDictionariesAreEquivalent(sourceDictionary, destinationDictionary);
        }
Пример #7
0
        public void Verify_WhenAssertionFuncReturnsNonNull_SubmitsTheFailure()
        {
            var failure  = new AssertionFailureBuilder("Boom").ToAssertionFailure();
            var failures = AssertionHelper.Eval(() =>
            {
                AssertionHelper.Verify(() => failure);
            });

            Assert.AreElementsEqual(new[] { failure }, failures);
        }
Пример #8
0
        public override void OnSave()
        {
            base.OnSave();

            //TODO: возможно это стоит переделать.

            AssertionHelper
            .AssertIsNotEmpty(Validatable.Login)
            .Return("UserName", "Имя пользователя должно быть задано.");
        }
Пример #9
0
 private void AssertCopyToNotThrowException(Action action, string failureMessage)
 {
     AssertionHelper.Explain(() =>
                             Assert.DoesNotThrow(() => action()),
                             innerFailures => new AssertionFailureBuilder(failureMessage)
                             .AddLabeledValue("Method", "CopyTo")
                             .SetStackTrace(Context.GetStackTraceData())
                             .AddInnerFailures(innerFailures)
                             .ToAssertionFailure());
 }
Пример #10
0
 public void TestSingleAssertionSuccess_DoNotThrowException()
 {
     Assert.DoesNotThrow(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             a.Add(true);
         });
     });
 }
Пример #11
0
 public void TestNoAssertion_DoNotThrowException()
 {
     Assert.DoesNotThrow(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             // no exception
         });
     });
 }
        public void ThenTheModifiedOfShouldBeModified(string field, string objectKey, string expectedValueKey)
        {
            var    expectedValue = m_scenarioContext.Get <object>(expectedValueKey);
            object actualValue   = TransformerHelper.GetActualValue(m_scenarioContext, field, objectKey);

            string expectedValueFixed = Regex.Replace(expectedValue.ToString(), @"\s+", string.Empty);
            string actualValueFixed   = Regex.Replace(actualValue.ToString(), @"\s+", string.Empty);

            AssertionHelper.AssertStrings(actualValueFixed, expectedValueFixed);
        }
Пример #13
0
 public void TestSingleAssertionFails_ThrowsException()
 {
     Assert.Throws <MultiException>(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             a.Add(false);
         });
     });
 }
        public async Task Sync_LoadTest_TwoWay_String()
        {
            CreateRandomStringLists(out var sourceItems, out var destinationItems);

            await CreateSyncAgent(sourceItems, destinationItems)
            .Configure((c) => c.SyncMode.SyncModePreset = SyncModePreset.TwoWay)
            .SyncAsync(CancellationToken.None).ConfigureAwait(false);

            AssertionHelper.VerifySortedSetsAreEquivalent(sourceItems, destinationItems);
        }
Пример #15
0
        public override void OnDelete()
        {
            AssertionHelper
            .AssertFalse(Validatable.IsNewEntry())
            .Return("Удаление невозможно. Вы пытаетесь удалить еще не сохраненную сущность.");

            AssertionHelper
            .AssertAny(ADORepository.Entities <T>().Is(Validatable))
            .Return("Удаление невозможно. Вы пытаетесь удалить сущность, которая уже была удалена.");
        }
Пример #16
0
 public void TestAnyOfMultiAssertionsFails_ThrowsException()
 {
     Assert.Throws <MultiException>(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             a.Add(true);
             a.Add(() => false);
         });
     });
 }
Пример #17
0
 public void TestMultiAssertionsSuccess_DoNotThrowException()
 {
     Assert.DoesNotThrow(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             a.Add(true);
             a.Add(() => true);
         });
     });
 }
Пример #18
0
        /// <summary>
        /// .ItReturns(x => x.Exception);
        /// </summary>
        public static IAssert <TSubject, TResult, TVars, TSequence> ItReturns <TSubject, TResult, TVars, TSequence> (
            this IAssert <TSubject, TResult, TVars, TSequence> assert,
            Expression <Func <TVars, TResult> > resultProvider)
        {
            var controller = assert.GetTestController();

            controller.AddAssertion(
                "Returns " + resultProvider,
                x => AssertionHelper.AssertObjectEquals("Result", resultProvider.Compile()(x.Vars), x.Result));
            return(assert);
        }
Пример #19
0
        public void VerlaadBeurtAanvragen(Guid?schipId, DateTime datum, string bijzonderheden)
        {
            AssertionHelper.AssertFieldIsNotNullOrDefault(datum, nameof(datum));

            VerlaadBeurt = new VerlaadBeurt
            {
                SchipId        = schipId,
                Datum          = datum,
                Bijzonderheden = bijzonderheden
            };
        }
Пример #20
0
        public BaseNamedEntity SetName(String name)
        {
            if (_name == "start")
            {
                throw AssertionHelper.Fail();
            }

            _nameProvider = null;
            _name         = name;
            return(this);
        }
Пример #21
0
 public void TestAnyOfMultiAssertionsFails_ButNoThrowFlag_DoNoThrowException()
 {
     Assert.DoesNotThrow(() =>
     {
         AssertionHelper.DoAssert(a =>
         {
             a.Add(true);
             a.Add(() => false);
         }, false);
     });
 }
Пример #22
0
        /// <summary>
        /// Verifies that a particular condition holds true.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If the condition evaluates to false, the assertion failure message will
        /// describe in detail the intermediate value of relevant sub-expressions within
        /// the condition.  Consequently the assertion failure will include more diagnostic
        /// information than if <see cref="Assert.IsTrue(bool, string, object[])" /> were used instead.
        /// </para>
        /// </remarks>
        /// <param name="condition">The conditional expression to evaluate.</param>
        /// <param name="messageFormat">The custom assertion message format, or null if none.</param>
        /// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
        /// <exception cref="ArgumentNullException">Thrown if <paramref name="condition"/> is null.</exception>
        /// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
        public static void That(Expression <System.Func <bool> > condition, string messageFormat, params object[] messageArgs)
        {
            if (condition == null)
            {
                throw new ArgumentNullException("condition");
            }

            AssertionFailure failure = AssertionConditionEvaluator.Eval(condition, true, messageFormat, messageArgs);

            AssertionHelper.Fail(failure);
        }
Пример #23
0
        public Snippet(
            SnippetAnnotationAnnotationAttribute annotationMetadata,
            Attribute assemblyAnnotation,
            Attribute typeAnnotation,
            Attribute methodAnnotation,
            T code)
        {
            AnnotationMetadata = annotationMetadata;
            AssemblyAnnotation = assemblyAnnotation;
            TypeAnnotation     = typeAnnotation;
            MemberAnnotation   = methodAnnotation;
            Member             = code;

            double acc;

            if (AnnotationMetadata.WeightAccumulationIsAdditive)
            {
                acc = 0.0;
                if (AssemblyAnnotation is WeightedAttribute)
                {
                    acc += ((WeightedAttribute)AssemblyAnnotation).Weight;
                }
                if (TypeAnnotation is WeightedAttribute)
                {
                    acc += ((WeightedAttribute)TypeAnnotation).Weight;
                }
                if (MemberAnnotation is WeightedAttribute)
                {
                    acc += ((WeightedAttribute)MemberAnnotation).Weight;
                }
            }
            else if (AnnotationMetadata.WeightAccumulationIsMultiplicative)
            {
                acc = 1.0;
                if (AssemblyAnnotation is WeightedAttribute)
                {
                    acc *= ((WeightedAttribute)AssemblyAnnotation).Weight;
                }
                if (TypeAnnotation is WeightedAttribute)
                {
                    acc *= ((WeightedAttribute)TypeAnnotation).Weight;
                }
                if (MemberAnnotation is WeightedAttribute)
                {
                    acc *= ((WeightedAttribute)MemberAnnotation).Weight;
                }
            }
            else
            {
                throw AssertionHelper.Fail();
            }

            Weight = acc;
        }
Пример #24
0
        public Layout this[Ref @ref]
        {
            get
            {
                @ref.AssertNotNull();
                var local = @ref.Sym.AssertCast <Local>();

                return(_locals_cache.GetOrCreate(local, () =>
                {
                    var t = @ref.Type();
                    if (_scheme[@ref] == MemoryTier.Private)
                    {
                        if (t.IsArray)
                        {
                            throw AssertionHelper.Fail();
                        }
                        else
                        {
                            (t.IsCudaPrimitive() || t.IsCudaVector()).AssertTrue();
                            var slot = new Reg {
                                Type = @ref.Type(), Name = @ref.Sym.Name
                            };
                            return new SlotLayout(@ref, slot);
                        }
                    }
                    else if (_scheme[@ref] == MemoryTier.Shared)
                    {
                        if (t.IsArray)
                        {
                            throw AssertionHelper.Fail();
                        }
                        else
                        {
                            throw AssertionHelper.Fail();
                        }
                    }
                    else if (_scheme[@ref] == MemoryTier.Global)
                    {
                        if (t.IsArray)
                        {
                            throw AssertionHelper.Fail();
                        }
                        else
                        {
                            throw AssertionHelper.Fail();
                        }
                    }
                    else
                    {
                        throw AssertionHelper.Fail();
                    }
                }));
            }
        }
Пример #25
0
 public override void UndoImpl()
 {
     try
     {
         DoImpl();
     }
     catch (ValidationException)
     {
         AssertionHelper.Fail();
     }
 }
Пример #26
0
 public static MethodInfo GetFunctionSignature(this Type t)
 {
     t.IsFType().AssertTrue();
     if (t.IsDelegate())
     {
         return(t.GetMethod("Invoke"));
     }
     else
     {
         throw AssertionHelper.Fail();
     }
 }
Пример #27
0
 private void AssertCopyToThrowException(Action action, string failureMessage, string label, object value)
 {
     AssertionHelper.Explain(() =>
                             Assert.Throws <Exception>(() => action()),
                             innerFailures => new AssertionFailureBuilder(
                                 "Expected the method to throw an exception " + failureMessage)
                             .AddLabeledValue("Method", "CopyTo")
                             .AddRawLabeledValue(label, value)
                             .SetStackTrace(Context.GetStackTraceData())
                             .AddInnerFailures(innerFailures)
                             .ToAssertionFailure());
 }
Пример #28
0
 protected int Dim(int dim)
 {
     if (dim == 0)
     {
         return(_height);
     }
     if (dim == 1)
     {
         return(_width);
     }
     throw AssertionHelper.Fail();
 }
Пример #29
0
        public void Validate(AbstractUser user, string password)
        {
            var source = user != null && user.PasswordHash == password.ComputeSHA256Hash();

            AssertionHelper
            .AssertTrue(source)
            .Return("Login", "Логин или пароль пользователя введен некорректно.");

            AssertionHelper
            .AssertTrue(user.Enabled)
            .Return("Login", "Пользователь с указанным логином не активен.");
        }
Пример #30
0
        /// <summary>
        /// Verifies that the sequence of values are sorted in the specified order.
        /// </summary>
        /// <typeparam name="T">The type of value.</typeparam>
        /// <param name="values">The sequence of values to be tested.</param>
        /// <param name="sortOrder">The expected sort order.</param>
        /// <param name="comparer">A comparison function to be used to compare two elements of the sequence, or null to use a default one.</param>
        /// <param name="messageFormat">The custom assertion message format, or null if none.</param>
        /// <param name="messageArgs">The custom assertion message arguments, or null if none.</param>
        /// <exception cref="AssertionException">Thrown if the verification failed unless the current <see cref="AssertionContext.AssertionFailureBehavior" /> indicates otherwise.</exception>
        public static void Sorted <T>(IEnumerable <T> values, SortOrder sortOrder, Comparison <T> comparer, string messageFormat, params object[] messageArgs)
        {
            AssertionHelper.Verify(() =>
            {
                bool first   = true;
                var previous = default(T);
                var sortInfo = SortOrderInfo.FromSortOrder(sortOrder);
                int delta;
                int index = 0;

                if (comparer == null)
                {
                    comparer = ComparisonSemantics.Default.Compare;
                }

                foreach (T value in values)
                {
                    if (!first)
                    {
                        try
                        {
                            delta = comparer(value, previous);
                        }
                        catch (InvalidOperationException exception)
                        {
                            return(new AssertionFailureBuilder(
                                       "Expected the elements to be sorted in a specific order but no implicit ordering comparison can be found for the subject type.")
                                   .SetMessage(messageFormat, messageArgs)
                                   .AddRawLabeledValue("Type", typeof(T))
                                   .AddException(exception)
                                   .ToAssertionFailure());
                        }

                        if (!sortInfo.VerifyDeltaSign(delta))
                        {
                            return(new AssertionFailureBuilder(
                                       "Expected the elements to be sorted in a specific order but the sequence of values mismatches at one position at least.")
                                   .SetMessage(messageFormat, messageArgs)
                                   .AddRawLabeledValue("Expected Sort Order", sortInfo.Description)
                                   .AddRawLabeledValue("Sequence", values)
                                   .AddRawLabeledValue("Failing Position", index)
                                   .ToAssertionFailure());
                        }
                    }

                    previous = value;
                    first    = false;
                    index++;
                }

                return(null);
            });
        }
Пример #31
0
        public static Result Error(string platform, string message, DateTime startTime, DateTime endTime)
        {
            var dummy =new AssertionHelper()
                {
                    Assert = new Assert(),
                    Log = new Log(),
                };

            dummy.Log.Write(message);

            return new Result(platform, ResultKind.Error, startTime, endTime, dummy);
        }