static MatTests() { VecTests.Use(); Arbitrary.Register(ArbitraryMat <Mat2, float> (2, 2)); Arbitrary.Register(ArbitraryMat <Mat3, float> (3, 3)); Arbitrary.Register(ArbitraryMat <Mat4, float> (4, 4)); }
/// <summary> /// Returns a random future DateTime by shifting the current UtcNow by a random number of days. /// </summary> /// <returns></returns> public static DateTime FutureDate() { int maximum = (int)DateTime.MaxValue.Subtract(DateTime.UtcNow).TotalDays; int offset = Arbitrary.Int32(0, maximum); return(DateTime.UtcNow.AddDays(offset)); }
public void Plist_Binary_TEST() { Xorshift random = new Xorshift(Seed); // Trailer for (int i = 0; i < 100000; ++i) { var trailer = new Plist.Trailer(); trailer.ShortVersion = (byte)(random.Generate() & 0xFF); trailer.OffsetIntSize = (byte)(random.Generate() & 0xFF); trailer.ObjectRefSize = (byte)(random.Generate() & 0xFF); trailer.NumObjects = (ulong)random.Generate() | ((ulong)random.Generate() << 32); trailer.TopObject = (ulong)random.Generate() | ((ulong)random.Generate() << 32); trailer.OffsetTableOffset = (ulong)random.Generate() | ((ulong)random.Generate() << 32); var ms = new MemoryStream(); Plist.WriteTrailerBinary(ms, trailer); var read = Plist.ReadTrailerBinary(ms.ToArray()); Assert.AreEqual(trailer.GetHashCode(), read.GetHashCode()); Assert.AreEqual(trailer, read); } for (int i = 0; i < 5000; ++i) { object value1 = Arbitrary.Plist(); var data = Plist.WriteObjectBinary(value1); object value2 = Plist.ReadObjectBinary(data); Assert.IsTrue(Plist.EqualObject(value1, value2, 1.0e-9, 1.0e-3), string.Format("serialize error [{0}]", i)); } }
private string GenerateString(int minimum, int maximum) { int upperCaseA = 65; int upperCaseZ = 90; int lowerCaseA = 97; int lowerCaseZ = 122; int length = Arbitrary.Int32(minimum, maximum); StringBuilder builder = new StringBuilder(); for (int i = 0; i < length; i++) { int c; if (Arbitrary.Boolean()) { c = Arbitrary.Int32(upperCaseA, upperCaseZ); } else { c = Arbitrary.Int32(lowerCaseA, lowerCaseZ); } builder.Append((char)c); } return(builder.ToString()); }
/// <summary> /// Returns a random past (historical) DateTime by shifting the current UtcNow by a random number of days. /// </summary> /// <returns></returns> public static DateTime PastDate() { int minimum = (int)DateTime.UtcNow.Subtract(DateTime.MinValue).TotalDays * -1; int offset = Arbitrary.Int32(minimum, 0); return(DateTime.UtcNow.AddDays(offset)); }
public void CheckNearestNeighbour <V, T> (Func <V, V, float> distance, string distDesc) where V : struct, IVec <V, float> { var prop = from tree in Prop.ForAll(ArbitraryKdTree <V, T> ()) from pos in Prop.ForAll(Arbitrary.Get <V> ()) from num in Prop.ForAll(Gen.ChooseInt(1, 4)) let nearest = tree.NearestNeighbours(pos, num, distance).AsPrintable() let lastBest = nearest.None() ? float.PositiveInfinity : distance(nearest.Last().Key, pos) select new { tree, pos, num, nearest, lastBest }; prop.Label("Not neighbours have longer distance: {0}, {1}", typeof(V).Name, distDesc) .Check(p => p.tree.Count == 0 || p.tree.All(pair => p.nearest.Contains(pair) || p.lastBest <= distance(pair.Key, p.pos))); prop.Label("Neighbours in right order: {0}, {1}", typeof(V).Name, distDesc) .Check(p => p.nearest.Zip(p.nearest.Skip(1), (p1, p2) => distance(p1.Key, p.pos) <= distance(p2.Key, p.pos)) .All(Fun.Identity)); // prop.Label ("Visualize").Check (p => // { // TestProgram.VConsole.ShowVisual (p.tree.ToVisual ()); // return true; // }); }
/* ## Implementing IArbitrary<T> ## We need an implementation of `IArbitrary<T>` interface for each type `T` ## we wish to use in our tests. This implementation generates random values ## of type `T`, and shrinks them when LinqCheck is looking for a minimal ## failing test case. ## ## So, we need to define an implementation of `IArbitrary<Seq<T>>`. The ## simplest way to achieve that is to create an instance `Arbitrary<T>` ## class, which stores the generator and shrinker for type `T`. Let's ## define a method that creates this object. */ public static IArbitrary <Seq <T> > ArbitrarySeq <T> () { /* * First we need to define the generator for `Seq<T>` type. Generators * have the type `Gen<T>` where T is the type of data produced. They * are defined as Linq expressions where complex types are constructed * with built-in or user-defined combinators. In this case we can * utilize the combinator that creates an `Gen<IEnumerable<T>>` given * a generator of type `Gen<T>`. * * We don't know yet what is the item type `T` which will be contained * in the sequence. Luckily we don't have to. We can assume that the * generator for `T` is already registered with LinqCheck, and get it * by calling `Arbitrary.Gen<T> ()`. */ return(new Arbitrary <Seq <T> > ( from e in Arbitrary.Gen <T> ().EnumerableOf() select e.ToSeq(), /* * We also need to provide a way to shrink the failed sequence * to simpler versions. Again, we take advantage of the fact * that `Seq<T>` implements `IEnumerable<T>`, so we can use * the built-in combinator to do the shrinking. Lastly, we * convert the shrinked IEnumerables back to Seqs. */ seq => from e in seq.ShrinkEnumerable() select e.ToSeq() )); }
public static Arbitrary <CborPropertyTestContext> PropertyTestInput() { Arbitrary <NonEmptyArray <CborDocument> > documentArb = Arb.Default.NonEmptyArray <CborDocument>(); Arbitrary <bool> convertArb = Arb.Default.Bool(); Gen <CborConformanceMode> conformanceModes = Gen.Elements( CborConformanceMode.Lax, CborConformanceMode.Strict, CborConformanceMode.Canonical, CborConformanceMode.Ctap2Canonical); Gen <CborPropertyTestContext> inputGen = from docs in documentArb.Generator from convert in convertArb.Generator from mode in conformanceModes select CborPropertyTestContextHelper.create(mode, convert, docs.Get); IEnumerable <CborPropertyTestContext> Shrinker(CborPropertyTestContext input) { var nonEmptyArrayInput = NonEmptyArray <CborDocument> .NewNonEmptyArray(input.RootDocuments); foreach (NonEmptyArray <CborDocument> shrunkDoc in documentArb.Shrinker(nonEmptyArrayInput)) { yield return(CborPropertyTestContextHelper.create(input.ConformanceMode, input.ConvertIndefiniteLengthItems, input.RootDocuments)); } } return(Arb.From(inputGen, Shrinker)); }
public void Plist_OSXCompatibilityTEST() { var path = Path.Combine(Application.streamingAssetsPath, "tmp.plist"); for (int i = 0; i < 100; ++i) { object value1 = Arbitrary.Plist(3); var bytes = Plist.WriteObjectBinary(value1); File.WriteAllBytes(path, bytes); OSXPlist.ConvertToXml(path); OSXPlist.ConvertToBinary(path); bytes = File.ReadAllBytes(path); File.Delete(path); var value2 = Plist.ReadObjectBinary(bytes); // because of xml serialization, lost milisecond acculacy... Assert.IsTrue(Plist.EqualObject(value1, value2, 1.0e-9, 1.5), string.Format("serialize error [{0}]", i)); } for (int i = 0; i < 100; ++i) { object value1 = Arbitrary.Plist(3); var bytes = Plist.WriteObjectBinary(value1); File.WriteAllBytes(path, bytes); OSXPlist.ConvertToXml(path); bytes = File.ReadAllBytes(path); File.Delete(path); var value2 = Plist.ReadObjectXML(bytes); // because of xml serialization, lost milisecond acculacy... Assert.IsTrue(Plist.EqualObject(value1, value2, 1.0e-9, 1.5), string.Format("serialize error [{0}]", i)); } for (int i = 0; i < 100; ++i) { object value1 = Arbitrary.Plist(3); var bytes = Plist.WriteObjectXML(value1); File.WriteAllBytes(path, bytes); OSXPlist.ConvertToBinary(path); bytes = File.ReadAllBytes(path); File.Delete(path); var value2 = Plist.ReadObjectBinary(bytes); // because of xml serialization, lost milisecond acculacy... Assert.IsTrue(Plist.EqualObject(value1, value2, 1.0e-9, 1.5), string.Format("serialize error [{0}]", i)); } }
static Schedule[] Noice() => Arbitrary.Schedules( DateTimeOffset.Now.ToUnixTimeSeconds(), 7200, 2, 3 ) .Take(10) .ToArray();
/// <summary> /// Returns a random past (historical) DateTime by shifting the current UtcNow by a random number of days. /// <para>The result will be greater than 1-Jan-1970.</para> /// </summary> /// <returns></returns> public static DateTime PastDateWin32() { DateTime min = new DateTime(1970, 1, 1); int minimum = (int)DateTime.UtcNow.Subtract(min).TotalDays * -1; int offset = Arbitrary.Int32(minimum, 0); return(DateTime.UtcNow.AddDays(offset)); }
public static TestCase <Data.Schedule, S.PrincipalClaim, S.Appointment[]> GetSchedule(string s) { switch (s) { case "NotOnRecord": return(new TestCase <Data.Schedule, S.PrincipalClaim, S.Appointment[]> { Given = new Data.Schedule[0], Arguments = new S.PrincipalClaim( Guid.NewGuid(), Guid.NewGuid().ToString() ), Expect = new S.Appointment[0] }); case "OnRecord": var claim = new S.PrincipalClaim( Guid.NewGuid(), Guid.NewGuid().ToString() ); var seed = Arbitrary.Appointments( DateTimeOffset.Now.ToUnixTimeSeconds(), 1800, 2, claim.Schedule ).Take(10).ToList(); return(new TestCase <Data.Schedule, S.PrincipalClaim, S.Appointment[]> { Given = new[] { new Data.Schedule { PrincipalId = claim.Id, Name = claim.Schedule, Appointments = seed } }, Arguments = claim, Expect = seed .Select(x => new S.Appointment { Start = x.Start, Participants = x.Participants .Select(p => new S.Participation { SubjectId = p.SubjectId, Name = p.Name }).ToList() }).OrderBy(x => x.Start).ToArray() }); default: throw new ArgumentException(nameof(s)); } }
void Start() { var bytes_binary = Plist.WriteObjectBinary(Arbitrary.Plist()); File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "arbitrary-binary.plist"), bytes_binary); var bytes_xml = Plist.WriteObjectXML(Arbitrary.Plist()); File.WriteAllBytes(Path.Combine(Application.streamingAssetsPath, "arbitrary-xml.plist"), bytes_xml); }
/// <summary> /// Generates a random distribution of `count` items for the given generator /// </summary> public static IEnumerable <KeyValuePair <T, Int32> > Distribution <T> (this Arbitrary <T> arb, Int32 size, Int32 count) { return(arb.Generator .Sample(size, count) .AsEnumerable() // working in FSharpList<T> would be awkward... but possible .GroupBy(vsn => vsn) .OrderBy(group => group.Count()) .Select(group => new KeyValuePair <T, Int32>(group.Key, group.Count()))); }
/// <summary> /// Returns a non-negative random value between 0 and the specified maximum. /// </summary> /// <param name="maximum">The inclusive upper bound of the random number to be generated, must be 256 or less.</param> /// <returns></returns> public static int Tiny(int maximum) { if (maximum > 256) { throw new ArgumentOutOfRangeException(nameof(maximum), "The maximum value of Tiny is 255."); } return((short)Arbitrary.Int32(0, maximum)); }
private static Arbitrary <To> MapArb <To, From>(Arbitrary <From> arb, Func <From, To> func) where To : class => Arb.Convert <From, To>( FsFunc.Create <From, To>(a => { var r = func(a); convertBackTable.GetValue(r, _ => a); return(r); }), FsFunc.Create <To, From>(b => convertBackTable.TryGetValue(b, out var result)
static BoundingTreeTests() { VecTests.Use(); Arbitrary.Register(ArbitraryAabb <Vec2> ()); Arbitrary.Register(ArbitraryAabb <Vec3> ()); Arbitrary.Register(ArbitraryAabb <Vec4> ()); Arbitrary.Register(ArbitraryKeyValuePair <Vec2, int> ()); Arbitrary.Register(ArbitraryKeyValuePair <Vec3, float> ()); Arbitrary.Register(ArbitraryKeyValuePair <Vec4, double> ()); }
public static Arbitrary <Q> ArbitraryQuat <Q, T> () where Q : struct, IQuat <Q, T> where T : struct, IEquatable <T> { var arb = Arbitrary.Get <T> (); var quat = default(Q); return(new Arbitrary <Q> ( from a in arb.Generate.FixedArrayOf(4) select quat.FromAxisAngle(a[0], a[1], a[2], a[3]))); }
public static Arbitrary <V> ArbitraryVec <V, T> (int size) where V : struct, IVec <V, T> where T : struct, IEquatable <T> { var arb = Arbitrary.Get <T> (); return(new Arbitrary <V> ( from a in arb.Generate.FixedArrayOf(size) select Vec.FromArray <V, T> (a), v => from a in v.ToArray <V, T> ().Map(arb.Shrink).Combinations() select Vec.FromArray <V, T> (a))); }
public void Plist_XML_TEST() { Xorshift random = new Xorshift(Seed); for (int i = 0; i < 1000; ++i) { object value1 = Arbitrary.Plist(); var data = Plist.WriteObjectXML(value1); object value2 = Plist.ReadObjectXML(data); Assert.IsTrue(Plist.EqualObject(value1, value2, 1.0e-9, 1.5), string.Format("serialize error [{0}]", i)); } }
public static Arbitrary <KdTree <V, T> > ArbitraryKdTree <V, T> () where V : struct, IVec <V, float> { var arb = Arbitrary.Get <KeyValuePair <V, T> > (); return(new Arbitrary <KdTree <V, T> > ( from pairs in arb.Generate.EnumerableOf() select new KdTree <V, T> (pairs), tree => from pairs in tree.ShrinkEnumerable() select new KdTree <V, T> (pairs))); }
public static Arbitrary <M> ArbitraryMat <M, T> (int cols, int rows) where M : struct, IMat <M, T> where T : struct, IEquatable <T> { var arb = Arbitrary.Get <T> (); return(new Arbitrary <M> ( from a in arb.Generate.FixedArrayOf(rows * cols) select Mat.FromArray <M, T> (a), m => from a in Mat.ToArray <M, T> (m).Map(arb.Shrink).Combinations() select Mat.FromArray <M, T> (a))); }
public static Arbitrary <KeyValuePair <K, V> > ArbitraryKeyValuePair <K, V> () { var arbKey = Arbitrary.Get <K> (); var arbValue = Arbitrary.Get <V> (); return(new Arbitrary <KeyValuePair <K, V> > ( from key in arbKey.Generate from value in arbValue.Generate select new KeyValuePair <K, V> (key, value), pair => from key in arbKey.Shrink(pair.Key) select new KeyValuePair <K, V> (key, pair.Value))); }
public Property Token_lexes() { return(Prop.ForAll(Arbitrary.PsuedoToken(), token => { var result = Lex(token.Text); var outputAsPsuedoTokens = result.ToPsuedoTokens(); var expectedPsuedoTokens = token.Yield().Append(PsuedoToken.EndOfFile()).ToList(); return expectedPsuedoTokens.SequenceEqual(outputAsPsuedoTokens) .Label($"Actual: {outputAsPsuedoTokens.DebugFormat()}") .Label($"Expected: {expectedPsuedoTokens.DebugFormat()}") .Collect(token.TokenType.Name); })); }
protected TArg AsParam <TArg>(string label, Arbitrary <TArg> arb) { if (!PropertyBasedTestContext.IsPreparation) { return((TArg)PropertyBasedTestContext.ActualParams[label]); } if (!PropertyBasedTestContext.ParamDefinitions.ContainsKey(label)) { PropertyBasedTestContext.ParamDefinitions.Add(label, arb); } return(default(TArg)); }
public void CheckAdding <V, T> () where V : struct, IVec <V, float> { var prop = from tree in Prop.ForAll(ArbitraryKdTree <V, T> ()) let cnt = tree.Count from key in Prop.ForAll(Arbitrary.Get <V> ().Generate) from val in Prop.ForAll(Arbitrary.Get <T> ().Generate) let added = tree.TryAdd(key, val) select new { tree, cnt, key, val, added }; prop.Label("Count is correct").Check(p => !p.added || p.cnt + 1 == p.tree.Count()); prop.Label("New value added").Check(p => !p.added || p.tree[p.key].Equals(p.val)); }
public static Arbitrary <Aabb <V> > ArbitraryAabb <V> () where V : struct, IVec <V, float> { var arb = Arbitrary.Get <V> (); return(new Arbitrary <Aabb <V> > ( from pos1 in arb.Generate from pos2 in arb.Generate select new Aabb <V> (pos1, pos2), bbox => from min in arb.Shrink(bbox.Min) from max in arb.Shrink(bbox.Max) select new Aabb <V> (min, max))); }
public Property Valid_token_sequence_lexes_back_to_itself() { return(Prop.ForAll(Arbitrary.PsuedoTokenList(), tokens => { var input = string.Concat(tokens.Select(t => t.Text)); var result = Lex(input); var outputAsPsuedoTokens = result.ToPsuedoTokens(); var expectedPsuedoTokens = tokens.Append(PsuedoToken.EndOfFile()).ToFixedList(); return expectedPsuedoTokens.SequenceEqual(outputAsPsuedoTokens) .Label($"Text: „{input.Escape()}„") .Label($"Actual: {outputAsPsuedoTokens.DebugFormat()}") .Label($"Expected: {expectedPsuedoTokens.DebugFormat()}"); })); }
private string GetString(int minimum, int maximum, string contains) { if (string.IsNullOrWhiteSpace(contains)) { throw new ArgumentNullException(nameof(contains), "The argument cannot be null.or empty."); } int length = contains.Length; string text = GenerateString(minimum, maximum); // Determine the location to insert the 'contains' so the length on the result is not more than the maximum. int location = Arbitrary.Int32(0, text.Length - length); return(text.Insert(location, contains)); }
public static TestCase <Data.Schedule, Guid, IEnumerable <S.PrincipalClaim> > ListSchedule(string s) { switch (s) { case "NotOnRecord": return(new TestCase <Data.Schedule, Guid, IEnumerable <S.PrincipalClaim> > { Given = new Data.Schedule[0], Arguments = Guid.NewGuid(), Expect = new S.PrincipalClaim[0] }); case "OnRecord": var principal = Guid.NewGuid(); var names = new[] { "adam", "bertil", "ceasar" }; return(new TestCase <Data.Schedule, Guid, IEnumerable <S.PrincipalClaim> > { Given = names .Select(x => new Data.Schedule { PrincipalId = principal, Name = x, Appointments = Arbitrary.Appointments( DateTimeOffset.Now.ToUnixTimeSeconds(), 1800, 2, x).Take(3).ToList() }).ToArray(), Arguments = principal, Expect = names .Select(x => new S.PrincipalClaim(principal, x)) }); default: throw new ArgumentException(nameof(s)); } }