Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions jsonschema/schema.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ func falseSchema() *Schema {
return &Schema{Not: &Schema{}}
}

// True returns a Schema that validates any JSON value.
// It is equivalent to the empty schema ({}), which marshals to the JSON literal true.
func True() *Schema { return &Schema{} }

// False returns a Schema that validates no JSON value.
// It is equivalent to the schema {"not": {}}, which marshals to the JSON literal false.
func False() *Schema { return falseSchema() }

// anchorInfo records the subschema to which an anchor refers, and whether
// the anchor keyword is $anchor or $dynamicAnchor.
type anchorInfo struct {
Expand Down
50 changes: 50 additions & 0 deletions jsonschema/schema_true_false_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package jsonschema

import (
"encoding/json"
"testing"
)

func TestTrueFalseConstructors_Marshal(t *testing.T) {
bt, err := json.Marshal(True())
if err != nil {
t.Fatalf("Marshal(True()) error: %v", err)
}
if string(bt) != "true" {
t.Fatalf("Marshal(True()) = %s, want true", string(bt))
}

bf, err := json.Marshal(False())
if err != nil {
t.Fatalf("Marshal(False()) error: %v", err)
}
if string(bf) != "false" {
t.Fatalf("Marshal(False()) = %s, want false", string(bf))
}
}

func TestTrueFalseConstructors_Validate(t *testing.T) {
rsTrue, err := True().Resolve(nil)
if err != nil {
t.Fatalf("True().Resolve() error: %v", err)
}
// Should validate any instance
cases := []any{nil, true, false, 0, 3.14, "x", map[string]any{"a": 1}, []any{1, 2}}
for i, c := range cases {
if err := rsTrue.Validate(c); err != nil {
t.Fatalf("True().Validate case %d failed: %v", i, err)
}
}

rsFalse, err := False().Resolve(nil)
if err != nil {
t.Fatalf("False().Resolve() error: %v", err)
}
// Should reject any instance
for i, c := range cases {
if err := rsFalse.Validate(c); err == nil {
t.Fatalf("False().Validate case %d succeeded unexpectedly", i)
}
}
}