|
1 |
| -package jsonschema |
| 1 | +package jsonschema_test |
2 | 2 |
|
3 |
| -import "testing" |
| 3 | +import ( |
| 4 | + "testing" |
4 | 5 |
|
5 |
| -// TestContainsRef ensures containsRef recursively searches definitions and items. |
6 |
| -func TestContainsRef(t *testing.T) { |
7 |
| - schema := Definition{ |
8 |
| - Type: Object, |
9 |
| - Properties: map[string]Definition{ |
10 |
| - "person": {Ref: "#/$defs/Person"}, |
11 |
| - }, |
12 |
| - Defs: map[string]Definition{ |
13 |
| - "Person": { |
14 |
| - Type: Object, |
15 |
| - Properties: map[string]Definition{ |
16 |
| - "friends": { |
17 |
| - Type: Array, |
18 |
| - Items: &Definition{Ref: "#/$defs/Person"}, |
19 |
| - }, |
20 |
| - }, |
21 |
| - }, |
22 |
| - }, |
| 6 | + "github.com/sashabaranov/go-openai/jsonschema" |
| 7 | +) |
| 8 | + |
| 9 | +// SelfRef struct used to produce a self-referential schema. |
| 10 | +type SelfRef struct { |
| 11 | + Friends []SelfRef `json:"friends"` |
| 12 | +} |
| 13 | + |
| 14 | +// Address struct referenced by Person without self-reference. |
| 15 | +type Address struct { |
| 16 | + Street string `json:"street"` |
| 17 | +} |
| 18 | + |
| 19 | +type Person struct { |
| 20 | + Address Address `json:"address"` |
| 21 | +} |
| 22 | + |
| 23 | +// TestGenerateSchemaForType_SelfRef ensures that self-referential types are not |
| 24 | +// flattened during schema generation. |
| 25 | +func TestGenerateSchemaForType_SelfRef(t *testing.T) { |
| 26 | + schema, err := jsonschema.GenerateSchemaForType(SelfRef{}) |
| 27 | + if err != nil { |
| 28 | + t.Fatalf("unexpected error: %v", err) |
23 | 29 | }
|
| 30 | + if _, ok := schema.Defs["SelfRef"]; !ok { |
| 31 | + t.Fatal("expected defs to contain SelfRef for self reference") |
| 32 | + } |
| 33 | +} |
24 | 34 |
|
25 |
| - if !containsRef(schema, "#/$defs/Person") { |
26 |
| - t.Fatal("expected to find reference in root") |
| 35 | +// TestGenerateSchemaForType_NoSelfRef ensures that non-self-referential types |
| 36 | +// are flattened and do not reappear in $defs. |
| 37 | +func TestGenerateSchemaForType_NoSelfRef(t *testing.T) { |
| 38 | + schema, err := jsonschema.GenerateSchemaForType(Person{}) |
| 39 | + if err != nil { |
| 40 | + t.Fatalf("unexpected error: %v", err) |
27 | 41 | }
|
28 |
| - if !containsRef(schema.Defs["Person"], "#/$defs/Person") { |
29 |
| - t.Fatal("expected to find self reference in defs") |
| 42 | + if _, ok := schema.Defs["Person"]; ok { |
| 43 | + t.Fatal("unexpected Person definition in defs") |
30 | 44 | }
|
31 |
| - if containsRef(schema, "#/$defs/Unknown") { |
32 |
| - t.Fatal("unexpected reference found") |
| 45 | + if _, ok := schema.Defs["Address"]; !ok { |
| 46 | + t.Fatal("expected Address definition in defs") |
33 | 47 | }
|
34 | 48 | }
|
0 commit comments