Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ir/document.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
64 changes: 57 additions & 7 deletions ir/unknown_enum.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
}
}

Expand All @@ -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) {
Expand Down
30 changes: 30 additions & 0 deletions ir/unknown_enum_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
6 changes: 6 additions & 0 deletions render/templates/client.gen_test.go.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
53 changes: 53 additions & 0 deletions testdata/debug/api/interactions.json
Original file line number Diff line number Diff line change
@@ -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"
}
]
}
}
]
33 changes: 33 additions & 0 deletions testdata/debug/pkg/debug/client.gen_test.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions testdata/debug/pkg/debug/ir.json
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@
}
]
},
"unknownEnum": "!v.Type.Valid()"
"unknownEnum": "v.Type != \"\" && !v.Type.Valid()"
},
{
"name": "Cat",
Expand Down Expand Up @@ -262,7 +262,7 @@
"required": true
}
],
"unknownEnum": "!v.Kind.Valid()"
"unknownEnum": "v.Kind != \"\" && !v.Kind.Valid()"
},
{
"name": "EventKind",
Expand Down
4 changes: 2 additions & 2 deletions testdata/debug/pkg/debug/types.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading