Establish shared domain schemas and offline validation
This commit is contained in:
195
internal/validation/decode.go
Normal file
195
internal/validation/decode.go
Normal file
@@ -0,0 +1,195 @@
|
||||
// Package validation supports this repository's contract checks. It is not a
|
||||
// consumer SDK: consumers may use their own conforming YAML and schema tools.
|
||||
package validation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
|
||||
"go.yaml.in/yaml/v4"
|
||||
)
|
||||
|
||||
// Decode uses go-yaml's parser and scalar resolution, adapting its node graph to
|
||||
// the documented JSON data model. Numbers retain their precision as json.Number.
|
||||
func Decode(data []byte) (any, error) {
|
||||
var document yaml.Node
|
||||
if err := yaml.Load(data, &document, yaml.WithUniqueKeys()); err != nil {
|
||||
return nil, fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
d := decoder{active: make(map[*yaml.Node]bool), values: make(map[*yaml.Node]any)}
|
||||
value, err := d.value(&document, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("decode: %w", err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
type decoder struct {
|
||||
active map[*yaml.Node]bool
|
||||
values map[*yaml.Node]any
|
||||
}
|
||||
|
||||
func (d *decoder) value(n *yaml.Node, path string) (any, error) {
|
||||
if n == nil {
|
||||
return nil, fmt.Errorf("%s: unresolved alias", pointer(path))
|
||||
}
|
||||
if d.active[n] {
|
||||
return nil, nodeError(n, path, "cyclic alias")
|
||||
}
|
||||
if value, found := d.values[n]; found {
|
||||
return value, nil
|
||||
}
|
||||
d.active[n] = true
|
||||
defer delete(d.active, n)
|
||||
var value any
|
||||
var err error
|
||||
switch n.Kind {
|
||||
case yaml.DocumentNode:
|
||||
if len(n.Content) != 1 {
|
||||
return nil, nodeError(n, path, "expected one document")
|
||||
}
|
||||
value, err = d.value(n.Content[0], path)
|
||||
case yaml.AliasNode:
|
||||
value, err = d.value(n.Alias, path)
|
||||
case yaml.MappingNode:
|
||||
if n.ShortTag() != "!!map" {
|
||||
return nil, nodeError(n, path, "unsupported mapping tag %q", n.Tag)
|
||||
}
|
||||
mapping := make(map[string]any, len(n.Content)/2)
|
||||
for i := 0; i < len(n.Content); i += 2 {
|
||||
keyValue, keyErr := d.value(n.Content[i], path)
|
||||
if keyErr != nil {
|
||||
return nil, keyErr
|
||||
}
|
||||
key, ok := keyValue.(string)
|
||||
if !ok {
|
||||
return nil, nodeError(n.Content[i], path, "mapping key must be a string")
|
||||
}
|
||||
childPath := path + "/" + escape(key)
|
||||
if _, exists := mapping[key]; exists {
|
||||
return nil, nodeError(n.Content[i], childPath, "duplicate mapping key %q", key)
|
||||
}
|
||||
mapping[key], err = d.value(n.Content[i+1], childPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
value = mapping
|
||||
case yaml.SequenceNode:
|
||||
if n.ShortTag() != "!!seq" {
|
||||
return nil, nodeError(n, path, "unsupported sequence tag %q", n.Tag)
|
||||
}
|
||||
sequence := make([]any, len(n.Content))
|
||||
for i, child := range n.Content {
|
||||
sequence[i], err = d.value(child, fmt.Sprintf("%s/%d", path, i))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
value = sequence
|
||||
case yaml.ScalarNode:
|
||||
value, err = scalar(n)
|
||||
if err != nil {
|
||||
return nil, nodeError(n, path, "%v", err)
|
||||
}
|
||||
default:
|
||||
return nil, nodeError(n, path, "expected a document value")
|
||||
}
|
||||
if err == nil {
|
||||
d.values[n] = value
|
||||
}
|
||||
return value, err
|
||||
}
|
||||
|
||||
func scalar(n *yaml.Node) (any, error) {
|
||||
switch n.ShortTag() {
|
||||
case "!!str":
|
||||
// go-yaml resolves decimal numbers outside machine-float range as
|
||||
// strings. Plain JSON numbers still retain numeric meaning in this
|
||||
// profile, including when the source serialization is JSON.
|
||||
if n.Style == 0 {
|
||||
if number, ok := jsonNumber(n.Value); ok {
|
||||
return number, nil
|
||||
}
|
||||
}
|
||||
return n.Value, nil
|
||||
case "!!timestamp":
|
||||
// Date-like scalars are text in the shared data model, not time.Time.
|
||||
return n.Value, nil
|
||||
case "!!bool", "!!null":
|
||||
var value any
|
||||
err := n.Decode(&value)
|
||||
return value, err
|
||||
case "!!int":
|
||||
text := strings.ReplaceAll(n.Value, "_", "")
|
||||
integer, ok := new(big.Int).SetString(text, 0)
|
||||
if !ok {
|
||||
integer, ok = new(big.Int).SetString(text, 10)
|
||||
}
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("invalid integer %q", n.Value)
|
||||
}
|
||||
return json.Number(integer.String()), nil
|
||||
case "!!float":
|
||||
// Normalize YAML's leading '+', '.5', and '5.' spellings, retaining the
|
||||
// decimal digits instead of converting through float64.
|
||||
text := strings.TrimPrefix(strings.ReplaceAll(n.Value, "_", ""), "+")
|
||||
mantissa, exponent, hasExponent := strings.Cut(strings.ToLower(text), "e")
|
||||
sign := ""
|
||||
if strings.HasPrefix(mantissa, "-") {
|
||||
sign, mantissa = "-", strings.TrimPrefix(mantissa, "-")
|
||||
}
|
||||
whole, fraction, hasPoint := strings.Cut(mantissa, ".")
|
||||
whole = strings.TrimLeft(whole, "0")
|
||||
if whole == "" {
|
||||
whole = "0"
|
||||
}
|
||||
text = sign + whole
|
||||
if hasPoint {
|
||||
if fraction == "" {
|
||||
fraction = "0"
|
||||
}
|
||||
text += "." + fraction
|
||||
}
|
||||
if hasExponent {
|
||||
text += "e" + exponent
|
||||
}
|
||||
if number, ok := jsonNumber(text); ok {
|
||||
return number, nil
|
||||
}
|
||||
return nil, fmt.Errorf("number %q is not a finite JSON number", n.Value)
|
||||
default:
|
||||
return nil, fmt.Errorf("tag %q has no shared JSON representation", n.Tag)
|
||||
}
|
||||
}
|
||||
|
||||
func jsonNumber(text string) (json.Number, bool) {
|
||||
if !json.Valid([]byte(text)) {
|
||||
return "", false
|
||||
}
|
||||
var value any
|
||||
decoder := json.NewDecoder(strings.NewReader(text))
|
||||
decoder.UseNumber()
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return "", false
|
||||
}
|
||||
number, ok := value.(json.Number)
|
||||
return number, ok
|
||||
}
|
||||
|
||||
func nodeError(n *yaml.Node, path, format string, args ...any) error {
|
||||
return fmt.Errorf("%s (line %d, column %d): %s", pointer(path), n.Line, n.Column, fmt.Sprintf(format, args...))
|
||||
}
|
||||
|
||||
func pointer(path string) string {
|
||||
if path == "" {
|
||||
return "/"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func escape(value string) string {
|
||||
return strings.ReplaceAll(strings.ReplaceAll(value, "~", "~0"), "/", "~1")
|
||||
}
|
||||
67
internal/validation/documentation_test.go
Normal file
67
internal/validation/documentation_test.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// This deliberately checks local Markdown destinations, not external services.
|
||||
// It also runs unchanged from an unpacked source archive.
|
||||
func TestDistributionDocuments(t *testing.T) {
|
||||
root := os.DirFS("../..")
|
||||
for _, required := range []string{
|
||||
"README.md", "AGENTS.md", "LICENSE", "COPYRIGHT", "VERSION", "go.mod", "go.sum",
|
||||
"docs/party.md", "docs/campaign.md", "docs/glossary.md", "docs/validation.md",
|
||||
"docs/compatibility.md", "docs/development.md", "docs/release.md", "docs/inventory.md",
|
||||
"docs/oss/attribution.md", "scripts/check.sh", ".woodpecker.yml",
|
||||
} {
|
||||
if _, err := fs.Stat(root, required); err != nil {
|
||||
t.Errorf("required distribution content %s: %v", required, err)
|
||||
}
|
||||
}
|
||||
version, err := fs.ReadFile(root, "VERSION")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fs.Stat(root, "docs/releases/"+strings.TrimSpace(string(version))+".md"); err != nil {
|
||||
t.Errorf("version-matched release note: %v", err)
|
||||
}
|
||||
link := regexp.MustCompile(`\[[^\]]*\]\(([^)]+)\)`)
|
||||
err = fs.WalkDir(root, ".", func(file string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
if entry.Name() == ".git" || entry.Name() == "dist" {
|
||||
return fs.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if filepath.Ext(file) != ".md" {
|
||||
return nil
|
||||
}
|
||||
data, err := fs.ReadFile(root, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, match := range link.FindAllSubmatch(data, -1) {
|
||||
destination := string(match[1])
|
||||
if strings.Contains(destination, "://") || strings.HasPrefix(destination, "#") {
|
||||
continue
|
||||
}
|
||||
destination, _, _ = strings.Cut(destination, "#")
|
||||
if _, err := fs.Stat(root, path.Join(path.Dir(file), destination)); err != nil {
|
||||
t.Errorf("%s links to missing %s: %v", file, destination, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
118
internal/validation/validate.go
Normal file
118
internal/validation/validate.go
Normal file
@@ -0,0 +1,118 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||||
)
|
||||
|
||||
const schemaBase = "https://forge.maximumdirect.net/eric/schemas/raw/tag/"
|
||||
|
||||
var contractNames = []string{"campaign", "glossary", "party"}
|
||||
|
||||
// Set is a compiled, offline schema set loaded from an unpacked distribution.
|
||||
type Set struct {
|
||||
schemas map[string]*jsonschema.Schema
|
||||
}
|
||||
|
||||
// Load compiles every contract, including meta-schema validation, using only
|
||||
// locally registered resources and the library's built-in dialect definitions.
|
||||
func Load(root fs.FS) (*Set, error) {
|
||||
version, err := fs.ReadFile(root, "VERSION")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read VERSION: %w", err)
|
||||
}
|
||||
compiler := jsonschema.NewCompiler()
|
||||
compiler.DefaultDraft(jsonschema.Draft2020)
|
||||
compiler.UseLoader(offlineLoader{})
|
||||
ids := make(map[string]string)
|
||||
for _, name := range contractNames {
|
||||
file := "schemas/" + name + ".schema.json"
|
||||
data, err := fs.ReadFile(root, file)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
if !json.Valid(data) {
|
||||
return nil, fmt.Errorf("%s: expected JSON syntax", file)
|
||||
}
|
||||
value, err := Decode(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
doc, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("%s: expected a schema object", file)
|
||||
}
|
||||
id := schemaBase + strings.TrimSpace(string(version)) + "/" + file
|
||||
if doc["$schema"] != "https://json-schema.org/draft/2020-12/schema" || doc["$id"] != id {
|
||||
return nil, fmt.Errorf("%s: expected Draft 2020-12 and $id %q", file, id)
|
||||
}
|
||||
if err := compiler.AddResource(id, value); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", file, err)
|
||||
}
|
||||
ids[name] = id
|
||||
}
|
||||
set := &Set{schemas: make(map[string]*jsonschema.Schema)}
|
||||
for _, name := range contractNames {
|
||||
schema, err := compiler.Compile(ids[name])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compile %s: %w", name, err)
|
||||
}
|
||||
set.schemas["maximumdirect."+name+".v1"] = schema
|
||||
}
|
||||
return set, nil
|
||||
}
|
||||
|
||||
type offlineLoader struct{}
|
||||
|
||||
func (offlineLoader) Load(url string) (any, error) {
|
||||
return nil, fmt.Errorf("schema resource %q is absent from the local distribution; network loading is disabled", url)
|
||||
}
|
||||
|
||||
// Validate checks structure, then the selected semantic rules. It does not
|
||||
// resolve imports or references, populate defaults, or mutate the input.
|
||||
func (s *Set) Validate(value any) error {
|
||||
doc, ok := value.(map[string]any)
|
||||
if !ok {
|
||||
return fmt.Errorf("structure: /: expected a document object")
|
||||
}
|
||||
version, ok := doc["schema_version"].(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("structure: /schema_version: expected a contract identifier string")
|
||||
}
|
||||
schema := s.schemas[version]
|
||||
if schema == nil {
|
||||
return fmt.Errorf("structure: /schema_version: unsupported contract %q", version)
|
||||
}
|
||||
if err := schema.Validate(value); err != nil {
|
||||
return fmt.Errorf("structure: %w", err)
|
||||
}
|
||||
if version == "maximumdirect.glossary.v1" {
|
||||
return uniqueGlossaryIDs(doc["collections"].(map[string]any))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func uniqueGlossaryIDs(collections map[string]any) error {
|
||||
names := make([]string, 0, len(collections))
|
||||
for name := range collections {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
entries := collections[name].(map[string]any)["entries"].([]any)
|
||||
seen := make(map[string]int, len(entries))
|
||||
for i, entry := range entries {
|
||||
id := entry.(map[string]any)["id"].(string)
|
||||
if previous, exists := seen[id]; exists {
|
||||
return fmt.Errorf("semantic: /collections/%s/entries/%d/id: duplicate ID %q (first at entry %d)", escape(name), i, id, previous)
|
||||
}
|
||||
seen[id] = i
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
283
internal/validation/validation_test.go
Normal file
283
internal/validation/validation_test.go
Normal file
@@ -0,0 +1,283 @@
|
||||
package validation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
)
|
||||
|
||||
func loadSet(t *testing.T) *Set {
|
||||
t.Helper()
|
||||
set, err := Load(os.DirFS("../.."))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func TestDocuments(t *testing.T) {
|
||||
set := loadSet(t)
|
||||
for _, directory := range []string{"examples", "tests/valid", "tests/invalid"} {
|
||||
err := filepath.WalkDir(filepath.Join("../..", directory), func(path string, entry fs.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
t.Run(filepath.ToSlash(path), func(t *testing.T) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value, err := Decode(data)
|
||||
var before []byte
|
||||
if err == nil {
|
||||
before, err = json.Marshal(value)
|
||||
}
|
||||
if err == nil {
|
||||
err = set.Validate(value)
|
||||
}
|
||||
if directory == "tests/invalid" {
|
||||
phase, _, _ := strings.Cut(entry.Name(), "-")
|
||||
if err == nil || !strings.HasPrefix(err.Error(), phase+":") {
|
||||
t.Fatalf("want %s failure, got %v", phase, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := json.Marshal(value)
|
||||
if err != nil || string(before) != string(after) {
|
||||
t.Fatalf("validation mutated value: %s -> %s, %v", before, after, err)
|
||||
}
|
||||
})
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefinedFieldShapes(t *testing.T) {
|
||||
set := loadSet(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
valid bool
|
||||
}{
|
||||
{"collection null", `collections: {weather: null}`, false},
|
||||
{"entries omitted", `collections: {weather: {description: context}}`, false},
|
||||
{"entries null", `collections: {weather: {entries: null}}`, false},
|
||||
{"entries empty", `collections: {weather: {entries: []}}`, true},
|
||||
{"aliases omitted", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed}]}}`, true},
|
||||
{"aliases null", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, aliases: null}]}}`, true},
|
||||
{"aliases empty", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, aliases: []}]}}`, true},
|
||||
{"aliases populated", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, aliases: [Breeze]}]}}`, true},
|
||||
{"aliases invalid item", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, aliases: [1]}]}}`, false},
|
||||
{"empty ID", `collections: {weather: {entries: [{id: "", name: Wind, category: speed}]}}`, false},
|
||||
{"category required", `collections: {weather: {entries: [{id: wind, name: Wind}]}}`, false},
|
||||
{"empty collection name", `collections: {"": {entries: []}}`, false},
|
||||
{"provenance empty", `collections: {weather: {entries: [], provenance: {}}}`, true},
|
||||
{"provenance absent metadata", `collections: {weather: {entries: [], provenance: {version: "", url: "", license: ""}}}`, true},
|
||||
{"provenance extension", `collections: {weather: {entries: [], provenance: {title: Sample, source_id: 2}}}`, true},
|
||||
{"provenance wrong known field", `collections: {weather: {entries: [], provenance: {ruleset: []}}}`, false},
|
||||
{"unknown fields have no instruction semantics", `collections: {weather: {entries: [], instruction: {arbitrary: data}}}`, true},
|
||||
{"null plural", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, plural: null}]}}`, true},
|
||||
{"empty plural", `collections: {weather: {entries: [{id: wind, name: Wind, category: speed, plural: ""}]}}`, false},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
value, err := Decode([]byte("schema_version: maximumdirect.glossary.v1\n" + test.body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := set.Validate(value); (err == nil) != test.valid {
|
||||
t.Fatalf("valid=%v, error=%v", test.valid, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
for _, test := range []struct {
|
||||
body string
|
||||
valid bool
|
||||
}{
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: null", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {}}}", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {name: Mira}, player: {}}}", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {name: Mira, classes: null}}}", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {name: Mira, classes: [{name: scout, level: 0}]}}}", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {name: Mira, classes: [{name: scout, level: 1.5}]}}}", false},
|
||||
{"schema_version: maximumdirect.party.v1\ncharacters: {mira: {character: {name: Mira, classes: [{name: scout, level: 1.0000000000000000000001}]}}}", false},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: example\nreferences: {}", true},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: example\nreferences: {glossaries: []}", true},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: example\nreferences: {party: null}", false},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: example\nreferences: {glossaries: [false]}", false},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: example\nreferences: null", false},
|
||||
{"schema_version: maximumdirect.campaign.v1\nid: null", false},
|
||||
{"schema_version: maximumdirect.campaign.v1\nname: Example", false},
|
||||
} {
|
||||
t.Run(test.body, func(t *testing.T) {
|
||||
value, err := Decode([]byte(test.body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := set.Validate(value); (err == nil) != test.valid {
|
||||
t.Fatalf("valid=%v, error=%v", test.valid, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeProfile(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
"a: 1\na: 2", "a: {b: 1, b: 2}", `{"a":1,"a":2}`,
|
||||
"---\na: 1\n---\na: 2", "1: value", "true: value", "? [a, b]\n: value",
|
||||
"a: !custom value", "a: !!binary Zm9v", "a: !!set {x: null}", "a: !!omap [{x: 1}]",
|
||||
"a: &cycle [*cycle]", "a: *unknown", "a: .inf", "a: -.Inf", "a: .NaN",
|
||||
"a: !!float true", "a: !!int false", "a: [broken", "a: &x {b: 1}\nc: {<<: *x}",
|
||||
} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
if _, err := Decode([]byte(input)); err == nil || !strings.HasPrefix(err.Error(), "decode:") {
|
||||
t.Fatalf("expected decoding failure, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
value, err := Decode([]byte(`
|
||||
date: 2026-11-28
|
||||
timestamp: 2026-11-28T12:30:00Z
|
||||
affirmative: yes
|
||||
switch: on
|
||||
enabled: true
|
||||
missing: ~
|
||||
quoted: "true"
|
||||
quoted_number: "1e500"
|
||||
tagged_string: !!str 1e500
|
||||
"<<": literal extension
|
||||
original: &items [one, two]
|
||||
copy: *items
|
||||
`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := map[string]any{
|
||||
"date": "2026-11-28", "timestamp": "2026-11-28T12:30:00Z",
|
||||
"affirmative": "yes", "switch": "on", "enabled": true, "missing": nil, "quoted": "true",
|
||||
"quoted_number": "1e500", "tagged_string": "1e500",
|
||||
"<<": "literal extension", "original": []any{"one", "two"}, "copy": []any{"one", "two"},
|
||||
}
|
||||
if !reflect.DeepEqual(value, want) {
|
||||
t.Fatalf("got %#v, want %#v", value, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNumericPrecision(t *testing.T) {
|
||||
for input, want := range map[string]string{
|
||||
"1234567890123456789012345678901234567890": "1234567890123456789012345678901234567890",
|
||||
"0.123456789012345678901234567890": "0.123456789012345678901234567890",
|
||||
".5": "0.5", "5.": "5.0", "+.5": "0.5", "-0.5": "-0.5", "1e500": "1e500",
|
||||
"0x10": "16", "0o10": "8", "0b10": "2", "010": "8", "1_000": "1000",
|
||||
} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
value, err := Decode([]byte("measurement: " + input))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
number, ok := value.(map[string]any)["measurement"].(json.Number)
|
||||
if !ok || number.String() != want {
|
||||
t.Fatalf("want exact JSON number %q, got %#v", want, value)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestYAMLJSONEquivalence(t *testing.T) {
|
||||
yamlBytes, err := os.ReadFile("../../examples/weather.yml")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jsonBytes, err := os.ReadFile("../../examples/weather.json")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
yamlValue, err := Decode(yamlBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
jsonValue, err := Decode(jsonBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(yamlValue, jsonValue) {
|
||||
t.Fatal("YAML and JSON represent different domain data")
|
||||
}
|
||||
data, err := json.Marshal(yamlValue)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roundTrip, err := Decode(data)
|
||||
if err != nil || !reflect.DeepEqual(yamlValue, roundTrip) {
|
||||
t.Fatalf("JSON conversion changed data: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
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{}
|
||||
for _, file := range []string{"VERSION", "schemas/campaign.schema.json", "schemas/glossary.schema.json", "schemas/party.schema.json"} {
|
||||
data, err := os.ReadFile(filepath.Join("../..", file))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files[file] = &fstest.MapFile{Data: data}
|
||||
}
|
||||
set, err := Load(files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value, err := Decode([]byte("schema_version: maximumdirect.campaign.v1\nid: offline"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := set.Validate(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
original := files["schemas/party.schema.json"].Data
|
||||
t.Run("shared reference in the same release", func(t *testing.T) {
|
||||
version := strings.TrimSpace(string(files["VERSION"].Data))
|
||||
reference := `"name": {"$ref": "` + schemaBase + version + `/schemas/glossary.schema.json#/$defs/text"}`
|
||||
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 {
|
||||
t.Fatalf("bundled cross-schema reference failed offline: %v", err)
|
||||
}
|
||||
})
|
||||
for name, replacement := range map[string]string{
|
||||
"missing reference": `"name": {"$ref": "https://example.invalid/missing.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["schemas/party.schema.json"] = &fstest.MapFile{Data: []byte(strings.Replace(string(original), `"name": {"$ref": "#/$defs/text"}`, replacement, 1))}
|
||||
if _, err := Load(files); err == nil {
|
||||
t.Fatal("incomplete or malformed distribution compiled")
|
||||
}
|
||||
})
|
||||
}
|
||||
files["schemas/party.schema.json"] = &fstest.MapFile{Data: original}
|
||||
files["schemas/party.schema.json"] = &fstest.MapFile{Data: []byte("title: not JSON")}
|
||||
if _, err := Load(files); err == nil {
|
||||
t.Fatal("a schema file 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")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user