Files
schemas/internal/validation/catalog_test.go

103 lines
2.9 KiB
Go

package validation
import (
"encoding/json"
"io/fs"
"os"
"strings"
"testing"
"testing/fstest"
)
func TestCatalogSelection(t *testing.T) {
root := os.DirFS("../..")
data, err := fs.ReadFile(root, "catalog.json")
if err != nil {
t.Fatal(err)
}
var catalog Catalog
if err := json.Unmarshal(data, &catalog); err != nil {
t.Fatal(err)
}
files := fstest.MapFS{}
for _, record := range catalog.Schemas {
content, err := fs.ReadFile(root, record.Path)
if err != nil {
t.Fatal(err)
}
files[record.Path] = &fstest.MapFile{Data: content}
}
record := catalog.Schemas[0]
next := record
next.Version = "99.0.0"
next.Path = "glossary/v99.0.0/schema.json"
next.ID = schemaBase + next.Path
var schema map[string]any
if err := json.Unmarshal(files[record.Path].Data, &schema); err != nil {
t.Fatal(err)
}
schema["$id"] = next.ID
schema["required"] = []string{"schema_version", "collections", "synthetic_test_field"}
content, err := json.Marshal(schema)
if err != nil {
t.Fatal(err)
}
files[next.Path] = &fstest.MapFile{Data: content}
catalog.Schemas = append(catalog.Schemas, next)
setCatalog := func() {
t.Helper()
data, err := json.Marshal(catalog)
if err != nil {
t.Fatal(err)
}
files["catalog.json"] = &fstest.MapFile{Data: data}
}
setCatalog()
set, err := Load(files)
if err != nil {
t.Fatal(err)
}
old := set.schemas[record.ID]
_, err = set.Select("glossary")
if err != nil {
t.Fatal(err)
}
newer, err := set.Select("glossary")
if err != nil {
t.Fatal(err)
}
value := map[string]any{"schema_version": "maximumdirect.glossary.v1", "collections": map[string]any{}}
if err := old.Validate(value); err != nil {
t.Fatal(err)
}
if err := newer.Validate(value); err == nil {
t.Fatal("selection did not distinguish definitions sharing a marker")
}
if _, err := set.Select("glossary@0.1.0"); err == nil {
t.Fatal("historical selection accepted")
}
for _, change := range []func(){
func() { catalog.Schemas = append(catalog.Schemas, record) },
func() { catalog.Schemas[0].ID += "/wrong" },
func() { catalog.Schemas[0].Path = "other/schema.json" },
func() { catalog.Schemas[0].Contract = "maximumdirect.rpg.party.v1" },
func() { catalog.Schemas = catalog.Schemas[1:] },
func() { delete(files, record.Path) },
} {
original := append([]Record(nil), catalog.Schemas...)
originalFile := files[record.Path]
change()
setCatalog()
if _, err := Load(files); err == nil {
t.Fatal("invalid inventory accepted")
}
catalog.Schemas = original
files[record.Path] = originalFile
}
setCatalog()
files[record.Path] = &fstest.MapFile{Data: []byte(strings.Replace(string(files[record.Path].Data), `"$ref": "#/$defs/text"`, `"$ref": "https://example.invalid/missing.json"`, 1))}
if _, err := Load(files); err == nil || !strings.Contains(err.Error(), "network loading is disabled") {
t.Fatalf("missing reference did not fail locally: %v", err)
}
}