Compare canonical paths by token spelling

This commit is contained in:
2026-10-09 03:23:08 +00:00
parent edc6660654
commit 9ac65ccc08
5 changed files with 151 additions and 16 deletions

View File

@@ -48,6 +48,106 @@ func TestPathRoundTripsSemanticKeys(t *testing.T) {
}
}
func TestPathContainmentMatchesPointerSpelling(t *testing.T) {
parse := func(pointer string) Path {
path, err := ParsePath(pointer)
if err != nil {
t.Fatalf("ParsePath(%q) error = %v", pointer, err)
}
return path
}
maximum := int(^uint(0) >> 1)
minimum := -maximum - 1
paths := []Path{
{},
Keys(""),
Keys("a"),
Keys("ab"),
Keys("a", "b"),
Keys("a/b"),
Keys("a~1b"),
Keys("~"),
Keys("0"),
Keys("01"),
Keys("+1"),
Keys("items").Index(0),
Keys("items").Index(maximum),
Keys("items").Index(minimum),
parse("/"),
parse("/a~1b"),
parse("/a~01b"),
parse("/~0"),
parse("/0"),
parse("/01"),
parse("/+1"),
parse("/items/0"),
parse("/items/" + strconv.Itoa(maximum)),
parse("/items/" + strconv.Itoa(minimum)),
Path{}.Index(-1),
}
for _, container := range paths {
for _, descendant := range paths {
got := pathContains(container, descendant)
want := pathContainsByPointer(container, descendant)
if got != want {
t.Errorf("pathContains(%q, %q) = %v, want %v", container.String(), descendant.String(), got, want)
}
}
}
}
func TestAppendUniquePathMatchesPointerSpelling(t *testing.T) {
parse := func(pointer string) Path {
path, err := ParsePath(pointer)
if err != nil {
t.Fatalf("ParsePath(%q) error = %v", pointer, err)
}
return path
}
paths := []Path{
Keys("a/b"), parse("/a~1b"),
Keys("a~1b"), parse("/a~01b"),
Keys("items").Index(0), parse("/items/0"), Keys("items", "0"),
Keys("items", "01"), parse("/items/01"),
Path{}.Index(-1), Keys("-1"),
Keys("a", "b"), Keys("a/b"),
}
var got, want []Path
for _, path := range paths {
got = appendUniquePath(got, path)
want = appendUniquePathByPointer(want, path)
}
if len(got) != len(want) {
t.Fatalf("unique path counts = %d, want %d", len(got), len(want))
}
for i := range got {
if got[i].String() != want[i].String() {
t.Fatalf("unique path %d = %q, want %q", i, got[i].String(), want[i].String())
}
}
}
func pathContainsByPointer(container, descendant Path) bool {
if !container.valid() || !descendant.valid() || len(container.segments) > len(descendant.segments) {
return false
}
prefix := container.String()
if prefix == "" {
return true
}
value := descendant.String()
return value == prefix || len(value) > len(prefix) && value[:len(prefix)] == prefix && value[len(prefix)] == '/'
}
func appendUniquePathByPointer(paths []Path, path Path) []Path {
for _, existing := range paths {
if existing.String() == path.String() {
return paths
}
}
return append(paths, path.clone())
}
func TestPathPreservesSegmentIntentAndImmutability(t *testing.T) {
t.Parallel()