add tests for bfs assertion

This commit is contained in:
Shreyas Goenka 2024-09-04 10:26:47 +02:00
parent 578019ba22
commit 176ced190e
No known key found for this signature in database
GPG Key ID: 92A07DF49CCB0622
2 changed files with 34 additions and 12 deletions

View File

@ -216,6 +216,10 @@ func getStructFields(typ reflect.Type) []reflect.StructField {
} }
fieldType := field.Type fieldType := field.Type
// Embedded types can only be struct{} or pointer to struct{}. Multiple
// levels of pointers are not allowed by the Go compiler. So we only
// dereference pointers once.
if fieldType.Kind() == reflect.Pointer { if fieldType.Kind() == reflect.Pointer {
fieldType = fieldType.Elem() fieldType = fieldType.Elem()
} }

View File

@ -10,9 +10,10 @@ import (
func TestFromTypeBasic(t *testing.T) { func TestFromTypeBasic(t *testing.T) {
type myStruct struct { type myStruct struct {
S string `json:"s"` S string `json:"s"`
I *int `json:"i,omitempty"` I *int `json:"i,omitempty"`
V interface{} `json:"v,omitempty"` V interface{} `json:"v,omitempty"`
TriplePointer ***int `json:"triple_pointer,omitempty"`
// These fields should be ignored in the resulting schema. // These fields should be ignored in the resulting schema.
NotAnnotated string NotAnnotated string
@ -84,6 +85,9 @@ func TestFromTypeBasic(t *testing.T) {
"v": { "v": {
Reference: &interfaceRef, Reference: &interfaceRef,
}, },
"triple_pointer": {
Reference: &intRef,
},
}, },
AdditionalProperties: false, AdditionalProperties: false,
Required: []string{"s"}, Required: []string{"s"},
@ -131,21 +135,35 @@ func TestFromTypeBasic(t *testing.T) {
} }
func TestGetStructFields(t *testing.T) { func TestGetStructFields(t *testing.T) {
type EmbeddedStruct struct { type InnerEmbeddedStruct struct {
I int InnerField float64
B bool }
type EmbeddedStructOne struct {
FieldOne int
*InnerEmbeddedStruct
}
type EmbeddedStructTwo struct {
FieldTwo bool
} }
type MyStruct struct { type MyStruct struct {
S string *EmbeddedStructOne
*EmbeddedStruct EmbeddedStructTwo
OuterField string
} }
fields := getStructFields(reflect.TypeOf(MyStruct{})) fields := getStructFields(reflect.TypeOf(MyStruct{}))
assert.Len(t, fields, 3) assert.Len(t, fields, 4)
assert.Equal(t, "S", fields[0].Name) assert.Equal(t, "OuterField", fields[0].Name)
assert.Equal(t, "I", fields[1].Name) assert.Equal(t, "FieldOne", fields[1].Name)
assert.Equal(t, "B", fields[2].Name)
// InnerField occurring after FieldTwo ensures BFS as opposed to DFS traversal.
assert.Equal(t, "FieldTwo", fields[2].Name)
assert.Equal(t, "InnerField", fields[3].Name)
} }
func TestFromTypeNested(t *testing.T) { func TestFromTypeNested(t *testing.T) {