diff --git a/docs/oracles.md b/docs/oracles.md index e48bcffd..787348ea 100644 --- a/docs/oracles.md +++ b/docs/oracles.md @@ -311,6 +311,43 @@ with the class as what varies it. nothing holds it. Ids are a letter (R ranges, M multirange, S sets, J literals/JSON/TypeConverter, E EF Core, A hosting/AOT), two digits and a slug, sorted. +## Sibling parity + +The claims hold each promise where a document makes it, so they find a bug at the site they check +and miss it at the sibling site that makes the same promise implicitly. The changelog shows that a +bug at one site tends to come back at its siblings. The receiver-shaped dispatch went from +`IsAdjacentTo` to `IsStrictlyLeftOf` to `RangeSet.Except(TRange)`, and the wrapper arities kept +lagging their primitive set. A **sibling parity sweep** (`*ParityTests` in the conventions project, +kind `differential`) runs two things that must agree on the same input and compares their answers. +It needs no ground truth: when the siblings disagree, one of them is wrong. + +| Sweep | One side | The other side | +|---|---|---| +| `SetWrapperParityTests` | each primitive value set | its wrapper arity closed over an identity element (`Same`, `SameText`) | +| `RangeSetLiftParityTests` | each range operation, predicate and accessor | the same on the one-element `RangeSet` holding the range | +| `LiteralEntryPointParityTests` | `Parse(string)` of a literal | the span overload, `TryParse`, JSON, the `TypeConverter` and configuration binding | + +The rules are the ones for any oracle, plus three of their own: + +- **The pair must be a promise.** Compare two sites only where a document says, or the design + requires, that they agree. Where the documents set them apart, compare through the documented + mapping, or leave the input out and cite the document in a comment. For example, a NodaTime + wrapper set refuses a non-ISO element that its primitive normalizes, and a `TypeConverter` reads + `""` as an absent value. +- **The identity has to be real.** `SetWrapperParityTests` closes each family over an element that + adds nothing: it parses with the exact inverse of the primitive's text form (`DateTime` with + `RoundtripKind`, NodaTime with its ISO pattern) and compares as the primitive does. A wrapper that + added anything would turn a family defect into a harness defect. +- **Make sure both sides really are distinct calls.** In generic code `TSet.Parse(string, …)` binds + to the span overload (see [testing.md](testing.md#the-sibling-parity-sweeps)), so a string-versus-span + comparison has to go through `StringOverloads`. A seed that breaks one side shows whether the sweep + reaches it. + +A disagreement goes through `Candidates.Verdict` like any other, with each failure line starting +with the row's type name. A disagreement already filed against another oracle gets its own rows here +under the same issue. #109 is the example: PostgreSQL disagrees with `IsUnboundedStart` on `(,)`, and +so does the range's own one-element multirange. + ## Generated operands Most sweeps enumerate their cases: shapes, small universes, five cultures. `DifferentialFuzzParityTests` diff --git a/docs/testing.md b/docs/testing.md index e1cc623a..14a2686e 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -307,6 +307,56 @@ overloads, `Add`, `Remove`, `Contains`, an unquoted `NULL` in the array literal, refuses rather than drops. It runs over families whose element type is a reference type, which is `StringSet` alone today and whatever is added later without anyone having to remember. +### The Sibling Parity Sweeps + +A bug found at one API site tends to come back at a sibling site that makes the same promise. The +changelog shows it repeatedly: `IsAdjacentTo` (6.2.1), then `IsStrictlyLeftOf` and `Except` (7.0.0), +then `RangeSet.Except(TRange)` (8.0.0). The wrapper arities kept lagging their primitive set. And +`==`/`!=` went untested on 18 of 20 set types. A claim-driven oracle checks each site against its own +document, so it can't see a promise two sites share without saying so. These three sweeps +(conventions project, one `[DynamicData]` row per discovered type) compare the two siblings directly. +They assert no ground truth: when the siblings disagree, one of them is wrong, and the failure line +names both answers. + +- **`SetWrapperParityTests`**: each primitive set against its wrapper arity closed over an + *identity* element (`Int32Set` against `Int32Set>`, `StringSet` against + `StringSet`, in `IdentityWrappers.cs`). An identity element parses, formats and compares + exactly as its primitive does, so the family's own code is the only difference. That's the + opposite of `WrapperElements`, whose elements get something wrong on purpose. The sweep runs the + family's probes plus its extremes, every subset shape, array literals derived from the element + texts (quoted, whitespace-padded, duplicated, out of order, empty, `NULL`, malformed) and JSON + documents (reordered, mistyped, quoted, padded). It compares every operation, `ParseValue` and + `FormatValue`, both overloads of `Parse` and `TryParse`, `ToString` with each format and provider, + the `TypeConverter`, JSON token kinds, and each sibling reading the other's document. It wants the + same element texts in the same order, or the same exception type. +- **`RangeSetLiftParityTests`**: each range against the one-element `RangeSet` holding it, over the + shape matrix `DomainParityOracleTests` uses (`RangeSpecs.cs`), extended with bounds at the domain's + minimum and maximum. For every ordered pair it compares each predicate with the set-set and + set-range overloads, and each operation with the named method and the operator (`|`, `&`, `-`). + For every range it compares each accessor, `Merge`, `Complement`, the literal, and `Contains(T)` + at every grid point. Results are compared as literals, so the bound values and inclusivity have to + match, not just a few `Contains` answers. +- **`LiteralEntryPointParityTests`**: one literal through every entry point: `Parse` and `TryParse` + (string and span), a JSON string, the `TypeConverter` and `IConfiguration` binding. It covers every + range union and each sealed variant (the union's answer narrowed to the variant's shape), every + multirange (including its explicit `IParsable` implementation) and every value set. The entry + points must produce equal values, or all refuse. A value set's JSON is its element array, so it + skips the JSON step here; `SetWrapperParityTests` covers that array. The empty string is an absent + value to the `TypeConverter` and the binder by design, so the converter and the binder never see it. + +The sweeps run in a few seconds altogether. Each one is seeded (`test/oracles/seeds/`), and their +disagreements are candidates in `candidates.json`: #141 (wrapper JSON reads accept tokens the +primitive refuses) and #109 (`IsUnboundedStart`/`IsUnboundedEnd` on `(,)`), found again here between +a range and its own multirange. + +**The `Parse(string)` trap.** In generic code constrained on `IRangeFactory` or `IValueSetFactory`, +`TSet.Parse(text, provider)` with a `string` argument calls the *span* overload. Both interfaces derive +from `ISpanParsable`. Overload resolution drops the base interface's `IParsable` +candidate whenever the derived interface's span candidate applies, and the implicit string-to-span +conversion makes it apply. So a sweep that means to compare the two overloads compares the span one +with itself. Call the string overloads through `StringOverloads` (constrained on `IParsable` +alone). The parity sweeps do this, and their `TryParse` seed was missed until they did. + ### Shape-Combination Matrix Every binary operation test must cover all five range shapes: `Finite`, `UnboundedStart`, `UnboundedEnd`, `EmptyRange`, `Infinity`. Tests instantiate the "other" operand in each shape and verify the result type and value. diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/DomainParityOracleTests.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/DomainParityOracleTests.cs index 4fdf357b..cb88b708 100644 --- a/test/CodoMetis.ValueRanges.Conventions.Tests/DomainParityOracleTests.cs +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/DomainParityOracleTests.cs @@ -1,7 +1,7 @@ using System.Diagnostics; using CodoMetis.ValueRanges.Core; using CodoMetis.ValueRanges.Oracles; -using NodaTime; +using static CodoMetis.ValueRanges.Conventions.Tests.RangeSpecs; namespace CodoMetis.ValueRanges.Conventions.Tests; @@ -39,32 +39,8 @@ public sealed class DomainParityOracleTests { private const string OracleName = nameof(DomainParityOracleTests); - private enum Shape { Empty, Infinity, Finite, UnboundedStart, UnboundedEnd } - - private sealed record Spec(Shape Shape, int Start, int End, bool StartInclusive, bool EndInclusive); - private sealed record Case(string Label, TRange Range, HashSet Model) where TRange : notnull; - private static readonly DateTime s_dateTimeOrigin = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Unspecified); - private static readonly LocalDateTime s_localOrigin = new(2026, 1, 1, 0, 0); - private static readonly Instant s_instantOrigin = Instant.FromUtc(2026, 1, 1, 0, 0); - - /// Grid index to element, order-preserving; a discrete type's step is one grid point. - private static readonly Dictionary s_embeddings = new() - { - [typeof(int)] = (Func)(k => k), - [typeof(long)] = (Func)(k => k), - [typeof(decimal)] = (Func)(k => k * 0.5m), - [typeof(DateOnly)] = (Func)(k => new DateOnly(2026, 1, 1).AddDays(k)), - [typeof(TimeOnly)] = (Func)(k => new TimeOnly(9, 0).AddMinutes(30 * k)), - [typeof(DateTime)] = (Func)(k => s_dateTimeOrigin.AddMinutes(30 * k)), - [typeof(DateTimeOffset)] = (Func)(k => new DateTimeOffset(s_dateTimeOrigin.AddMinutes(30 * k), TimeSpan.FromHours(1))), - [typeof(LocalDate)] = (Func)(k => new LocalDate(2026, 1, 1).PlusDays(k)), - [typeof(LocalDateTime)] = (Func)(k => s_localOrigin.PlusMinutes(30 * k)), - [typeof(Instant)] = (Func)(k => s_instantOrigin.Plus(Duration.FromMinutes(30 * k))), - [typeof(YearMonth)] = (Func)(k => new YearMonth(2026, 1).PlusMonths(k)) - }; - [TestMethod] public void Discovery_FindsEveryRangeType_AndEveryElementHasAnEmbedding() { @@ -72,7 +48,7 @@ public void Discovery_FindsEveryRangeType_AndEveryElementHasAnEmbedding() Assert.IsTrue(types.Count >= 11, $"Discovered {types.Count} range types, fewer than the 11 known to exist."); - var unembedded = types.Where(pair => !s_embeddings.ContainsKey(pair.Element)).Select(pair => pair.Range.Name).ToList(); + var unembedded = types.Where(pair => !Embeddings.ContainsKey(pair.Element)).Select(pair => pair.Range.Name).ToList(); Assert.AreEqual(0, unembedded.Count, "A range type's element has no embedding, so the sweep cannot reach it — add one: " + string.Join(", ", unembedded)); } @@ -85,7 +61,7 @@ public void EveryRangeType_EveryOrderedPair_MatchesSetTheory() foreach (var (range, element) in RangeProbes.AllRangeTypes()) { - if (!s_embeddings.ContainsKey(element)) continue; // reported by the discovery test + if (!Embeddings.ContainsKey(element)) continue; // reported by the discovery test var result = Reflect.InvokeGeneric<(int Checks, List Failures)>(typeof(DomainParityOracleTests), nameof(Sweep), range, element); Assert.IsTrue(result.Checks > 100_000, $"{range.Name}: expected well over 100,000 checks, made {result.Checks}."); failures.AddRange(result.Failures); @@ -100,7 +76,7 @@ private static (int Checks, List Failures) Sweep() where TRange : class, IRangeFactory, IRange where T : struct, IComparable, IEquatable { - var valueOf = (Func)s_embeddings[typeof(T)]; + var valueOf = (Func)Embeddings[typeof(T)]; var discrete = TRange.IsDiscrete; // The discrete grid: one index per value, bounds inside the universe. The continuous grid: @@ -109,7 +85,7 @@ private static (int Checks, List Failures) Sweep() int[] bounds = discrete ? [1, 2, 3, 4, 5, 6] : [2, 4, 6, 8, 10, 12]; var cases = EnumerateSpecs(bounds) - .Select(spec => new Case($"{typeof(TRange).Name} {Describe(spec, k => TRange.FormatValue(valueOf(k), null, System.Globalization.CultureInfo.InvariantCulture))}", Build(spec, valueOf), ModelOf(spec, gridMax))) + .Select(spec => new Case($"{typeof(TRange).Name} {Describe(spec, valueOf)}", Build(spec, valueOf), ModelOf(spec, gridMax))) .ToList(); var failures = new List(); @@ -178,25 +154,6 @@ void CheckSet(string operation, HashSet actual, HashSet expected) HashSet ModelOfSet(RangeSet set) => [.. Enumerable.Range(0, gridMax + 1).Where(k => set.Contains(valueOf(k)))]; } - private static IEnumerable EnumerateSpecs(int[] bounds) - { - yield return new(Shape.Empty, 0, 0, false, false); - yield return new(Shape.Infinity, 0, 0, false, false); - - foreach (var bound in bounds) - foreach (var inclusive in (bool[]) [true, false]) - { - yield return new(Shape.UnboundedStart, 0, bound, false, inclusive); - yield return new(Shape.UnboundedEnd, bound, 0, inclusive, false); - } - - foreach (var start in bounds) - foreach (var end in bounds.Where(end => end >= start)) - foreach (var startInclusive in (bool[]) [true, false]) - foreach (var endInclusive in (bool[]) [true, false]) - yield return new(Shape.Finite, start, end, startInclusive, endInclusive); - } - /// The values a specification holds, from the specification alone. private static HashSet ModelOf(Spec spec, int gridMax) { @@ -216,30 +173,6 @@ private static HashSet ModelOf(Spec spec, int gridMax) static bool AtOrBefore(int k, int bound, bool inclusive) => k < bound || (k == bound && inclusive); } - private static TRange Build(Spec spec, Func valueOf) - where TRange : IRangeFactory, IRange - where T : struct, IComparable, IEquatable => - spec.Shape switch - { - Shape.Empty => TRange.Empty, - Shape.Infinity => TRange.Infinite, - Shape.Finite => TRange.CreateFinite(valueOf(spec.Start), valueOf(spec.End), spec.StartInclusive, spec.EndInclusive), - Shape.UnboundedStart => TRange.CreateUnboundedStart(valueOf(spec.End), spec.EndInclusive), - Shape.UnboundedEnd => TRange.CreateUnboundedEnd(valueOf(spec.Start), spec.StartInclusive), - _ => throw new UnreachableException() - }; - - private static string Describe(Spec spec, Func text) => - spec.Shape switch - { - Shape.Empty => "empty", - Shape.Infinity => "(,)", - Shape.Finite => $"{(spec.StartInclusive ? '[' : '(')}{text(spec.Start)},{text(spec.End)}{(spec.EndInclusive ? ']' : ')')}", - Shape.UnboundedStart => $"(,{text(spec.End)}{(spec.EndInclusive ? ']' : ')')}", - Shape.UnboundedEnd => $"{(spec.StartInclusive ? '[' : '(')}{text(spec.Start)},)", - _ => throw new UnreachableException() - }; - private static bool IsContiguous(HashSet values) => values.Count == 0 || values.Max() - values.Min() + 1 == values.Count; private static HashSet Hull(HashSet values) => values.Count == 0 ? [] : [.. Enumerable.Range(values.Min(), values.Max() - values.Min() + 1)]; diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/IdentityWrappers.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/IdentityWrappers.cs new file mode 100644 index 00000000..6e5f818f --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/IdentityWrappers.cs @@ -0,0 +1,143 @@ +using System.Globalization; +using NodaTime; +using NodaTime.Text; + +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// A wrapper element that adds nothing to the primitive it wraps: it parses exactly what the primitive +/// parses, formats exactly as the primitive formats, and compares as the primitive compares. A wrapper +/// arity closed over it must therefore answer every question exactly as its primitive set does — which +/// is what asserts, with no ground truth needed. +/// +/// +/// The representative wrappers in are deliberately not identities +/// ( trims and compares by culture, narrows the grammar), because +/// they exist to prove that a family overrides what its element gets wrong. A parity sweep needs the +/// opposite: an element that gets nothing wrong, so every disagreement is the family's. +/// +public interface IIdentity + where TSelf : IIdentity +{ + /// The wrapped primitive. + TPrimitive Value { get; } + + /// Wraps unchanged. + static abstract TSelf Wrap(TPrimitive value); +} + +/// +/// The identity wrapper over a struct primitive: every BCL element type of a value set family and the +/// five NodaTime ones. Parsing reads the round-trip form each family hands its element, without the +/// shifts a bare Parse would apply (a DateTime read with , +/// a NodaTime value with its ISO pattern). +/// +public readonly record struct Same : IIdentity, T>, IFormattable, IParsable>, IComparable> + where T : struct, IEquatable, IComparable, IFormattable +{ + private static readonly Func s_parse = IdentityParse.For(); + + private Same(T value) => Value = value; + + /// + public T Value { get; } + + /// + public static Same Wrap(T value) => new(value); + + public static Same Parse(string s, IFormatProvider? provider) => new(s_parse(s)); + + public static bool TryParse(string? s, IFormatProvider? provider, out Same result) + { + try + { + result = new(s_parse(s!)); + return true; + } + catch (Exception ex) when (ex is FormatException or ArgumentException or OverflowException or UnparsableValueException) + { + result = default; + return false; + } + } + + public int CompareTo(Same other) => Value.CompareTo(other.Value); + + public string ToString(string? format, IFormatProvider? formatProvider) => Value.ToString(format, formatProvider ?? CultureInfo.InvariantCulture); + + public override string ToString() => Value.ToString(null, CultureInfo.InvariantCulture); +} + +/// +/// The identity wrapper over : the text is the value, untrimmed and unvalidated, and +/// the comparison is 's own (culture-sensitive) one — which the string family must +/// override with ordinal exactly as StringSet sorts. +/// +public readonly record struct SameText : IIdentity, IFormattable, IParsable, IComparable +{ + private readonly string? _value; + + private SameText(string value) => _value = value; + + /// + public string Value => _value ?? ""; + + /// + public static SameText Wrap(string value) => new(value); + + public static SameText Parse(string s, IFormatProvider? provider) => new(s ?? throw new ArgumentNullException(nameof(s))); + + public static bool TryParse(string? s, IFormatProvider? provider, out SameText result) + { + result = s is null ? default : new(s); + return s is not null; + } + + public int CompareTo(SameText other) => string.Compare(Value, other.Value, StringComparison.CurrentCulture); + + public string ToString(string? format, IFormatProvider? formatProvider) => Value; + + public override string ToString() => Value; +} + +/// The identity wrapper for each primitive element type; unknown ones throw so a new family cannot go unswept. +internal static class IdentityWrappers +{ + internal static Type For(Type primitive) => + primitive == typeof(string) + ? typeof(SameText) + : IdentityParse.Supports(primitive) + ? typeof(Same<>).MakeGenericType(primitive) + : throw new InvalidOperationException( + $"No identity wrapper for the element type '{primitive.Name}'. Add its parse to IdentityParse so the " + + "new family is covered by SetWrapperParityTests."); +} + +/// The exact inverse of each primitive's invariant text form. +internal static class IdentityParse +{ + private static readonly Dictionary s_parsers = new() + { + [typeof(short)] = (Func)(s => short.Parse(s, CultureInfo.InvariantCulture)), + [typeof(int)] = (Func)(s => int.Parse(s, CultureInfo.InvariantCulture)), + [typeof(long)] = (Func)(s => long.Parse(s, CultureInfo.InvariantCulture)), + [typeof(decimal)] = (Func)(s => decimal.Parse(s, NumberStyles.Float, CultureInfo.InvariantCulture)), + [typeof(Guid)] = (Func)(s => Guid.Parse(s, CultureInfo.InvariantCulture)), + [typeof(DateOnly)] = (Func)(s => DateOnly.Parse(s, CultureInfo.InvariantCulture)), + [typeof(TimeOnly)] = (Func)(s => TimeOnly.Parse(s, CultureInfo.InvariantCulture)), + [typeof(DateTime)] = (Func)(s => DateTime.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)), + [typeof(DateTimeOffset)] = (Func)(s => DateTimeOffset.Parse(s, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind)), + [typeof(LocalDate)] = (Func)(s => LocalDatePattern.Iso.Parse(s).GetValueOrThrow()), + [typeof(LocalDateTime)] = (Func)(s => LocalDateTimePattern.ExtendedIso.Parse(s).GetValueOrThrow()), + [typeof(Instant)] = (Func)(s => InstantPattern.ExtendedIso.Parse(s).GetValueOrThrow()), + [typeof(LocalTime)] = (Func)(s => LocalTimePattern.ExtendedIso.Parse(s).GetValueOrThrow()), + [typeof(YearMonth)] = (Func)(s => YearMonthPattern.Iso.Parse(s).GetValueOrThrow()) + }; + + internal static bool Supports(Type primitive) => s_parsers.ContainsKey(primitive); + + internal static Func For() => + s_parsers.TryGetValue(typeof(T), out var parse) + ? (Func)parse + : throw new InvalidOperationException($"No identity parse for '{typeof(T).Name}'."); +} diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/LiteralEntryPointParityTests.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/LiteralEntryPointParityTests.cs new file mode 100644 index 00000000..4806e597 --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/LiteralEntryPointParityTests.cs @@ -0,0 +1,325 @@ +using System.ComponentModel; +using System.Globalization; +using System.Text.Json; +using CodoMetis.ValueRanges.Core; +using CodoMetis.ValueRanges.Oracles; +using Microsoft.Extensions.Configuration; + +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// One literal, every entry point that reads one: Parse(string), Parse(ReadOnlySpan<char>), +/// both TryParse overloads, a JSON string, the TypeConverter and IConfiguration +/// binding — for every discovered range union and each of its sealed variants, every multirange and +/// every value set. They produce an equal value, or they all refuse it. +/// +/// +/// +/// Every entry point is documented as "the literal", and each was wired separately: the span parser +/// is the one the string overload widens to, JSON goes through its own converter (and a variant's +/// converter defers to the union's), the TypeConverter is inherited by a variant unless it has +/// its own, and configuration binding adds the binder's own rules on top of the converter. Each has +/// been the one entry point that got a literal wrong before (#30–#32, #114). The sweep asserts no +/// value — only that the entry points agree, so a literal nobody thought to test is still checked. +/// +/// +/// A variant has no parser of its own; its expected answer is the union's, narrowed: the same value +/// when the literal has the variant's shape, a refusal otherwise. Refusals are compared as refusals, +/// whatever the exception (the binder wraps the converter's in an +/// ); an exception that is not a refusal — a +/// , an — is its own outcome. +/// +/// +/// Two documented exceptions shape the grid. A value set's JSON form is the element array, not the +/// literal, so the literal reaches a set through the other entry points (its JSON array is +/// 's). And the TypeConverter converts an empty string to +/// , an absent value, which configuration binding relies on +/// (docs/serialization.md, ConfigurationBindingTests), so the empty literal goes only +/// through the parsers and JSON. +/// +/// +[TestClass] +public sealed class LiteralEntryPointParityTests +{ + /// The property configuration binds the literal into. + public sealed class Holder + { + public T? Value { get; set; } + } + + public sealed record LiteralRow(string Label, Func, int> Sweep) + { + public override string ToString() => Label; + } + + public static IEnumerable Rows + { + get + { + foreach (var (rangeType, elementType) in RangeProbes.AllRangeTypes()) + { + yield return [new LiteralRow(rangeType.Name, failures => Reflect.InvokeGeneric( + typeof(LiteralEntryPointParityTests), nameof(SweepRange), [rangeType, elementType], failures))]; + yield return [new LiteralRow($"RangeSet<{rangeType.Name}>", failures => Reflect.InvokeGeneric( + typeof(LiteralEntryPointParityTests), nameof(SweepRangeSet), [rangeType, elementType], failures))]; + } + + foreach (var (setType, elementType) in SetProbes.AllSetTypes()) + yield return [new LiteralRow(Display(setType), failures => Reflect.InvokeGeneric( + typeof(LiteralEntryPointParityTests), nameof(SweepSet), [setType, elementType], failures))]; + } + } + + [TestMethod] + public void Discovery_FindsEveryRow() + { + // 11 ranges, their 11 multiranges, 30 set types. + const int knownRows = 52; + var rows = Rows.Count(); + Assert.IsTrue(rows >= knownRows, $"Found {rows} rows, fewer than {knownRows}."); + } + + [TestMethod] + [DynamicData(nameof(Rows))] + public void OneLiteral_ReadsAlikeThroughEveryEntryPoint(LiteralRow row) + { + var failures = new List(); + var checks = row.Sweep(failures); + + Assert.IsTrue(checks >= 200, $"{row}: only {checks} checks ran."); + + Candidates.Verdict(nameof(LiteralEntryPointParityTests), failures, + $"{row}: of {checks} checks, the entry points read one literal differently", shown: 30, rowPrefix: row.Label + " "); + } + + // ---------------------------------------------------------------- ranges + + private static int SweepRange(List failures) + where TRange : class, IRangeFactory, IRange + where T : struct, IComparable, IEquatable + { + var label = typeof(TRange).Name; + var shapes = RangeProbes.Shapes(); + var variants = shapes.Select(shape => shape.GetType()).ToArray(); + var checks = 0; + + foreach (var literal in RangeLiterals()) + { + var parsed = Read(() => StringOverloads.Parse(literal, CultureInfo.InvariantCulture)); + + checks += Agree(failures, $"{label} {Show(literal)}", parsed, Entries(literal, + ("Parse(span)", () => TRange.Parse(literal.AsSpan(), CultureInfo.InvariantCulture)), + ("TryParse", () => StringOverloads.TryParse(literal, CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("TryParse(span)", () => TRange.TryParse(literal.AsSpan(), CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("JSON", () => JsonSerializer.Deserialize(JsonSerializer.Serialize(literal))!))); + + // Each variant reads the literal as the union does, narrowed to its shape. + foreach (var variant in variants) + { + var narrowed = parsed.Value is { } value && value.GetType() != variant + ? Outcome.Refused + : parsed; + + checks += Reflect.InvokeGeneric(typeof(LiteralEntryPointParityTests), nameof(AgreeVariant), + [variant], failures, $"{label}.{variant.Name} {Show(literal)}", literal, narrowed); + } + } + + return checks; + } + + private static int AgreeVariant(List failures, string name, string literal, Outcome expected) + where TVariant : class => + Agree(failures, name, expected, Entries(literal, + ("JSON", () => JsonSerializer.Deserialize(JsonSerializer.Serialize(literal))!))); + + /// + /// The five shapes' literals, the bounds' texts and the domain's extremes, and their neighbours: + /// padded, re-cased, quoted, inverted, unterminated, decorated. + /// + private static IEnumerable RangeLiterals() + where TRange : IRangeFactory, IRange + where T : struct, IComparable, IEquatable + { + string Text(object value) => TRange.FormatValue((T)value, null, CultureInfo.InvariantCulture); + + var (lo, hi) = (Text(RangeProbes.Bounds[typeof(T)].Low), Text(RangeProbes.Bounds[typeof(T)].High)); + var (min, max) = (Text(RangeSpecs.Extremes[typeof(T)].Min), Text(RangeSpecs.Extremes[typeof(T)].Max)); + + foreach (var shape in RangeProbes.Shapes()) + { + var literal = ((IFormattable)shape).ToString(null, CultureInfo.InvariantCulture); + yield return literal; + yield return literal.ToUpperInvariant(); + yield return $" {literal} "; + yield return $"\t{literal}\n"; + yield return literal + "x"; + } + + string[] grid = + [ + "", " ", "[", "x", "EMPTY", "Empty", " empty ", "empty x", "(,)", "[,]", "(,]", "[,)", "( , )", "(\"\",\"\")", + $"[{lo},{hi})", $"[{lo},{hi}]", $"({lo},{hi})", $"({lo},{hi}]", $"[ {lo} , {hi} )", $"[{lo} ,{hi})", + $"[\"{lo}\",\"{hi}\")", $"[\" {lo} \",\" {hi} \")", $"[\"{lo}\" ,\"{hi}\" )", $"[{hi},{lo})", $"[{lo},{lo})", + $"[{lo},{lo}]", $"({lo},{lo}]", $"[{lo},)", $"(,{hi}]", $"[{lo},{hi}", $"{lo},{hi}", $"[{lo},{hi})x", + $"[{lo},{hi},{hi})", $"[{lo};{hi})", $"[\"\",{hi})", $"[{lo},\"\")", $"[\\{lo},{hi})", $"[{lo}\\,{hi})", + "[-infinity,infinity]", "(-infinity,infinity)", $"[{lo},infinity)", $"[{lo},infinity]", $"(-infinity,{hi}]", + $"[-infinity,{hi})", "[\"-infinity\",\"infinity\")", "[INFINITY,)", + $"[{min},{max}]", $"[{min},{max})", $"({min},{max})", $"[{min},)", $"(,{max}]", $"[{max},)", $"(,{min})", + $"[{min},{min}]", $"[{max},{max}]", $"({max},{max}]" + ]; + + foreach (var literal in grid) yield return literal; + } + + // ---------------------------------------------------------------- multiranges + + private static int SweepRangeSet(List failures) + where TRange : class, IRangeFactory, IRange + where T : struct, IComparable, IEquatable + { + var label = $"RangeSet<{typeof(TRange).Name}>"; + var checks = 0; + + var ranges = RangeLiterals().Where(literal => TRange.TryParse(literal, CultureInfo.InvariantCulture, out _)) + .Select(literal => literal.Trim()) + .Distinct() + .ToList(); + + IEnumerable Literals() + { + string[] fixedLiterals = ["{}", "{ }", " {} ", "", " ", "{", "}", "{{}}", "{empty}", "{EMPTY}", "{empty,empty}", "{(,)}", "{ (,) }", "x"]; + foreach (var literal in fixedLiterals) yield return literal; + + foreach (var range in ranges) + { + yield return $"{{{range}}}"; + yield return $"{{ {range} }}"; + yield return $"{{{range},{range}}}"; + yield return $"{{{range},}}"; + yield return $"{{,{range}}}"; + yield return $"{{{range}"; + yield return range; + yield return $"{{{range}}}x"; + yield return $"{{{{{range}}}}}"; + } + + for (var i = 0; i + 1 < ranges.Count; i++) + { + yield return $"{{{ranges[i]},{ranges[i + 1]}}}"; + yield return $"{{{ranges[i + 1]}, {ranges[i]}}}"; + yield return $"{{{ranges[i]};{ranges[i + 1]}}}"; + } + } + + foreach (var literal in Literals()) + { + var parsed = Read(() => RangeSet.Parse(literal, CultureInfo.InvariantCulture)); + + checks += Agree(failures, $"{label} {Show(literal)}", parsed, Entries>(literal, + ("Parse(span)", () => RangeSet.Parse(literal.AsSpan(), CultureInfo.InvariantCulture)), + ("TryParse", () => RangeSet.TryParse(literal, CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("IParsable.Parse", () => StringOverloads.Parse>(literal, CultureInfo.InvariantCulture)), + ("IParsable.TryParse", () => StringOverloads.TryParse>(literal, CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("TryParse(span)", () => RangeSet.TryParse(literal.AsSpan(), CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("JSON", () => JsonSerializer.Deserialize>(JsonSerializer.Serialize(literal))!))); + } + + return checks; + } + + // ---------------------------------------------------------------- value sets + + private static int SweepSet(List failures) + where TSet : class, IValueSetFactory, IValueSet + where TElement : IEquatable + { + var label = Display(typeof(TSet)); + var checks = 0; + var texts = SetProbes.For().Select(value => TSet.FormatValue(value, null, CultureInfo.InvariantCulture)).ToList(); + + foreach (var literal in SetWrapperParityTests.LiteralGrid(texts)) + { + var parsed = Read(() => StringOverloads.Parse(literal, CultureInfo.InvariantCulture)); + + checks += Agree(failures, $"{label} {Show(literal)}", parsed, Entries(literal, + ("Parse(span)", () => TSet.Parse(literal.AsSpan(), CultureInfo.InvariantCulture)), + ("TryParse", () => StringOverloads.TryParse(literal, CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")), + ("TryParse(span)", () => TSet.TryParse(literal.AsSpan(), CultureInfo.InvariantCulture, out var r) ? r : throw new FormatException("TryParse: false")))); + } + + return checks; + } + + // ---------------------------------------------------------------- the comparison + + /// What one entry point made of the literal: a value, a refusal, or an exception that is neither. + private sealed record Outcome(object? Value, string Text) + { + internal static readonly Outcome Refused = new(null, "refused"); + } + + private static Outcome Read(Func read) + { + try + { + var value = read(); + return value is null ? new(null, "null") : new(value, $"{value.GetType().Name} {value}"); + } + catch (Exception ex) when (ex is FormatException or JsonException or InvalidOperationException or ArgumentException + or NotSupportedException or OverflowException) + { + return Outcome.Refused; + } + catch (Exception ex) + { + return new(null, $"throws {ex.GetType().Name}"); + } + } + + /// + /// The entry points every type shares — the TypeConverter and configuration binding — after + /// the type's own. + /// + private static IEnumerable<(string Name, Func Read)> Entries(string literal, params (string, Func)[] own) + where TValue : class + { + foreach (var (name, read) in own) + yield return (name, () => read()); + + // An empty string is an absent value to the TypeConverter and the binder, never a value or a + // refusal: documented (docs/serialization.md, "An empty string converts to null"). + if (literal.Length == 0) yield break; + + yield return ("TypeConverter", () => TypeDescriptor.GetConverter(typeof(TValue)).ConvertFromInvariantString(literal)!); + yield return ("configuration", () => new ConfigurationBuilder() + .AddInMemoryCollection([new KeyValuePair("Value", literal)]) + .Build() + .Get>()?.Value + ?? throw new InvalidOperationException("bound no value")); + } + + private static int Agree(List failures, string name, Outcome expected, IEnumerable<(string Name, Func Read)> entries) + { + var checks = 0; + foreach (var (entry, read) in entries) + { + checks++; + var actual = Read(read); + + if (actual.Text != expected.Text) + failures.Add($"{name} {entry}: {actual.Text}, but Parse → {expected.Text}"); + else if (actual.Value is not null && !actual.Value.Equals(expected.Value)) + failures.Add($"{name} {entry}: {actual.Text} prints alike but is not equal to what Parse read"); + } + + return checks; + } + + private static string Show(string literal) => JsonSerializer.Serialize(literal); + + private static string Display(Type type) => + type.IsGenericType + ? $"{type.Name[..type.Name.IndexOf('`')]}<{string.Join(", ", type.GetGenericArguments().Select(Display))}>" + : type.Name; +} diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSetLiftParityTests.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSetLiftParityTests.cs new file mode 100644 index 00000000..9d78f511 --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSetLiftParityTests.cs @@ -0,0 +1,195 @@ +using System.Globalization; +using CodoMetis.ValueRanges.Core; +using CodoMetis.ValueRanges.Oracles; +using static CodoMetis.ValueRanges.Conventions.Tests.RangeSpecs; + +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// A range and the one-element holding it answer every question alike: +/// over every ordered pair of the shape matrix, a set operation on the two one-element sets (and on the +/// set with the bare range) equals the set built from the range operation's result, every predicate +/// gives the same answer, and every unary accessor reads the same bound — for every discovered range type. +/// +/// +/// +/// The range engines and the multirange code are two implementations of the same algebra, and the +/// receiver-shaped dispatch bug has crossed between them: IsAdjacentTo (6.2.1), then +/// IsStrictlyLeftOf and Except (7.0.0), then RangeSet.Except(TRange) (8.0.0). The +/// set-theory oracles find such a bug where they look — at grid points inside a small universe. This +/// sweep needs no model at all, so it also looks where no model reaches: bounds at the domain's minimum +/// and maximum, results compared structurally (bound values, inclusivity, shape) rather than through +/// Contains at a few points, and the operator spellings (|, &, -) beside +/// the named methods. +/// +/// +/// The matrix is over four grid bounds plus the two domain +/// extremes. A specification the type cannot construct (a discrete bound past the domain's last step) +/// is skipped — holds construction there. One +/// [DynamicData] row per range type; a failure line starts with the type's name. +/// +/// +[TestClass] +public sealed class RangeSetLiftParityTests +{ + public sealed record LiftRow(string Label, Func, int> Sweep) + { + public override string ToString() => Label; + } + + public static IEnumerable Rows => + RangeProbes.AllRangeTypes().Select(pair => new object[] + { + new LiftRow(pair.Range.Name, failures => Reflect.InvokeGeneric( + typeof(RangeSetLiftParityTests), nameof(Sweep), [pair.Range, pair.Element], failures)) + }); + + [TestMethod] + public void Discovery_FindsEveryRangeType() + { + const int knownRangeTypes = 11; + var rows = Rows.Count(); + Assert.IsTrue(rows >= knownRangeTypes, $"Found {rows} range types, fewer than {knownRangeTypes}."); + + var missing = RangeProbes.AllRangeTypes().Where(pair => !Embeddings.ContainsKey(pair.Element) || !Extremes.ContainsKey(pair.Element)) + .Select(pair => pair.Range.Name).ToList(); + Assert.AreEqual(0, missing.Count, "A range type's element has no embedding or no extremes in RangeSpecs: " + string.Join(", ", missing)); + } + + [TestMethod] + [DynamicData(nameof(Rows))] + public void Range_AndItsOneElementRangeSet_AnswerAlike(LiftRow row) + { + var failures = new List(); + var checks = row.Sweep(failures); + + Assert.IsTrue(checks >= 100_000, $"{row}: only {checks} checks ran."); + + Candidates.Verdict(nameof(RangeSetLiftParityTests), failures, + $"{row}: of {checks} checks, the one-element RangeSet disagrees with its range", shown: 30, rowPrefix: row.Label + " "); + } + + private static int Sweep(List failures) + where TRange : class, IRangeFactory, IRange + where T : struct, IComparable, IEquatable + { + var label = typeof(TRange).Name; + var valueOf = ValueOf(); + var checks = 0; + + // Four grid bounds — enough for disjoint, adjacent, overlapping and nested pairs — and the + // domain's extremes. A continuous type takes even positions, so an exclusive bound leaves a gap. + int[] bounds = TRange.IsDiscrete ? [DomainMin, 1, 2, 3, 4, DomainMax] : [DomainMin, 2, 4, 6, 8, DomainMax]; + + var cases = new List<(string Name, TRange Range, RangeSet Lifted)>(); + foreach (var spec in EnumerateSpecs(bounds)) + { + TRange range; + try + { + range = Build(spec, valueOf); + } + catch (Exception ex) when (ex is ArgumentException or OverflowException or InvalidOperationException) + { + continue; + } + + cases.Add((Describe(spec, valueOf), range, RangeSet.From([range]))); + } + + // The points Contains(T) is asked about: every grid position, the half-steps between, the extremes. + T[] points = [.. Enumerable.Range(0, 11).Select(valueOf), valueOf(DomainMin), valueOf(DomainMax)]; + + foreach (var (name, a, lifted) in cases) + { + Unary("IsEmpty", a.IsEmpty().ToString(), lifted.IsEmpty().ToString()); + Unary("IsInfinity", a.IsInfinity().ToString(), lifted.IsInfinity().ToString()); + Unary("IsFinite", a.IsFinite().ToString(), lifted.IsFinite().ToString()); + Unary("IsUnboundedStart", a.IsUnboundedStart().ToString(), lifted.IsUnboundedStart().ToString()); + Unary("IsUnboundedEnd", a.IsUnboundedEnd().ToString(), lifted.IsUnboundedEnd().ToString()); + Unary("LowerBound", Value(a.LowerBound()), Value(lifted.LowerBound())); + Unary("UpperBound", Value(a.UpperBound()), Value(lifted.UpperBound())); + Unary("LowerBoundInclusive", a.LowerBoundInclusive().ToString(), lifted.LowerBoundInclusive().ToString()); + Unary("UpperBoundInclusive", a.UpperBoundInclusive().ToString(), lifted.UpperBoundInclusive().ToString()); + Unary("Merge", Outcome(() => Show(a)), Outcome(() => Show(lifted.Merge()))); + Unary("Complement", Outcome(() => TRange.Infinite.Except(a).ToString()), Outcome(() => lifted.Complement().ToString())); + Unary("ToString", a.IsEmpty() ? "{}" : "{" + Show(a) + "}", Outcome(() => lifted.ToString())); + + foreach (var point in points) + Unary($"Contains({TRange.FormatValue(point, null, CultureInfo.InvariantCulture)})", + Outcome(() => a.Contains(point).ToString()), Outcome(() => lifted.Contains(point).ToString())); + + void Unary(string operation, string range, string set) + { + checks++; + if (!string.Equals(range, set, StringComparison.Ordinal)) + failures.Add($"{label} {name} {operation}: range → {range}, RangeSet → {set}"); + } + } + + foreach (var (aName, a, setA) in cases) + foreach (var (bName, b, setB) in cases) + { + Predicate("Contains", () => a.Contains(b), () => setA.Contains(setB), () => setA.Contains(b)); + Predicate("IsContainedBy", () => a.IsContainedBy(b), () => setB.Contains(setA), () => setB.Contains(a)); + Predicate("Overlaps", () => a.Overlaps(b), () => setA.Overlaps(setB), () => setA.Overlaps(b)); + Predicate("IsAdjacentTo", () => a.IsAdjacentTo(b), () => setA.IsAdjacentTo(setB), () => setA.IsAdjacentTo(b)); + Predicate("IsStrictlyLeftOf", () => a.IsStrictlyLeftOf(b), () => setA.IsStrictlyLeftOf(setB), () => setA.IsStrictlyLeftOf(b)); + Predicate("IsStrictlyRightOf", () => a.IsStrictlyRightOf(b), () => setA.IsStrictlyRightOf(setB), () => setA.IsStrictlyRightOf(b)); + Predicate("DoesNotExtendRightOf", () => a.DoesNotExtendRightOf(b), () => setA.DoesNotExtendRightOf(setB), () => setA.DoesNotExtendRightOf(b)); + Predicate("DoesNotExtendLeftOf", () => a.DoesNotExtendLeftOf(b), () => setA.DoesNotExtendLeftOf(setB), () => setA.DoesNotExtendLeftOf(b)); + Predicate("Equals", () => a.Equals(b), () => setA.Equals(setB), () => setA == setB); + + Operation("Intersect", () => RangeSet.From([a.Intersect(b)]), + ("Intersect(set)", () => setA.Intersect(setB)), ("Intersect(range)", () => setA.Intersect(b)), + ("& set", () => setA & setB), ("& range", () => setA & b)); + Operation("Union", () => a.Union(b), + ("Union(set)", () => setA.Union(setB)), ("Union(range)", () => setA.Union(b)), + ("| set", () => setA | setB), ("| range", () => setA | b)); + Operation("Except", () => a.Except(b), + ("Except(set)", () => setA.Except(setB)), ("Except(range)", () => setA.Except(b)), + ("- set", () => setA - setB), ("- range", () => setA - b)); + Operation("Merge", () => RangeSet.From([a.Merge(b)]), + ("Union(set).Merge()", () => RangeSet.From([setA.Union(setB).Merge()]))); + + void Predicate(string operation, Func range, Func setSet, Func setRange) + { + var expected = Outcome(() => range().ToString()); + Compare(operation, expected, $"{operation}(set)", Outcome(() => setSet().ToString())); + Compare(operation, expected, $"{operation}(range)", Outcome(() => setRange().ToString())); + } + + void Operation(string operation, Func> range, params (string Name, Func> Run)[] lifted) + { + var expected = Outcome(() => range().ToString()); + foreach (var (setOperation, run) in lifted) + Compare(operation, expected, setOperation, Outcome(() => run().ToString())); + } + + void Compare(string operation, string range, string setOperation, string set) + { + checks++; + if (!string.Equals(range, set, StringComparison.Ordinal)) + failures.Add($"{label} {aName} {operation} {bName}: range → {range}, RangeSet {setOperation} → {set}"); + } + } + + return checks; + + string Show(TRange range) => ((IFormattable)range).ToString(null, CultureInfo.InvariantCulture); + + string Value(T? value) => value is { } v ? TRange.FormatValue(v, null, CultureInfo.InvariantCulture) : "null"; + } + + private static string Outcome(Func run) + { + try + { + return run() ?? "null"; + } + catch (Exception ex) + { + return $"throws {ex.GetType().Name}"; + } + } +} diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSpecs.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSpecs.cs new file mode 100644 index 00000000..f0885d69 --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/RangeSpecs.cs @@ -0,0 +1,126 @@ +using System.Diagnostics; +using System.Globalization; +using CodoMetis.ValueRanges.Core; +using NodaTime; + +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// The shape matrix the range sweeps enumerate: every shape, every bound position on a small grid and +/// every inclusivity, embedded into each discovered element type in order. Shared by +/// , which checks each pair against set theory, and +/// , which checks each pair against its one-element multiranges. +/// +internal static class RangeSpecs +{ + internal enum Shape { Empty, Infinity, Finite, UnboundedStart, UnboundedEnd } + + internal sealed record Spec(Shape Shape, int Start, int End, bool StartInclusive, bool EndInclusive); + + /// The grid positions that stand for the element domain's minimum and maximum. + internal const int DomainMin = int.MinValue, DomainMax = int.MaxValue; + + private static readonly DateTime s_dateTimeOrigin = new(2026, 1, 1, 0, 0, 0, DateTimeKind.Unspecified); + private static readonly LocalDateTime s_localOrigin = new(2026, 1, 1, 0, 0); + private static readonly Instant s_instantOrigin = Instant.FromUtc(2026, 1, 1, 0, 0); + + /// Grid index to element, order-preserving; a discrete type's step is one grid point. + internal static readonly Dictionary Embeddings = new() + { + [typeof(int)] = (Func)(k => k), + [typeof(long)] = (Func)(k => k), + [typeof(decimal)] = (Func)(k => k * 0.5m), + [typeof(DateOnly)] = (Func)(k => new DateOnly(2026, 1, 1).AddDays(k)), + [typeof(TimeOnly)] = (Func)(k => new TimeOnly(9, 0).AddMinutes(30 * k)), + [typeof(DateTime)] = (Func)(k => s_dateTimeOrigin.AddMinutes(30 * k)), + [typeof(DateTimeOffset)] = (Func)(k => new DateTimeOffset(s_dateTimeOrigin.AddMinutes(30 * k), TimeSpan.FromHours(1))), + [typeof(LocalDate)] = (Func)(k => new LocalDate(2026, 1, 1).PlusDays(k)), + [typeof(LocalDateTime)] = (Func)(k => s_localOrigin.PlusMinutes(30 * k)), + [typeof(Instant)] = (Func)(k => s_instantOrigin.Plus(Duration.FromMinutes(30 * k))), + [typeof(YearMonth)] = (Func)(k => new YearMonth(2026, 1).PlusMonths(k)) + }; + + /// The least and greatest value of each element domain, which no grid position reaches. + internal static readonly Dictionary Extremes = new() + { + [typeof(int)] = (int.MinValue, int.MaxValue), + [typeof(long)] = (long.MinValue, long.MaxValue), + [typeof(decimal)] = (decimal.MinValue, decimal.MaxValue), + [typeof(DateOnly)] = (DateOnly.MinValue, DateOnly.MaxValue), + [typeof(TimeOnly)] = (TimeOnly.MinValue, TimeOnly.MaxValue), + [typeof(DateTime)] = (DateTime.MinValue, DateTime.MaxValue), + [typeof(DateTimeOffset)] = (DateTimeOffset.MinValue, DateTimeOffset.MaxValue), + [typeof(LocalDate)] = (LocalDate.MinIsoValue, LocalDate.MaxIsoValue), + [typeof(LocalDateTime)] = (LocalDateTime.MinIsoValue, LocalDateTime.MaxIsoValue), + [typeof(Instant)] = (Instant.MinValue, Instant.MaxValue), + [typeof(YearMonth)] = (new YearMonth(-9998, 1), new YearMonth(9999, 12)) + }; + + /// + /// The embedding of , with and + /// mapped to the domain's extremes. + /// + internal static Func ValueOf() + { + var embed = (Func)Embeddings[typeof(T)]; + var (min, max) = Extremes[typeof(T)]; + + return k => k switch + { + DomainMin => (T)min, + DomainMax => (T)max, + _ => embed(k) + }; + } + + /// Both unbounded shapes at every bound, and every finite range between two bounds, with every inclusivity. + internal static IEnumerable EnumerateSpecs(int[] bounds) + { + yield return new(Shape.Empty, 0, 0, false, false); + yield return new(Shape.Infinity, 0, 0, false, false); + + foreach (var bound in bounds) + foreach (var inclusive in (bool[]) [true, false]) + { + yield return new(Shape.UnboundedStart, 0, bound, false, inclusive); + yield return new(Shape.UnboundedEnd, bound, 0, inclusive, false); + } + + foreach (var start in bounds) + foreach (var end in bounds.Where(end => end >= start)) + foreach (var startInclusive in (bool[]) [true, false]) + foreach (var endInclusive in (bool[]) [true, false]) + yield return new(Shape.Finite, start, end, startInclusive, endInclusive); + } + + internal static TRange Build(Spec spec, Func valueOf) + where TRange : IRangeFactory, IRange + where T : struct, IComparable, IEquatable => + spec.Shape switch + { + Shape.Empty => TRange.Empty, + Shape.Infinity => TRange.Infinite, + Shape.Finite => TRange.CreateFinite(valueOf(spec.Start), valueOf(spec.End), spec.StartInclusive, spec.EndInclusive), + Shape.UnboundedStart => TRange.CreateUnboundedStart(valueOf(spec.End), spec.EndInclusive), + Shape.UnboundedEnd => TRange.CreateUnboundedEnd(valueOf(spec.Start), spec.StartInclusive), + _ => throw new UnreachableException() + }; + + /// The specification as a literal, with each bound written by the type's own FormatValue. + internal static string Describe(Spec spec, Func valueOf) + where TRange : IRangeFactory + where T : struct, IComparable, IEquatable + { + string Text(int k) => TRange.FormatValue(valueOf(k), null, CultureInfo.InvariantCulture); + + return spec.Shape switch + { + Shape.Empty => "empty", + Shape.Infinity => "(,)", + Shape.Finite => $"{(spec.StartInclusive ? '[' : '(')}{Text(spec.Start)},{Text(spec.End)}{(spec.EndInclusive ? ']' : ')')}", + Shape.UnboundedStart => $"(,{Text(spec.End)}{(spec.EndInclusive ? ']' : ')')}", + Shape.UnboundedEnd => $"{(spec.StartInclusive ? '[' : '(')}{Text(spec.Start)},)", + _ => throw new UnreachableException() + }; + } +} diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/SetWrapperParityTests.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/SetWrapperParityTests.cs new file mode 100644 index 00000000..79d86fea --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/SetWrapperParityTests.cs @@ -0,0 +1,431 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Reflection; +using System.Text.Json; +using CodoMetis.ValueRanges.Core; +using CodoMetis.ValueRanges.Oracles; +using NodaTime; + +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// Every primitive value set answers exactly as its wrapper arity closed over an identity element +/// (Int32Set and Int32Set<Same<int>>): every operation, every parse and format +/// entry point, JSON both ways and the TypeConverter give the same value, or throw the same +/// exception type on the same bad input. Nothing here says what the right answer is; the two siblings +/// only have to agree. +/// +/// +/// +/// The wrapper arities have lagged their primitive set more than once — "as DecimalSet does" is a +/// recurring changelog phrase — and each time the divergence was found at one entry point and fixed +/// there. The claim-driven oracles check each family against its documents, so they cannot see a promise +/// the two siblings share implicitly. A differential sweep needs no ground truth: an identity element +/// (, ) leaves the family's own code as the only difference, +/// so whichever side disagrees is the defect. +/// +/// +/// The input grid is the family's probes from plus its extremes (the domain's +/// minimum and maximum, the strings that need escaping), every subset shape built from them, and array +/// literals and JSON documents derived from their text: quoted and whitespace-padded elements, +/// duplicates, out of order, empty, NULL, and the malformed neighbours of each. One +/// [DynamicData] row per family; a failure line starts with the family's name, which is what a +/// candidate row in test/oracles/candidates.json is scoped by. +/// +/// +/// A probe the primitive family rewrites (a NodaTime date in another calendar) is left out: a +/// wrapper family cannot build its element from the normalized primitive, so it refuses one instead — +/// the documented rule (docs/architecture.md), not a disagreement between siblings. +/// +/// +[TestClass] +public sealed class SetWrapperParityTests +{ + private static readonly CultureInfo German = CultureInfo.GetCultureInfo("de-DE"); + + /// The values at the edge of each element domain, and the strings an array literal must escape. + private static readonly Dictionary Extremes = new() + { + [typeof(string)] = ["", " padded ", "NULL", "null", "a,b", "{x}", "quo\"te", "back\\slash", "tab\there", "ü"], + [typeof(Guid)] = [Guid.Empty, Guid.AllBitsSet], + [typeof(short)] = [short.MinValue, short.MaxValue], + [typeof(int)] = [int.MinValue, int.MaxValue], + [typeof(long)] = [long.MinValue, long.MaxValue], + [typeof(decimal)] = [decimal.MinValue, decimal.MaxValue, 0.0000000000000000000000000001m, 1.10m], + [typeof(DateOnly)] = [DateOnly.MinValue, DateOnly.MaxValue], + [typeof(TimeOnly)] = [TimeOnly.MinValue, TimeOnly.MaxValue], + [typeof(DateTime)] = [DateTime.MinValue, DateTime.MaxValue, DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc)], + [typeof(DateTimeOffset)] = [DateTimeOffset.MinValue, DateTimeOffset.MaxValue, + new DateTimeOffset(2024, 6, 15, 10, 30, 0, TimeSpan.FromHours(14))], + [typeof(LocalDate)] = [LocalDate.MinIsoValue, LocalDate.MaxIsoValue], + [typeof(LocalDateTime)] = [LocalDateTime.MinIsoValue, LocalDateTime.MaxIsoValue], + [typeof(Instant)] = [Instant.MinValue, Instant.MaxValue], + [typeof(LocalTime)] = [LocalTime.Midnight, LocalTime.MaxValue], + [typeof(YearMonth)] = [new YearMonth(-9998, 1), new YearMonth(9999, 12)] + }; + + private static readonly string?[] Formats = [null, "", "G", "D", "O"]; + + /// One row per primitive family; the label is the prefix of every failure line and candidate row. + public sealed record ParityRow(string Label, Func, int> Sweep) + { + public override string ToString() => Label; + } + + public static IEnumerable Rows => + Pairs().Select(pair => new object[] + { + new ParityRow(pair.Primitive.Name, failures => Reflect.InvokeGeneric( + typeof(SetWrapperParityTests), nameof(Sweep), + [pair.Primitive, pair.Element, pair.Wrapper, IdentityWrappers.For(pair.Element)], failures)) + }); + + private static IEnumerable<(Type Primitive, Type Element, Type Wrapper)> Pairs() + { + foreach (var (setType, element) in SetProbes.AllSetTypes().Where(pair => !pair.Set.IsGenericType)) + { + var family = setType.Assembly.GetType(setType.FullName + "`1") + ?? throw new InvalidOperationException($"{setType.Name} has no wrapper arity {setType.Name}."); + + yield return (setType, element, family.MakeGenericType(IdentityWrappers.For(element))); + } + } + + [TestMethod] + public void Discovery_PairsEveryPrimitiveFamilyWithItsWrapperArity() + { + // 10 core families and 5 NodaTime ones, each with its wrapper arity, as of 9.0.0. + const int knownFamilies = 15; + var rows = Rows.Count(); + Assert.IsTrue(rows >= knownFamilies, $"Found {rows} primitive families, fewer than {knownFamilies}."); + + var wrapperFamilies = SetProbes.AllSetTypes().Count(pair => pair.Set.IsGenericType); + Assert.AreEqual(wrapperFamilies, rows, "Every wrapper family must have a primitive sibling, and every primitive family a wrapper arity."); + } + + [TestMethod] + [DynamicData(nameof(Rows))] + public void PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike(ParityRow row) + { + var failures = new List(); + var checks = row.Sweep(failures); + + Assert.IsTrue(checks >= 1_000, $"{row}: only {checks} checks ran."); + + Candidates.Verdict(nameof(SetWrapperParityTests), failures, + $"{row}: of {checks} checks, the wrapper arity disagrees with its primitive set", shown: 30, rowPrefix: row.Label + " "); + } + + // ---------------------------------------------------------------- the sweep + + private static int Sweep(List failures) + where TPrimSet : class, IValueSetFactory, IValueSet + where TPrim : IEquatable + where TWrapSet : class, IValueSetFactory, IValueSet + where TWrap : struct, IEquatable, IIdentity + { + var label = typeof(TPrimSet).Name; + var wrap = $"{typeof(TPrimSet).Name}<{typeof(TWrap).Name.Split('`')[0]}>"; + var checks = 0; + + // ---- the universe: probes the family keeps as given, plus the domain's extremes + var universe = SetProbes.For() + .Concat(Extremes[typeof(TPrim)].Cast()) + .Where(value => TPrimSet.From(value).Values.Single().Equals(value)) + .DistinctBy(value => TPrimSet.FormatValue(value, null, CultureInfo.InvariantCulture)) + .ToArray(); + + var sets = SubsetShapes(universe).ToList(); + + // ---- element format and parse + var elementTexts = new List(); + foreach (var value in universe) + { + var text = TPrimSet.FormatValue(value, null, CultureInfo.InvariantCulture); + elementTexts.Add(text); + + foreach (var format in Formats) + foreach (var provider in (CultureInfo[])[CultureInfo.InvariantCulture, German]) + Compare($"FormatValue({Show(text)}, {Show(format)}, {provider.Name})", + Outcome(() => TPrimSet.FormatValue(value, format, provider)), + Outcome(() => TWrapSet.FormatValue(TWrap.Wrap(value), format, provider))); + } + + foreach (var text in ElementTextGrid(elementTexts)) + Compare($"ParseValue({Show(text)})", + Outcome(() => ElementText(TPrimSet.ParseValue(text.AsSpan(), CultureInfo.InvariantCulture))), + Outcome(() => ElementText(TWrapSet.ParseValue(text.AsSpan(), CultureInfo.InvariantCulture).Value))); + + // ---- construction, unary state and formatting, per set + var primCount = Property("Count"); + var primIsEmpty = Property("IsEmpty"); + var wrapCount = Property("Count"); + var wrapIsEmpty = Property("IsEmpty"); + + foreach (var elements in sets) + { + var name = Name(elements); + var prim = TPrimSet.From(elements); + var wrapped = elements.Select(TWrap.Wrap).ToArray(); + + Compare($"From({name})", Render(prim), Outcome(() => Render(TWrapSet.From(wrapped)))); + Compare($"From(reversed, duplicated {name})", + Outcome(() => Render(TPrimSet.From([.. Enumerable.Reverse(elements), .. elements]))), + Outcome(() => Render(TWrapSet.From([.. Enumerable.Reverse(wrapped), .. wrapped])))); + Compare($"From(span {name})", + Outcome(() => Render(TPrimSet.From(elements.AsSpan()))), + Outcome(() => Render(TWrapSet.From(wrapped.AsSpan())))); + Compare($"repeated Add {name}", + Outcome(() => Render(elements.Aggregate(TPrimSet.Empty, (set, value) => set.Add(value)))), + Outcome(() => Render(wrapped.Aggregate(TWrapSet.Empty, (set, value) => set.Add(value))))); + + var wrapSet = TWrapSet.From(wrapped); + + Compare($"{name}.Count", primCount.GetValue(prim)!.ToString()!, wrapCount.GetValue(wrapSet)!.ToString()!); + Compare($"{name}.IsEmpty", primIsEmpty.GetValue(prim)!.ToString()!, wrapIsEmpty.GetValue(wrapSet)!.ToString()!); + Compare($"{name}.ToString()", Outcome(prim.ToString), Outcome(wrapSet.ToString)); + + foreach (var format in Formats) + foreach (var provider in (CultureInfo[])[CultureInfo.InvariantCulture, German]) + Compare($"{name}.ToString({Show(format)}, {provider.Name})", + Outcome(() => prim.ToString(format, provider)), + Outcome(() => wrapSet.ToString(format, provider))); + + Compare($"TypeConverter.ConvertToInvariantString({name})", + Outcome(() => TypeDescriptor.GetConverter(typeof(TPrimSet)).ConvertToInvariantString(prim)), + Outcome(() => TypeDescriptor.GetConverter(typeof(TWrapSet)).ConvertToInvariantString(wrapSet))); + + // ---- JSON write: the same token kinds, and each side reads the other's document as the same value + var primJson = JsonSerializer.Serialize(prim); + var wrapJson = Outcome(() => JsonSerializer.Serialize(wrapSet)); + + Compare($"JSON token kinds of {name}", TokenKinds(primJson), Outcome(() => TokenKinds(wrapJson))); + Compare($"JSON write {name}, read as {label}", Render(prim), + Outcome(() => Render(JsonSerializer.Deserialize(wrapJson)!))); + Compare($"JSON write {name}, read as {wrap}", Render(prim), + Outcome(() => Render(JsonSerializer.Deserialize(primJson)!))); + + // ---- element operations, with every element of the universe + foreach (var value in universe) + { + var element = TWrap.Wrap(value); + var shown = Show(ElementText(value)); + + Compare($"{name}.Contains({shown})", Outcome(() => prim.Contains(value).ToString()), Outcome(() => wrapSet.Contains(element).ToString())); + Compare($"{name}.Add({shown})", Outcome(() => Render(prim.Add(value))), Outcome(() => Render(wrapSet.Add(element)))); + Compare($"{name}.Remove({shown})", Outcome(() => Render(prim.Remove(value))), Outcome(() => Render(wrapSet.Remove(element)))); + } + } + + // ---- binary operations, over every ordered pair of set shapes + var primEquality = Operator("op_Equality"); + var primInequality = Operator("op_Inequality"); + var wrapEquality = Operator("op_Equality"); + var wrapInequality = Operator("op_Inequality"); + + foreach (var leftElements in sets) + foreach (var rightElements in sets) + { + var pair = $"{Name(leftElements)} ? {Name(rightElements)}"; + var (pl, pr) = (TPrimSet.From(leftElements), TPrimSet.From(rightElements)); + var (wl, wr) = (TWrapSet.From(leftElements.Select(TWrap.Wrap)), TWrapSet.From(rightElements.Select(TWrap.Wrap))); + + Compare(pair.Replace("?", "Union"), Outcome(() => Render(pl.Union(pr))), Outcome(() => Render(wl.Union(wr)))); + Compare(pair.Replace("?", "Intersect"), Outcome(() => Render(pl.Intersect(pr))), Outcome(() => Render(wl.Intersect(wr)))); + Compare(pair.Replace("?", "Except"), Outcome(() => Render(pl.Except(pr))), Outcome(() => Render(wl.Except(wr)))); + + Compare(pair.Replace("?", "Overlaps"), Outcome(() => pl.Overlaps(pr).ToString()), Outcome(() => wl.Overlaps(wr).ToString())); + Compare(pair.Replace("?", "IsSubsetOf"), Outcome(() => pl.IsSubsetOf(pr).ToString()), Outcome(() => wl.IsSubsetOf(wr).ToString())); + Compare(pair.Replace("?", "IsSupersetOf"), Outcome(() => pl.IsSupersetOf(pr).ToString()), Outcome(() => wl.IsSupersetOf(wr).ToString())); + Compare(pair.Replace("?", "IsProperSubsetOf"), Outcome(() => pl.IsProperSubsetOf(pr).ToString()), Outcome(() => wl.IsProperSubsetOf(wr).ToString())); + Compare(pair.Replace("?", "IsProperSupersetOf"), Outcome(() => pl.IsProperSupersetOf(pr).ToString()), Outcome(() => wl.IsProperSupersetOf(wr).ToString())); + Compare(pair.Replace("?", "Equals"), Outcome(() => pl.Equals(pr).ToString()), Outcome(() => wl.Equals(wr).ToString())); + Compare(pair.Replace("?", "=="), primEquality.Invoke(null, [pl, pr])!.ToString()!, wrapEquality.Invoke(null, [wl, wr])!.ToString()!); + Compare(pair.Replace("?", "!="), primInequality.Invoke(null, [pl, pr])!.ToString()!, wrapInequality.Invoke(null, [wl, wr])!.ToString()!); + } + + // ---- literals through every text entry point + var primConverter = TypeDescriptor.GetConverter(typeof(TPrimSet)); + var wrapConverter = TypeDescriptor.GetConverter(typeof(TWrapSet)); + + foreach (var literal in LiteralGrid(elementTexts)) + { + var shown = Show(literal); + + Compare($"Parse({shown})", + Outcome(() => Render(StringOverloads.Parse(literal, CultureInfo.InvariantCulture))), + Outcome(() => Render(StringOverloads.Parse(literal, CultureInfo.InvariantCulture)))); + Compare($"Parse({shown}, de-DE)", + Outcome(() => Render(StringOverloads.Parse(literal, German))), + Outcome(() => Render(StringOverloads.Parse(literal, German)))); + Compare($"Parse(span {shown})", + Outcome(() => Render(TPrimSet.Parse(literal.AsSpan(), CultureInfo.InvariantCulture))), + Outcome(() => Render(TWrapSet.Parse(literal.AsSpan(), CultureInfo.InvariantCulture)))); + Compare($"TryParse({shown})", + Outcome(() => StringOverloads.TryParse(literal, CultureInfo.InvariantCulture, out var p) ? Render(p) : $"false, {Render(p)}"), + Outcome(() => StringOverloads.TryParse(literal, CultureInfo.InvariantCulture, out var w) ? Render(w) : $"false, {Render(w)}")); + Compare($"TryParse(span {shown})", + Outcome(() => TPrimSet.TryParse(literal.AsSpan(), CultureInfo.InvariantCulture, out var p) ? Render(p) : $"false, {Render(p)}"), + Outcome(() => TWrapSet.TryParse(literal.AsSpan(), CultureInfo.InvariantCulture, out var w) ? Render(w) : $"false, {Render(w)}")); + Compare($"TypeConverter.ConvertFromInvariantString({shown})", + Outcome(() => Render((TPrimSet)primConverter.ConvertFromInvariantString(literal)!)), + Outcome(() => Render((TWrapSet)wrapConverter.ConvertFromInvariantString(literal)!))); + Compare($"TypeConverter.ConvertFrom(de-DE, {shown})", + Outcome(() => Render((TPrimSet)primConverter.ConvertFrom(null, German, literal)!)), + Outcome(() => Render((TWrapSet)wrapConverter.ConvertFrom(null, German, literal)!))); + } + + // ---- JSON documents read by both + foreach (var json in JsonGrid(sets.Select(elements => JsonSerializer.Serialize(TPrimSet.From(elements))))) + Compare($"JSON read {json}", + Outcome(() => Render(JsonSerializer.Deserialize(json))), + Outcome(() => Render(JsonSerializer.Deserialize(json)))); + + return checks; + + void Compare(string operation, string primitive, string wrapper) + { + checks++; + if (!string.Equals(primitive, wrapper, StringComparison.Ordinal)) + failures.Add($"{label} {operation}: {label} → {primitive}, {wrap} → {wrapper}"); + } + + string Render(object? set) => set switch + { + null => "null", + TPrimSet primitive => Elements(primitive.Values), + TWrapSet wrapperSet => Elements(wrapperSet.Values.Select(element => element.Value)), + _ => throw new UnreachableException() + }; + + // The primitive's own text form, in the set's order: a lost scale, kind or offset shows, and so + // does an order the family did not sort by. + string Elements(IEnumerable values) => + JsonSerializer.Serialize(values.Select(ElementText).ToArray()); + + string ElementText(TPrim value) => TPrimSet.FormatValue(value, null, CultureInfo.InvariantCulture); + + string Name(TPrim[] elements) => + "{" + string.Join(",", elements.Select(value => ElementText(value))) + "}"; + } + + // ---------------------------------------------------------------- grids + + /// The empty set, every singleton, consecutive pairs, alternate elements and the whole universe. + private static IEnumerable SubsetShapes(TPrim[] universe) + { + yield return []; + foreach (var value in universe) yield return [value]; + for (var i = 0; i + 1 < universe.Length; i++) yield return [universe[i], universe[i + 1]]; + yield return [.. universe.Where((_, index) => index % 2 == 0)]; + yield return [.. universe.Where((_, index) => index % 2 == 1)]; + yield return universe; + } + + /// Each element text, padded, quoted, and its malformed neighbours. + private static IEnumerable ElementTextGrid(List texts) + { + foreach (var text in texts) + { + yield return text; + yield return $" {text} "; + yield return $"\t{text}"; + yield return $"\"{text}\""; + yield return text.ToUpperInvariant(); + yield return text + "x"; + } + + yield return ""; + yield return " "; + yield return "NULL"; + yield return "infinity"; + yield return "-infinity"; + } + + /// + /// Array literals over the family's element texts: well-formed, padded, quoted, duplicated, out of + /// order, empty, with NULL, and their malformed neighbours. + /// + internal static IEnumerable LiteralGrid(List texts) + { + var (t0, t1) = (texts[0], texts[Math.Min(1, texts.Count - 1)]); + + string[] fixedLiterals = + [ + "{}", "{ }", " {} ", "", " ", "{", "}", "{{}}", "[1:1]={" + Quote(t0) + "}", + $"{{{t0}}}", $"{{{Quote(t0)}}}", $"{{{Padded(t0)}}}", $"{{ {t0} }}", + $"{{{t0},{t1}}}", $"{{{t1},{t0}}}", $"{{{t0},{t0}}}", $"{{{Quote(t0)},{Quote(t0)}}}", + $"{{ {t0} , {t1} }}", $"{{{Padded(t1)},{Padded(t0)}}}", + "{" + string.Join(",", texts.Select(Quote)) + "}", + "{" + string.Join(",", texts.AsEnumerable().Reverse().Select(Quote)) + "}", + "{" + string.Join(",", texts.Concat(texts).Select(Padded)) + "}", + "{NULL}", $"{{{t0},NULL}}", "{\"NULL\"}", "{null}", "{ NULL }", + $"{{{t0},}}", $"{{,{t0}}}", $"{{{t0}", $"{t0}}}", t0, $"{{{Quote(t0)}x}}", $"{{\"{t0}}}", + $"{{{t0}\"}}", $"{{{{{t0}}}}}", $"{{{t0};{t1}}}", $"{{{Quote(t0)} {Quote(t1)}}}", $"{{\\{t0}}}" + ]; + + foreach (var literal in fixedLiterals) yield return literal; + + foreach (var text in texts) + { + yield return $"{{{text}}}"; + yield return $"{{{Quote(text)}}}"; + yield return $"{{{Padded(text)}}}"; + } + + static string Quote(string text) => "\"" + text.Replace("\\", "\\\\").Replace("\"", "\\\"") + "\""; + + static string Padded(string text) => "\" " + text.Replace("\\", "\\\\").Replace("\"", "\\\"") + " \""; + } + + /// The documents the primitive writes, and their neighbours: reordered, duplicated, mistyped, malformed. + private static IEnumerable JsonGrid(IEnumerable written) + { + var documents = written.ToList(); + foreach (var json in documents) yield return json; + + var tokens = JsonDocument.Parse(documents.OrderByDescending(json => json.Length).First()) + .RootElement.EnumerateArray().Select(element => element.GetRawText()).ToList(); + + yield return "[" + string.Join(",", tokens.AsEnumerable().Reverse().Concat(tokens)) + "]"; + + foreach (var token in tokens.Take(3)) + { + yield return $"[{token},{token}]"; + yield return $"[{token},null]"; + yield return token.StartsWith('"') ? $"[{token.Trim('"')}]" : $"[\"{token}\"]"; + yield return $"[\" {token.Trim('"')} \"]"; + yield return $"[[{token}]]"; + } + + foreach (var json in (string[])["null", "[]", "[null]", "{}", "\"{}\"", "[true]", "[{}]", "[", "1", "\"\"", "[\"\"]"]) + yield return json; + } + + // ---------------------------------------------------------------- helpers + + private static string Outcome(Func run) + { + try + { + return run() ?? "null"; + } + catch (Exception ex) + { + return $"throws {ex.GetType().Name}"; + } + } + + private static string TokenKinds(string json) => + string.Join(",", JsonDocument.Parse(json).RootElement.EnumerateArray().Select(element => element.ValueKind)); + + private static string Show(string? text) => text is null ? "null" : JsonSerializer.Serialize(text); + + private static PropertyInfo Property(string name) => + typeof(TSet).GetProperty(name) ?? throw new InvalidOperationException($"{typeof(TSet).Name} has no public {name}."); + + private static MethodInfo Operator(string name) => + typeof(TSet).GetMethod(name, BindingFlags.Public | BindingFlags.Static, [typeof(TSet), typeof(TSet)]) + ?? throw new InvalidOperationException($"{typeof(TSet).Name} declares no {name}(TSet, TSet)."); +} diff --git a/test/CodoMetis.ValueRanges.Conventions.Tests/StringOverloads.cs b/test/CodoMetis.ValueRanges.Conventions.Tests/StringOverloads.cs new file mode 100644 index 00000000..5af5d81b --- /dev/null +++ b/test/CodoMetis.ValueRanges.Conventions.Tests/StringOverloads.cs @@ -0,0 +1,22 @@ +namespace CodoMetis.ValueRanges.Conventions.Tests; + +/// +/// Calls the overloads of Parse and TryParse from generic code. +/// +/// +/// Under a constraint that derives from (IRangeFactory, +/// IValueSetFactory), TSet.Parse(text, provider) with a argument does +/// not call the string overload: overload resolution removes a base interface's candidate when a +/// derived interface's is applicable, and +/// is applicable through the implicit string-to-span conversion. A sweep that means to compare the two +/// overloads would compare the span overload with itself. Constraining on +/// alone leaves only the string candidates, which dispatch to the type's own string methods. +/// +internal static class StringOverloads +{ + internal static TSelf Parse(string s, IFormatProvider? provider) where TSelf : IParsable + => TSelf.Parse(s, provider); + + internal static bool TryParse(string? s, IFormatProvider? provider, out TSelf result) where TSelf : IParsable + => TSelf.TryParse(s, provider, out result!); +} diff --git a/test/oracles/candidates.json b/test/oracles/candidates.json index 5678b544..4e2baa87 100644 --- a/test/oracles/candidates.json +++ b/test/oracles/candidates.json @@ -989,5 +989,194 @@ "row": " over empty as ", "family": "an empty captured collection cannot be a VALUES query root", "issue": "#137" + }, + { + "oracle": "SetWrapperParityTests", + "row": "DecimalSet JSON read [\"", + "family": "wrapper element JSON reader uses the literal grammar, wider than the primitive set's", + "issue": "#141", + "method": "PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike" + }, + { + "oracle": "SetWrapperParityTests", + "row": "Int16Set JSON read [\"", + "family": "wrapper element JSON reader uses the literal grammar, wider than the primitive set's", + "issue": "#141", + "method": "PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike" + }, + { + "oracle": "SetWrapperParityTests", + "row": "Int32Set JSON read [\"", + "family": "wrapper element JSON reader uses the literal grammar, wider than the primitive set's", + "issue": "#141", + "method": "PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike" + }, + { + "oracle": "SetWrapperParityTests", + "row": "Int64Set JSON read [\"", + "family": "wrapper element JSON reader uses the literal grammar, wider than the primitive set's", + "issue": "#141", + "method": "PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike" + }, + { + "oracle": "SetWrapperParityTests", + "row": "GuidSet JSON read [\" ", + "family": "wrapper element JSON reader uses the literal grammar, wider than the primitive set's", + "issue": "#141", + "method": "PrimitiveSet_AndItsIdentityWrapperArity_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateTimeOffsetRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateTimeOffsetRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateTimeRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DateTimeRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DecimalRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "DecimalRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "InstantRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "InstantRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "Int32Range (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "Int32Range (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "Int64Range (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "Int64Range (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "LocalDateRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "LocalDateRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "LocalDateTimeRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "LocalDateTimeRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "TimeRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "TimeRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "YearMonthRange (,) IsUnboundedStart:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" + }, + { + "oracle": "RangeSetLiftParityTests", + "row": "YearMonthRange (,) IsUnboundedEnd:", + "family": "IsUnboundedStart/IsUnboundedEnd test the variant; lower_inf/upper_inf are true for (,)", + "issue": "#109", + "method": "Range_AndItsOneElementRangeSet_AnswerAlike" } ] diff --git a/test/oracles/claims.json b/test/oracles/claims.json index 5e846409..6385614a 100644 --- a/test/oracles/claims.json +++ b/test/oracles/claims.json @@ -897,7 +897,8 @@ ], "heldBy": [ "SpanParsingTests", - "LiteralCorpusProbeTests" + "LiteralCorpusProbeTests", + "LiteralEntryPointParityTests" ] }, { @@ -937,7 +938,8 @@ "heldBy": [ "TypeConverterContractTests", "ConfigurationBindingTests", - "CultureEntryPointProbeTests" + "CultureEntryPointProbeTests", + "LiteralEntryPointParityTests" ] }, { @@ -1201,7 +1203,8 @@ "*Set.From" ], "heldBy": [ - "SetJsonConverterTests" + "SetJsonConverterTests", + "SetWrapperParityTests" ] }, { @@ -1353,7 +1356,8 @@ ], "heldBy": [ "RangeSetComparisonTests", - "ExecutedQueryTests" + "ExecutedQueryTests", + "RangeSetLiftParityTests" ] }, { @@ -1430,7 +1434,8 @@ ], "heldBy": [ "SmallModelOracleTests", - "RangeSetTests" + "RangeSetTests", + "RangeSetLiftParityTests" ] }, { @@ -2159,7 +2164,8 @@ "WrapperGrammarContractTests", "SetParseFormatTests", "SetJsonConverterTests", - "TemporalLiteralStrictnessContractTests" + "TemporalLiteralStrictnessContractTests", + "SetWrapperParityTests" ] }, { diff --git a/test/oracles/oracles.json b/test/oracles/oracles.json index 2b4703f6..4fb308a6 100644 --- a/test/oracles/oracles.json +++ b/test/oracles/oracles.json @@ -107,6 +107,24 @@ "kind": "metamorphic", "against": "construct(deconstruct(x)) == x, for every bounded variant of every discovered range type" }, + { + "class": "SetWrapperParityTests", + "project": "CodoMetis.ValueRanges.Conventions.Tests", + "kind": "differential", + "against": "the primitive set, for its wrapper arity closed over an identity element: every operation, parse and format entry point, JSON both ways and the TypeConverter" + }, + { + "class": "RangeSetLiftParityTests", + "project": "CodoMetis.ValueRanges.Conventions.Tests", + "kind": "differential", + "against": "the range itself, for the one-element RangeSet holding it: every predicate, operation and accessor over the shape matrix with the domain's extremes, for every discovered range type" + }, + { + "class": "LiteralEntryPointParityTests", + "project": "CodoMetis.ValueRanges.Conventions.Tests", + "kind": "differential", + "against": "Parse(string), for the same literal through the span overload, TryParse, JSON, the TypeConverter and configuration binding, for every discovered range, variant, multirange and value set type" + }, { "class": "ShapeMatrixParityTests", "project": "CodoMetis.ValueRanges.EFCore.PostgreSQL.IntegrationTests", diff --git a/test/oracles/seeds/multirange-upper-inc-reads-lower-bound.patch b/test/oracles/seeds/multirange-upper-inc-reads-lower-bound.patch new file mode 100644 index 00000000..f789f082 --- /dev/null +++ b/test/oracles/seeds/multirange-upper-inc-reads-lower-bound.patch @@ -0,0 +1,17 @@ +Seed: RangeSet.UpperBoundInclusive reads the last element's lower inclusivity, a sibling accessor copied without its bound renamed +Oracles: RangeSetLiftParityTests +Fails: every one-element set whose range has differing lower and upper inclusivity: upper_inc disagrees with the range it holds, on every range type + +diff --git a/src/CodoMetis.ValueRanges/RangeSet.cs b/src/CodoMetis.ValueRanges/RangeSet.cs +index ee6f28c..399cab8 100644 +--- a/src/CodoMetis.ValueRanges/RangeSet.cs ++++ b/src/CodoMetis.ValueRanges/RangeSet.cs +@@ -342,7 +342,7 @@ public sealed class RangeSet + /// Returns if the set's last element has an inclusive upper + /// bound — equivalent to the PostgreSQL upper_inc function on multiranges. + /// +- public bool UpperBoundInclusive() => !_elements.IsEmpty && _elements[^1].UpperBoundInclusive(); ++ public bool UpperBoundInclusive() => !_elements.IsEmpty && _elements[^1].LowerBoundInclusive(); + + // ------------------------------------------------------------------------- + // Query operations diff --git a/test/oracles/seeds/set-tryparse-reads-blank-as-empty.patch b/test/oracles/seeds/set-tryparse-reads-blank-as-empty.patch new file mode 100644 index 00000000..c7aa3ccc --- /dev/null +++ b/test/oracles/seeds/set-tryparse-reads-blank-as-empty.patch @@ -0,0 +1,17 @@ +Seed: Int32Set.TryParse(string) reads a blank literal as the empty set, where Parse and every other entry point refuse it +Oracles: LiteralEntryPointParityTests, SetWrapperParityTests +Fails: Int32Set: TryParse of "" and " " against Parse, and against the wrapper arity's TryParse + +diff --git a/src/CodoMetis.ValueRanges/Sets/Int32Set.cs b/src/CodoMetis.ValueRanges/Sets/Int32Set.cs +index b5a960f..9477c3d 100644 +--- a/src/CodoMetis.ValueRanges/Sets/Int32Set.cs ++++ b/src/CodoMetis.ValueRanges/Sets/Int32Set.cs +@@ -87,7 +87,7 @@ public sealed class Int32Set : IValueSet, IValueSetFactory, + /// Returns and on failure. + /// + public static bool TryParse(string? s, IFormatProvider? provider, out Int32Set result) +- => SetFormat.TryParse(s.AsSpan(), provider, out result); ++ => SetFormat.TryParse(string.IsNullOrWhiteSpace(s) ? "{}" : s.AsSpan(), provider, out result); + + /// + /// Tries to parse a PostgreSQL array literal from a character span. diff --git a/test/oracles/seeds/wrapper-integer-elements-written-as-strings.patch b/test/oracles/seeds/wrapper-integer-elements-written-as-strings.patch new file mode 100644 index 00000000..41f7dd56 --- /dev/null +++ b/test/oracles/seeds/wrapper-integer-elements-written-as-strings.patch @@ -0,0 +1,17 @@ +Seed: Int64Set serializes its elements through the text converter, so the wrapper arity writes JSON strings where Int64Set writes numbers +Oracles: SetWrapperParityTests +Fails: Int64Set: every JSON token kind, and each sibling reading the other's document + +diff --git a/src/CodoMetis.ValueRanges/Sets/Int64Set.cs b/src/CodoMetis.ValueRanges/Sets/Int64Set.cs +index 210f5a0..f7ab8ff 100644 +--- a/src/CodoMetis.ValueRanges/Sets/Int64Set.cs ++++ b/src/CodoMetis.ValueRanges/Sets/Int64Set.cs +@@ -209,7 +209,7 @@ public sealed class Int64Set : + /// . + /// + static JsonConverter? IValueSetFactory, TElement>.ElementJsonConverter +- => ValueSetIntegerElementJsonConverter, TElement>.Instance; ++ => ValueSetTextElementJsonConverter, TElement>.Instance; + + /// + /// Parses a PostgreSQL array literal into an , re-validating