Verify versioned contracts and exact offline distribution selection

This commit is contained in:
2026-11-29 04:35:26 +00:00
parent 053219b8da
commit e2e86a0a71
5 changed files with 184 additions and 43 deletions

View File

@@ -2,10 +2,13 @@ package main
import ( import (
"bytes" "bytes"
"encoding/json"
"os" "os"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
"forge.maximumdirect.net/eric/schemas/internal/validation"
) )
func TestCommand(t *testing.T) { func TestCommand(t *testing.T) {
@@ -39,6 +42,70 @@ func TestCommand(t *testing.T) {
} }
} }
func TestExactDefinitions(t *testing.T) {
root := t.TempDir()
data, err := os.ReadFile("../../catalog.json")
if err != nil {
t.Fatal(err)
}
var catalog validation.Catalog
if err := json.Unmarshal(data, &catalog); err != nil {
t.Fatal(err)
}
write := func(path string, body []byte) {
t.Helper()
target := filepath.Join(root, path)
if err := os.MkdirAll(filepath.Dir(target), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(target, body, 0644); err != nil {
t.Fatal(err)
}
}
var glossary validation.Record
for _, record := range catalog.Schemas {
data, err := os.ReadFile("../../" + record.Path)
if err != nil {
t.Fatal(err)
}
write(record.Path, data)
if record.Name == "glossary" {
glossary = record
}
}
data, err = os.ReadFile("../../" + glossary.Path)
if err != nil {
t.Fatal(err)
}
var schema map[string]any
if err := json.Unmarshal(data, &schema); err != nil {
t.Fatal(err)
}
glossary.Version = "0.2.0"
glossary.Path = "glossary/v0.2.0/schema.json"
glossary.ID = "https://schemas.maximumdirect.net/" + glossary.Path
schema["$id"] = glossary.ID
schema["required"] = []string{"schema_version", "collections", "synthetic_test_field"}
data, err = json.Marshal(schema)
if err != nil {
t.Fatal(err)
}
write(glossary.Path, data)
catalog.Schemas = append(catalog.Schemas, glossary)
data, err = json.Marshal(catalog)
if err != nil {
t.Fatal(err)
}
write("catalog.json", data)
write("document.json", []byte(`{"schema_version":"maximumdirect.glossary.v1","collections":{}}`))
for selection, want := range map[string]int{"glossary@0.1.0": 0, "glossary@0.2.0": 1} {
var stdout, stderr bytes.Buffer
if got := run([]string{"-root", root, "-schema", selection, filepath.Join(root, "document.json")}, &stdout, &stderr); got != want {
t.Fatalf("%s exit %d, want %d: %s", selection, got, want, &stderr)
}
}
}
func TestJSONSyntax(t *testing.T) { func TestJSONSyntax(t *testing.T) {
file := filepath.Join(t.TempDir(), "document.json") file := filepath.Join(t.TempDir(), "document.json")
if err := os.WriteFile(file, []byte("schema_version: maximumdirect.rpg.campaign.v1\nid: sample"), 0600); err != nil { if err := os.WriteFile(file, []byte("schema_version: maximumdirect.rpg.campaign.v1\nid: sample"), 0600); err != nil {

View File

@@ -11,7 +11,7 @@ in this distribution's [LICENSE](../../LICENSE). The selected revision is not
publicly available at the forge during this adoption. This snapshot makes the publicly available at the forge during this adoption. This snapshot makes the
incorporated source independently inspectable in the distribution. incorporated source independently inspectable in the distribution.
The active [shared glossary schema](../../schemas/glossary.schema.json) adapts The active [shared glossary schema](../../glossary/v0.1.0/schema.json) adapts
that source with an envelope, changed defined fields, structural extensions, that source with an envelope, changed defined fields, structural extensions,
and provenance. The snapshot records origin; it is not a supported contract and provenance. The snapshot records origin; it is not a supported contract
or an additional schema that consumers need to register. or an additional schema that consumers need to register.

View File

@@ -16,7 +16,7 @@ func TestDistributionDocuments(t *testing.T) {
root := os.DirFS("../..") root := os.DirFS("../..")
for _, required := range []string{ for _, required := range []string{
"README.md", "AGENTS.md", "LICENSE", "COPYRIGHT", "VERSION", "go.mod", "go.sum", "README.md", "AGENTS.md", "LICENSE", "COPYRIGHT", "VERSION", "go.mod", "go.sum",
"docs/party.md", "docs/campaign.md", "docs/glossary.md", "docs/validation.md", "catalog.json", "docs/catalog.md", "docs/validation.md",
"docs/compatibility.md", "docs/development.md", "docs/release.md", "docs/inventory.md", "docs/compatibility.md", "docs/development.md", "docs/release.md", "docs/inventory.md",
"docs/oss/attribution.md", "scripts/check.sh", ".woodpecker.yml", "docs/oss/attribution.md", "scripts/check.sh", ".woodpecker.yml",
} { } {
@@ -24,6 +24,16 @@ func TestDistributionDocuments(t *testing.T) {
t.Errorf("required distribution content %s: %v", required, err) t.Errorf("required distribution content %s: %v", required, err)
} }
} }
set := loadSet(t)
for _, record := range set.Catalog.Schemas {
if _, err := fs.Stat(root, path.Join(path.Dir(record.Path), "semantics.md")); err != nil {
t.Error(err)
}
entries, err := fs.ReadDir(root, path.Join(path.Dir(record.Path), "examples"))
if err != nil || len(entries) == 0 {
t.Errorf("%s missing examples: %v", record.Path, err)
}
}
version, err := fs.ReadFile(root, "VERSION") version, err := fs.ReadFile(root, "VERSION")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@@ -0,0 +1,37 @@
package validation
import (
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
)
func TestCanonicalStaticPaths(t *testing.T) {
set := loadSet(t)
server := httptest.NewServer(http.FileServer(http.Dir("../..")))
defer server.Close()
for _, record := range set.Catalog.Schemas {
t.Run(record.Name, func(t *testing.T) {
route := strings.TrimPrefix(record.ID, schemaBase)
response, err := server.Client().Get(server.URL + "/" + route)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
got, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
want, err := os.ReadFile("../../" + record.Path)
if err != nil {
t.Fatal(err)
}
if response.StatusCode != 200 || string(got) != string(want) {
t.Fatalf("canonical path %s did not serve the exact schema bytes", record.ID)
}
})
}
}

View File

@@ -22,7 +22,11 @@ func loadSet(t *testing.T) *Set {
func TestDocuments(t *testing.T) { func TestDocuments(t *testing.T) {
set := loadSet(t) set := loadSet(t)
for _, directory := range []string{"examples", "tests/valid", "tests/invalid"} { directories := []string{"tests/valid", "tests/invalid"}
for _, record := range set.Catalog.Schemas {
directories = append(directories, filepath.Dir(record.Path)+"/examples")
}
for _, directory := range directories {
err := filepath.WalkDir(filepath.Join("../..", directory), func(path string, entry fs.DirEntry, walkErr error) error { err := filepath.WalkDir(filepath.Join("../..", directory), func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil { if walkErr != nil {
return walkErr return walkErr
@@ -41,7 +45,7 @@ func TestDocuments(t *testing.T) {
before, err = json.Marshal(value) before, err = json.Marshal(value)
} }
if err == nil { if err == nil {
err = set.Validate(value) err = validateFixture(t, set, value)
} }
if directory == "tests/invalid" { if directory == "tests/invalid" {
phase, _, _ := strings.Cut(entry.Name(), "-") phase, _, _ := strings.Cut(entry.Name(), "-")
@@ -99,7 +103,7 @@ func TestDefinedFieldShapes(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := set.Validate(value); (err == nil) != test.valid { if err := validateFixture(t, set, value); (err == nil) != test.valid {
t.Fatalf("valid=%v, error=%v", test.valid, err) t.Fatalf("valid=%v, error=%v", test.valid, err)
} }
}) })
@@ -128,7 +132,7 @@ func TestDefinedFieldShapes(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := set.Validate(value); (err == nil) != test.valid { if err := validateFixture(t, set, value); (err == nil) != test.valid {
t.Fatalf("valid=%v, error=%v", test.valid, err) t.Fatalf("valid=%v, error=%v", test.valid, err)
} }
}) })
@@ -193,7 +197,7 @@ func TestJSONDecoding(t *testing.T) {
if !reflect.DeepEqual(value, want) { if !reflect.DeepEqual(value, want) {
t.Fatalf("JSON decoding changed data: got %#v, want %#v", value, want) t.Fatalf("JSON decoding changed data: got %#v, want %#v", value, want)
} }
if err := loadSet(t).Validate(value); err != nil { if err := validateFixture(t, loadSet(t), value); err != nil {
t.Fatal(err) t.Fatal(err)
} }
for _, input := range []string{ for _, input := range []string{
@@ -229,11 +233,11 @@ func TestNumericPrecision(t *testing.T) {
} }
func TestYAMLJSONEquivalence(t *testing.T) { func TestYAMLJSONEquivalence(t *testing.T) {
yamlBytes, err := os.ReadFile("../../examples/weather.yml") yamlBytes, err := os.ReadFile("../../glossary/v0.1.0/examples/weather.yml")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
jsonBytes, err := os.ReadFile("../../examples/weather.json") jsonBytes, err := os.ReadFile("../../glossary/v0.1.0/examples/weather.json")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -258,57 +262,80 @@ func TestYAMLJSONEquivalence(t *testing.T) {
} }
} }
// validateFixture chooses the known initial definition for domain-focused fixtures.
// Public CLI selection is always explicit and tested separately.
func validateFixture(t *testing.T, set *Set, value any) error {
t.Helper()
selection := "glossary@0.1.0"
if doc, ok := value.(map[string]any); ok {
switch doc["schema_version"] {
case "maximumdirect.rpg.party.v1":
selection = "rpg/party@0.1.0"
case "maximumdirect.rpg.campaign.v1":
selection = "rpg/campaign@0.1.0"
}
}
schema, err := set.Select(selection)
if err != nil {
t.Fatal(err)
}
return schema.Validate(value)
}
func TestDistributionAndOfflineResolution(t *testing.T) { func TestDistributionAndOfflineResolution(t *testing.T) {
// Only the distributed schemas and version are needed; no checkout or HTTP
// resource loader is available through this in-memory filesystem.
files := fstest.MapFS{} files := fstest.MapFS{}
for _, file := range []string{"VERSION", "schemas/campaign.schema.json", "schemas/glossary.schema.json", "schemas/party.schema.json"} { root := os.DirFS("../..")
data, err := os.ReadFile(filepath.Join("../..", file)) catalogBytes, err := fs.ReadFile(root, "catalog.json")
if err != nil {
t.Fatal(err)
}
var catalog Catalog
if err := json.Unmarshal(catalogBytes, &catalog); err != nil {
t.Fatal(err)
}
files["catalog.json"] = &fstest.MapFile{Data: catalogBytes}
for _, record := range catalog.Schemas {
data, err := fs.ReadFile(root, record.Path)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
files[file] = &fstest.MapFile{Data: data} files[record.Path] = &fstest.MapFile{Data: data}
} }
partyPath := "rpg/party/v0.1.0/schema.json"
original := files[partyPath].Data
replacement := `"name": {"$ref": "` + schemaBase + `glossary/v0.1.0/schema.json#/$defs/text"}`
files[partyPath] = &fstest.MapFile{Data: []byte(strings.Replace(string(original), `"name": {"$ref": "#/$defs/text"}`, replacement, 1))}
set, err := Load(files) set, err := Load(files)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
value, err := Decode([]byte("schema_version: maximumdirect.rpg.campaign.v1\nid: offline")) selected, err := set.Select("rpg/party@0.1.0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
if err := set.Validate(value); err != nil { value, err := Decode([]byte("schema_version: maximumdirect.rpg.party.v1\ncharacters: {mira: {character: {name: Mira}}}"))
if err != nil {
t.Fatal(err) t.Fatal(err)
} }
original := files["schemas/party.schema.json"].Data if err := selected.Validate(value); err != nil {
t.Run("shared reference in the same release", func(t *testing.T) { t.Fatal(err)
version := strings.TrimSpace(string(files["VERSION"].Data)) }
reference := `"name": {"$ref": "` + schemaBase + version + `/schemas/glossary.schema.json#/$defs/text"}` files["VERSION"] = &fstest.MapFile{Data: []byte("2099.01.0\n")}
files["schemas/party.schema.json"] = &fstest.MapFile{Data: []byte(strings.Replace(string(original), `"name": {"$ref": "#/$defs/text"}`, reference, 1))} if _, err := Load(files); err != nil {
if _, err := Load(files); err != nil { t.Fatalf("distribution version changed schema identities: %v", err)
t.Fatalf("bundled cross-schema reference failed offline: %v", err) }
} for _, replacement := range []string{
}) `"name": {"$ref": "https://example.invalid/missing.json"}`,
for name, replacement := range map[string]string{ `"name": {"type": 123}`,
"missing reference": `"name": {"$ref": "https://example.invalid/missing.json"}`, `"name": {"$ref": "https://schemas.maximumdirect.net/glossary/v9.0.0/schema.json"}`,
"bad schema keyword": `"name": {"type": 123}`,
"mixed release": `"name": {"$ref": "https://forge.maximumdirect.net/eric/schemas/raw/tag/v0.0.0/schemas/glossary.schema.json"}`,
} { } {
t.Run(name, func(t *testing.T) { files[partyPath] = &fstest.MapFile{Data: []byte(strings.Replace(string(original), `"name": {"$ref": "#/$defs/text"}`, replacement, 1))}
files["schemas/party.schema.json"] = &fstest.MapFile{Data: []byte(strings.Replace(string(original), `"name": {"$ref": "#/$defs/text"}`, replacement, 1))} if _, err := Load(files); err == nil {
if _, err := Load(files); err == nil { t.Fatal("malformed schema or absent reference compiled")
t.Fatal("incomplete or malformed distribution compiled") }
}
})
} }
files["schemas/party.schema.json"] = &fstest.MapFile{Data: original} files[partyPath] = &fstest.MapFile{Data: []byte("title: not JSON")}
files["schemas/party.schema.json"] = &fstest.MapFile{Data: []byte("title: not JSON")}
if _, err := Load(files); err == nil { if _, err := Load(files); err == nil {
t.Fatal("a schema file accepted non-JSON syntax") t.Fatal("schema accepted non-JSON syntax")
}
files["schemas/party.schema.json"] = &fstest.MapFile{Data: original}
files["VERSION"] = &fstest.MapFile{Data: []byte("v9.0.0\n")}
if _, err := Load(files); err == nil {
t.Fatal("schema IDs did not match the distribution's version")
} }
} }