Skip to content

Commit fe54d35

Browse files
authored
fix: nullable enum fields (#92)
1 parent 98d467d commit fe54d35

File tree

2 files changed

+51
-2
lines changed

2 files changed

+51
-2
lines changed

openapi/generator.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -842,8 +842,8 @@ func (g *Generator) enumFromStructField(sf reflect.StructField, fname string, pa
842842
values := strings.Split(etag, ",")
843843
sftype := sf.Type
844844

845-
// Use underlying element type if its an array or a slice.
846-
if sftype.Kind() == reflect.Slice || sftype.Kind() == reflect.Array {
845+
// Use underlying element type if it's an array/slice/pointer
846+
for sftype.Kind() == reflect.Ptr || sftype.Kind() == reflect.Slice || sftype.Kind() == reflect.Array {
847847
sftype = sftype.Elem()
848848
}
849849
for _, val := range values {

openapi/generator_test.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,55 @@ func TestNewSchemaFromStructFieldFormat(t *testing.T) {
392392
assert.Equal(t, sor.Schema.Format, "email")
393393
}
394394

395+
func TestNewSchemaFromEnumField(t *testing.T) {
396+
g := gen(t)
397+
398+
type T struct {
399+
A string `enum:"a,b,c"`
400+
B int `enum:"1,2,3"`
401+
C *string `enum:"d,e,f"`
402+
D *int `enum:"4,5,6"`
403+
E []string `enum:"g,h,i"`
404+
F *[]string `enum:"j,k,l"`
405+
G **string `enum:"m,n,o"`
406+
H **[]string `enum:"p,q,r"`
407+
I **[]float64 `enum:"7.0,8.1,9.2"`
408+
}
409+
410+
tests := []struct {
411+
fname string
412+
expectedEnum []interface{}
413+
isSlice bool
414+
}{
415+
{"A", []interface{}{"a", "b", "c"}, false},
416+
{"B", []interface{}{int64(1), int64(2), int64(3)}, false},
417+
{"C", []interface{}{"d", "e", "f"}, false},
418+
{"D", []interface{}{int64(4), int64(5), int64(6)}, false},
419+
{"E", []interface{}{"g", "h", "i"}, true},
420+
{"F", []interface{}{"j", "k", "l"}, true},
421+
{"G", []interface{}{"m", "n", "o"}, false},
422+
{"H", []interface{}{"p", "q", "r"}, false},
423+
{"I", []interface{}{7.0, 8.1, 9.2}, false},
424+
}
425+
426+
typ := reflect.TypeOf(T{})
427+
428+
for i, tt := range tests {
429+
t.Run(tt.fname, func(t *testing.T) {
430+
sor := g.newSchemaFromStructField(typ.Field(i), true, tt.fname, typ)
431+
assert.NotNil(t, sor)
432+
var enum []interface{}
433+
if tt.isSlice {
434+
enum = sor.Items.Enum
435+
} else {
436+
enum = sor.Enum
437+
}
438+
assert.Equal(t, tt.expectedEnum, enum)
439+
})
440+
441+
}
442+
}
443+
395444
func diffJSON(a, b []byte) (bool, error) {
396445
var j, j2 interface{}
397446
if err := json.Unmarshal(a, &j); err != nil {

0 commit comments

Comments
 (0)