Skip to content

Commit 8665ad7

Browse files
authored
Increase jsonschema test coverage (sashabaranov#1040)
1 parent 8d681e7 commit 8665ad7

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

jsonschema/json_additional_test.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package jsonschema_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/sashabaranov/go-openai/jsonschema"
7+
)
8+
9+
// Test Definition.Unmarshal, including success path, validation error,
10+
// JSON syntax error and type mismatch during unmarshalling.
11+
func TestDefinitionUnmarshal(t *testing.T) {
12+
schema := jsonschema.Definition{
13+
Type: jsonschema.Object,
14+
Properties: map[string]jsonschema.Definition{
15+
"name": {Type: jsonschema.String},
16+
},
17+
}
18+
19+
var dst struct {
20+
Name string `json:"name"`
21+
}
22+
if err := schema.Unmarshal(`{"name":"foo"}`, &dst); err != nil {
23+
t.Fatalf("unexpected error: %v", err)
24+
}
25+
if dst.Name != "foo" {
26+
t.Errorf("expected name to be foo, got %q", dst.Name)
27+
}
28+
29+
if err := schema.Unmarshal(`{`, &dst); err == nil {
30+
t.Error("expected error for malformed json")
31+
}
32+
33+
if err := schema.Unmarshal(`{"name":1}`, &dst); err == nil {
34+
t.Error("expected validation error")
35+
}
36+
37+
numSchema := jsonschema.Definition{Type: jsonschema.Number}
38+
var s string
39+
if err := numSchema.Unmarshal(`123`, &s); err == nil {
40+
t.Error("expected unmarshal type error")
41+
}
42+
}
43+
44+
// Ensure GenerateSchemaForType returns an error when encountering unsupported types.
45+
func TestGenerateSchemaForTypeUnsupported(t *testing.T) {
46+
type Bad struct {
47+
Ch chan int `json:"ch"`
48+
}
49+
if _, err := jsonschema.GenerateSchemaForType(Bad{}); err == nil {
50+
t.Fatal("expected error for unsupported type")
51+
}
52+
}
53+
54+
// Validate should fail when provided data does not match the expected container types.
55+
func TestValidateInvalidContainers(t *testing.T) {
56+
objSchema := jsonschema.Definition{Type: jsonschema.Object}
57+
if jsonschema.Validate(objSchema, 1) {
58+
t.Error("expected object validation to fail for non-map input")
59+
}
60+
61+
arrSchema := jsonschema.Definition{Type: jsonschema.Array, Items: &jsonschema.Definition{Type: jsonschema.String}}
62+
if jsonschema.Validate(arrSchema, 1) {
63+
t.Error("expected array validation to fail for non-slice input")
64+
}
65+
}
66+
67+
// Validate should return false when $ref cannot be resolved.
68+
func TestValidateRefNotFound(t *testing.T) {
69+
refSchema := jsonschema.Definition{Ref: "#/$defs/Missing"}
70+
if jsonschema.Validate(refSchema, "data", jsonschema.WithDefs(map[string]jsonschema.Definition{})) {
71+
t.Error("expected validation to fail when reference is missing")
72+
}
73+
}

0 commit comments

Comments
 (0)