diff --git a/ir/document.go b/ir/document.go index 7d11f933..aa13b564 100644 --- a/ir/document.go +++ b/ir/document.go @@ -82,7 +82,7 @@ func FromDocument(doc *openapi.Document, packageName, userAgent string, producti } if debug { - markUnknownEnums(schemas) + markUnknownEnums(schemas, operations) } hasURL, hasDuration, hasDate, hasDateTimeOrInt := needsSpecialImports(schemas, operations) diff --git a/ir/unknown_enum.go b/ir/unknown_enum.go index 3773d3a1..89af7dfa 100644 --- a/ir/unknown_enum.go +++ b/ir/unknown_enum.go @@ -9,7 +9,7 @@ import ( // value the specification does not list: it decodes, since an enum is a plain string or number, but is news. type enums struct { byName map[string]*Schema - zero map[string]string // the zero value of each enum type, which an optional member holds while left out + zero map[string]string // the zero value of each enum type, which a member holds while left out holds map[string]bool // whether a named type holds an enum, as found so far } @@ -40,17 +40,66 @@ func zeroOf(typ string) string { return "0" } -// markUnknownEnums gives each schema that holds an enum, if not through a type alias, its UnknownEnum. -func markUnknownEnums(schemas []Schema) { +// markUnknownEnums gives each schema a response of ops may hold that holds an enum, if not through a type alias, its +// UnknownEnum. A request's is never checked, so a type only requests hold needs none. +func markUnknownEnums(schemas []Schema, ops []Operation) { e := newEnums(schemas) + decoded := map[string]bool{} + for _, op := range ops { + if op.SuccessReturn != nil && !op.RawBytesSuccess && !op.StreamSuccess { + e.reach(op.SuccessReturn.String(), decoded) + } + + for _, r := range op.Responses { + if r.GoType != nil && !r.IsRawBytes && !r.IsStream { + e.reach(r.GoType.String(), decoded) + } + } + } + for i := range schemas { - if s := &schemas[i]; !s.IsTypeAlias && e.holdsEnum(s.Name) { + if s := &schemas[i]; decoded[s.Name] && !s.IsTypeAlias && e.holdsEnum(s.Name) { s.UnknownEnum = e.method(s) } } } +// reach adds to seen each named type a value of the Go type typ may hold, typ's own included. +func (e *enums) reach(typ string, seen map[string]bool) { + typ = strings.TrimLeft(typ, "*[]") + + if key, value, ok := mapTypes(typ); ok { + e.reach(key, seen) + e.reach(value, seen) + + return + } + + s := e.byName[typ] + if s == nil || seen[typ] { + return + } + + seen[typ] = true + + switch s.Kind { + case SchemaKindAlias: + e.reach(s.Type, seen) + case SchemaKindMap: + e.reach(s.MapKey, seen) + e.reach(s.MapValue, seen) + case SchemaKindUnion: + for _, v := range s.UnionVariants { + e.reach(v.Type, seen) + } + default: + for _, f := range s.Fields { + e.reach(f.Type, seen) + } + } +} + // holdsEnum reports whether a value of the Go type typ may hold an enum. func (e *enums) holdsEnum(typ string) bool { if elem, ok := strings.CutPrefix(typ, "*"); ok { @@ -132,7 +181,7 @@ func (e *enums) method(s *Schema) string { } case SchemaKindTuple: for _, f := range s.Fields { - add("v."+f.Name, f.Type, false) + add("v."+f.Name, f.Type, true) } default: for _, f := range s.Fields { @@ -141,7 +190,8 @@ func (e *enums) method(s *Schema) string { name = strings.TrimPrefix(f.Type, "*") } - add("v."+name, f.Type, !f.Required) + // even a required member is at its zero value where what holds it was left out or null + add("v."+name, f.Type, true) } } @@ -158,7 +208,7 @@ func convert(typ, expr string) string { } // check is an expression true if expr, of the Go type typ, holds a value of an enum the enum does not list, or "" -// if typ holds no enum. Where optional, the zero value of an enum is one left out, and fine. depth names the +// if typ holds no enum. Where optional, as for a member, the zero value of an enum is one left out, and fine. depth names the // variables of nested loops. func (e *enums) check(expr, typ string, optional bool, depth int) string { if !e.holdsEnum(typ) { diff --git a/ir/unknown_enum_internal_test.go b/ir/unknown_enum_internal_test.go index ed6cdaa3..f74a8185 100644 --- a/ir/unknown_enum_internal_test.go +++ b/ir/unknown_enum_internal_test.go @@ -36,3 +36,33 @@ func TestEnumsCheck(t *testing.T) { } } } + +func TestMarkUnknownEnums(t *testing.T) { + t.Parallel() + + schemas := []Schema{ + {Name: "Status", Kind: SchemaKindEnum, Type: "string"}, + {Name: "Item", Kind: SchemaKindStruct, Fields: []Field{{Name: "Status", Type: "Status", Required: true}}}, + {Name: "Page", Kind: SchemaKindStruct, Fields: []Field{{Name: "Results", Type: "[]Item"}}}, + {Name: "Problem", Kind: SchemaKindStruct, Fields: []Field{{Name: "Code", Type: "Status"}}}, + {Name: "Filter", Kind: SchemaKindStruct, Fields: []Field{{Name: "Status", Type: "Status"}}}, + } + + markUnknownEnums(schemas, []Operation{{ + SuccessReturn: &GoType{Name: "Page", IsPointer: true}, + Responses: Responses{{GoType: &GoType{Name: "Page"}, IsSuccess: true}, {GoType: &GoType{Name: "Problem"}}}, + RequestBody: &ReqBody{TypeName: "Filter"}, + }}) + + for _, s := range schemas { + want := map[string]string{ + "Item": `v.Status != "" && !v.Status.Valid()`, + "Page": "slices.ContainsFunc(v.Results, func(x Item) bool { return x.unknownEnum() })", + "Problem": `v.Code != "" && !v.Code.Valid()`, + }[s.Name] // a request's filter is never checked, so it has none + + if s.UnknownEnum != want { + t.Errorf("%s: UnknownEnum = %q, want %q", s.Name, s.UnknownEnum, want) + } + } +} diff --git a/render/templates/client.gen_test.go.tmpl b/render/templates/client.gen_test.go.tmpl index bb660762..93219a7f 100644 --- a/render/templates/client.gen_test.go.tmpl +++ b/render/templates/client.gen_test.go.tmpl @@ -476,6 +476,12 @@ func TestClient_Interactions(t *testing.T) { t.Fatalf("{{.Op.Name}}: %v", err) }{{ if $check }} else { apitest.DecodedAsSent(t, "{{.Op.Name}}", out, last.Body, jsonOpts) + {{- $name := .Op.Name }}{{ if $.Debug }}{{ with $.UnknownEnum "out" .Op.SuccessReturn.Nilable }} + + if {{ . }} { + t.Errorf("{{ $name }}: holds a value of an enum the specification does not list") + } + {{- end }}{{ end }} }{{ end }} {{- else}} err == nil { t.Fatal("{{.Op.Name}}: expected error") diff --git a/testdata/debug/api/interactions.json b/testdata/debug/api/interactions.json new file mode 100644 index 00000000..fd1341a0 --- /dev/null +++ b/testdata/debug/api/interactions.json @@ -0,0 +1,53 @@ +[ + { + "request": { + "method": "GET", + "url": "https://api.example.com/item", + "header": { + "Authorization": "Bearer *****" + } + }, + "response": { + "statusCode": 200, + "header": { + "Content-Type": "application/json" + }, + "body": { + "id": "a", + "status": "active", + "events": [ + { + "kind": "created" + } + ], + "labels": { + "x": "archived" + } + } + } + }, + { + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "header": { + "Authorization": "Bearer *****" + } + }, + "response": { + "statusCode": 200, + "header": { + "Content-Type": "application/json" + }, + "body": [ + { + "id": "a" + }, + { + "id": "b", + "status": "archived" + } + ] + } + } +] diff --git a/testdata/debug/pkg/debug/client.gen_test.go b/testdata/debug/pkg/debug/client.gen_test.go index 14190f93..32f8a8fe 100644 --- a/testdata/debug/pkg/debug/client.gen_test.go +++ b/testdata/debug/pkg/debug/client.gen_test.go @@ -15,6 +15,7 @@ import ( "net/url" "os" "path/filepath" + "slices" "testing" "github.com/MarkRosemaker/cassette" @@ -700,3 +701,35 @@ func TestClient_Error(t *testing.T) { }) }) } + +func TestClient_Interactions(t *testing.T) { + ctx := t.Context() + t.Setenv("DEBUG_TOKEN", "**************************************************") + + last := &apitest.LastBody{Next: apitest.Replay(t, "../../api/interactions.json")} + + c, err := NewClient(WithHTTPClient(&http.Client{Transport: last})) + if err != nil { + t.Fatal(err) + } + + if out, err := c.GetItem(ctx); err != nil { + t.Fatalf("GetItem: %v", err) + } else { + apitest.DecodedAsSent(t, "GetItem", out, last.Body, jsonOpts) + + if out != nil && out.unknownEnum() { + t.Errorf("GetItem: holds a value of an enum the specification does not list") + } + } + + if out, err := c.ListItems(ctx); err != nil { + t.Fatalf("ListItems: %v", err) + } else { + apitest.DecodedAsSent(t, "ListItems", out, last.Body, jsonOpts) + + if slices.ContainsFunc(out, func(x Item) bool { return x.unknownEnum() }) { + t.Errorf("ListItems: holds a value of an enum the specification does not list") + } + } +} diff --git a/testdata/debug/pkg/debug/ir.json b/testdata/debug/pkg/debug/ir.json index bf137431..ed145f52 100644 --- a/testdata/debug/pkg/debug/ir.json +++ b/testdata/debug/pkg/debug/ir.json @@ -197,7 +197,7 @@ } ] }, - "unknownEnum": "!v.Type.Valid()" + "unknownEnum": "v.Type != \"\" && !v.Type.Valid()" }, { "name": "Cat", @@ -262,7 +262,7 @@ "required": true } ], - "unknownEnum": "!v.Kind.Valid()" + "unknownEnum": "v.Kind != \"\" && !v.Kind.Valid()" }, { "name": "EventKind", diff --git a/testdata/debug/pkg/debug/types.gen.go b/testdata/debug/pkg/debug/types.gen.go index 199b6c0b..0b7ef24e 100644 --- a/testdata/debug/pkg/debug/types.gen.go +++ b/testdata/debug/pkg/debug/types.gen.go @@ -118,7 +118,7 @@ func (v *Block) MarshalJSONTo(enc *jsontext.Encoder) error { // unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode // records. func (v *Block) unknownEnum() bool { - return !v.Type.Valid() + return v.Type != "" && !v.Type.Valid() } // Cat defines a model @@ -164,7 +164,7 @@ type Event struct { // unknownEnum reports whether v holds a value of an enum the specification does not list, a response debug mode // records. func (v *Event) unknownEnum() bool { - return !v.Kind.Valid() + return v.Kind != "" && !v.Kind.Valid() } // EventKind defines a model