Exemplo n.º 1
0
            public void _1_1_5Product_AnyInputValues_Success()
            {
                var testable = new _1_1_5();

                Prop.ForAll <int, int>(
                    Arb.From <int>().Filter(x => x > 0 && x < Math.Pow(10, 6)),
                    Arb.From <int>().Filter(x => x > 0 && x < Math.Pow(10, 3)),
                    (a, b) =>
                {
                    var result = testable.Run(a, b);

                    Assert.That(result == a * b);
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 2
0
            public void Pow_AnyInputValues_Success()
            {
                var testable = new _1_1_3();

                Prop.ForAll <int, int>(
                    Arb.From <int>().Filter(x => x > 0 && x < 10),
                    Arb.From <int>().Filter(x => x > 0 && x < 10),
                    (a, n) =>
                {
                    var result = testable.Run(a, n);

                    Assert.That(result == Math.Pow(a, n));
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 3
0
        //public static Arbitrary<ITypeSelector[]> Selectors()
        //{
        //    return Gen.Sequence(Gen.Elements(AvailableSelectors)).ToArbitrary();
        //}

        public static Arbitrary <TypeTable> TypeTable()
        {
            Func <TypeTable> generator = () =>
            {
                var table     = new TypeTable(Faker.Generators.Booleans.Bool());
                var selectors = AvailableSelectors.GetRandomSelection(Generators.Numbers.Int(0, 10));
                foreach (var selector in selectors)
                {
                    table.AddSelector(selector);
                }
                return(table);
            };

            return(Arb.From(Gen.Fresh(generator)));
        }
Exemplo n.º 4
0
        public Property TestRoundTripBytes()
        {
            var arb =
                Arb.From <byte[]>().Filter(bytes => bytes.Length % 8 == 0);

            return(Prop.ForAll(
                       arb,
                       bytes =>
            {
                var words = Rfc1751.Encode(bytes);
                var result = Rfc1751.Decode(words, out var parityError);
                Assert.Equal(Base16.Encode(bytes), Base16.Encode(result.Span));
                Assert.False(parityError);
            }));
        }
Exemplo n.º 5
0
            public Arbitrary <TelemetryGen[]> Array()
            {
                var arrayGen = Telemetry().Generator.ArrayOf();
                var arrayArb = Arb.From(arrayGen, ShrinkArray);

                IEnumerable <TelemetryGen[]> ShrinkArray(TelemetryGen[] array)
                {
                    var shrunkInstances = array.Select(y => Telemetry().Shrinker(y).ToArray());
                    var shrunkArray     = Arb.Default.NonEmptyArray <TelemetryGen>().Shrinker(NonEmptyArray <TelemetryGen> .NewNonEmptyArray(array)).Select(y => y.Item);

                    return(shrunkInstances.Concat(shrunkArray));
                }

                return(arrayArb);
            }
Exemplo n.º 6
0
            public void PropertyCombine_AnyInputValues_DifferenceShouldBeConstantForAllValues()
            {
                var testable = new _2_1_2();

                Prop.ForAll <int, int>(Arb.From <int>().Filter(x => x > 0 && x < 5), Arb.From <int>().Filter(x => x > 0 && x < 10),
                                       (k, n) =>
                {
                    var init = Enumerable.Range(0, k).Select(x => 0).ToArray();
                    var last = Enumerable.Range(0, k).Select(x => n).ToArray();

                    var result = testable.Run(k, n);

                    Assert.That(result.First().SequenceEqual(init));
                    Assert.That(result.Last().SequenceEqual(last));
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 7
0
 public Property TestRoundTrip()
 {
     return(Prop.ForAll(
                Arb.From <byte[]>(),
                bytes =>
     {
         var base58 = Base58Check.ConvertTo(bytes);
         // Oversize the buffer
         var result = new byte[bytes.Length + 8];
         var count = Base58Check.ConvertFrom(base58, result);
         // trim to decoded size
         result = result.AsSpan().Slice(0, count).ToArray();
         Assert.Equal(bytes.Length, count);
         Assert.Equal(bytes, result);
     }));
 }
Exemplo n.º 8
0
            public void PropertyCombine_AnyInputValues_AnalogAndMainSolutionShouldBeEqual()
            {
                var testable = new _2_1_1();

                Prop.ForAll(Arb.From <int>().Filter(x => x > 0 && x < 5), Arb.From <int>().Filter(x => x > 0 && x < 10),
                            (k, n) =>
                {
                    var result       = testable.Run(k, n).Select(x => x.ToList()).ToList();
                    var analogResult = testable.SimpleAnalog(k, n);

                    for (var i = 0; i < result.Count; i++)
                    {
                        Assert.That(result[i].SequenceEqual(analogResult[i]));
                    }
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 9
0
        public void Getting_all_values_or_none_from_an_enumerable_of_nullables_should_yield_None_for_an_empty_one_or_if_any_value_is_null()
        {
            var options = Arb.From <int?[]>()
                          .Convert(
                xs => xs.Select(x => Option.From <int?>(x)),
                ys => ys.Select(o => o.GetOrElse(default(int?))).ToArray());

            ForAll(options, xs => {
                var sut = xs.AllOrNone();

                return(xs.Count() == 0 || xs.Any(x => !x.IsSome)
                    ? sut.Equals(Option.None)
                    : sut.Get().SequenceEqual(xs.Select(o => o.Where(x => x.HasValue).Select(x => x.Value).Get())));
            })
            .QuickCheckThrowOnFailure();
        }
Exemplo n.º 10
0
            public void _1_1_9_AnyInputValues_Success()
            {
                var testable = new _1_1_9();

                Prop.ForAll(
                    Arb.From <int>().Filter(x => x > 0 && x < Math.Pow(10, 5)),
                    n =>
                {
                    var arr = Enumerable.Range(0, n + 1).Select(x => (int?)null).ToList();
                    var f   = testable.Run(n);
                    //var fr = testable.Rec(n, arr);
                    var fr = testable.Rec1(n, 0, 0, 0);

                    Assert.That(f == fr);
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 11
0
        /// <summary>
        /// Allows FsCheck to randomly generate byte[] instances divisible by 4
        /// </summary>
        public static Arbitrary <Mod4Binary> Mod4Binary()
        {
            // Mod4Binary encapsulates the following domain rules
            Func <Byte[], Boolean> isValid = (data) => (data != null) &&
                                             (data.Length > 0) &&
                                             (data.Length % 4 == 0);

            return(Arb.From(// generator
                       from data in Arb.Generate <Byte[]>()
                       where isValid(data)
                       select new Mod4Binary(data)
                       // shrinker
                       , (input) => from data in Arb.Shrink(input.Data)
                       where  isValid(data)
                       select new Mod4Binary(data)));
        }
Exemplo n.º 12
0
 public ExtractionBuilderTests()
 {
     _objGen = from d in Gen.Choose(0, int.MaxValue).Select(x => (double)x)
               from str in Arb.From <NonNull <string> >().Generator
               from i in Arb.From <int>().Generator
               from iArray in Arb.From <int[]>().Generator
               from floats in Arb.From <List <float> >().Generator
               select new ExtractionTestObject
     {
         StringTest    = str.Get,
         DoubleTest    = d,
         IntTest       = i,
         IntArrayTest  = iArray,
         FloatListTest = floats
     };
 }
Exemplo n.º 13
0
        public void ExactCoverProblemsWithNoSolutionsTest()
        {
            Func <int, string> makeLabel = numSolutions => string.Format(
                "Expected no solutions but got {0}",
                numSolutions);

            var arbMatrix = Arb.From(GenMatrixOfIntWithNoSolutions());

            var property = Prop.ForAll(arbMatrix, matrix =>
            {
                var solutions = new Dlx().Solve(matrix).ToList();
                return((!solutions.Any()).Label(makeLabel(solutions.Count())));
            });

            Check.One(Config, property);
        }
Exemplo n.º 14
0
        /// <summary>
        /// generates PositiveTime instances by leveraging FsCheck's
        /// built-in support for generating and shrinking TimeSpan instances
        /// </summary>
        /// <returns>an IArbitrary capable of producing PositiveTime instances</returns>
        public static Arbitrary <PositiveTime> PositiveTime()
        {
            bool IsPositive(Time value) => value > Time.Zero;

            return(Arb.From(
                       // generator
                       from t in Arb.Generate <Time>()
                       where IsPositive(t)
                       select new PositiveTime(t),
                       // shrinker
                       positive =>
                       from t in Arb.Shrink(positive.Value)
                       where IsPositive(t)
                       select new PositiveTime(t)
                       ));
        }
Exemplo n.º 15
0
        public override Property Post(PersonStore store, PersonStoreSimulator simulator)
        {
            var queries =
                from entity in Gen.Elements((IEnumerable <PersonEntity>)simulator.Persons)
                from nationalId in Gen.Elements(entity.RowKey, null, "750329709752307")
                from country in Gen.Elements(entity.PartitionKey, null, "India")
                from eyeColor in Gen.Elements(entity.EyeColor, null, "Red")
                where nationalId != null || country != null || eyeColor != null
                select(nationalId, country, eyeColor);

            return(Prop.ForAll(Arb.From(queries), query =>
                               SearchResultsAreEquivalent(
                                   store.Search(query.nationalId, query.country, query.eyeColor).Result,
                                   simulator.Search(query.nationalId, query.country, query.eyeColor).Result
                                   )
                               ));
        }
Exemplo n.º 16
0
        /// <summary>
        /// Allows FsCheck to randomly generate fszmq.Message instances
        /// </summary>
        public static Arbitrary <fszmq.Message> Message()
        {
            // Generates an empty fszmq.Message
            var empty = Gen.Constant(new fszmq.Message());

            // Generates a fszmq.Message with random content
            var random = from data in Arb.Generate <NonNull <Byte[]> >()
                         select new fszmq.Message(data.Get);

            // Creates a random distribution weighted in favor of messages with random content
            var distribution = Gen.Frequency(
                new WeightAndValue <GenMessage>(2, random)
                , new WeightAndValue <GenMessage>(1, empty)
                );

            return(Arb.From(distribution));
        }
Exemplo n.º 17
0
        public void ShinkerProperties()
        {
            var config    = Configuration.QuickThrowOnFailure;
            var sut       = new Concurrent <int, int, int>(() => 1, 3);
            var generator = Arb.From(sut.Generator(new Collection <ConcurrentCommand.Command <int, int> > {
                new IntSutIdentity()
            }), sut.Shrinker);

            Prop.ForAll(generator, testCase =>
            {
                var uniqeClients = MakeClientsUniqe(testCase);
                var shrunken     = sut.Shrinker(uniqeClients).ToList();
                var flatClients  = Flatten(uniqeClients);
                return(AllShunkenClientsElementOfOriginal(shrunken, flatClients)
                       .And(OnlyOneElementOfOriginalNotInShrunken(shrunken, flatClients)));
            }).Check(config);
        }
Exemplo n.º 18
0
            public void PropertyCombine_AnyInputValues_DifferenceShouldBeConstantForAllValues()
            {
                var testable = new _2_1_4();

                Prop.ForAll(
                    Arb.From <int>().Filter(x => x > 0 && x < 7),
                    k =>
                {
                    var result       = testable.Run(k).Select(x => x.ToList()).ToList();
                    var analogResult = testable.SimpleAnalog(k, 0);

                    for (var i = 0; i < result.Count; i++)
                    {
                        Assert.That(result[i].SequenceEqual(analogResult[i]));
                    }
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 19
0
        private static Property TestRelialityForEnabledFlag(
            bool isEnabled,
            int retryCount,
            TimeSpan retryInterval,
            Func <ReceivingProcessingMode, RetryReliability> getReliability,
            Action <ReceivingProcessingMode> extraFixtureSetup = null)
        {
            return(Prop.ForAll(
                       Gen.Frequency(
                           Tuple.Create(2, Gen.Constant(retryInterval.ToString())),
                           Tuple.Create(1, Arb.From <string>().Generator))
                       .ToArbitrary(),
                       retryIntervalText =>
            {
                // Arrange
                ReceivingProcessingMode pmode = CreateValidPMode();
                RetryReliability r = getReliability(pmode);
                r.IsEnabled = isEnabled;
                r.RetryCount = retryCount;
                r.RetryInterval = retryIntervalText;
                extraFixtureSetup?.Invoke(pmode);

                // Act
                ValidationResult result = ReceivingProcessingModeValidator.Instance.Validate(pmode);

                // Assert
                bool correctConfigured =
                    retryCount > 0 &&
                    r.RetryInterval.AsTimeSpan() > default(TimeSpan);

                bool expected =
                    !isEnabled && !correctConfigured ||
                    !isEnabled ||
                    correctConfigured;

                return expected.Equals(result.IsValid)
                .Label(result.AppendValidationErrorsToErrorMessage(string.Empty))
                .Classify(result.IsValid, "Valid PMode")
                .Classify(!result.IsValid, "Invalid PMode")
                .Classify(correctConfigured, "Correct Reliability")
                .Classify(!correctConfigured, "Incorrect Reliability")
                .Classify(isEnabled, "Reliability is enabled")
                .Classify(!isEnabled, "Reliability is disabled");
            }));
        }
Exemplo n.º 20
0
        public static Arbitrary <Result <TOk, TError> > Result <TOk, TError>()
        {
            Gen <Result <TOk, TError> > ok = Arb
                                             .From <TOk>()
                                             .Generator
                                             .Select(Domain.Result <TOk, TError> .Ok);


            Gen <Result <TOk, TError> > error = Arb
                                                .From <TError>()
                                                .Generator
                                                .Select(Domain.Result <TOk, TError> .Error);

            return(Gen.Frequency(
                       Tuple.Create(1, ok),
                       Tuple.Create(1, error))
                   .ToArbitrary());
        }
Exemplo n.º 21
0
        public Property SimpleStringPropertyExtraction()
        {
            return(Prop.ForAll <ExtractionTestObject>(Arb.From(_objGen), testObject =>
            {
                const string extractionString = "StringTest";

                var expression = ExtractionExpressionBuilder
                                 .BuildExtractionExpression(
                    typeof(ExtractionTestObject),
                    extractionString
                    );
                var parameter = Expression.Parameter(typeof(ExtractionTestObject));
                var lambda = Expression.Lambda <Func <ExtractionTestObject, string> >(expression, parameter);
                var func = lambda.Compile();

                var result = func(testObject);
            }));
        }
Exemplo n.º 22
0
        public void ExactCoverProblemsWithSingleSolutionTest()
        {
            Func <int, string> makeLabel = numSolutions => string.Format(
                "Expected exactly one solution but got {0}",
                numSolutions);

            var arbMatrix = Arb.From(GenMatrixOfIntWithSingleSolution());

            var property = Prop.ForAll(arbMatrix, matrix =>
            {
                var solutions = new Dlx().Solve(matrix).ToList();
                var p1        = (solutions.Count() == 1).Label(makeLabel(solutions.Count()));
                var p2        = CheckSolutions(solutions, matrix);
                return(FsCheckUtils.And(p1, p2));
            });

            Check.One(Config, property);
        }
Exemplo n.º 23
0
        public static Arbitrary <Tuple <IByteBuf, ReadInstruction> > ChannelReads()
        {
            Func <IByteBuf, ReadMode, Tuple <IByteBuf, ReadInstruction> > producer = (buf, mode) =>
            {
                if (mode == ReadMode.Full)
                {
                    return(new Tuple <IByteBuf, ReadInstruction>(buf,
                                                                 new ReadInstruction(mode, buf.ReadableBytes, buf.ReadableBytes)));
                }
                var partialBytesToRead = ThreadLocalRandom.Current.Next(1, buf.ReadableBytes - 1);
                // TODO: find a way to use Gen here
                return(new Tuple <IByteBuf, ReadInstruction>(buf,
                                                             new ReadInstruction(mode, partialBytesToRead, buf.ReadableBytes)));
            };
            var fsFunc = Create(producer);

            return(Arb.From(Gen.Map2(fsFunc, BufferGenerators.ByteBuf().Generator, GenReadMode())));
        }
Exemplo n.º 24
0
            public void _1_1_7_AnyInputValues_Success()
            {
                var testable = new _1_1_7();

                Prop.ForAll(
                    Arb.From <int>().Filter(x => x > 0 && x < Math.Pow(10, 6)),
                    Arb.From <int>().Filter(x => x > 0 && x < Math.Pow(10, 6)),
                    (a, d) =>
                {
                    if (d > a)
                    {
                        d = a;
                    }

                    var(q, r) = testable.Run(a, d);

                    Assert.That(q == a / d && r == a % d);
                }).QuickCheckThrowOnFailure();
            }
Exemplo n.º 25
0
        /// <summary>
        /// Allows FsCheck to randomly generate fszmq.Version instances
        /// </summary>
        public static Arbitrary <fszmq.Version> Version()
        {
            // Generates a version when the actual values are unknown
            var unknown = Gen.Constant(fszmq.Version.Unknown);
            // Generates a version from random known values
            var random = from data in Arb.Generate <NonNegativeInt>().Three()
                         let major                         = data.Item1.Item
                                                 let minor = data.Item2.Item
                                                             let revision = data.Item3.Item
                                                                            select fszmq.Version.NewVersion(major, minor, revision);


            // Creates a random distribution weighted in favor of version with random values
            var distribution = Gen.Frequency(
                new WeightAndValue <GenVersion>(2, random)
                , new WeightAndValue <GenVersion>(1, unknown)
                );

            return(Arb.From(distribution));
        }
Exemplo n.º 26
0
        public Property EqualsParties(NonEmptyString roleA, NonEmptyString roleB)
        {
            return(Prop.ForAll(
                       Gen.OneOf(
                           Arb.From <NonEmptyString>().Generator.Select(x => Tuple.Create(x, x)))
                       .Three()
                       .ToArbitrary(),
                       xs =>
            {
                (NonEmptyString idA, NonEmptyString idB) = xs.Item2;
                (NonEmptyString typeA, NonEmptyString typeB) = xs.Item3;

                var a = new Party(roleA.Get, new PartyId(idA.Get, typeA.Get));
                var b = new Party(roleB.Get, new PartyId(idB.Get, typeB.Get));

                var equalId = idA.Equals(idB);
                var equalType = typeA.Equals(typeB);

                return a.Equals(b) == (equalId && equalType);
            }));
        }
Exemplo n.º 27
0
            private Arbitrary <TelemetryGen> Telemetry()
            {
                Gen <int> ChooseInt(int min, int max)
                {
                    return(Arb.From(Gen.Choose(min, max)).Generator);
                }

                var gen =
                    from negMs in ChooseInt(0, MaxRandomMs)
                    from deviceId in ChooseInt(1, NumDevices)
                    from propertyId in ChooseInt(1, NumProperties)
                    select new TelemetryGen(negMs, deviceId, propertyId);

                var arb = Arb.From(gen, ShrinkTelemetryGen);

                IEnumerable <TelemetryGen> ShrinkTelemetryGen(TelemetryGen x)
                {
                    if (x.DevId != 1)
                    {
                        yield return(x.With(DevId: 1));
                    }

                    if (x.PropId != 1)
                    {
                        yield return(x.With(PropId: 1));
                    }

                    if (x.NegMs != 0)
                    {
                        yield return(x.With(NegMs: x.NegMs / 2));

                        yield return(x.With(NegMs: x.NegMs - 1));
                    }
                }

                return(arb);
            }
Exemplo n.º 28
0
        public static Arbitrary <IDictionary <string, string> > Model()
        {
            var tagOpeningChars =
                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
            var tagOtherChars =
                tagOpeningChars + "0123456789";

            Func <char, char[], string> merge = (first, rest) =>
            {
                var target = new char[rest.Length + 1];
                target[0] = first;
                Array.Copy(rest, 0, target, 1, rest.Length);
                return(new string(target));
            };

            var tagGen =
                from opening in
                Gen.Elements(tagOpeningChars.ToCharArray())
                from rest in
                Gen.ArrayOf(Gen.Elements(tagOtherChars.ToCharArray()))
                from replacement in
                Arb.Generate <NonNull <string> >()
                select
                new KeyValuePair <string, string>(merge(opening, rest),
                                                  replacement.Get);

            var modelGen =
                Gen.NonEmptyListOf(tagGen)
                .Select(tags =>
                        new Dictionary <string, string>(
                            tags.GroupBy(kv => kv.Key)
                            .Select(g => g.First()))
                        as IDictionary <string, string>);

            return(Arb.From(modelGen));
        }
Exemplo n.º 29
0
        public void ExactCoverProblemsWithMultipleSolutionsTest()
        {
            var arbNumSolutions = Arb.From(Gen.Choose(2, 5));

            var property = Prop.ForAll(arbNumSolutions, numSolutions =>
            {
                Func <int, string> makeLabel = actualNumSolutions => string.Format(
                    "Expected exactly {0} solutions but got {1}",
                    numSolutions, actualNumSolutions);

                var arbMatrix = Arb.From(GenMatrixOfIntWithMultipleSolutions(numSolutions));

                return(Prop.ForAll(arbMatrix, matrix =>
                {
                    var solutions = new Dlx().Solve(matrix).ToList();
                    var actualNumSolutions = solutions.Count();
                    var p1 = (actualNumSolutions == numSolutions).Label(makeLabel(actualNumSolutions));
                    var p2 = CheckSolutions(solutions, matrix);
                    return FsCheckUtils.And(p1, p2);
                }));
            });

            Check.One(Config, property);
        }
Exemplo n.º 30
0
 public static Arbitrary <TaglessString> TaglessString()
 {
     return(Arb.From <NonNull <string> >()
            .Convert(nonNull => new TaglessString(nonNull.Get),
                     tagless => NonNull <string> .NewNonNull(tagless.Value)));
 }