diff --git a/.gitignore b/.gitignore index 6d5e3f2..5a829de 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,6 @@ coverage.html # superpowers / SDD working notes (never committed) /.superpowers/ + +# rapid writes failfiles into the package directory on a failing property +testdata/rapid/ diff --git a/CLAUDE.md b/CLAUDE.md index 332cffe..ef9081e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,6 +34,34 @@ go vet ./... Module floor is **Go 1.25** (conservative for a public library; PPM consumes it fine at 1.26). +## Property tests (`internal/proptest/`) + +Property-based tests live in `internal/proptest/`, adapted from `pypa/packaging`'s +Hypothesis suite using `pgregory.net/rapid`. + +**Every file in that directory must stay a `_test.go` file.** rapid is MPL-2.0, and a +single non-test file there would pull it into this public library's non-test import +graph. The invariant is checkable: + +```bash +go list -deps ./... # must NOT contain pgregory.net/rapid +go list -deps -test ./... # must contain it +``` + +The cost is that these tests may only use exported API — which is why they assert +observable behavior (ordering, normalization, round-tripping, matching) rather than +parsed-field structure. + +**The properties do not replace the conformance tables**, and vice versa. A round-trip +property is invariant to a change of canonical form, so it cannot detect that +`Requirement.String()`'s output shape moved; only `requirement/conformance_test.go` +catches that. Both are load-bearing. This was established by mutation testing, and +the reasoning is recorded in the `internal/proptest` package doc. + +Keep the random seed. `rapid.Check` takes no seed option by design; a fixed seed +degenerates into a slow, unreadable table test. Name every `Draw` so failures are +reproducible from the printed output. + ## Code Style - Follow standard Go conventions. diff --git a/NOTICE b/NOTICE index 3a1a328..1baf292 100644 --- a/NOTICE +++ b/NOTICE @@ -91,3 +91,19 @@ cross-product parameters and the invalid-requirement cases of class TestRequirementParsing, licensed under the Apache License, Version 2.0. Translated from Python/pytest to Go table-driven tests; the parametrize cross-product is expressed as a curated subset with equivalent coverage. + +The internal/proptest package's property tests are adapted from +pypa/packaging's Hypothesis property suite (https://github.com/pypa/packaging), +Copyright (c) Donald Stufft and individual contributors, specifically +tests/property/strategies.py's generators and the version-ordering, +version-normalization, version-release, and specifier-matching properties, +licensed under the Apache License, Version 2.0. Translated from +Python/Hypothesis to Go/pgregory.net/rapid; upstream properties that assert on +parsed-field structure have no counterpart here, since this module exports no +such accessors. The tests/property/test_ranges_*.py files are deliberately not +ported: no packaging.ranges counterpart exists in this module. + +pgregory.net/rapid is licensed under the Mozilla Public License, Version 2.0. +It is a test-only dependency: internal/proptest contains only _test.go files, +so rapid does not appear in this module's non-test import graph and is not +built into any consumer that imports this library. diff --git a/go.mod b/go.mod index 70b1c63..f80d21e 100644 --- a/go.mod +++ b/go.mod @@ -17,4 +17,5 @@ require ( github.com/pmezard/go-difflib v1.0.0 // indirect golang.org/x/sys v0.47.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect + pgregory.net/rapid v1.3.0 // indirect ) diff --git a/go.sum b/go.sum index 5f01fb0..e90b61d 100644 --- a/go.sum +++ b/go.sum @@ -22,3 +22,5 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +pgregory.net/rapid v1.3.0 h1:vBvO0VSqti75J1jjYqpgPNBLKMd1+gxa9fYo7vk/Exc= +pgregory.net/rapid v1.3.0/go.mod h1:dPlE4OBBxgXPqkP79flB6sJL1dx5azpI7HQ9MY9Z7uk= diff --git a/internal/proptest/gen_test.go b/internal/proptest/gen_test.go new file mode 100644 index 0000000..0f3d0b3 --- /dev/null +++ b/internal/proptest/gen_test.go @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Package proptest holds the module's property-based tests, adapted from +// pypa/packaging's Hypothesis suite (tests/property/) at pinned upstream SHA +// 4eb0753dba8fcaaac8eb75463374e448f0931558, plus properties specific to this +// module's own API contracts. +// +// # Why this package contains only _test.go files +// +// The generators below are shared by the version, requirement, marker, and +// extras property tests. Go cannot share _test.go helpers across packages, so +// the obvious alternative is a normal (non-test) file in an internal package — +// but that would put pgregory.net/rapid, which is MPL-2.0, into the non-test +// import graph of a public, dual-Apache-2.0-OR-MIT library. +// +// Keeping every file here a _test.go file keeps rapid strictly test-only: +// +// go list -deps ./... # rapid absent +// go list -deps -test ./... # rapid present +// +// The cost is that these tests can only use the exported API of the packages +// they exercise. That is not a real limitation for the properties here — they +// are all statements about observable behavior (ordering, normalization, +// round-tripping, specifier matching) rather than about internal structure. +// +// # Determinism +// +// rapid.Check takes no seed option; the seed comes from the -rapid.seed flag +// and defaults to random. That is deliberate and should stay that way. A fixed +// seed would run the same examples on every invocation, which is just a table +// test with extra steps and none of the table's readability. On failure rapid +// prints the reproducing -rapid.seed and the value of every named Draw, so +// every Draw below is named. +// +// # These properties do NOT subsume the conformance tables +// +// Established by mutation testing, not by assumption. Reverting +// Requirement.String()'s conditional marker separator to the unconditional +// " ; " form leaves every property in this package passing, because a +// round-trip property is invariant to a change of canonical form: it detects +// non-idempotence and parse failures, never "the canonical form moved". That +// mutation is caught only by requirement/conformance_test.go, which asserts +// exact bytes against upstream. +// +// The division of labor is therefore load-bearing: properties pin invariants +// over a wide input space, the conformance tables pin the exact output shape +// against pypa/packaging. Deleting either because the other exists will let +// real regressions through. +// +// Mutation testing also found a genuine gap here: dropping the trailing-zero +// Normalize() in version/version.go's cmpkey survived every property until +// TestExactMatchIsZeroPaddingSymmetric was added, because Version.Equal pads +// independently and only specifier matching observes that normalization. +package proptest + +import ( + "strconv" + "strings" + + "pgregory.net/rapid" + + "github.com/posit-dev/go-python-packaging/version" +) + +// Generators below mirror pypa/packaging's tests/property/strategies.py. Where +// a generator diverges from upstream, the divergence is annotated — an +// unannotated divergence is a bug in this file, not a licence to change the +// library. + +// smallInt mirrors upstream's small_ints: st.integers(min_value=0, max_value=20). +func smallInt() *rapid.Generator[int] { return rapid.IntRange(0, 20) } + +// preTag mirrors upstream's pre_tags: st.sampled_from(["a", "b", "rc"]). +// +// Note these are the *normalized* spellings only. The alternate spellings +// (alpha, beta, c, pre, preview) are exercised by the normalization properties, +// which need to pair each spelling with its expected normal form. +func preTag() *rapid.Generator[string] { + return rapid.SampledFrom([]string{"a", "b", "rc"}) +} + +// orderedOp and equalityOp mirror upstream's _ordered_ops and _equality_ops. +func orderedOp() *rapid.Generator[string] { + return rapid.SampledFrom([]string{">=", "<=", ">", "<"}) +} + +func equalityOp() *rapid.Generator[string] { + return rapid.SampledFrom([]string{"==", "!="}) +} + +// releaseParts mirrors upstream's release_segment before the "." join: 1 to 4 +// components, each a small_int. minSegments raises the floor, which ~= needs +// because it rejects a single-segment operand. +func releaseParts(minSegments int) *rapid.Generator[[]int] { + return rapid.SliceOfN(smallInt(), minSegments, 4) +} + +// releaseSegment mirrors upstream's release_segment: a dotted release string +// such as "3.14.0". +func releaseSegment() *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + return joinInts(releaseParts(1).Draw(t, "release")) + }) +} + +func joinInts(parts []int) string { + s := make([]string, len(parts)) + for i, p := range parts { + s[i] = strconv.Itoa(p) + } + return strings.Join(s, ".") +} + +// localLabel mirrors upstream's local_labels: 1 to 3 dot-joined segments, each +// either numeric (0-100) or one of a small pool of words. +func localLabel() *rapid.Generator[string] { + segment := rapid.OneOf( + rapid.Custom(func(t *rapid.T) string { + return strconv.Itoa(rapid.IntRange(0, 100).Draw(t, "localNumeric")) + }), + rapid.SampledFrom([]string{"abc", "ubuntu", "local", "patch", "dev"}), + ) + return rapid.Custom(func(t *rapid.T) string { + return strings.Join(rapid.SliceOfN(segment, 1, 3).Draw(t, "localSegments"), ".") + }) +} + +// versionString mirrors upstream's pep440_versions composite, but returns the +// string rather than a parsed Version. +// +// Returning a string is a deliberate divergence, and it is the safe direction. +// This module's version.Version has no exported fields and no exported +// constructor other than Parse/MustParse, and a zero-value Version{} panics in +// String() (version/version.go:290 indexes release[0] unconditionally). A +// generator that built Version values structurally would therefore be both +// impossible and a landmine; generating the string and routing it through +// Parse is the only correct construction path. +func versionString(includeLocal bool, minSegments int) *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + var b strings.Builder + + // Epoch: upstream draws from [None, 0, 1, 2, 3]. + if epoch := rapid.SampledFrom([]int{-1, 0, 1, 2, 3}).Draw(t, "epoch"); epoch >= 0 { + b.WriteString(strconv.Itoa(epoch)) + b.WriteString("!") + } + + b.WriteString(joinInts(releaseParts(minSegments).Draw(t, "releaseParts"))) + + if rapid.Bool().Draw(t, "hasPre") { + b.WriteString(preTag().Draw(t, "preTag")) + b.WriteString(strconv.Itoa(smallInt().Draw(t, "preNum"))) + } + if rapid.Bool().Draw(t, "hasPost") { + b.WriteString(".post") + b.WriteString(strconv.Itoa(smallInt().Draw(t, "postNum"))) + } + if rapid.Bool().Draw(t, "hasDev") { + b.WriteString(".dev") + b.WriteString(strconv.Itoa(smallInt().Draw(t, "devNum"))) + } + if includeLocal && rapid.Bool().Draw(t, "hasLocal") { + b.WriteString("+") + b.WriteString(localLabel().Draw(t, "localLabel")) + } + + return b.String() + }) +} + +// nonlocalVersionString mirrors upstream's nonlocal_versions. Ordered +// specifiers (>=, <=, >, <) reject a local label on the right-hand side, so +// any property that puts a generated version there must use this. +func nonlocalVersionString() *rapid.Generator[string] { + return versionString(false, 1) +} + +// releaseVersionString mirrors upstream's release_versions: a final release, +// with no pre, post, dev, or local segment. Wildcard (==X.*) and ~= operands +// need this, since a suffixed operand is rejected or reinterpreted. +func releaseVersionString(minSegments int) *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + return joinInts(releaseParts(minSegments).Draw(t, "finalRelease")) + }) +} + +// parsedVersion draws a generated version string and parses it. +// +// A parse failure here is a genuine defect, not a filtered-out case: every +// string these generators emit is a valid PEP 440 version by construction. +// This is why no property in this package calls rapid's equivalent of +// Hypothesis's assume() on parseability — heavy filtering would risk rapid's +// "too few valid examples" error, and there is nothing to filter. +func parsedVersion(t *rapid.T, g *rapid.Generator[string], label string) version.Version { + raw := g.Draw(t, label) + v, err := version.Parse(raw) + if err != nil { + t.Fatalf("generated version %q failed to parse: %v", raw, err) + } + return v +} + +// mustParse parses a version string that the caller constructed and asserts it +// is valid. +func mustParse(t *rapid.T, s string) version.Version { + v, err := version.Parse(s) + if err != nil { + t.Fatalf("version.Parse(%q): unexpected error %v", s, err) + } + return v +} + +// mustSpecifiers parses a specifier string and asserts it is valid. +func mustSpecifiers(t *rapid.T, s string) version.Specifiers { + ss, err := version.NewSpecifiers(s) + if err != nil { + t.Fatalf("version.NewSpecifiers(%q): unexpected error %v", s, err) + } + return ss +} + +// newSpecifiersOrError parses a specifier string that the property expects to +// be INVALID, returning the error for the caller to assert on. +// +// This exists because mustSpecifiers treats an error as a test failure, which +// is the wrong reporting direction for a rejection property. +func newSpecifiersOrError(s string) (version.Specifiers, error) { + return version.NewSpecifiers(s) +} + +// A note on filtering, since it is the one rapid hazard worth stating once: +// Hypothesis's assume() maps to rapid's t.Skip, but rapid ERRORS OUT if a +// property generates too few valid examples, so heavy skipping turns a test +// red rather than merely reducing coverage. Where a property only holds on a +// subset of generated values, the properties in this package therefore +// `return` early -- a trivially-satisfied example -- instead of skipping. +// Nothing here filters aggressively enough to need assume() semantics. + +// specifierString mirrors upstream's pep440_specifier_strings: one specifier +// clause spanning the operator shapes PEP 440 allows. +// +// Upstream's include_arbitrary option is deliberately not ported. Its own +// comment records that it skips unparsable === literals because they break the +// range algebra it tests, and this module has no range algebra — so the option +// would add a shape with no property to exercise it. +func specifierString() *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + switch rapid.SampledFrom([]string{"ordered", "equality", "wildcard", "compatible"}).Draw(t, "shape") { + case "ordered": + // Locals are rejected on the RHS of an ordered operator. + return orderedOp().Draw(t, "orderedOp") + nonlocalVersionString().Draw(t, "orderedOperand") + case "equality": + return equalityOp().Draw(t, "equalityOp") + versionString(true, 1).Draw(t, "equalityOperand") + case "wildcard": + return equalityOp().Draw(t, "wildcardOp") + releaseVersionString(1).Draw(t, "wildcardOperand") + ".*" + default: // compatible + return "~=" + releaseVersionString(2).Draw(t, "compatibleOperand") + } + }) +} + +// specifierSetString mirrors upstream's rich_specifier_sets: 1 to 3 clauses +// joined by commas. +func specifierSetString() *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + return strings.Join(rapid.SliceOfN(specifierString(), 1, 3).Draw(t, "clauses"), ",") + }) +} diff --git a/internal/proptest/roundtrip_test.go b/internal/proptest/roundtrip_test.go new file mode 100644 index 0000000..00785ce --- /dev/null +++ b/internal/proptest/roundtrip_test.go @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Round-trip and idempotence properties specific to this module's own API +// contracts. These have no pypa/packaging counterpart: they assert promises +// this module's doc comments make, which nothing else tests. + +package proptest + +import ( + "strings" + "testing" + + "pgregory.net/rapid" + + "github.com/posit-dev/go-python-packaging/extras" + "github.com/posit-dev/go-python-packaging/marker" + "github.com/posit-dev/go-python-packaging/requirement" +) + +// requirementString generates a PEP 508 requirement. +// +// Every requirement is built by rendering a string and handing it to Parse. A +// hand-built Requirement is not an option: its URL and Specifiers fields are +// both exported, but String() selects between them in a switch +// (requirement/requirement.go:113-119), so a value with both set silently +// drops the Specifiers. Parse never produces that state -- the PEP 508 grammar +// makes the two mutually exclusive -- so generating through Parse keeps the +// generator inside the space of values the type actually inhabits. +func requirementString() *rapid.Generator[string] { + return rapid.Custom(func(t *rapid.T) string { + var b strings.Builder + + b.WriteString(rapid.SampledFrom([]string{ + "requests", "flask", "Django", "numpy", "pytest-cov", + "zope.interface", "ruamel.yaml", "a", "A.B-C_D", + }).Draw(t, "name")) + + if rapid.Bool().Draw(t, "hasExtras") { + ex := rapid.SliceOfN( + rapid.SampledFrom([]string{"security", "tests", "dev", "all", "socks"}), + 1, 3, + ).Draw(t, "extras") + b.WriteString("[" + strings.Join(ex, ",") + "]") + } + + // URL and specifiers are mutually exclusive in the grammar. + hasURL := rapid.Bool().Draw(t, "hasURL") + if hasURL { + b.WriteString(" @ ") + b.WriteString(rapid.SampledFrom([]string{ + "https://example.com/pkg-1.0.tar.gz", + "file:///tmp/pkg-1.0-py3-none-any.whl", + "git+https://github.com/example/pkg@main", + }).Draw(t, "url")) + } else if rapid.Bool().Draw(t, "hasSpecifiers") { + b.WriteString(specifierSetString().Draw(t, "specifiers")) + } + + if rapid.Bool().Draw(t, "hasMarker") { + // The separator is asymmetric, and this generator has to respect + // it or it emits strings the grammar rejects: a URL must be + // followed by " ; " because a bare ";" could be part of the URL, + // while without a URL the separator is "; ". This mirrors + // requirement.String() and is the rule pypa/packaging uses. + if hasURL { + b.WriteString(" ; ") + } else { + b.WriteString("; ") + } + b.WriteString(markerString().Draw(t, "marker")) + } + + return b.String() + }) +} + +// markerString generates a PEP 508 environment marker expression. +func markerString() *rapid.Generator[string] { + atom := rapid.Custom(func(t *rapid.T) string { + variable := rapid.SampledFrom([]string{ + "python_version", "sys_platform", "os_name", "platform_machine", + "implementation_name", "extra", + }).Draw(t, "markerVar") + op := rapid.SampledFrom([]string{"==", "!=", ">=", "<=", ">", "<", "in", "not in"}).Draw(t, "markerOp") + value := rapid.SampledFrom([]string{ + "3.12", "linux", "posix", "x86_64", "cpython", "win32", "darwin", "test", + }).Draw(t, "markerValue") + + return variable + " " + op + " \"" + value + "\"" + }) + + return rapid.Custom(func(t *rapid.T) string { + atoms := rapid.SliceOfN(atom, 1, 3).Draw(t, "markerAtoms") + if len(atoms) == 1 { + return atoms[0] + } + joiner := rapid.SampledFrom([]string{" and ", " or "}).Draw(t, "markerJoiner") + return strings.Join(atoms, joiner) + }) +} + +// TestRequirementStringRoundTrip checks the promise made verbatim at +// requirement/requirement.go:101-102 -- "Parse(r.String()) yields an +// equivalent Requirement" -- which nothing tested before. +// +// Equivalence is asserted as String() equality, deliberately, and NOT with +// reflect.DeepEqual. DeepEqual reports two Requirements unequal even when +// String() is byte-identical, and even when parsing the same input twice: the +// specifier struct stores its operator as a func field +// (version/specifier.go:100, type operatorFunc at :91), and DeepEqual reports +// any two non-nil funcs unequal. That is a property of reflection, not a defect +// in the round-trip, and it cannot be fixed by canonicalizing the retained +// original string. +func TestRequirementStringRoundTrip(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + raw := requirementString().Draw(t, "requirement") + + r, err := requirement.Parse(raw) + if err != nil { + t.Fatalf("generated requirement %q failed to parse: %v", raw, err) + } + + rendered := r.String() + + again, err := requirement.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q.String()) = Parse(%q) failed: %v", raw, rendered, err) + } + + if got := again.String(); got != rendered { + t.Fatalf("round-trip not stable: %q -> %q -> %q", raw, rendered, got) + } + + // Field-level equivalence for everything that is comparable without + // reflect.DeepEqual. + if again.Name != r.Name { + t.Fatalf("Name changed across round-trip: %q -> %q", r.Name, again.Name) + } + if again.URL != r.URL { + t.Fatalf("URL changed across round-trip: %q -> %q", r.URL, again.URL) + } + if strings.Join(again.Extras, ",") != strings.Join(r.Extras, ",") { + t.Fatalf("Extras changed across round-trip: %v -> %v", r.Extras, again.Extras) + } + if again.Specifiers.String() != r.Specifiers.String() { + t.Fatalf("Specifiers changed across round-trip: %q -> %q", + r.Specifiers, again.Specifiers) + } + if again.Marker.String() != r.Marker.String() { + t.Fatalf("Marker changed across round-trip: %q -> %q", r.Marker, again.Marker) + } + }) +} + +func TestMarkerStringRoundTrip(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + raw := markerString().Draw(t, "marker") + + m, err := marker.Parse(raw) + if err != nil { + t.Fatalf("generated marker %q failed to parse: %v", raw, err) + } + + rendered := m.String() + + again, err := marker.Parse(rendered) + if err != nil { + t.Fatalf("Parse(%q.String()) = Parse(%q) failed: %v", raw, rendered, err) + } + + if got := again.String(); got != rendered { + t.Fatalf("marker round-trip not stable: %q -> %q -> %q", raw, rendered, got) + } + + // A parsed non-empty marker must not report itself empty, or a + // requirement carrying it would render without it. + if m.IsEmpty() { + t.Fatalf("marker %q parsed to an empty Marker", raw) + } + }) +} + +func TestExtrasNormalizeIsIdempotent(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + // PEP 685 normalization: runs of -, _ and . collapse to a single -, + // and the name is lowercased. Draw raw names spanning those forms + // rather than only well-formed ones. + name := rapid.Custom(func(t *rapid.T) string { + parts := rapid.SliceOfN( + rapid.SampledFrom([]string{"Extra", "TESTS", "dev", "a", "Foo9", "bar"}), + 1, 4, + ).Draw(t, "nameParts") + sep := rapid.SampledFrom([]string{"-", "_", ".", "--", "__", "._-"}).Draw(t, "nameSep") + return strings.Join(parts, sep) + }).Draw(t, "extraName") + + once := extras.Normalize(name) + twice := extras.Normalize(once) + + if once != twice { + t.Fatalf("Normalize is not idempotent: %q -> %q -> %q", name, once, twice) + } + + // A normalized name is already in normal form, so it must be + // lowercase and free of the separators normalization collapses. + if once != strings.ToLower(once) { + t.Fatalf("Normalize(%q) = %q is not lowercase", name, once) + } + for _, bad := range []string{"_", "."} { + if strings.Contains(once, bad) { + t.Fatalf("Normalize(%q) = %q still contains %q", name, once, bad) + } + } + }) +} + +// TestSpecifiersStringRoundTrip ports upstream's +// test_specifier_set_str_round_trip_general. +func TestSpecifiersStringRoundTrip(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + raw := specifierSetString().Draw(t, "specifierSet") + + ss := mustSpecifiers(t, raw) + rendered := ss.String() + + again := mustSpecifiers(t, rendered) + + if got := again.String(); got != rendered { + t.Fatalf("specifier round-trip not stable: %q -> %q -> %q", raw, rendered, got) + } + + // Behavioral equivalence: the re-parsed set must accept exactly the + // same versions. String() equality alone would not catch a renderer + // that dropped a clause it could also not re-read. + for range 8 { + v := parsedVersion(t, versionString(false, 1), "candidate") + if ss.Check(v) != again.Check(v) { + t.Fatalf("round-tripped specifier %q disagrees with %q on %q", + rendered, raw, v) + } + } + }) +} diff --git a/internal/proptest/specifier_test.go b/internal/proptest/specifier_test.go new file mode 100644 index 0000000..77e604c --- /dev/null +++ b/internal/proptest/specifier_test.go @@ -0,0 +1,268 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Specifier matching properties, ported from pypa/packaging's +// tests/property/test_specifier_matching.py, test_specifier_comparison.py, and +// test_specifier_implied.py at pinned SHA +// 4eb0753dba8fcaaac8eb75463374e448f0931558. +// +// Upstream's specifier properties are far broader than what is portable here. +// This module exposes no SpecifierSet algebra (no &, no is_unsatisfiable, no +// filter), so the intersection, unsatisfiability, and filtering families have +// no counterpart -- they belong to go-pubgrub's versionset, tracked separately. +// What is portable is the matching relation itself, which is what Check does. + +package proptest + +import ( + "fmt" + "strings" + "testing" + + "pgregory.net/rapid" +) + +func TestGreaterEqualMatchesIffOrderingHolds(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + // Ordered operators reject a local label on the right-hand side. + bound := nonlocalVersionString().Draw(t, "bound") + candidate := parsedVersion(t, nonlocalVersionString(), "candidate") + + boundVersion := mustParse(t, bound) + ss := mustSpecifiers(t, ">="+bound) + + // A pre-release candidate is excluded by default unless the specifier + // itself mentions a pre-release, which is a separate rule from the + // ordering relation under test here. Restrict to the case where the + // two rules cannot interact. + if candidate.IsPreRelease() || boundVersion.IsPreRelease() { + return + } + + want := candidate.GreaterThanOrEqual(boundVersion) + if got := ss.Check(candidate); got != want { + t.Fatalf("Check(%q) against %q = %v, want %v (ordering says %v)", + candidate, ">="+bound, got, want, want) + } + }) +} + +func TestStrictOperatorsExcludeTheBoundItself(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + bound := nonlocalVersionString().Draw(t, "bound") + v := mustParse(t, bound) + + for _, op := range []string{">", "<"} { + if mustSpecifiers(t, op+bound).Check(v) { + t.Fatalf("%q should not match its own bound %q", op+bound, v) + } + } + + // And the inclusive forms must match it. + for _, op := range []string{">=", "<=", "=="} { + if !mustSpecifiers(t, op+bound).Check(v) { + t.Fatalf("%q should match its own bound %q", op+bound, v) + } + } + }) +} + +func TestNotEqualIsExactInverseOfEqual(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + bound := nonlocalVersionString().Draw(t, "bound") + candidate := parsedVersion(t, versionString(true, 1), "candidate") + + eq := mustSpecifiers(t, "=="+bound) + ne := mustSpecifiers(t, "!="+bound) + + if eq.Check(candidate) == ne.Check(candidate) { + t.Fatalf("==%s and !=%s both returned %v for %q", + bound, bound, eq.Check(candidate), candidate) + } + }) +} + +func TestWildcardIsSupersetOfExact(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + // A wildcard operand must be a plain final release; a suffixed operand + // is rejected outright for dev and post. + bound := releaseVersionString(1).Draw(t, "bound") + candidate := parsedVersion(t, versionString(false, 1), "candidate") + + exact := mustSpecifiers(t, "=="+bound) + wildcard := mustSpecifiers(t, "=="+bound+".*") + + if exact.Check(candidate) && !wildcard.Check(candidate) { + t.Fatalf("%q matches ==%s but not ==%s.*", candidate, bound, bound) + } + }) +} + +func TestWildcardIgnoresTrailingSegments(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + bound := releaseVersionString(1).Draw(t, "bound") + extra := smallInt().Draw(t, "extraSegment") + + ss := mustSpecifiers(t, "=="+bound+".*") + + // The prefix match includes the bare bound and any extension of it. + for _, candidate := range []string{bound, fmt.Sprintf("%s.%d", bound, extra)} { + if !ss.Check(mustParse(t, candidate)) { + t.Fatalf("==%s.* should match %q", bound, candidate) + } + } + }) +} + +// TestExactMatchIsZeroPaddingSymmetric ports upstream's +// test_zero_padding_matches and test_zero_padding_symmetric: == compares +// release tuples with zero padding, so the operand and the candidate may carry +// different numbers of trailing zeros and must still match. +// +// This property was added after mutation testing: deleting the trailing-zero +// Normalize() in cmpkey (version/version.go:218) left every other property in +// this package passing, because Version.Equal pads independently. Only +// specifier matching observes that normalization. +func TestExactMatchIsZeroPaddingSymmetric(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + parts := releaseParts(1).Draw(t, "releaseParts") + zeros := rapid.IntRange(1, 3).Draw(t, "trailingZeroCount") + + short := joinInts(parts) + padded := short + strings.Repeat(".0", zeros) + + // ==short must match the padded candidate, and ==padded must match the + // short one. Both directions, since the padding can be on either side. + if !mustSpecifiers(t, "=="+short).Check(mustParse(t, padded)) { + t.Fatalf("==%s should match %q", short, padded) + } + if !mustSpecifiers(t, "=="+padded).Check(mustParse(t, short)) { + t.Fatalf("==%s should match %q", padded, short) + } + + // And the ordered operators agree: neither is strictly greater. + if mustSpecifiers(t, ">"+short).Check(mustParse(t, padded)) { + t.Fatalf(">%s should not match %q, which is equal to it", short, padded) + } + if mustSpecifiers(t, "<"+short).Check(mustParse(t, padded)) { + t.Fatalf("<%s should not match %q, which is equal to it", short, padded) + } + }) +} + +// TestCompatibleReleaseEqualsExpansion ports upstream's +// test_compatible_matches_iff_expansion_matches: ~=X.Y is defined as +// >=X.Y,==X.* -- the two forms must agree on every candidate. +func TestCompatibleReleaseEqualsExpansion(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + parts := releaseParts(2).Draw(t, "boundParts") + candidate := parsedVersion(t, versionString(false, 2), "candidate") + + bound := joinInts(parts) + prefix := joinInts(parts[:len(parts)-1]) + + compatible := mustSpecifiers(t, "~="+bound) + expansion := mustSpecifiers(t, fmt.Sprintf(">=%s,==%s.*", bound, prefix)) + + if got, want := compatible.Check(candidate), expansion.Check(candidate); got != want { + t.Fatalf("~=%s = %v but >=%s,==%s.* = %v for %q", + bound, got, bound, prefix, want, candidate) + } + }) +} + +func TestCommaSeparatedIsConjunction(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + clauses := rapid.SliceOfN(specifierString(), 2, 3).Draw(t, "clauses") + candidate := parsedVersion(t, versionString(false, 1), "candidate") + + joined := mustSpecifiers(t, strings.Join(clauses, ",")) + + want := true + for _, c := range clauses { + if !mustSpecifiers(t, c).Check(candidate) { + want = false + break + } + } + + if got := joined.Check(candidate); got != want { + t.Fatalf("%q on %q = %v, want %v (conjunction of %v)", + strings.Join(clauses, ","), candidate, got, want, clauses) + } + }) +} + +// TestAddingClauseCanOnlyNarrow ports upstream's +// test_adding_clause_can_only_narrow: a specifier set is a conjunction, so an +// additional clause can never admit a version the shorter set rejected. +func TestAddingClauseCanOnlyNarrow(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base := specifierString().Draw(t, "baseClause") + extra := specifierString().Draw(t, "extraClause") + candidate := parsedVersion(t, versionString(false, 1), "candidate") + + narrow := mustSpecifiers(t, base+","+extra) + + if narrow.Check(candidate) && !mustSpecifiers(t, base).Check(candidate) { + t.Fatalf("%q matches the narrower %q but not %q", + candidate, base+","+extra, base) + } + }) +} + +// TestLocalLabelIgnoredByOrderedSpecifiers ports upstream's +// test_local_ignored_for_ordering_specifiers. This is the property the +// local-normalization fix in version/version.go had to preserve. +func TestLocalLabelIgnoredByOrderedSpecifiers(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base := nonlocalVersionString().Draw(t, "base") + label := localLabel().Draw(t, "localLabel") + + bare := mustParse(t, base) + withLocal := mustParse(t, base+"+"+label) + + // An ordered specifier compares against the candidate's public part, + // so adding a local label must not change the verdict. + for _, op := range []string{">=", "<="} { + spec := mustSpecifiers(t, op+base) + if spec.Check(bare) != spec.Check(withLocal) { + t.Fatalf("%q: local label changed the verdict for %q vs %q", + op+base, bare, withLocal) + } + } + }) +} + +func TestOrderedSpecifiersRejectLocalOperand(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base := releaseVersionString(1).Draw(t, "base") + label := localLabel().Draw(t, "localLabel") + + // PEP 440 forbids a local label on the right-hand side of an ordered + // operator, because a local label has no meaning across projects. + for _, op := range []string{">=", "<=", ">", "<"} { + if _, err := newSpecifiersOrError(op + base + "+" + label); err == nil { + t.Fatalf("%q should be rejected: local label on an ordered operator", + op+base+"+"+label) + } + } + }) +} + +func TestZeroPaddedCandidateMatchesSameSpecifiers(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + bound := nonlocalVersionString().Draw(t, "bound") + parts := releaseParts(1).Draw(t, "candidateParts") + + short := joinInts(parts) + padded := short + ".0" + + for _, op := range []string{">=", "<=", ">", "<", "==", "!="} { + ss := mustSpecifiers(t, op+bound) + if got, want := ss.Check(mustParse(t, padded)), ss.Check(mustParse(t, short)); got != want { + t.Fatalf("%q: %q gave %v but zero-padded %q gave %v", + op+bound, short, want, padded, got) + } + } + }) +} diff --git a/internal/proptest/version_normalization_test.go b/internal/proptest/version_normalization_test.go new file mode 100644 index 0000000..c5bed6a --- /dev/null +++ b/internal/proptest/version_normalization_test.go @@ -0,0 +1,349 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Normalization properties, ported from pypa/packaging's +// tests/property/test_version_normalization.py at pinned SHA +// 4eb0753dba8fcaaac8eb75463374e448f0931558. +// +// These are the properties that PEP 440's "Normalization" section defines: the +// many accepted spellings of one version must all parse to the same value, and +// String() must render the single normal form. + +package proptest + +import ( + "fmt" + "strconv" + "strings" + "testing" + + "pgregory.net/rapid" +) + +// padInt renders n with count extra leading zeros, e.g. padInt(7, 2) == "007". +// Upstream's padded_int strategy does the same. +func padInt(n, zeros int) string { + return strings.Repeat("0", zeros) + strconv.Itoa(n) +} + +func TestPreReleaseCaseInsensitive(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + n := smallInt().Draw(t, "preNum") + + lower := fmt.Sprintf("%s%s%d", release, tag, n) + upper := fmt.Sprintf("%s%s%d", release, strings.ToUpper(tag), n) + + assertSameVersion(t, lower, upper) + }) +} + +func TestPostAndDevCaseInsensitive(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := smallInt().Draw(t, "num") + + for _, base := range []string{"post", "dev"} { + lower := fmt.Sprintf("%s.%s%d", release, base, n) + // Upper ("POST") and title ("Post") spellings. Built by hand + // rather than with strings.Title, which is deprecated. + title := strings.ToUpper(base[:1]) + base[1:] + for _, variant := range []string{strings.ToUpper(base), title} { + assertSameVersion(t, lower, fmt.Sprintf("%s.%s%d", release, variant, n)) + } + } + }) +} + +func TestNormalFormIsLowercase(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + n := smallInt().Draw(t, "preNum") + + v := mustParse(t, fmt.Sprintf("%s%s%d", release, strings.ToUpper(tag), n)) + + if got := v.String(); got != strings.ToLower(got) { + t.Fatalf("normalized form %q is not lowercase", got) + } + }) +} + +func TestLeadingZerosStripped(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + n := smallInt().Draw(t, "num") + zeros := rapid.IntRange(1, 3).Draw(t, "zeroCount") + release := releaseSegment().Draw(t, "release") + + // Release components, and the pre/post/dev numerals, are integers: + // leading zeros carry no meaning and must normalize away. + cases := [][2]string{ + {fmt.Sprintf("1.%d", n), fmt.Sprintf("1.%s", padInt(n, zeros))}, + {fmt.Sprintf("%sa%d", release, n), fmt.Sprintf("%sa%s", release, padInt(n, zeros))}, + {fmt.Sprintf("%s.post%d", release, n), fmt.Sprintf("%s.post%s", release, padInt(n, zeros))}, + {fmt.Sprintf("%s.dev%d", release, n), fmt.Sprintf("%s.dev%s", release, padInt(n, zeros))}, + } + + for _, c := range cases { + assertSameVersion(t, c[0], c[1]) + } + }) +} + +func TestPreReleaseSeparatorsNormalizeAway(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + n := smallInt().Draw(t, "preNum") + sep := rapid.SampledFrom([]string{".", "-", "_"}).Draw(t, "separator") + + canonical := fmt.Sprintf("%s%s%d", release, tag, n) + + // A separator is permitted before the tag, between the tag and the + // numeral, or both; all normalize to the bare form. + assertSameVersion(t, canonical, fmt.Sprintf("%s%s%s%d", release, sep, tag, n)) + assertSameVersion(t, canonical, fmt.Sprintf("%s%s%s%d", release, tag, sep, n)) + assertSameVersion(t, canonical, fmt.Sprintf("%s%s%s%s%d", release, sep, tag, sep, n)) + + // And the normal form carries no separator before the tag. + if got := mustParse(t, canonical).String(); strings.Contains(got, sep+tag) { + t.Fatalf("normal form %q should not contain separator %q before %q", got, sep, tag) + } + }) +} + +// TestPreReleaseAlternateSpellings is the property that rstudio/package-manager#19369 +// was a counterexample to: "alpha" must normalize to "a", not match nothing. +func TestPreReleaseAlternateSpellings(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := smallInt().Draw(t, "preNum") + + spelling := rapid.SampledFrom([][2]string{ + {"alpha", "a"}, + {"beta", "b"}, + {"c", "rc"}, + {"pre", "rc"}, + {"preview", "rc"}, + }).Draw(t, "spelling") + + long := fmt.Sprintf("%s%s%d", release, spelling[0], n) + short := fmt.Sprintf("%s%s%d", release, spelling[1], n) + + assertSameVersion(t, short, long) + + // The normal form uses the short spelling, so the long one must be + // absent from the rendered output. + // + // Guarded on the long spelling being strictly longer: "c" normalizes + // to "rc", which *contains* "c", so a substring check is meaningless + // for that pair. assertSameVersion above already proves that pair + // shares a normal form. + if len(spelling[0]) > len(spelling[1]) { + if got := mustParse(t, long).String(); strings.Contains(got, spelling[0]) { + t.Fatalf("normal form of %q is %q, should use short spelling %q", long, got, spelling[1]) + } + } + }) +} + +func TestPostReleaseAlternateSpellings(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := smallInt().Draw(t, "postNum") + alt := rapid.SampledFrom([]string{"rev", "r"}).Draw(t, "altSpelling") + + canonical := fmt.Sprintf("%s.post%d", release, n) + assertSameVersion(t, canonical, fmt.Sprintf("%s.%s%d", release, alt, n)) + + if got := mustParse(t, fmt.Sprintf("%s.%s%d", release, alt, n)).String(); !strings.Contains(got, ".post") { + t.Fatalf("normal form %q should render %q as .post", got, alt) + } + }) +} + +func TestOmittedNumeralEqualsZero(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + + // Pre-release: an omitted numeral means 0, and the normal form + // makes the 0 explicit. + assertSameVersion(t, fmt.Sprintf("%s%s0", release, tag), fmt.Sprintf("%s%s", release, tag)) + + // Post and dev likewise. + assertSameVersion(t, release+".post0", release+".post") + assertSameVersion(t, release+".dev0", release+".dev") + + for _, bare := range []string{fmt.Sprintf("%s%s", release, tag), release + ".post", release + ".dev"} { + if got := mustParse(t, bare).String(); !strings.HasSuffix(got, "0") { + t.Fatalf("normal form of %q is %q, should end with an explicit 0", bare, got) + } + } + }) +} + +// TestDashNumberIsImplicitPost ports upstream's test_dash_number_is_implicit_post: +// "1.0-5" is shorthand for "1.0.post5". +func TestDashNumberIsImplicitPost(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := rapid.IntRange(1, 999).Draw(t, "postNum") + + assertSameVersion(t, fmt.Sprintf("%s.post%d", release, n), fmt.Sprintf("%s-%d", release, n)) + }) +} + +func TestVPrefixIgnored(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + n := smallInt().Draw(t, "preNum") + + for _, prefix := range []string{"v", "V"} { + assertSameVersion(t, release, prefix+release) + + // Combined with a pre-release, per upstream's + // test_v_prefix_with_pre_release. + withPre := fmt.Sprintf("%s%s%d", release, tag, n) + assertSameVersion(t, withPre, prefix+withPre) + } + + // The normal form drops the prefix entirely. + got := mustParse(t, "v"+release).String() + if strings.HasPrefix(got, "v") || strings.HasPrefix(got, "V") { + t.Fatalf("normal form %q should not carry a v prefix", got) + } + }) +} + +func TestSurroundingWhitespaceStripped(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + + // Upstream draws from space, tab, newline, carriage return, form feed + // and vertical tab. Note this is about a *version* string; a trailing + // line break in a PEP 508 *requirement* is rejected, which is a + // different rule tested in requirement/conformance_test.go. + ws := rapid.SampledFrom([]string{" ", "\t", "\n", "\r", "\f", "\v"}).Draw(t, "whitespace") + lead := rapid.IntRange(0, 3).Draw(t, "leadCount") + trail := rapid.IntRange(0, 3).Draw(t, "trailCount") + + padded := strings.Repeat(ws, lead) + release + strings.Repeat(ws, trail) + assertSameVersion(t, release, padded) + + if got := mustParse(t, padded).String(); got != strings.TrimSpace(got) { + t.Fatalf("normal form %q retains surrounding whitespace", got) + } + }) +} + +func TestLocalSeparatorsNormalizeToDot(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + segments := rapid.SliceOfN( + rapid.SampledFrom([]string{"abc", "ubuntu", "1", "42", "x9"}), + 2, 4, + ).Draw(t, "localSegments") + sep := rapid.SampledFrom([]string{"-", "_"}).Draw(t, "localSeparator") + + dotted := release + "+" + strings.Join(segments, ".") + separated := release + "+" + strings.Join(segments, sep) + + assertSameVersion(t, dotted, separated) + + if got := mustParse(t, separated).String(); strings.Contains(got, sep) { + t.Fatalf("normal form %q should not retain local separator %q", got, sep) + } + }) +} + +// TestNormalizationIsIdempotent is one of this module's own properties: once +// normalized, re-parsing must be a fixed point. Without it, every other +// normalization property could hold while String() still emitted something +// that drifts on a second pass. +func TestNormalizationIsIdempotent(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + v := parsedVersion(t, versionString(true, 1), "version") + + once := v.String() + twice := mustParse(t, once).String() + + if once != twice { + t.Fatalf("normalization is not idempotent: %q then %q", once, twice) + } + + // And the round-trip preserves value, not just rendering. + if !v.Equal(mustParse(t, once)) { + t.Fatalf("Parse(%q.String()) is not equal to the original", v) + } + }) +} + +// TestLocalLabelDoesNotAffectPublicPart checks Public() and Local() agree with +// the rendered form. Upstream expresses this against the .public and .local +// attributes; these are the exported equivalents here. +func TestLocalLabelDoesNotAffectPublicPart(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base := nonlocalVersionString().Draw(t, "base") + label := localLabel().Draw(t, "localLabel") + + bare := mustParse(t, base) + withLocal := mustParse(t, base+"+"+label) + + if got, want := withLocal.Public(), bare.String(); got != want { + t.Fatalf("Public() = %q, want %q", got, want) + } + if withLocal.Local() == "" { + t.Fatalf("Local() is empty for %q", withLocal) + } + if got := withLocal.String(); !strings.HasPrefix(got, withLocal.Public()+"+") { + t.Fatalf("String() = %q should be Public() + \"+\" + Local()", got) + } + + // A local label never changes the pre/post classification. + if bare.IsPreRelease() != withLocal.IsPreRelease() { + t.Fatalf("local label changed IsPreRelease for %q", base) + } + if bare.IsPostRelease() != withLocal.IsPostRelease() { + t.Fatalf("local label changed IsPostRelease for %q", base) + } + }) +} + +// assertSameVersion asserts two spellings parse to the same value AND render +// to the same normal form. Value equality alone would be too weak: two +// spellings could compare equal while String() disagreed. +func assertSameVersion(t *rapid.T, canonical, variant string) { + a := mustParse(t, canonical) + b := mustParse(t, variant) + + if !a.Equal(b) { + t.Fatalf("%q and %q should parse to equal versions, got %q vs %q", + canonical, variant, a, b) + } + if a.String() != b.String() { + t.Fatalf("%q and %q should share a normal form, got %q vs %q", + canonical, variant, a.String(), b.String()) + } +} + +// TestBaseVersionStripsSuffixes ports upstream's test_base_version_strips_suffixes. +func TestBaseVersionStripsSuffixes(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + v := parsedVersion(t, versionString(true, 1), "version") + + base := mustParse(t, v.BaseVersion()) + + if base.IsPreRelease() || base.IsPostRelease() { + t.Fatalf("BaseVersion() %q of %q still has a pre or post segment", v.BaseVersion(), v) + } + if base.Local() != "" { + t.Fatalf("BaseVersion() %q of %q still has a local label", v.BaseVersion(), v) + } + // The base version can never exceed the version it came from. + if base.GreaterThan(v) && !v.IsPreRelease() { + t.Fatalf("BaseVersion() %q should not exceed %q", base, v) + } + }) +} diff --git a/internal/proptest/version_ordering_test.go b/internal/proptest/version_ordering_test.go new file mode 100644 index 0000000..f4c656f --- /dev/null +++ b/internal/proptest/version_ordering_test.go @@ -0,0 +1,381 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +// Ordering properties, ported from pypa/packaging's +// tests/property/test_version_ordering.py at pinned SHA +// 4eb0753dba8fcaaac8eb75463374e448f0931558. +// +// Upstream's suite also asserts the *shape* of parsed fields — that +// version.release is a tuple of non-negative ints, that version.pre is a +// (letter, int) pair, and so on. Those are not ported, for two reasons: this +// module exports no accessor for epoch, release, pre, post, or dev (only +// String, BaseVersion, Public, Local, Original, IsPreRelease, IsPostRelease +// and the comparison methods), and in Go the field types make most of those +// assertions statically true rather than testable. What remains portable is +// the observable part, which is also the part a resolver depends on: ordering. + +package proptest + +import ( + "fmt" + "strings" + "testing" + + "pgregory.net/rapid" + + "github.com/posit-dev/go-python-packaging/version" +) + +// parseOrFatal parses a literal version from a plain (non-property) table +// test. Property tests use mustParse, which reports through *rapid.T. +func parseOrFatal(t *testing.T, s string) version.Version { + t.Helper() + v, err := version.Parse(s) + if err != nil { + t.Fatalf("version.Parse(%q): unexpected error %v", s, err) + } + return v +} + +func TestEpochSortsByNumericValue(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + a := rapid.IntRange(0, 5).Draw(t, "epochA") + b := rapid.IntRange(0, 5).Draw(t, "epochB") + release := releaseSegment().Draw(t, "sharedRelease") + + va := mustParse(t, fmt.Sprintf("%d!%s", a, release)) + vb := mustParse(t, fmt.Sprintf("%d!%s", b, release)) + + switch { + case a < b: + if !va.LessThan(vb) { + t.Fatalf("epoch %d should sort below %d at release %s", a, b, release) + } + case a > b: + if !va.GreaterThan(vb) { + t.Fatalf("epoch %d should sort above %d at release %s", a, b, release) + } + default: + if !va.Equal(vb) { + t.Fatalf("equal epochs %d should compare equal at release %s", a, release) + } + } + }) +} + +func TestImplicitEpochIsZero(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + + implicit := mustParse(t, release) + explicit := mustParse(t, "0!"+release) + + if !implicit.Equal(explicit) { + t.Fatalf("%q and %q should be equal, got %q vs %q", + release, "0!"+release, implicit, explicit) + } + }) +} + +func TestHigherEpochBeatsAnyRelease(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + epoch := rapid.IntRange(1, 5).Draw(t, "higherEpoch") + lowRelease := releaseSegment().Draw(t, "epochZeroRelease") + highRelease := releaseSegment().Draw(t, "higherEpochRelease") + + // The epoch dominates: no release value at epoch 0 can outrank a + // version at a higher epoch, however large. + zero := mustParse(t, lowRelease) + higher := mustParse(t, fmt.Sprintf("%d!%s", epoch, highRelease)) + + if !higher.GreaterThan(zero) { + t.Fatalf("%q should outrank %q regardless of release values", higher, zero) + } + }) +} + +func TestReleaseSortsLikeZeroPaddedTuple(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + a := rapid.SliceOfN(rapid.IntRange(0, 50), 1, 4).Draw(t, "releaseA") + b := rapid.SliceOfN(rapid.IntRange(0, 50), 1, 4).Draw(t, "releaseB") + + va := mustParse(t, joinInts(a)) + vb := mustParse(t, joinInts(b)) + + // Independent reference: compare the two release tuples + // component-wise, treating a missing component as 0. This is the + // definition PEP 440 gives; it is not derived from the library. + want := comparePaddedTuples(a, b) + + if got := va.Compare(vb); got != want { + t.Fatalf("Compare(%q, %q) = %d, want %d (zero-padded tuple order)", + joinInts(a), joinInts(b), got, want) + } + }) +} + +func comparePaddedTuples(a, b []int) int { + n := max(len(a), len(b)) + for i := range n { + av, bv := 0, 0 + if i < len(a) { + av = a[i] + } + if i < len(b) { + bv = b[i] + } + if av != bv { + if av < bv { + return -1 + } + return 1 + } + } + return 0 +} + +func TestTrailingZerosAreEqual(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + base := rapid.SliceOfN(smallInt(), 1, 3).Draw(t, "baseRelease") + extra := rapid.IntRange(1, 3).Draw(t, "trailingZeroCount") + + short := joinInts(base) + padded := short + strings.Repeat(".0", extra) + + if !mustParse(t, short).Equal(mustParse(t, padded)) { + t.Fatalf("%q and %q should be equal", short, padded) + } + }) +} + +// TestFullSuffixChain is the composite of upstream's individual +// dev/alpha/beta/rc/final/post ordering properties: +// +// .devN < aN < bN < rcN < final < .postN +func TestFullSuffixChain(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := smallInt().Draw(t, "suffixNum") + post := smallInt().Draw(t, "postNum") + + chain := []string{ + fmt.Sprintf("%s.dev%d", release, n), + fmt.Sprintf("%sa%d", release, n), + fmt.Sprintf("%sb%d", release, n), + fmt.Sprintf("%src%d", release, n), + release, + fmt.Sprintf("%s.post%d", release, post), + } + + for i := range len(chain) - 1 { + lo, hi := mustParse(t, chain[i]), mustParse(t, chain[i+1]) + if !lo.LessThan(hi) { + t.Fatalf("expected %q < %q in the suffix chain", chain[i], chain[i+1]) + } + } + }) +} + +func TestCEqualsRC(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + n := smallInt().Draw(t, "preNum") + + c := mustParse(t, fmt.Sprintf("%sc%d", release, n)) + rc := mustParse(t, fmt.Sprintf("%src%d", release, n)) + + if !c.Equal(rc) { + t.Fatalf("c%d and rc%d should be equal at release %s, got %q vs %q", + n, n, release, c, rc) + } + + // And the "c" spelling must sort above beta, which is what makes the + // c-is-rc aliasing observable rather than cosmetic. + b := mustParse(t, fmt.Sprintf("%sb%d", release, n)) + if !c.GreaterThan(b) { + t.Fatalf("c%d should sort above b%d at release %s", n, n, release) + } + }) +} + +// TestSuffixChainWithinPreRelease ports upstream's +// TestOrderingWithinPreRelease: .devN < < .postN, all sharing one +// pre-release. +func TestSuffixChainWithinPreRelease(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + preNum := smallInt().Draw(t, "preNum") + devNum := smallInt().Draw(t, "devNum") + postNum := smallInt().Draw(t, "postNum") + + pre := fmt.Sprintf("%s%s%d", release, tag, preNum) + chain := []string{ + fmt.Sprintf("%s.dev%d", pre, devNum), + pre, + fmt.Sprintf("%s.post%d", pre, postNum), + } + + for i := range len(chain) - 1 { + lo, hi := mustParse(t, chain[i]), mustParse(t, chain[i+1]) + if !lo.LessThan(hi) { + t.Fatalf("expected %q < %q within a pre-release", chain[i], chain[i+1]) + } + } + }) +} + +// TestNumericOrderingWithinSharedPrefix covers upstream's pre/post/dev numeric +// ordering properties in one place: within a single suffix kind, ordering is +// numeric, not lexicographic. This is the shape that produced the silent wrong +// answer in rstudio/package-manager#19369. +func TestNumericOrderingWithinSharedPrefix(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + release := releaseSegment().Draw(t, "release") + tag := preTag().Draw(t, "preTag") + a := smallInt().Draw(t, "numA") + b := smallInt().Draw(t, "numB") + + forms := map[string]string{ + "pre": "%s" + tag + "%d", + "post": "%s.post%d", + "dev": "%s.dev%d", + } + + for kind, format := range forms { + va := mustParse(t, fmt.Sprintf(format, release, a)) + vb := mustParse(t, fmt.Sprintf(format, release, b)) + + want := 0 + if a < b { + want = -1 + } else if a > b { + want = 1 + } + + if got := va.Compare(vb); got != want { + t.Fatalf("%s: Compare(%q, %q) = %d, want %d", kind, va, vb, got, want) + } + } + }) +} + +// orderedSpecExample is PEP 440's own worked ordering example, quoted verbatim +// from upstream's ORDERED_VERSIONS. Indices 13-15 are the local-label entries; +// upstream excludes them from the strict-ordering pass because a local label +// orders only against versions sharing its public part. +var orderedSpecExample = []string{ + "1.dev0", "1.0.dev456", "1.0a1", "1.0a2.dev456", "1.0a12.dev456", "1.0a12", + "1.0b1.dev456", "1.0b2", "1.0b2.post345.dev456", "1.0b2.post345", + "1.0rc1.dev456", "1.0rc1", "1.0", "1.0+abc.5", "1.0+abc.7", "1.0+5", + "1.0.post456.dev34", "1.0.post456", "1.0.15", "1.1.dev1", +} + +var localIndices = map[int]bool{13: true, 14: true, 15: true} + +// TestSpecExamplePairwiseOrdering is a plain table test, not a property. +// Upstream's equivalent is likewise not @given-driven: the list is PEP 440's +// normative example, so there is nothing to generate. +func TestSpecExamplePairwiseOrdering(t *testing.T) { + for i := range orderedSpecExample { + for j := i + 1; j < len(orderedSpecExample); j++ { + if localIndices[i] || localIndices[j] { + continue + } + + lo := parseOrFatal(t, orderedSpecExample[i]) + hi := parseOrFatal(t, orderedSpecExample[j]) + + if !lo.LessThan(hi) { + t.Errorf("PEP 440 spec example: expected %q (index %d) < %q (index %d)", + orderedSpecExample[i], i, orderedSpecExample[j], j) + } + } + } +} + +// TestSpecExampleLocalOrdering asserts the part upstream's strict pass skips: +// the three local labels order among themselves and sit above their shared +// public version. +func TestSpecExampleLocalOrdering(t *testing.T) { + // "1.0+5" is numeric and "1.0+abc.N" is lexicographic; PEP 440 orders a + // numeric local segment above an alphabetic one, so +5 is the greatest of + // the three despite appearing last in the spec's list. The first pair also + // covers "a local label sorts above its bare public version". + for _, tc := range []struct{ lower, higher string }{ + {"1.0", "1.0+abc.5"}, + {"1.0+abc.5", "1.0+abc.7"}, + {"1.0+abc.7", "1.0+5"}, + } { + lo := parseOrFatal(t, tc.lower) + hi := parseOrFatal(t, tc.higher) + if !lo.LessThan(hi) { + t.Errorf("expected %q < %q", tc.lower, tc.higher) + } + } +} + +func TestVersionComparisonIsTotalOrder(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + // Total order is the property a resolver actually depends on, and it + // has no upstream counterpart. Drawn from versions sharing a release + // segment as well as fully independent ones, because ties and + // near-ties are where antisymmetry and transitivity break. + a := parsedVersion(t, versionString(true, 1), "a") + b := parsedVersion(t, versionString(true, 1), "b") + c := parsedVersion(t, versionString(true, 1), "c") + + ab, ba := a.Compare(b), b.Compare(a) + + // Totality: every pair is comparable, and Compare returns one of -1, 0, 1. + for _, got := range []int{ab, ba} { + if got < -1 || got > 1 { + t.Fatalf("Compare returned %d, want one of -1, 0, 1 (%q vs %q)", got, a, b) + } + } + + // Antisymmetry. + if ab != -ba { + t.Fatalf("antisymmetry: Compare(%q,%q)=%d but Compare(%q,%q)=%d", a, b, ab, b, a, ba) + } + + // Reflexivity. + if a.Compare(a) != 0 { + t.Fatalf("reflexivity: Compare(%q,%q) = %d, want 0", a, a, a.Compare(a)) + } + + // Transitivity of <=. + if a.LessThanOrEqual(b) && b.LessThanOrEqual(c) && !a.LessThanOrEqual(c) { + t.Fatalf("transitivity: %q <= %q <= %q but not %q <= %q", a, b, c, a, c) + } + + // Equal versions must agree with Compare == 0, and the convenience + // methods must agree with Compare. + if a.Equal(b) != (ab == 0) { + t.Fatalf("Equal/Compare disagree for %q vs %q: Equal=%v Compare=%d", a, b, a.Equal(b), ab) + } + if a.LessThan(b) != (ab < 0) { + t.Fatalf("LessThan/Compare disagree for %q vs %q", a, b) + } + if a.GreaterThan(b) != (ab > 0) { + t.Fatalf("GreaterThan/Compare disagree for %q vs %q", a, b) + } + }) +} + +// TestSortedVersionsMatchesCompare checks the exported sort.Interface +// implementation agrees with Compare, since a resolver sorts candidate lists +// through it rather than comparing pairwise. +func TestSortedVersionsMatchesCompare(t *testing.T) { + rapid.Check(t, func(t *rapid.T) { + a := parsedVersion(t, versionString(false, 1), "a") + b := parsedVersion(t, versionString(false, 1), "b") + + sv := version.SortedVersions{a, b} + if got, want := sv.Less(0, 1), a.Compare(b) < 0; got != want { + t.Fatalf("SortedVersions.Less(%q, %q) = %v, want %v", a, b, got, want) + } + if sv.Len() != 2 { + t.Fatalf("SortedVersions.Len() = %d, want 2", sv.Len()) + } + }) +} diff --git a/version/local_normalization_test.go b/version/local_normalization_test.go new file mode 100644 index 0000000..126aec8 --- /dev/null +++ b/version/local_normalization_test.go @@ -0,0 +1,117 @@ +// SPDX-License-Identifier: Apache-2.0 OR MIT + +package version + +import "testing" + +// Local-label normalization, per PEP 440: "-" and "_" separators inside a +// local version label MUST be normalized to ".". +// +// Reference behavior measured against pypa/packaging at pinned SHA +// 4eb0753dba8fcaaac8eb75463374e448f0931558 (reporting itself as 26.3.dev0), +// read from source rather than a pip-installed copy -- the released 26.2 +// differs from the pinned tree in unrelated ways. +// +// Found by the property tests in internal/proptest. + +func TestLocalLabelSeparatorsNormalize(t *testing.T) { + for _, tc := range []struct { + in string + want string + }{ + {"1.0+abc.abc", "1.0+abc.abc"}, + {"1.0+abc-abc", "1.0+abc.abc"}, + {"1.0+abc_abc", "1.0+abc.abc"}, + {"1.0+abc-def.ghi_jkl", "1.0+abc.def.ghi.jkl"}, + {"1.0+ubuntu-1", "1.0+ubuntu.1"}, + // Case is lowered as well, and the two rules compose. + {"1.0+Ubuntu-1", "1.0+ubuntu.1"}, + {"1.0+ABC_DEF", "1.0+abc.def"}, + } { + v, err := Parse(tc.in) + if err != nil { + t.Errorf("Parse(%q): unexpected error %v", tc.in, err) + continue + } + if got := v.String(); got != tc.want { + t.Errorf("Parse(%q).String() = %q, want %q", tc.in, got, tc.want) + } + if got := v.Local(); got != tc.want[len("1.0+"):] { + t.Errorf("Parse(%q).Local() = %q, want %q", tc.in, got, tc.want[len("1.0+"):]) + } + } +} + +func TestLocalLabelSeparatorFormsAreEqual(t *testing.T) { + for _, tc := range [][2]string{ + {"1.0+abc.abc", "1.0+abc-abc"}, + {"1.0+abc.abc", "1.0+abc_abc"}, + {"1.0+a.b.c", "1.0+a-b_c"}, + {"1.0+ubuntu.1", "1.0+ubuntu-1"}, + } { + a, err := Parse(tc[0]) + if err != nil { + t.Fatalf("Parse(%q): %v", tc[0], err) + } + b, err := Parse(tc[1]) + if err != nil { + t.Fatalf("Parse(%q): %v", tc[1], err) + } + if !a.Equal(b) { + t.Errorf("%q and %q should be equal, got %q vs %q", tc[0], tc[1], a, b) + } + } +} + +// TestLocalLabelSeparatorOrdering is the regression test for the silent wrong +// answer the un-normalized label produced. +// +// cmpkey splits a local label on "." to compare it segment by segment, with a +// numeric segment ordering above an alphabetic one. Without separator +// normalization, "ubuntu-2" is one alphabetic segment rather than two, so the +// comparison falls back to lexicographic ordering of the whole label and +// "ubuntu-10" sorts BELOW "ubuntu-2". +func TestLocalLabelSeparatorOrdering(t *testing.T) { + for _, tc := range []struct { + lower, higher string + }{ + // The dotted form was always correct; the dash and underscore forms + // were not, and must now agree with it. + {"1.0+ubuntu.2", "1.0+ubuntu.10"}, + {"1.0+ubuntu-2", "1.0+ubuntu-10"}, + {"1.0+ubuntu_2", "1.0+ubuntu_10"}, + {"1.0+abc-1", "1.0+abc-2"}, + {"1.0+deb-9", "1.0+deb-11"}, + } { + lo, err := Parse(tc.lower) + if err != nil { + t.Fatalf("Parse(%q): %v", tc.lower, err) + } + hi, err := Parse(tc.higher) + if err != nil { + t.Fatalf("Parse(%q): %v", tc.higher, err) + } + if !lo.LessThan(hi) { + t.Errorf("expected %q < %q (numeric local segment ordering)", tc.lower, tc.higher) + } + } +} + +// TestSurroundingWhitespaceIncludesVerticalTab covers the second divergence +// the property tests surfaced. Go's \s is [\t\n\f\r ] and omits the vertical +// tab; Python's re \s is [ \t\n\r\f\v] and includes it, so pypa/packaging +// accepts "1.0\v" where a bare \s* anchor would reject it. +func TestSurroundingWhitespaceIncludesVerticalTab(t *testing.T) { + for _, ws := range []string{" ", "\t", "\n", "\r", "\f", "\v"} { + for _, in := range []string{ws + "1.0", "1.0" + ws, ws + "1.0" + ws} { + v, err := Parse(in) + if err != nil { + t.Errorf("Parse(%q): unexpected error %v", in, err) + continue + } + if got := v.String(); got != "1.0" { + t.Errorf("Parse(%q).String() = %q, want %q", in, got, "1.0") + } + } + } +} diff --git a/version/version.go b/version/version.go index 8b50c19..f5ae28e 100644 --- a/version/version.go +++ b/version/version.go @@ -90,7 +90,28 @@ func (ln letterNumber) isNull() bool { } func init() { - versionRegex = regexp.MustCompile(`(?i)^\s*` + regex + `\s*$`) + // The surrounding-whitespace class must include the vertical tab. Go's + // \s is [\t\n\f\r ] and excludes \v, while Python's re \s is + // [ \t\n\r\f\v] and includes it -- so anchoring with a bare \s* would + // reject "1.0\v", which pypa/packaging accepts. + versionRegex = regexp.MustCompile(`(?i)^[\s\v]*` + regex + `[\s\v]*$`) +} + +// localVersionSeparators matches the separators PEP 440 permits inside a local +// version label. It mirrors pypa/packaging's _local_version_separators. +var localVersionSeparators = regexp.MustCompile(`[._-]`) + +// normalizeLocal normalizes a local version label: PEP 440 requires "-" and +// "_" separators to be rewritten as ".", and the label to be lowercased. +// +// Normalizing the separator is not cosmetic. cmpkey splits the label on "." +// to compare it segment by segment, with numeric segments ordering above +// alphabetic ones, so an un-normalized "ubuntu-2" is treated as a single +// alphabetic segment and compared lexicographically. That makes +// "1.0+ubuntu-10" sort BELOW "1.0+ubuntu-2" -- a silent wrong answer of the +// same kind as rstudio/package-manager#19369. +func normalizeLocal(local string) string { + return localVersionSeparators.ReplaceAllString(strings.ToLower(local), ".") } // MustParse is like Parse but panics if the version cannot be parsed. @@ -150,7 +171,7 @@ func Parse(v string) (Version, error) { case "dev_n": devN, err = part.NewBigInt(m) case "local": - local = strings.ToLower(m) + local = normalizeLocal(m) } if err != nil { return Version{}, fmt.Errorf("failed to parse version (%s): %w", v, err)