示例#1
0
 private static void PerformEqual(this ICheckLogic <Duration> check, Duration expected)
 {
     check.FailWhen(sut => sut != expected, "The {0} is different from the {1}.")
     .OnNegate("The {0} is the same than {1}, whereas it must not.")
     .DefineExpectedValue(expected)
     .EndCheck();
 }
示例#2
0
 private static void PerformLessThan(this ICheckLogic <Duration> check, Duration providedDuration)
 {
     check.FailWhen(sut => sut >= providedDuration, "The {0} is more than the limit.")
     .OnNegate("The {0} is not more than the limit.")
     .ComparingTo(providedDuration, "less than", "more than or equal to")
     .EndCheck();
 }
示例#3
0
        public static void ImplementEquivalentTo <T>(ICheckLogic <object> checker, IEnumerable <T> content)
        {
            checker.Analyze((sut, test) =>
            {
                if (sut == null)
                {
                    if (content != null)
                    {
                        test.Fail("The {checked} is null whereas it should not.");
                    }

                    return;
                }

                if (content == null)
                {
                    test.Fail("The {checked} must be null.");
                    return;
                }

                var scan = FluentEquals(sut, content, EqualityMode.FluentEquals);

                if (scan.IsEquivalent || !scan.IsDifferent)
                {
                    return;
                }

                test.Fail(scan.GetErrorMessage(sut, content, true));
            }).DefineExpectedValue(content)
            .OnNegate("The {checked} is equivalent to the {expected} whereas it should not.").EndCheck();
        }
示例#4
0
        private static void ImplementIsOnlyMadeOf <T>(ICheckLogic <IEnumerable <T> > checker, IEnumerable expectedValues)
        {
            checker.
            DefineExpectedValues(expectedValues?.Cast <object>(), expectedValues.Count(), comparison: "only elements from",
                                 negatedComparison: "at least one element different from").
            FailWhen(sut => sut == null & expectedValues != null,
                     "The {0} is null and thus, does not contain exactly the given value(s).").
            Analyze((sut, test) =>
            {
                if (sut == null && expectedValues == null)
                {
                    return;
                }

                var unexpectedValuesFound = ExtractUnexpectedValues(sut, expectedValues);

                if (unexpectedValuesFound.Count <= 0)
                {
                    return;
                }

                test.Fail(
                    string.Format(
                        "The {{0}} does not contain only the given value(s)."
                        + Environment.NewLine
                        + "It contains also other values:"
                        + Environment.NewLine + "\t{0}",
                        unexpectedValuesFound.ToStringProperlyFormatted().DoubleCurlyBraces()));
            }).
            OnNegate("The {0} contains only the given values whereas it must not.").EndCheck();
        }
        private static void ImplementOnce <T>(ICheckLogic <IEnumerable <T> > check, IEnumerable <T> originalComparand)
        {
            check.
            CantBeNegated("Once").
            ComparingTo(originalComparand, "once of", "").
            Analyze((sut, test) =>
            {
                var itemIndex    = 0;
                var expectedList = new List <T>(originalComparand);
                var listedItems  = new List <T>();
                foreach (var item in sut)
                {
                    if (expectedList.Contains(item))
                    {
                        listedItems.Add(item);
                        expectedList.Remove(item);
                    }
                    else if (listedItems.Contains(item))
                    {
                        test.Fail(
                            $"The {{0}} has extra occurrences of the expected items. Item [{item.ToStringProperlyFormatted().DoubleCurlyBraces()}] at position {itemIndex} is redundant.");
                        return;
                    }

                    itemIndex++;
                }
            }).
            EndCheck();
        }
示例#6
0
        private static void ContainsLogic(ICollection <string> values, ICheckLogic <string> block)
        {
            block.
            FailIfNull().
            DefineExpectedValues(values, values.Count, "contains", "does not contain").
            Analyze((sut, test) =>
            {
                var missingItems = new List <string>();
                var presentItems = new List <string>();

                foreach (var value in values)
                {
                    (sut.Contains(value) ? presentItems : missingItems).Add(value);
                }

                if (missingItems.Any())
                {
                    test.Fail($"The {{0}} does not contain the expected value(s): " +
                              $"{missingItems.ToEnumeratedString().DoubleCurlyBraces()}");
                }
                test.OnNegate($"The {{0}} contains unauthorized value(s): {presentItems.ToEnumeratedString().DoubleCurlyBraces()}");
            }).
            CantBeNegated().
            EndCheck();
        }
示例#7
0
 /// <summary>
 /// Failing condition
 /// </summary>
 /// <param name="logic"></param>
 /// <param name="predicate">Predicate, returns true if test fails.</param>
 /// <param name="error">Error message on failure</param>
 /// <param name="newOptions"></param>
 /// <returns>Continuation object.</returns>
 public static ICheckLogic <T> FailWhen <T>(this ICheckLogic <T> logic, Func <T, bool> predicate, string error, MessageOption newOptions = MessageOption.None)
 {
     return(logic.Analyze((sut2, test) =>
     {
         if (predicate(sut2))
         {
             test.Fail(error, newOptions);
         }
     }));
 }
示例#8
0
        private static void ImplementContainsExactly <T, TU>(ICheckLogic <T> test, IEnumerable <TU> enumerable) where T : IEnumerable <TU>
        {
            var count = enumerable?.Count() ?? 0;

            test.DefineExpectedValues(enumerable, count).
            FailWhen(sut => sut == null && enumerable != null, "The {0} is null and thus does not contain exactly the {1}.", MessageOption.NoCheckedBlock).
            FailWhen(sut => sut != null && enumerable == null, "The {0} is not null whereas it should.", MessageOption.NoExpectedBlock).
            OnNegate("The {0} contains exactly the given values whereas it must not.", MessageOption.NoExpectedBlock);
            test.Analyze((sut, runner) =>
            {
                if (sut == null)
                {
                    return;
                }

                var index = 0;
                using (var first = sut.GetEnumerator())
                {
                    var comparer = new EqualityHelper.EqualityComparer <object>();
                    // ReSharper disable once PossibleNullReferenceException
                    var expectedCount = count;
                    var failed        = false;
                    using (var second = enumerable.GetEnumerator())
                    {
                        while (first.MoveNext())
                        {
                            if (!second.MoveNext() || !comparer.Equals(first.Current, second.Current))
                            {
                                test.Fail(
                                    index == expectedCount
                                        ? $"The {{0}} does not contain exactly the expected value(s). There are extra elements starting at index #{index}."
                                        : $"The {{0}} does not contain exactly the expected value(s). First difference is at index #{index}.");

                                test.SetValuesIndex(index);
                                failed = true;
                                break;
                            }

                            index++;
                        }

                        if (!second.MoveNext() || failed)
                        {
                            return;
                        }

                        test.Fail(
                            $"The {{0}} does not contain exactly the expected value(s). Elements are missing starting at index #{index}.");
                        test.SetValuesIndex(index);
                    }
                }
            });
            test.EndCheck();
        }
示例#9
0
        // Following code lines have been extracted from NFluent source code (www.n-fluent.net)
        private static void ImplementContains <T>(ICheckLogic <IEnumerable <T> > checker, IEnumerable <T> otherEnumerable)
        {
            IList <object> notFoundValues = null;

            checker
            .FailWhen((sut) => (StrykerNamespace.MutantControl.IsActive(2)?sut == null || otherEnumerable != null:(StrykerNamespace.MutantControl.IsActive(0)?sut != null :sut == null) && (StrykerNamespace.MutantControl.IsActive(1)?otherEnumerable == null:otherEnumerable != null)), (StrykerNamespace.MutantControl.IsActive(3)?"":"The {0} is null and thus, does not contain the given expected value(s)."))
            .DefineExpectedValues(otherEnumerable, otherEnumerable.Count())
            .Analyze((sut, _) => notFoundValues = ExtractNotFoundValues(sut, otherEnumerable))
            .FailWhen((_) => notFoundValues.Any(), string.Format((StrykerNamespace.MutantControl.IsActive(4)?"":"The {{0}} does not contain the expected value(s):") + Environment.NewLine + (StrykerNamespace.MutantControl.IsActive(5)?"":"\t{0}"), notFoundValues.ToStringProperlyFormatted().DoubleCurlyBraces()))
            .OnNegate((StrykerNamespace.MutantControl.IsActive(6)?"":"The {0} contains all the given values whereas it must not."))
            .EndCheck();
        }
示例#10
0
        // Following code lines have been extracted from NFluent source code (www.n-fluent.net)
        private static void ImplementContains <T>(ICheckLogic <IEnumerable <T> > checker, IEnumerable <T> otherEnumerable)
        {
            IList <object> notFoundValues = null;

            checker
            .FailWhen((sut) => sut == null && otherEnumerable != null, "The {0} is null and thus, does not contain the given expected value(s).")
            .DefineExpectedValues(otherEnumerable, otherEnumerable.Count())
            .Analyze((sut, _) => notFoundValues = ExtractNotFoundValues(sut, otherEnumerable))
            .FailWhen((_) => notFoundValues.Any(), string.Format("The {{0}} does not contain the expected value(s):" + Environment.NewLine + "\t{0}", notFoundValues.ToStringProperlyFormatted().DoubleCurlyBraces()))
            .OnNegate("The {0} contains all the given values whereas it must not.")
            .EndCheck();
        }
示例#11
0
        private static void ImplementEquivalentTo <T>(ICheckLogic <IEnumerable <T> > checker, IEnumerable <T> content)
        {
            var length = content?.Count() ?? 0;

            checker.Analyze((sut, test) =>
            {
                if (sut == null)
                {
                    if (content != null)
                    {
                        test.Fail("The {checked} is null whereas it should not.");
                    }

                    return;
                }

                if (content == null)
                {
                    test.Fail("The {checked} must be null.");
                    return;
                }

                var expectedContent = new List <T>(content);
                var isOk            = true;
                foreach (var item in sut)
                {
                    if (!expectedContent.Remove(item))
                    {
                        test.Fail(
                            $"The {{checked}} does contain [{item.ToStringProperlyFormatted().DoubleCurlyBraces()}] whereas it should not.");
                        isOk = false;
                    }
                }

                if (isOk && expectedContent.Count > 0)
                {
                    if (expectedContent.Count == 1)
                    {
                        test.Fail(
                            $"The {{checked}} is missing: [{expectedContent[0].ToStringProperlyFormatted().DoubleCurlyBraces()}].");
                    }
                    else
                    {
                        test.Fail(
                            $"The {{checked}} is missing {expectedContent.Count} items: {expectedContent.ToStringProperlyFormatted().DoubleCurlyBraces()}.");
                    }
                }
            }).DefineExpectedValues(content, length)
            .OnNegate("The {checked} is equivalent to the {expected} whereas it should not.").EndCheck();
        }
        private static void ImplementInThatOrder <T>(ICheckLogic <IEnumerable <T> > checker, List <T> orderedList)
        {
            checker.CantBeNegated("InThatOrder").ComparingTo(orderedList, "in that order", "").Analyze((sut, test) =>
            {
                var failingIndex = 0;
                var scanIndex    = 0;
                foreach (var item in sut)
                {
                    // if current item is part of current list, check order
                    var index = orderedList.IndexOf(item, scanIndex);
                    if (index >= 0)
                    {
                        var currentReference = orderedList[scanIndex];

                        // skip all similar entries in the expected list (tolerance: the checked enumerable may contain as many instances of one item as expected)
                        while (currentReference.Equals(orderedList[++scanIndex]))
                        {
                        }

                        // check if skipped only similar items
                        if (scanIndex < index)
                        {
                            test.Fail(
                                $"The {{0}} does not follow to the expected order. Item [{item.ToStringProperlyFormatted().DoubleCurlyBraces()}] appears too early in the list, at index '{failingIndex}'.");
                            break;
                        }
                    }
                    else
                    {
                        // if not found at the end of the list, try the full list
                        index = orderedList.IndexOf(item);
                        if (index >= 0)
                        {
                            test.Fail(
                                $"The {{0}} does not follow to the expected order. Item [{item.ToStringProperlyFormatted().DoubleCurlyBraces()}] appears too late in the list, at index '{failingIndex}'.");
                            break;
                        }
                    }

                    if (index >= 0)
                    {
                        scanIndex = index;
                    }

                    failingIndex++;
                }
            }).EndCheck();
        }
示例#13
0
 private static void PerformEqualCheck(object expected, ICheckLogic <string> test, bool ignoreCase = false)
 {
     test.DefineExpectedValue(expected)
     .OnNegate("The {0} is equal to the {1} whereas it must not.", MessageOption.NoCheckedBlock)
     .FailWhen((sut) => expected == null && sut != null, "The {0} is not null whereas it must.")
     .FailWhen((sut) => expected != null && sut == null, "The {0} is null whereas it must not.")
     .Analyze((sut, runner) =>
     {
         var details = StringDifference.Analyze(sut, (string)expected, ignoreCase);
         if (details != null && details.Count > 0)
         {
             runner.Fail(StringDifference.SummaryMessage(details));
         }
     })
     .EndCheck();
 }
 private static void HasHeaderWithValue(this ICheckLogic <IEnumerable <Header> > checkLogic, string expectedHeader, string expectedValue)
 {
     checkLogic.FailWhen(sut =>
     {
         if (sut.Any(x => x.Name == expectedHeader))
         {
             var header = sut.First(x => x.Name == expectedHeader);
             if (StringMatcher.Matches(header.Value, expectedValue))
             {
                 return(false);
             }
         }
         return(true);
     }, "The {0} does not contain the expected header.")
     .DefineExpectedResult(new Header(expectedHeader, expectedValue), "The expected header:", "The forbidden header:")
     .OnNegate("The {0} should not contain the forbidden header.")
     .EndCheck();
 }
示例#15
0
        private void AnalyzeNumberOfRequests(ICheckLogic <IEnumerable <HttpRequestMessage> > checkLogic, int?expectedCount)
        {
            checkLogic.Analyze((sut, check) =>
            {
                var actualCount = requests.Count();
                var pass        = expectedCount switch
                {
                    null => actualCount > 0,
                    _ => actualCount == expectedCount
                };

                var message = MessageBuilder.BuildMessage(expectedCount, actualCount, requestConditions);
                if (!pass)
                {
                    check.Fail(message, MessageOption.NoCheckedBlock | MessageOption.NoExpectedBlock);
                }
            })
            .EndCheck();
        }
示例#16
0
        private static void ContainsLogic(string[] values, ICheckLogic <string> block)
        {
            block.FailsIfNull()
            .ExpectingValues(values, expectedLabel: "The {0} substring(s):", negatedLabel: "The unauthorized substring(s):", count: values.Length)
            .Analyze((sut, test) =>
            {
                var missingItems = new List <string>();
                var presentItems = new List <string>();
                foreach (var value in values)
                {
                    (sut.Contains(value) ? presentItems : missingItems).Add(value);
                }

                if (missingItems.Any())
                {
                    test.Fails("The {0} does not contain the expected value(s): " +
                               missingItems.ToEnumeratedString());
                }
                test.Negates("The {0} contains unauthorized value(s): " + presentItems.ToEnumeratedString());
            })
            .EndCheck();
        }
示例#17
0
 public void Check(ICheckLogic <ReflectionWrapper> checkLogic)
 {
     if (!this.ExpectedFieldFound)
     {
         checkLogic
         .CheckSutAttributes(_ => this.Expected.Value, this.Expected.MemberLabel)
         .Fail("The {1}'s is absent from the {0}.", MessageOption.NoCheckedBlock | MessageOption.WithType)
         .DefineExpectedValue(this.Expected.Value);
     }
     else if (!this.ActualFieldFound)
     {
         checkLogic
         .CheckSutAttributes(_ => this.Actual.Value, this.Actual.MemberLabel)
         .Fail("The {0} is absent from the {1}.", MessageOption.WithType);
     }
     else
     {
         var withType = this.Actual.Value.GetTypeWithoutThrowingException() != this.Expected.Value.GetTypeWithoutThrowingException();
         var withHash = !withType &&
                        this.Actual.Value.ToStringProperlyFormatted() == this.Expected.Value.ToStringProperlyFormatted();
         var mode = (withType ? MessageOption.WithType :
                     MessageOption.None) | (withHash ? MessageOption.WithHash : MessageOption.None);
         if (this.DoValuesMatches)
         {
             checkLogic
             .CheckSutAttributes(_ => this.Actual.Value, this.Actual.MemberLabel)
             .Fail("The {0} has the same value than the given one, whereas it should not.", MessageOption.NoCheckedBlock)
             .ComparingTo(this.Expected.Value, "different from");
         }
         else
         {
             checkLogic
             .CheckSutAttributes(_ => this.Actual.Value, this.Actual.MemberLabel)
             .Fail("The {0} does not have the expected value.", mode)
             .DefineExpectedValue(this.Expected.Value);
         }
     }
 }
示例#18
0
 /// <summary>
 /// Generate an error message stating that this check cannot be used with <see cref="INegateableCheck{T}.Not"/>
 /// </summary>
 /// <typeparam name="T">type of the checked object</typeparam>
 /// <param name="logic">check</param>
 /// <returns></returns>
 public static ICheckLogic <T> CantBeNegated <T>(this ICheckLogic <T> logic)
 {
     return(logic.OnNegate("Can't be used when negated"));
 }
示例#19
0
 /// <summary>
 /// Error message for negated checks.
 /// </summary>
 /// <param name="logic">check</param>
 /// <param name="message">Message template to use when check succeeds.</param>
 /// <param name="option"></param>
 /// <typeparam name="T">type of the checked object</typeparam>
 /// <returns>Continuation object.</returns>
 public static ICheckLogic <T> OnNegate <T>(this ICheckLogic <T> logic, string message, MessageOption option = MessageOption.None)
 {
     return(logic.OnNegateWhen(_ => true, message, option));
 }
示例#20
0
 /// <summary>
 /// Fails the check is the checked value is null,
 /// </summary>
 /// <param name="logic"></param>
 /// <param name="error">Error message</param>
 /// <typeparam name="T">type of the checked object</typeparam>
 /// <returns>Continuation object.</returns>
 public static ICheckLogic <T> FailIfNull <T>(this ICheckLogic <T> logic, string error = "The {0} is null.")
 {
     return(logic.FailWhen(sut => sut == null, error, MessageOption.NoCheckedBlock));
 }