Skip to content

Commit

Permalink
add test
Browse files Browse the repository at this point in the history
  • Loading branch information
blwsh committed Dec 26, 2024
1 parent 969d5bc commit 6fc2bd2
Showing 1 changed file with 107 additions and 0 deletions.
107 changes: 107 additions & 0 deletions jsonschema/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,110 @@ func structToMap(t *testing.T, v any) map[string]any {
}
return got
}

type basicStruct struct {
Name string `json:"name"`
}

type nestedStruct struct {
User basicStruct `json:"user"`
}

type nullableValueStruct struct {
Name *string `json:"name"`
}

type arrayStruct struct {
Names []string `json:"names"`
}

func TestGenerateSchemaForType(t *testing.T) {
type args struct {
v any
}
tests := []struct {
name string
args args
want *jsonschema.Definition
wantErr bool
}{
{
name: "Test with basic struct",
args: args{v: basicStruct{}},
want: &jsonschema.Definition{
Type: []jsonschema.DataType{jsonschema.Object},
Properties: map[string]jsonschema.Definition{
"name": {
Type: []jsonschema.DataType{jsonschema.String},
},
},
Required: []string{"name"},
AdditionalProperties: false,
},
},
{
name: "Test with nested struct",
args: args{v: nestedStruct{}},
want: &jsonschema.Definition{
Type: []jsonschema.DataType{jsonschema.Object},
Properties: map[string]jsonschema.Definition{
"user": {
Type: []jsonschema.DataType{jsonschema.Object},
Properties: map[string]jsonschema.Definition{
"name": {
Type: []jsonschema.DataType{jsonschema.String},
},
},
Required: []string{"name"},
AdditionalProperties: false,
},
},
Required: []string{"user"},
AdditionalProperties: false,
},
},
{
name: "Test with nullable value struct",
args: args{v: nullableValueStruct{}},
want: &jsonschema.Definition{
Type: []jsonschema.DataType{jsonschema.Object},
Properties: map[string]jsonschema.Definition{
"name": {
Type: []jsonschema.DataType{jsonschema.String, jsonschema.Null},
},
},
Required: []string{"name"},
AdditionalProperties: false,
},
},
{
name: "Test with array struct",
args: args{v: arrayStruct{}},
want: &jsonschema.Definition{
Type: []jsonschema.DataType{jsonschema.Object},
Properties: map[string]jsonschema.Definition{
"names": {
Type: []jsonschema.DataType{jsonschema.Array},
Items: &jsonschema.Definition{
Type: []jsonschema.DataType{jsonschema.String},
},
},
},
Required: []string{"names"},
AdditionalProperties: false,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := jsonschema.GenerateSchemaForType(tt.args.v)
if (err != nil) != tt.wantErr {
t.Errorf("GenerateSchemaForType() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("GenerateSchemaForType() got = %v, want %v", got, tt.want)
}
})
}
}

0 comments on commit 6fc2bd2

Please sign in to comment.