using System.Globalization; namespace Anubis.Tests; /// /// Property tests without external packages (ADR 0003, 0004): many generated cases from a fixed /// seed, so a failure always repeats, and a message that names the seed and the failing case. /// internal static class Property { public const int DefaultSeed = 20261110; public const int DefaultCases = 200; public static void ForAll(Func generate, Action property, int cases = DefaultCases, int seed = DefaultSeed) { var gen = new Gen(seed); for (var i = 0; i < cases; i++) { var value = generate(gen); try { property(value); } catch (Exception ex) when (ex is not AssertInconclusiveException) { throw new AssertFailedException( string.Create(CultureInfo.InvariantCulture, $"Proprietà violata al caso {i} (seme {seed}): {value}"), ex); } } } } /// /// Fixed-seed generator based on SplitMix64. Unlike a seeded , its sequence is /// fixed by this code, so it stays the same on every platform and .NET version. /// internal sealed class Gen(int seed) { private ulong _state = unchecked((ulong)(long)seed); public ulong NextUInt64() { var z = _state += 0x9E3779B97F4A7C15UL; z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9UL; z = (z ^ (z >> 27)) * 0x94D049BB133111EBUL; return z ^ (z >> 31); } /// Uniform integer in [, ). public long Long(long minInclusive, long maxExclusive) { ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(minInclusive, maxExclusive); var range = unchecked((ulong)(maxExclusive - minInclusive)); var limit = ulong.MaxValue - (ulong.MaxValue % range); ulong x; do { x = NextUInt64(); } while (x >= limit); return unchecked(minInclusive + (long)(x % range)); } public int Int(int minInclusive, int maxExclusive) => (int)Long(minInclusive, maxExclusive); public bool Bool() => (NextUInt64() & 1UL) == 1UL; /// Uniform value in [0, 1). public double Double() => (NextUInt64() >> 11) * (1.0 / (1UL << 53)); /// A standard normal value (Box–Muller), for synthetic price series and returns. public double Normal() { var u = 1.0 - Double(); var v = Double(); return Math.Sqrt(-2.0 * Math.Log(u)) * Math.Cos(2.0 * Math.PI * v); } /// A decimal in [, ] with at most decimals. public decimal Decimal(decimal min, decimal max, int scale) { ArgumentOutOfRangeException.ThrowIfGreaterThan(min, max); ArgumentOutOfRangeException.ThrowIfNegative(scale); ArgumentOutOfRangeException.ThrowIfGreaterThan(scale, 18); var unit = 1m; for (var i = 0; i < scale; i++) { unit /= 10m; } var low = decimal.Ceiling(min / unit); var high = decimal.Floor(max / unit); if (low > high) { throw new ArgumentException("Nessun valore con questa scala nell'intervallo.", nameof(scale)); } var steps = high - low; if (steps >= long.MaxValue) { throw new ArgumentException("Intervallo troppo ampio per questa scala.", nameof(scale)); } var k = Long(0, (long)steps + 1); return (low + k) * unit; } public T Pick(IReadOnlyList items) { ArgumentOutOfRangeException.ThrowIfZero(items.Count); return items[Int(0, items.Count)]; } }