diff --git a/jsonschema/json_test.go b/jsonschema/json_test.go index 673db86d..f511df6b 100644 --- a/jsonschema/json_test.go +++ b/jsonschema/json_test.go @@ -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) + } + }) + } +}