Files
go-sip/contracts/current_contract_test.go
T

69 lines
2.0 KiB
Go

package contracts_test
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// The current, project-owned contracts have one schema per transport surface.
// Historical upstream bundles are not fallback validators for these inputs.
func TestCurrentContractExamples(t *testing.T) {
for _, surface := range []string{"config-read", "task-discovery", "mq"} {
t.Run(surface, func(t *testing.T) {
root := filepath.Join("local", surface+".schema.json")
raw, err := os.ReadFile(root)
if err != nil {
t.Fatal(err)
}
value, err := jsonschema.UnmarshalJSON(bytes.NewReader(raw))
if err != nil {
t.Fatal(err)
}
compiler := jsonschema.NewCompiler()
compiler.AssertFormat()
const base = "https://go-sip.local/contracts/current/"
if err := compiler.AddResource(base+surface+".schema.json", value); err != nil {
t.Fatal(err)
}
schema, err := compiler.Compile(base + surface + ".schema.json")
if err != nil {
t.Fatal(err)
}
positives, err := filepath.Glob(filepath.Join("local", "examples", surface+"-*.json"))
if err != nil || len(positives) == 0 {
t.Fatalf("missing positive examples: %v", err)
}
negatives, err := filepath.Glob(filepath.Join("local", "examples", "invalid", surface+"-*.json"))
if err != nil || len(negatives) == 0 {
t.Fatalf("missing negative examples: %v", err)
}
for _, tc := range []struct {
files []string
valid bool
}{{positives, true}, {negatives, false}} {
for _, path := range tc.files {
t.Run(strings.TrimSuffix(filepath.Base(path), ".json"), func(t *testing.T) {
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
var value any
if err := json.Unmarshal(raw, &value); err != nil {
t.Fatal(err)
}
if err := schema.Validate(value); (err == nil) != tc.valid {
t.Fatalf("valid=%v, validation error=%v", tc.valid, err)
}
})
}
}
})
}
}