61 lines
2.6 KiB
Go
61 lines
2.6 KiB
Go
package validate
|
|
|
|
import (
|
|
"context"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestSchemaLocationsCheckUnusedDeclarations(t *testing.T) {
|
|
for _, test := range []struct {
|
|
name, schema string
|
|
wantError bool
|
|
}{
|
|
{"unused external", `{"$defs":{"unused":{"$ref":"other.json"}},"type":"string"}`, true},
|
|
{"annotation is data", `{"examples":[{"$ref":"other.json"}],"default":{"$ref":"other.json"},"type":"string"}`, false},
|
|
{"internal escaped key", `{"$defs":{"a/b~c":{"type":"string"}},"$ref":"#/$defs/a~1b~0c"}`, false},
|
|
{"URI escaped key", `{"$defs":{"a # %/雪":{"type":"string"}}}`, false},
|
|
{"internal anchor", `{"$defs":{"value":{"$anchor":"item","type":"string"}},"$ref":"#item"}`, false},
|
|
{"dynamic reference", `{"$dynamicAnchor":"node","type":"object","properties":{"child":{"$dynamicRef":"#node"}}}`, false},
|
|
{"recursive", `{"$id":"https://example.invalid/root","$defs":{"node":{"$anchor":"node","anyOf":[{"type":"null"},{"$ref":"#node"}]}},"$ref":"#/$defs/node"}`, false},
|
|
{"embedded old dialect annotation", `{"$defs":{"old":{"$id":"old","$schema":"http://json-schema.org/draft-07/schema#","$defs":{"unused":{"$ref":"other.json"}},"type":"string"}}}`, false},
|
|
{"embedded old dialect definition", `{"$defs":{"old":{"$id":"old","$schema":"http://json-schema.org/draft-07/schema#","definitions":{"unused":{"$ref":"other.json"}}}}}`, true},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
doc, err := decodeJSONValue(context.Background(), []byte(test.schema))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = compileSchemaDocument(context.Background(), "promptkit-schema:///root.json", doc)
|
|
if test.wantError && (err == nil || !strings.Contains(err.Error(), "external schema resource")) {
|
|
t.Fatalf("expected external resource error, got %v", err)
|
|
}
|
|
if !test.wantError && err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSchemaLocationsPreserveRootValidation(t *testing.T) {
|
|
doc, err := decodeJSONValue(context.Background(), []byte(`{"$defs":{"number":{"type":"integer","minimum":2}},"$ref":"#/$defs/number"}`))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
schema, err := compileSchemaDocument(context.Background(), "promptkit-schema:///root.json", doc)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := schema.Validate(3); err != nil {
|
|
t.Fatalf("valid instance: %v", err)
|
|
}
|
|
if err := schema.Validate("not a number"); err == nil {
|
|
t.Fatal("invalid instance was accepted")
|
|
}
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
cancel()
|
|
if _, err := compileSchemaDocument(ctx, "promptkit-schema:///root.json", doc); err != context.Canceled {
|
|
t.Fatalf("canceled compilation = %v", err)
|
|
}
|
|
}
|