From 74ccce816ddfb5088e7ca8865c9381372d665978 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 11:04:28 +0000 Subject: [PATCH 1/2] feat: generated tests use go-api-libs/api/apitest The helpers every library's generated tests carried, the servers, the replay of recorded interactions, the check of what a call decoded and a type's round trip, now come from the shared package apitest, given the library's JSON options. The flags that only decided which of them to write are gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- go.mod | 2 +- go.sum | 4 +- golden_test.go | 1 + interactions.go | 6 +- interactions_test.go | 8 +- ir/ir.go | 28 +- ir/testcases.go | 15 - ir/testcases_test.go | 8 - render/imports.go | 1 + render/render_test.go | 9 +- render/templates/client.gen_test.go.tmpl | 427 +------------- render/templates/types.gen_test.go.tmpl | 35 +- testdata/auth/pkg/auth/client.gen_test.go | 363 +----------- testdata/debug/pkg/debug/client.gen_test.go | 90 +-- testdata/debug/pkg/debug/types.gen_test.go | 41 +- testdata/golden/pkg/golden/client.gen_test.go | 525 +++--------------- testdata/golden/pkg/golden/types.gen_test.go | 119 ++-- vendor/github.com/go-api-libs/api/README.md | 2 +- .../go-api-libs/api/apitest/apitest.go | 113 ++++ .../go-api-libs/api/apitest/compare.go | 243 ++++++++ .../go-api-libs/api/apitest/replay.go | 97 ++++ .../github.com/go-api-libs/api/devtool.json | 4 +- vendor/modules.txt | 3 +- 23 files changed, 658 insertions(+), 1486 deletions(-) create mode 100644 vendor/github.com/go-api-libs/api/apitest/apitest.go create mode 100644 vendor/github.com/go-api-libs/api/apitest/compare.go create mode 100644 vendor/github.com/go-api-libs/api/apitest/replay.go diff --git a/go.mod b/go.mod index eb7ecf96..3bcbbc50 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/MarkRosemaker/openapi-flatten v0.0.0-20261112181512-46b453b2a7e8 github.com/MarkRosemaker/ordmap v0.0.0-20261112181350-ce24cb2b5e89 github.com/ettle/strcase v0.2.0 - github.com/go-api-libs/api v0.0.0-20261112190634-bde25c574d51 + github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 github.com/spf13/afero v1.15.0 mvdan.cc/gofumpt v0.12.0 ) diff --git a/go.sum b/go.sum index 7049c307..d4c91d43 100644 --- a/go.sum +++ b/go.sum @@ -30,8 +30,8 @@ github.com/MarkRosemaker/yaml2json v0.0.0-20261109120453-1b901dbf7e8f h1:Z3r19i6 github.com/MarkRosemaker/yaml2json v0.0.0-20261109120453-1b901dbf7e8f/go.mod h1:DxNA9SDFrzw+RHsnxjIxjUzHy0I4+3hZg7R13u3SBvE= github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= -github.com/go-api-libs/api v0.0.0-20261112190634-bde25c574d51 h1:JVrl63yl8vSasO3y4K81aIOYjvyuprdZzKJD8PqStnY= -github.com/go-api-libs/api v0.0.0-20261112190634-bde25c574d51/go.mod h1:nJuMPHY4qEhbWBvTdDFOPK+LC3Uo8RM9kPhIQfzXv4s= +github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 h1:RFKpEFiUdwh2G9RVUyopW9pskMNkMJXNn+Z+u727Bww= +github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622/go.mod h1:nJuMPHY4qEhbWBvTdDFOPK+LC3Uo8RM9kPhIQfzXv4s= github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971 h1:SAGMMY0sujlZjekNUL4cvoACSOKdOj55CrikCTFzAdU= github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971/go.mod h1:z0z6qkZc45AvoRnluq7PkVSlSSF25sT0diJ+vrubYfA= github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= diff --git a/golden_test.go b/golden_test.go index 352f8720..75cba00f 100644 --- a/golden_test.go +++ b/golden_test.go @@ -12,6 +12,7 @@ import ( // needs. These keep those modules in go.mod and in vendor. _ "github.com/MarkRosemaker/cassette" _ "github.com/go-api-libs/api" + _ "github.com/go-api-libs/api/apitest" _ "github.com/go-api-libs/api/server" _ "github.com/go-api-libs/api/union" ) diff --git a/interactions.go b/interactions.go index 197c3f48..a9da4ace 100644 --- a/interactions.go +++ b/interactions.go @@ -577,7 +577,7 @@ func timeLiteral(t time.Time) string { // generated test reads like a value a person wrote, not a blob to decode. // Anything it doesn't recognize (maps, unions, oneOf/anyOf, or a mismatch // between v and what goType expects) falls back to decoding v's own compact -// JSON into goType at test time via mustDecodeBody, which is always correct +// JSON into goType at test time via apitest.MustDecode, which is always correct // even where a literal is not worth hand-rolling. func bodyLiteral(doc *ir.Document, goType string, v any) string { switch { @@ -667,7 +667,7 @@ func bodyLiteral(doc *ir.Document, goType string, v any) string { return lit } - return fmt.Sprintf("mustDecodeBody[%s](t, %s)", goType, fallbackJSON(v)) + return fmt.Sprintf("apitest.MustDecode[%s](t, %s, jsonOpts)", goType, fallbackJSON(v)) } // findSchema returns doc's named component schema for goType, or nil if @@ -815,7 +815,7 @@ func scalarLiteral(goType string, v any) (string, bool) { } // fallbackJSON returns v's compact JSON encoding as a quoted Go string -// literal, for embedding in a mustDecodeBody call. Object members are sorted +// literal, for embedding in an apitest.MustDecode call. Object members are sorted // by name: v holds maps, so that generating twice writes the same code. func fallbackJSON(v any) string { data, err := json.Marshal(v, json.Deterministic(true)) diff --git a/interactions_test.go b/interactions_test.go index 1534084f..1b0d9b8b 100644 --- a/interactions_test.go +++ b/interactions_test.go @@ -657,10 +657,10 @@ func TestBodyLiteral(t *testing.T) { {"Flag", `true`, "FlagTrue"}, {"Color", `"dark red"`, "ColorDarkRed"}, // a value the enum does not declare is decoded at test time, so the test shows the mismatch - {"Level", `7`, `mustDecodeBody[Level](t, "7")`}, - {"Color", `3`, `mustDecodeBody[Color](t, "3")`}, + {"Level", `7`, `apitest.MustDecode[Level](t, "7", jsonOpts)`}, + {"Color", `3`, `apitest.MustDecode[Color](t, "3", jsonOpts)`}, {"Score", `9.5`, "Score(9.5)"}, - {"Tags", `{"a":"b"}`, `mustDecodeBody[Tags](t, "{\"a\":\"b\"}")`}, + {"Tags", `{"a":"b"}`, `apitest.MustDecode[Tags](t, "{\"a\":\"b\"}", jsonOpts)`}, {"Pet", `{"name":"Rex","level":3}`, "Pet{\nName: \"Rex\",\nLevel: LevelThree,\n}"}, {"Pet", `{}`, "Pet{}"}, {"*Pet", `null`, "nil"}, @@ -671,7 +671,7 @@ func TestBodyLiteral(t *testing.T) { {"*float64", `2.5`, "new(2.5)"}, {"*Score", `9.5`, "new(Score(9.5))"}, {"[]Level", `[1,3]`, "[]Level{LevelOne, LevelThree}"}, - {"[]string", `"x"`, `mustDecodeBody[[]string](t, "\"x\"")`}, + {"[]string", `"x"`, `apitest.MustDecode[[]string](t, "\"x\"", jsonOpts)`}, {"bool", `false`, "false"}, } { var v any diff --git a/ir/ir.go b/ir/ir.go index e391fdd9..e65d7772 100644 --- a/ir/ir.go +++ b/ir/ir.go @@ -53,22 +53,8 @@ type Document struct { InteractionCalls InteractionCalls `json:"-"` } -func (d Document) NeedMustDecodeBody() bool { - return d.InteractionCalls.UseMustDecodeBody() -} - type InteractionCalls []InteractionCall -func (ics InteractionCalls) UseMustDecodeBody() bool { - for _, ic := range ics { - if ic.UsesMustDecodeBody() { - return true - } - } - - return false -} - // InteractionCall is one operation call extracted from a recorded interaction. type InteractionCall struct { Op *Operation // matched operation @@ -84,19 +70,13 @@ type InteractionCall struct { // BodyLiteral is a Go expression for the recorded request body, set // whenever Op.RequestBody is non-nil: a composite literal of the // request body's type when every field could be expressed that way, - // falling back to a runtime JSON decode (mustDecodeBody) for values a + // falling back to a runtime JSON decode (apitest.MustDecode) for values a // literal can't cleanly represent. Either way the replayed request // carries the same body the interaction was recorded with, instead of // a zero value. BodyLiteral string } -// UsesMustDecodeBody reports whether the body literal decodes a value at test time, anywhere in it: a field of a -// struct literal may, where the rest of it is written out. -func (ic InteractionCall) UsesMustDecodeBody() bool { - return strings.Contains(ic.BodyLiteral, "mustDecodeBody[") -} - // InteractionParam is one query param with its Go literal value. type InteractionParam struct { FieldName string // PascalCase field name on the params struct @@ -717,12 +697,6 @@ func (doc Document) HasTagged() bool { return slices.ContainsFunc(doc.Schemas, func(s Schema) bool { return s.Tagged != nil }) } -// HasOptionalAuthCalls reports whether an interaction calls an operation whose credentials are optional, whose -// recording may lack them. -func (d Document) HasOptionalAuthCalls() bool { - return slices.ContainsFunc(d.InteractionCalls, func(ic InteractionCall) bool { return ic.Op.Auth != "" && ic.Op.AuthOptional }) -} - // EncodesItself reports whether the type has a MarshalJSONTo method of its own. func (s Schema) EncodesItself() bool { return s.Tagged != nil || s.AllOfUnion != nil || s.Unimplemented != "" diff --git a/ir/testcases.go b/ir/testcases.go index e9bfc7c1..fad39a0d 100644 --- a/ir/testcases.go +++ b/ir/testcases.go @@ -162,18 +162,3 @@ func (op Operation) BodilessFailures() Responses { return rs } - -// NeedsBodyServer reports whether a generated test answers with a body of its choosing, see newBodyServer. -func (doc Document) NeedsBodyServer() bool { - return doc.HasErrorResponses() || doc.HasStructSuccess() || slices.ContainsFunc(doc.Operations, func(op Operation) bool { - return len(op.BodilessFailures()) > 0 || doc.DebugDecoded(op) != nil - }) -} - -// NeedsUnknownMember reports whether a generated test sends a value with a member no type declares, see -// withUnknownMember. -func (doc Document) NeedsUnknownMember() bool { - return doc.HasStructSuccess() || slices.ContainsFunc(doc.Operations, func(op Operation) bool { - return slices.ContainsFunc(op.ErrorResponses(), doc.LenientError) - }) -} diff --git a/ir/testcases_test.go b/ir/testcases_test.go index 72e6b092..47cb8833 100644 --- a/ir/testcases_test.go +++ b/ir/testcases_test.go @@ -163,12 +163,4 @@ func TestDocument_DebugAndBodilessResponses(t *testing.T) { if got := op.BodilessFailures(); len(got) != 1 || got[0].StatusCode != "409" { t.Errorf("got %+v, want the 409 alone", got) } - - if !debug.NeedsBodyServer() || !debug.NeedsUnknownMember() { - t.Error("want both helpers") - } - - if (ir.Document{}).NeedsBodyServer() || (ir.Document{}).NeedsUnknownMember() { - t.Error("no operations: want neither helper") - } } diff --git a/render/imports.go b/render/imports.go index f9a18cf0..9fcec519 100644 --- a/render/imports.go +++ b/render/imports.go @@ -39,6 +39,7 @@ var importPaths = map[string]string{ "uuid": "uuid", "api": "github.com/go-api-libs/api", + "apitest": "github.com/go-api-libs/api/apitest", "cassette": "github.com/MarkRosemaker/cassette", "civil": "cloud.google.com/go/civil", "jsonutil": "github.com/MarkRosemaker/jsonutil", diff --git a/render/render_test.go b/render/render_test.go index bc1ecbc3..ecafce34 100644 --- a/render/render_test.go +++ b/render/render_test.go @@ -438,12 +438,9 @@ func TestFiles_ClientTest(t *testing.T) { t.Error("missing package declaration") } - if !contains(content, "func newTestServer(") { - t.Error("missing newTestServer helper") - } - - if !contains(content, "type roundTripFunc func(*http.Request) (*http.Response, error)") || !contains(content, "RoundTrip(") { - t.Error("missing testRoundTripper") + // the helpers come from apitest, not from the generated file + if !contains(content, "apitest.NewServer(t, ") || !contains(content, "apitest.RoundTripFunc(") || contains(content, "func newTestServer(") { + t.Error("not using the helpers of apitest") } if !contains(content, `"ListPets"`) { diff --git a/render/templates/client.gen_test.go.tmpl b/render/templates/client.gen_test.go.tmpl index e3a21876..bb660762 100644 --- a/render/templates/client.gen_test.go.tmpl +++ b/render/templates/client.gen_test.go.tmpl @@ -5,61 +5,6 @@ package {{.PackageName}} -func newTestServer(t *testing.T, status int) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - })) - t.Cleanup(srv.Close) - return srv -} - -{{ if .NeedsBodyServer -}} -// newBodyServer is the base URL of a server that answers every request with status, contentType and body. -func newBodyServer(t *testing.T, status int, contentType string, body []byte) *url.URL { - t.Helper() - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", contentType) - w.WriteHeader(status) - _, _ = w.Write(body) - })) - t.Cleanup(srv.Close) - - u, err := url.Parse(srv.URL) - if err != nil { - t.Fatal(err) - } - - return u -} - -{{ end -}} -{{ if .NeedsUnknownMember -}} -// withUnknownMember is v as JSON, with a member no type declares added to it. -func withUnknownMember(t *testing.T, v any) []byte { - t.Helper() - - b, err := json.Marshal(v, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if string(b) == "{}" { - return []byte(`{"not_a_member_of_any_type": true}`) - } - - return append([]byte(`{"not_a_member_of_any_type": true, `), b[1:]...) -} - -{{ end -}} -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { - return f(r) -} - func TestClient_Error(t *testing.T) { {{range .Operations}} t.Run({{printf "%q" .Name}}, func(t *testing.T) { @@ -74,7 +19,7 @@ func TestClient_Error(t *testing.T) { t.Setenv({{printf "%q" .EnvName }}, {{ or .Example `"**************************************************"` }}) {{end}} t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -92,7 +37,7 @@ func TestClient_Error(t *testing.T) { {{ if not .Responses.HasDefault -}} t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -184,7 +129,7 @@ func TestClient_Error(t *testing.T) { sent []byte ) - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -223,7 +168,7 @@ func TestClient_Error(t *testing.T) { sent []byte ) - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -259,7 +204,7 @@ func TestClient_Error(t *testing.T) { {{- with $.StrictSuccess . }} t.Run("unknown member", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, withUnknownMember(t, {{$.MinimalLiteral .GoType.Name}})))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, apitest.WithUnknownMember(t, {{$.MinimalLiteral .GoType.Name}}, jsonOpts)))) if err != nil { t.Fatal(err) } @@ -278,7 +223,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps an unknown member", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, withUnknownMember(t, {{$.MinimalLiteral .GoType.Name}}))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, apitest.WithUnknownMember(t, {{$.MinimalLiteral .GoType.Name}}, jsonOpts))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -303,7 +248,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json"))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json"))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -330,7 +275,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) if err != nil { t.Fatal(err) } @@ -354,7 +299,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, body))) if err != nil { t.Fatal(err) } @@ -373,7 +318,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("{{.StatusCode}} response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -388,7 +333,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("{{.StatusCode}} response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, "foo", nil))) if err != nil { t.Fatal(err) } @@ -406,7 +351,7 @@ func TestClient_Error(t *testing.T) { t.Run("{{.StatusCode}} response debug mode keeps an unknown member", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, withUnknownMember(t, {{$.MinimalLiteral .GoType.Name}}))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, {{printf "%q" .ContentType}}, apitest.WithUnknownMember(t, {{$.MinimalLiteral .GoType.Name}}, jsonOpts))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -430,7 +375,7 @@ func TestClient_Error(t *testing.T) { {{- range .BodilessFailures }} t.Run("{{.StatusCode}} response without a body", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, {{.GoConstant}}, "", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, {{.GoConstant}}, "", nil))) if err != nil { t.Fatal(err) } @@ -464,7 +409,7 @@ func TestClient_Params(t *testing.T) { {{end}} var got *http.Request - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -500,342 +445,6 @@ func TestClient_Params(t *testing.T) { } {{ end }} {{if .InteractionCalls}} -func replay(t *testing.T) http.RoundTripper { - t.Helper() - - interactions, err := cassette.InteractionsReadFile("../../api/interactions.json") - if err != nil { - t.Fatal(err) - } - - {{/* Every call must be the next recording, with its headers exact but the User-Agent, which names whatever tool - made the recording, and every recording must be called. */ -}} - match := cassette.MatchRequest( - cassette.CompareHeaders("User-Agent"), - {{- if .HasOptionalAuthCalls }} - cassette.OptionalAuthorization(func(req *http.Request) bool { return req.Context().Value(optionalAuthKey{}) != nil }), - {{- end }} - ) - - rec := cassette.Replay(interactions, cassette.InOrder(), cassette.WithMatcher(func(req *http.Request, ia cassette.Request) error { - err := match(req, ia) - if err == nil || req.Body == nil { - return err - } - - {{/* matching drained the body and put it back to be read again */ -}} - sent, rerr := io.ReadAll(req.Body) - if rerr != nil { - return err - } - - req.Body = io.NopCloser(bytes.NewReader(sent)) - - {{/* the body is the one recorded but for the tags the client fills in: match the rest as it is sent */ -}} - var a, b any - if json.Unmarshal(ia.Body, &a) != nil || json.Unmarshal(sent, &b) != nil || !jsonSameButTags(a, b) { - return err - } - - ia.Body = sent - - return match(req, ia) - })) - - t.Cleanup(func() { - if unused := rec.Unused(); len(unused) > 0 { - t.Errorf("%d recorded interactions were never replayed, the first: %s %s", len(unused), unused[0].Request.Method, &unused[0].Request.URL) - } - }) - - return rec -} - -// lastBody passes requests on to next, and keeps the body of the last response, so that a test can compare what a call -// decoded with what was sent. -type lastBody struct { - next http.RoundTripper - body []byte -} - -func (l *lastBody) RoundTrip(req *http.Request) (*http.Response, error) { - rsp, err := l.next.RoundTrip(req) - if err != nil { - return nil, err - } - - defer rsp.Body.Close() - - if l.body, err = io.ReadAll(rsp.Body); err != nil { - return nil, err - } - - rsp.Body = io.NopCloser(bytes.NewReader(l.body)) - - return rsp, nil -} - -// decodedAsSent fails unless out, what a call decoded from body, encodes to what body holds. A member one side lacks is -// fine where the other holds nothing there (null, false, 0, "", [], an object of nothing but such members, or the zero -// text of a date, a time or a UUID), as an optional value left out is, and so is a tag one side leaves out (see -// jsonInferredTag); members may come in another order. A value may be written another way, as long as it -// is the same: a time as the same instant, a UUID with or without dashes, a number as a string of it. -func decodedAsSent(t *testing.T, op string, out any, body []byte) { - t.Helper() - - encoded, err := json.Marshal(out, jsonOpts) - if err != nil { - t.Fatalf("%s: encoding what was decoded: %v", op, err) - } - - var sent, got any - if err := json.Unmarshal(body, &sent); err != nil { - t.Fatalf("%s: the recorded body: %v", op, err) - } - - if err := json.Unmarshal(encoded, &got); err != nil { - t.Fatalf("%s: %v", op, err) - } - - if at, same := jsonSame(sent, got, ""); !same { - t.Errorf("%s: decoded something else than was sent, at %q:\nsent %s\ngot %s", op, at, body, encoded) - } -} - -// jsonSame reports whether the JSON values a and b, decoded into any, hold the same, as decodedAsSent compares them, -// and where they first differ if not. -func jsonSame(a, b any, at string) (string, bool) { - if jsonEmpty(a) && jsonEmpty(b) || jsonSameInstant(a, b) || jsonSameInstant(b, a) || - jsonSameNumber(a, b) || jsonSameNumber(b, a) { - return "", true - } - - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return at, false - } - - names := slices.Sorted(maps.Keys(a)) - for name := range b { - if _, ok := a[name]; !ok { - names = append(names, name) - } - } - - for _, name := range names { - if jsonInferredTag(a, b, name) || jsonInferredTag(b, a, name) { - continue - } - - if where, same := jsonSame(a[name], b[name], at+"/"+name); !same { - return where, false - } - } - - return "", true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return at, false - } - - for i := range a { - if where, same := jsonSame(a[i], b[i], at+"/"+strconv.Itoa(i)); !same { - return where, false - } - } - - return "", true - case string: - b, ok := b.(string) - if !ok { - return at, false - } - - if a == b { - return "", true - } - - if ua, ok := jsonUUID(a); ok { - if ub, ok := jsonUUID(b); ok { - return at, ua == ub - } - } - - ta, errA := time.Parse(time.RFC3339Nano, a) - tb, errB := time.Parse(time.RFC3339Nano, b) - - return at, errA == nil && errB == nil && ta.Equal(tb) - default: - return at, a == b - } -} - -// jsonSameInstant reports whether a is a Unix time, in seconds or milliseconds, and b a date-time of the same instant, -// as a type that takes either writes one as the other. -func jsonSameInstant(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - ts, err := time.Parse(time.RFC3339Nano, s) - - return err == nil && (float64(ts.Unix()) == n || float64(ts.UnixMilli()) == n) -} - -// jsonSameNumber reports whether a is a number and b a string of the same number, as a string type writes one. -func jsonSameNumber(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - f, err := strconv.ParseFloat(s, 64) - - return err == nil && f == n -} - -// jsonUUID is s, a UUID with or without dashes, as its 32 hex digits in lower case. -func jsonUUID(s string) (string, bool) { - hex := strings.ToLower(strings.ReplaceAll(s, "-", "")) - if len(hex) != 32 || len(s) != 32 && len(s) != 36 || strings.Trim(hex, "0123456789abcdef") != "" { - return "", false - } - - return hex, true -} - -// jsonEmpty reports whether v, a JSON value decoded into any, holds nothing: null, false, 0, "", [], an object whose -// members hold nothing, or the text a zero date, time or UUID is written as, which is what an empty one decodes into: -// null read into a struct is written back as its members, empty. -func jsonEmpty(v any) bool { - switch v := v.(type) { - case nil: - return true - case bool: - return !v - case float64: - return v == 0 - case string: - return v == "" || v == "0000-00-00" || v == "0001-01-01T00:00:00Z" || v == "00000000-0000-0000-0000-000000000000" - case []any: - return len(v) == 0 - case map[string]any: - for _, m := range v { - if !jsonEmpty(m) { - return false - } - } - - return true - default: - return false - } -} - -// jsonInferredTag reports whether the object a lacks the member name, which b holds as a tag: the name of a member both -// hold. A tagged object may leave its tag out, and decoding it infers the tag from the member that is set, which -// encoding then writes. -func jsonInferredTag(a, b map[string]any, name string) bool { - if _, ok := a[name]; ok { - return false - } - - tag, ok := b[name].(string) - if !ok { - return false - } - - _, inA := a[tag] - _, inB := b[tag] - - return inA && inB -} - -// jsonSameButTags reports whether the JSON values a and b, decoded into any, are the same, but for tags either leaves -// out (see jsonInferredTag): the request a call sends for one that was recorded without them. -func jsonSameButTags(a, b any) bool { - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return false - } - - for name := range a { - if _, ok := b[name]; !ok && !jsonInferredTag(b, a, name) { - return false - } - } - - for name, vb := range b { - va, ok := a[name] - if !ok && !jsonInferredTag(a, b, name) || ok && !jsonSameButTags(va, vb) { - return false - } - } - - return true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return false - } - - for i := range a { - if !jsonSameButTags(a[i], b[i]) { - return false - } - } - - return true - default: - return a == b - } -} - -{{ if .HasOptionalAuthCalls -}} - -// optionalAuthKey marks the context of a call to an operation whose credentials are optional. -type optionalAuthKey struct{} - -// optionalAuth is ctx for a call to an operation whose credentials are optional, whose recording may lack them. -func optionalAuth(ctx context.Context) context.Context { - return context.WithValue(ctx, optionalAuthKey{}, true) -} - -{{ end -}} -{{ if .NeedMustDecodeBody -}} - -// mustDecodeBody decodes data, the recorded JSON for one request body value -// (or field of one) an interaction's own literal couldn't be built for, into -// T so a replayed call still carries the value it was recorded with. -func mustDecodeBody[T any](t *testing.T, data string) T { - t.Helper() - - var v T - if err := json.Unmarshal([]byte(data), &v, jsonOpts); err != nil { - t.Fatalf("decoding request body fixture: %v", err) - } - - return v -} - -{{ end -}} - func TestClient_Interactions(t *testing.T) { ctx := t.Context() {{- with $.Auth.Bearer.Name}} @@ -849,7 +458,7 @@ func TestClient_Interactions(t *testing.T) { t.Setenv({{printf "%q" .EnvName }}, {{ or .Example `"**************************************************"` }}) {{end}} - last := &lastBody{next: replay(t)} + last := &apitest.LastBody{Next: apitest.Replay(t, "../../api/interactions.json")} c, err := NewClient(WithHTTPClient(&http.Client{Transport: last})) if err != nil { @@ -858,7 +467,7 @@ func TestClient_Interactions(t *testing.T) { {{range .InteractionCalls}} {{- if .Op.SuccessReturn}} {{- $check := and .IsSuccess (not .Op.RawBytesSuccess) (not .Op.StreamSuccess) }} - if {{ if $check }}out{{ else }}_{{ end }}, err := c.{{.Op.Name}}({{ if and .Op.Auth .Op.AuthOptional }}optionalAuth(ctx){{ else }}ctx{{ end }}{{range .PathArgs}}, {{.}}{{end}}{{if .Op.ParamsInStruct}}, {{ if not .Op.ParamsInStruct.Required }}&{{ end }}{{.Op.ParamStructName}}{ + if {{ if $check }}out{{ else }}_{{ end }}, err := c.{{.Op.Name}}({{ if and .Op.Auth .Op.AuthOptional }}apitest.OptionalAuth(ctx){{ else }}ctx{{ end }}{{range .PathArgs}}, {{.}}{{end}}{{if .Op.ParamsInStruct}}, {{ if not .Op.ParamsInStruct.Required }}&{{ end }}{{.Op.ParamStructName}}{ {{range .QueryArgs}}{{.FieldName}}: {{.Literal}}, {{ end -}} {{range .HeaderArgs}}{{.FieldName}}: {{.Literal}}, @@ -866,7 +475,7 @@ func TestClient_Interactions(t *testing.T) { {{- if .IsSuccess}} err != nil { t.Fatalf("{{.Op.Name}}: %v", err) }{{ if $check }} else { - decodedAsSent(t, "{{.Op.Name}}", out, last.body) + apitest.DecodedAsSent(t, "{{.Op.Name}}", out, last.Body, jsonOpts) }{{ end }} {{- else}} err == nil { t.Fatal("{{.Op.Name}}: expected error") @@ -876,7 +485,7 @@ func TestClient_Interactions(t *testing.T) { {{- end}} {{- end}} {{else}} - if err := c.{{.Op.Name}}({{ if and .Op.Auth .Op.AuthOptional }}optionalAuth(ctx){{ else }}ctx{{ end }}{{range .PathArgs}}, {{.}}{{end}}{{if .Op.ParamsInStruct}}, {{ if not .Op.ParamsInStruct.Required }}&{{ end }}{{.Op.ParamStructName}}{ + if err := c.{{.Op.Name}}({{ if and .Op.Auth .Op.AuthOptional }}apitest.OptionalAuth(ctx){{ else }}ctx{{ end }}{{range .PathArgs}}, {{.}}{{end}}{{if .Op.ParamsInStruct}}, {{ if not .Op.ParamsInStruct.Required }}&{{ end }}{{.Op.ParamStructName}}{ {{range .QueryArgs}}{{.FieldName}}: {{.Literal}}, {{ end -}} {{range .HeaderArgs}}{{.FieldName}}: {{.Literal}}, diff --git a/render/templates/types.gen_test.go.tmpl b/render/templates/types.gen_test.go.tmpl index 33faf2a0..96e2e135 100644 --- a/render/templates/types.gen_test.go.tmpl +++ b/render/templates/types.gen_test.go.tmpl @@ -34,7 +34,7 @@ func TestUnions_RoundTrip(t *testing.T) { t.Run("{{ $u.Union }}/{{ .FieldName }}", func(t *testing.T) { v := {{ .Value }} - roundTrip(t, {{ $u.Union }}{ {{- .FieldName }}: {{ if not .ByValue }}&{{ end }}v}, func(u {{ $u.Union }}) bool { return u.{{ .FieldName }} != {{ .Unset }} }) + apitest.RoundTrip(t, {{ $u.Union }}{ {{- .FieldName }}: {{ if not .ByValue }}&{{ end }}v}, func(u {{ $u.Union }}) bool { return u.{{ .FieldName }} != {{ .Unset }} }, jsonOpts) }) {{- end }} {{- end }} @@ -49,41 +49,10 @@ func TestTagged_RoundTrip(t *testing.T) { {{- range .Values }} t.Run("{{ $s.Type }}/{{ .Value }}", func(t *testing.T) { - roundTrip(t, {{ .Literal }}, func(v {{ $s.Type }}) bool { return v.{{ $s.Field }} == {{ printf "%q" .Value }} }) + apitest.RoundTrip(t, {{ .Literal }}, func(v {{ $s.Type }}) bool { return v.{{ $s.Field }} == {{ printf "%q" .Value }} }, jsonOpts) }) {{- end }} {{- end }} } {{- end }} -{{- if or .UnionRoundTrips .TaggedRoundTrips }} - -// roundTrip encodes in and decodes it strictly into a new value, which set must report holds the variant in did, and -// which must encode as in did. -func roundTrip[T any](t *testing.T, in T, set func(T) bool) { - t.Helper() - - raw, err := json.Marshal(&in, jsonOpts) - if err != nil { - t.Fatal(err) - } - - var got T - if err := json.Unmarshal(raw, &got, jsonOpts); err != nil { - t.Fatalf("%s: %v", raw, err) - } - - if !set(got) { - t.Fatalf("%s decoded as another variant: %+v", raw, got) - } - - again, err := json.Marshal(&got, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(again, raw) { - t.Errorf("encoded %s, then %s", raw, again) - } -} -{{- end }} {{ end -}} diff --git a/testdata/auth/pkg/auth/client.gen_test.go b/testdata/auth/pkg/auth/client.gen_test.go index 4591433a..d870a450 100644 --- a/testdata/auth/pkg/auth/client.gen_test.go +++ b/testdata/auth/pkg/auth/client.gen_test.go @@ -5,42 +5,18 @@ package auth import ( - "bytes" - "context" "encoding/json/jsontext" - "encoding/json/v2" "errors" "io" - "maps" "net/http" "net/http/httptest" "net/url" - "slices" - "strconv" - "strings" "testing" - "time" - "github.com/MarkRosemaker/cassette" "github.com/go-api-libs/api" + "github.com/go-api-libs/api/apitest" ) -func newTestServer(t *testing.T, status int) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - })) - t.Cleanup(srv.Close) - return srv -} - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { - return f(r) -} - func TestClient_Error(t *testing.T) { t.Run("ListItems", func(t *testing.T) { t.Setenv("API_TOKEN", "**************************************************") @@ -51,7 +27,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("API_KEY", "****") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -66,7 +42,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -150,7 +126,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("API_KEY", "****") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -165,7 +141,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -249,7 +225,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("API_KEY", "****") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -264,7 +240,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -297,7 +273,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("API_KEY", "****") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -312,7 +288,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -337,315 +313,6 @@ func TestClient_Error(t *testing.T) { }) } -func replay(t *testing.T) http.RoundTripper { - t.Helper() - - interactions, err := cassette.InteractionsReadFile("../../api/interactions.json") - if err != nil { - t.Fatal(err) - } - - match := cassette.MatchRequest( - cassette.CompareHeaders("User-Agent"), - cassette.OptionalAuthorization(func(req *http.Request) bool { return req.Context().Value(optionalAuthKey{}) != nil }), - ) - - rec := cassette.Replay(interactions, cassette.InOrder(), cassette.WithMatcher(func(req *http.Request, ia cassette.Request) error { - err := match(req, ia) - if err == nil || req.Body == nil { - return err - } - - sent, rerr := io.ReadAll(req.Body) - if rerr != nil { - return err - } - - req.Body = io.NopCloser(bytes.NewReader(sent)) - - var a, b any - if json.Unmarshal(ia.Body, &a) != nil || json.Unmarshal(sent, &b) != nil || !jsonSameButTags(a, b) { - return err - } - - ia.Body = sent - - return match(req, ia) - })) - - t.Cleanup(func() { - if unused := rec.Unused(); len(unused) > 0 { - t.Errorf("%d recorded interactions were never replayed, the first: %s %s", len(unused), unused[0].Request.Method, &unused[0].Request.URL) - } - }) - - return rec -} - -// lastBody passes requests on to next, and keeps the body of the last response, so that a test can compare what a call -// decoded with what was sent. -type lastBody struct { - next http.RoundTripper - body []byte -} - -func (l *lastBody) RoundTrip(req *http.Request) (*http.Response, error) { - rsp, err := l.next.RoundTrip(req) - if err != nil { - return nil, err - } - - defer rsp.Body.Close() - - if l.body, err = io.ReadAll(rsp.Body); err != nil { - return nil, err - } - - rsp.Body = io.NopCloser(bytes.NewReader(l.body)) - - return rsp, nil -} - -// decodedAsSent fails unless out, what a call decoded from body, encodes to what body holds. A member one side lacks is -// fine where the other holds nothing there (null, false, 0, "", [], an object of nothing but such members, or the zero -// text of a date, a time or a UUID), as an optional value left out is, and so is a tag one side leaves out (see -// jsonInferredTag); members may come in another order. A value may be written another way, as long as it -// is the same: a time as the same instant, a UUID with or without dashes, a number as a string of it. -func decodedAsSent(t *testing.T, op string, out any, body []byte) { - t.Helper() - - encoded, err := json.Marshal(out, jsonOpts) - if err != nil { - t.Fatalf("%s: encoding what was decoded: %v", op, err) - } - - var sent, got any - if err := json.Unmarshal(body, &sent); err != nil { - t.Fatalf("%s: the recorded body: %v", op, err) - } - - if err := json.Unmarshal(encoded, &got); err != nil { - t.Fatalf("%s: %v", op, err) - } - - if at, same := jsonSame(sent, got, ""); !same { - t.Errorf("%s: decoded something else than was sent, at %q:\nsent %s\ngot %s", op, at, body, encoded) - } -} - -// jsonSame reports whether the JSON values a and b, decoded into any, hold the same, as decodedAsSent compares them, -// and where they first differ if not. -func jsonSame(a, b any, at string) (string, bool) { - if jsonEmpty(a) && jsonEmpty(b) || jsonSameInstant(a, b) || jsonSameInstant(b, a) || - jsonSameNumber(a, b) || jsonSameNumber(b, a) { - return "", true - } - - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return at, false - } - - names := slices.Sorted(maps.Keys(a)) - for name := range b { - if _, ok := a[name]; !ok { - names = append(names, name) - } - } - - for _, name := range names { - if jsonInferredTag(a, b, name) || jsonInferredTag(b, a, name) { - continue - } - - if where, same := jsonSame(a[name], b[name], at+"/"+name); !same { - return where, false - } - } - - return "", true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return at, false - } - - for i := range a { - if where, same := jsonSame(a[i], b[i], at+"/"+strconv.Itoa(i)); !same { - return where, false - } - } - - return "", true - case string: - b, ok := b.(string) - if !ok { - return at, false - } - - if a == b { - return "", true - } - - if ua, ok := jsonUUID(a); ok { - if ub, ok := jsonUUID(b); ok { - return at, ua == ub - } - } - - ta, errA := time.Parse(time.RFC3339Nano, a) - tb, errB := time.Parse(time.RFC3339Nano, b) - - return at, errA == nil && errB == nil && ta.Equal(tb) - default: - return at, a == b - } -} - -// jsonSameInstant reports whether a is a Unix time, in seconds or milliseconds, and b a date-time of the same instant, -// as a type that takes either writes one as the other. -func jsonSameInstant(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - ts, err := time.Parse(time.RFC3339Nano, s) - - return err == nil && (float64(ts.Unix()) == n || float64(ts.UnixMilli()) == n) -} - -// jsonSameNumber reports whether a is a number and b a string of the same number, as a string type writes one. -func jsonSameNumber(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - f, err := strconv.ParseFloat(s, 64) - - return err == nil && f == n -} - -// jsonUUID is s, a UUID with or without dashes, as its 32 hex digits in lower case. -func jsonUUID(s string) (string, bool) { - hex := strings.ToLower(strings.ReplaceAll(s, "-", "")) - if len(hex) != 32 || len(s) != 32 && len(s) != 36 || strings.Trim(hex, "0123456789abcdef") != "" { - return "", false - } - - return hex, true -} - -// jsonEmpty reports whether v, a JSON value decoded into any, holds nothing: null, false, 0, "", [], an object whose -// members hold nothing, or the text a zero date, time or UUID is written as, which is what an empty one decodes into: -// null read into a struct is written back as its members, empty. -func jsonEmpty(v any) bool { - switch v := v.(type) { - case nil: - return true - case bool: - return !v - case float64: - return v == 0 - case string: - return v == "" || v == "0000-00-00" || v == "0001-01-01T00:00:00Z" || v == "00000000-0000-0000-0000-000000000000" - case []any: - return len(v) == 0 - case map[string]any: - for _, m := range v { - if !jsonEmpty(m) { - return false - } - } - - return true - default: - return false - } -} - -// jsonInferredTag reports whether the object a lacks the member name, which b holds as a tag: the name of a member both -// hold. A tagged object may leave its tag out, and decoding it infers the tag from the member that is set, which -// encoding then writes. -func jsonInferredTag(a, b map[string]any, name string) bool { - if _, ok := a[name]; ok { - return false - } - - tag, ok := b[name].(string) - if !ok { - return false - } - - _, inA := a[tag] - _, inB := b[tag] - - return inA && inB -} - -// jsonSameButTags reports whether the JSON values a and b, decoded into any, are the same, but for tags either leaves -// out (see jsonInferredTag): the request a call sends for one that was recorded without them. -func jsonSameButTags(a, b any) bool { - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return false - } - - for name := range a { - if _, ok := b[name]; !ok && !jsonInferredTag(b, a, name) { - return false - } - } - - for name, vb := range b { - va, ok := a[name] - if !ok && !jsonInferredTag(a, b, name) || ok && !jsonSameButTags(va, vb) { - return false - } - } - - return true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return false - } - - for i := range a { - if !jsonSameButTags(a[i], b[i]) { - return false - } - } - - return true - default: - return a == b - } -} - -// optionalAuthKey marks the context of a call to an operation whose credentials are optional. -type optionalAuthKey struct{} - -// optionalAuth is ctx for a call to an operation whose credentials are optional, whose recording may lack them. -func optionalAuth(ctx context.Context) context.Context { - return context.WithValue(ctx, optionalAuthKey{}, true) -} - func TestClient_Interactions(t *testing.T) { ctx := t.Context() t.Setenv("API_TOKEN", "**************************************************") @@ -655,7 +322,7 @@ func TestClient_Interactions(t *testing.T) { t.Setenv("API_KEY", "****") - last := &lastBody{next: replay(t)} + last := &apitest.LastBody{Next: apitest.Replay(t, "../../api/interactions.json")} c, err := NewClient(WithHTTPClient(&http.Client{Transport: last})) if err != nil { @@ -665,19 +332,19 @@ func TestClient_Interactions(t *testing.T) { if out, err := c.ListItems(ctx); err != nil { t.Fatalf("ListItems: %v", err) } else { - decodedAsSent(t, "ListItems", out, last.body) + apitest.DecodedAsSent(t, "ListItems", out, last.Body, jsonOpts) } - if out, err := c.GetFeed(optionalAuth(ctx)); err != nil { + if out, err := c.GetFeed(apitest.OptionalAuth(ctx)); err != nil { t.Fatalf("GetFeed: %v", err) } else { - decodedAsSent(t, "GetFeed", out, last.body) + apitest.DecodedAsSent(t, "GetFeed", out, last.Body, jsonOpts) } - if out, err := c.GetFeed(optionalAuth(ctx)); err != nil { + if out, err := c.GetFeed(apitest.OptionalAuth(ctx)); err != nil { t.Fatalf("GetFeed: %v", err) } else { - decodedAsSent(t, "GetFeed", out, last.body) + apitest.DecodedAsSent(t, "GetFeed", out, last.Body, jsonOpts) } if err := c.GetAdmin(ctx); err != nil { diff --git a/testdata/debug/pkg/debug/client.gen_test.go b/testdata/debug/pkg/debug/client.gen_test.go index c15d5905..dab5a814 100644 --- a/testdata/debug/pkg/debug/client.gen_test.go +++ b/testdata/debug/pkg/debug/client.gen_test.go @@ -19,65 +19,15 @@ import ( "github.com/MarkRosemaker/cassette" "github.com/go-api-libs/api" + "github.com/go-api-libs/api/apitest" ) -func newTestServer(t *testing.T, status int) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - })) - t.Cleanup(srv.Close) - return srv -} - -// newBodyServer is the base URL of a server that answers every request with status, contentType and body. -func newBodyServer(t *testing.T, status int, contentType string, body []byte) *url.URL { - t.Helper() - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", contentType) - w.WriteHeader(status) - _, _ = w.Write(body) - })) - t.Cleanup(srv.Close) - - u, err := url.Parse(srv.URL) - if err != nil { - t.Fatal(err) - } - - return u -} - -// withUnknownMember is v as JSON, with a member no type declares added to it. -func withUnknownMember(t *testing.T, v any) []byte { - t.Helper() - - b, err := json.Marshal(v, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if string(b) == "{}" { - return []byte(`{"not_a_member_of_any_type": true}`) - } - - return append([]byte(`{"not_a_member_of_any_type": true, `), b[1:]...) -} - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { - return f(r) -} - func TestClient_Error(t *testing.T) { t.Run("GetItem", func(t *testing.T) { t.Setenv("DEBUG_TOKEN", "**************************************************") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -92,7 +42,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -169,7 +119,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps an unknown member", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", withUnknownMember(t, Item{}))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, Item{}, jsonOpts))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -190,7 +140,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -215,7 +165,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) if err != nil { t.Fatal(err) } @@ -235,7 +185,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "application/json", body))) if err != nil { t.Fatal(err) } @@ -252,7 +202,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("404 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -265,7 +215,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("404 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "foo", nil))) if err != nil { t.Fatal(err) } @@ -280,7 +230,7 @@ func TestClient_Error(t *testing.T) { t.Run("404 response debug mode keeps an unknown member", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "application/json", withUnknownMember(t, Problem{}))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "application/json", apitest.WithUnknownMember(t, Problem{}, jsonOpts))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -303,7 +253,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("DEBUG_TOKEN", "**************************************************") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -318,7 +268,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -395,7 +345,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -420,7 +370,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) if err != nil { t.Fatal(err) } @@ -439,7 +389,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("DEBUG_TOKEN", "**************************************************") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -454,7 +404,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -531,7 +481,7 @@ func TestClient_Error(t *testing.T) { t.Run("debug mode keeps a body it cannot decode", func(t *testing.T) { file := filepath.Join(t.TempDir(), "interactions.json") - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(file)) if err != nil { t.Fatal(err) } @@ -556,7 +506,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", []byte("invalid json"))), WithDebugFile(filepath.Join(blocker, "interactions.json"))) if err != nil { t.Fatal(err) } @@ -575,7 +525,7 @@ func TestClient_Error(t *testing.T) { t.Setenv("DEBUG_TOKEN", "**************************************************") t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -590,7 +540,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { diff --git a/testdata/debug/pkg/debug/types.gen_test.go b/testdata/debug/pkg/debug/types.gen_test.go index bfebc6fe..441e6b2f 100644 --- a/testdata/debug/pkg/debug/types.gen_test.go +++ b/testdata/debug/pkg/debug/types.gen_test.go @@ -5,9 +5,9 @@ package debug import ( - "bytes" - "encoding/json/v2" "testing" + + "github.com/go-api-libs/api/apitest" ) // TestEnums_Valid checks that every member of an enum is valid, and that a value of its type none is, is not. @@ -28,12 +28,12 @@ func TestEnums_Valid(t *testing.T) { func TestUnions_RoundTrip(t *testing.T) { t.Run("Pet/Cat", func(t *testing.T) { v := Cat{} - roundTrip(t, Pet{Cat: &v}, func(u Pet) bool { return u.Cat != nil }) + apitest.RoundTrip(t, Pet{Cat: &v}, func(u Pet) bool { return u.Cat != nil }, jsonOpts) }) t.Run("Pet/Dog", func(t *testing.T) { v := Dog{} - roundTrip(t, Pet{Dog: &v}, func(u Pet) bool { return u.Dog != nil }) + apitest.RoundTrip(t, Pet{Dog: &v}, func(u Pet) bool { return u.Dog != nil }, jsonOpts) }) } @@ -41,39 +41,10 @@ func TestUnions_RoundTrip(t *testing.T) { // encodes it and decodes it strictly: the tag must come back, and the struct encode as before. func TestTagged_RoundTrip(t *testing.T) { t.Run("Block/paragraph", func(t *testing.T) { - roundTrip(t, Block{Type: "paragraph", Paragraph: new(Text{})}, func(v Block) bool { return v.Type == "paragraph" }) + apitest.RoundTrip(t, Block{Type: "paragraph", Paragraph: new(Text{})}, func(v Block) bool { return v.Type == "paragraph" }, jsonOpts) }) t.Run("Block/divider", func(t *testing.T) { - roundTrip(t, Block{Type: "divider"}, func(v Block) bool { return v.Type == "divider" }) + apitest.RoundTrip(t, Block{Type: "divider"}, func(v Block) bool { return v.Type == "divider" }, jsonOpts) }) } - -// roundTrip encodes in and decodes it strictly into a new value, which set must report holds the variant in did, and -// which must encode as in did. -func roundTrip[T any](t *testing.T, in T, set func(T) bool) { - t.Helper() - - raw, err := json.Marshal(&in, jsonOpts) - if err != nil { - t.Fatal(err) - } - - var got T - if err := json.Unmarshal(raw, &got, jsonOpts); err != nil { - t.Fatalf("%s: %v", raw, err) - } - - if !set(got) { - t.Fatalf("%s decoded as another variant: %+v", raw, got) - } - - again, err := json.Marshal(&got, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(again, raw) { - t.Errorf("encoded %s, then %s", raw, again) - } -} diff --git a/testdata/golden/pkg/golden/client.gen_test.go b/testdata/golden/pkg/golden/client.gen_test.go index a4425907..92b0bbb1 100644 --- a/testdata/golden/pkg/golden/client.gen_test.go +++ b/testdata/golden/pkg/golden/client.gen_test.go @@ -5,82 +5,27 @@ package golden import ( - "bytes" "encoding/json/jsontext" "encoding/json/v2" "errors" "io" - "maps" "net" "net/http" "net/http/httptest" "net/url" - "slices" - "strconv" "strings" "testing" "time" "cloud.google.com/go/civil" - "github.com/MarkRosemaker/cassette" "github.com/go-api-libs/api" + "github.com/go-api-libs/api/apitest" ) -func newTestServer(t *testing.T, status int) *httptest.Server { - t.Helper() - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(status) - })) - t.Cleanup(srv.Close) - return srv -} - -// newBodyServer is the base URL of a server that answers every request with status, contentType and body. -func newBodyServer(t *testing.T, status int, contentType string, body []byte) *url.URL { - t.Helper() - - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", contentType) - w.WriteHeader(status) - _, _ = w.Write(body) - })) - t.Cleanup(srv.Close) - - u, err := url.Parse(srv.URL) - if err != nil { - t.Fatal(err) - } - - return u -} - -// withUnknownMember is v as JSON, with a member no type declares added to it. -func withUnknownMember(t *testing.T, v any) []byte { - t.Helper() - - b, err := json.Marshal(v, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if string(b) == "{}" { - return []byte(`{"not_a_member_of_any_type": true}`) - } - - return append([]byte(`{"not_a_member_of_any_type": true, `), b[1:]...) -} - -type roundTripFunc func(*http.Request) (*http.Response, error) - -func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { - return f(r) -} - func TestClient_Error(t *testing.T) { t.Run("GetPage", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -95,7 +40,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -175,7 +120,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "application/json", body))) if err != nil { t.Fatal(err) } @@ -192,7 +137,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("401 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -205,7 +150,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("401 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "foo", nil))) if err != nil { t.Fatal(err) } @@ -223,7 +168,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "application/json", body))) if err != nil { t.Fatal(err) } @@ -240,7 +185,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("404 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -253,7 +198,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("404 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "foo", nil))) if err != nil { t.Fatal(err) } @@ -266,7 +211,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("429 response without a body", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusTooManyRequests, "", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusTooManyRequests, "", nil))) if err != nil { t.Fatal(err) } @@ -279,7 +224,7 @@ func TestClient_Error(t *testing.T) { t.Run("Search", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -294,7 +239,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -371,7 +316,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetTrial", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -386,7 +331,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -461,7 +406,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown member", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", withUnknownMember(t, Trial{})))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, Trial{}, jsonOpts)))) if err != nil { t.Fatal(err) } @@ -476,7 +421,7 @@ func TestClient_Error(t *testing.T) { t.Run("UpdateUser", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -491,7 +436,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -566,7 +511,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown member", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", withUnknownMember(t, User{})))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, User{}, jsonOpts)))) if err != nil { t.Fatal(err) } @@ -581,7 +526,7 @@ func TestClient_Error(t *testing.T) { t.Run("PatchUser", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -596,7 +541,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -625,7 +570,7 @@ func TestClient_Error(t *testing.T) { sent []byte ) - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -664,7 +609,7 @@ func TestClient_Error(t *testing.T) { sent []byte ) - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -703,7 +648,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "application/json", body))) if err != nil { t.Fatal(err) } @@ -720,7 +665,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("401 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -733,7 +678,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("401 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnauthorized, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnauthorized, "foo", nil))) if err != nil { t.Fatal(err) } @@ -751,7 +696,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnprocessableEntity, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnprocessableEntity, "application/json", body))) if err != nil { t.Fatal(err) } @@ -768,7 +713,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("422 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnprocessableEntity, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnprocessableEntity, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -781,7 +726,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("422 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusUnprocessableEntity, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusUnprocessableEntity, "foo", nil))) if err != nil { t.Fatal(err) } @@ -794,7 +739,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("409 response without a body", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusConflict, "", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusConflict, "", nil))) if err != nil { t.Fatal(err) } @@ -807,7 +752,7 @@ func TestClient_Error(t *testing.T) { t.Run("CreateEntry", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -822,7 +767,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -899,7 +844,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetValue", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -914,7 +859,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -991,7 +936,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetBlock", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1006,7 +951,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1083,7 +1028,7 @@ func TestClient_Error(t *testing.T) { t.Run("CreateDatabase", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1098,7 +1043,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1175,7 +1120,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetProperty", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1190,7 +1135,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1267,7 +1212,7 @@ func TestClient_Error(t *testing.T) { t.Run("ListReports", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1282,7 +1227,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1359,7 +1304,7 @@ func TestClient_Error(t *testing.T) { t.Run("ListPeople", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1374,7 +1319,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1449,7 +1394,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown member", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusOK, "application/json", withUnknownMember(t, ListPeopleOk{})))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusOK, "application/json", apitest.WithUnknownMember(t, ListPeopleOk{}, jsonOpts)))) if err != nil { t.Fatal(err) } @@ -1464,7 +1409,7 @@ func TestClient_Error(t *testing.T) { t.Run("CreateSchedule", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1479,7 +1424,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1554,7 +1499,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown member", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusCreated, "application/json", withUnknownMember(t, CreateScheduleCreated{})))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusCreated, "application/json", apitest.WithUnknownMember(t, CreateScheduleCreated{}, jsonOpts)))) if err != nil { t.Fatal(err) } @@ -1572,7 +1517,7 @@ func TestClient_Error(t *testing.T) { t.Fatal(err) } - c, err := NewClient(WithBaseURL(newBodyServer(t, 529, "application/json", body))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, 529, "application/json", body))) if err != nil { t.Fatal(err) } @@ -1589,7 +1534,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("529 response decoding error", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, 529, "application/json", []byte("invalid json")))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, 529, "application/json", []byte("invalid json")))) if err != nil { t.Fatal(err) } @@ -1602,7 +1547,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("529 response unknown content type", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, 529, "foo", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, 529, "foo", nil))) if err != nil { t.Fatal(err) } @@ -1617,7 +1562,7 @@ func TestClient_Error(t *testing.T) { t.Run("DownloadReport", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1632,7 +1577,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1682,7 +1627,7 @@ func TestClient_Error(t *testing.T) { t.Run("DeleteSchedule", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1697,7 +1642,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1723,7 +1668,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetFile", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1738,7 +1683,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1764,7 +1709,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetRanges", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1779,7 +1724,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1854,7 +1799,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("404 response without a body", func(t *testing.T) { - c, err := NewClient(WithBaseURL(newBodyServer(t, http.StatusNotFound, "", nil))) + c, err := NewClient(WithBaseURL(apitest.BodyServer(t, http.StatusNotFound, "", nil))) if err != nil { t.Fatal(err) } @@ -1867,7 +1812,7 @@ func TestClient_Error(t *testing.T) { t.Run("GetStatus", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1882,7 +1827,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1932,7 +1877,7 @@ func TestClient_Error(t *testing.T) { t.Run("QueryStyles", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1947,7 +1892,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -1973,7 +1918,7 @@ func TestClient_Error(t *testing.T) { t.Run("CreateView", func(t *testing.T) { t.Run("transport error", func(t *testing.T) { - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(*http.Request) (*http.Response, error) { return nil, io.EOF }, )})) if err != nil { @@ -1988,7 +1933,7 @@ func TestClient_Error(t *testing.T) { }) t.Run("unknown status code", func(t *testing.T) { - srv := newTestServer(t, http.StatusTeapot) + srv := apitest.NewServer(t, http.StatusTeapot) baseURL, err := url.Parse(srv.URL) if err != nil { @@ -2019,7 +1964,7 @@ func TestClient_Params(t *testing.T) { t.Run("ListReports", func(t *testing.T) { var got *http.Request - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -2081,7 +2026,7 @@ func TestClient_Params(t *testing.T) { t.Run("QueryStyles", func(t *testing.T) { var got *http.Request - c, err := NewClient(WithHTTPClient(&http.Client{Transport: roundTripFunc( + c, err := NewClient(WithHTTPClient(&http.Client{Transport: apitest.RoundTripFunc( func(r *http.Request) (*http.Response, error) { got = r @@ -2134,324 +2079,10 @@ func TestClient_Params(t *testing.T) { }) } -func replay(t *testing.T) http.RoundTripper { - t.Helper() - - interactions, err := cassette.InteractionsReadFile("../../api/interactions.json") - if err != nil { - t.Fatal(err) - } - - match := cassette.MatchRequest( - cassette.CompareHeaders("User-Agent"), - ) - - rec := cassette.Replay(interactions, cassette.InOrder(), cassette.WithMatcher(func(req *http.Request, ia cassette.Request) error { - err := match(req, ia) - if err == nil || req.Body == nil { - return err - } - - sent, rerr := io.ReadAll(req.Body) - if rerr != nil { - return err - } - - req.Body = io.NopCloser(bytes.NewReader(sent)) - - var a, b any - if json.Unmarshal(ia.Body, &a) != nil || json.Unmarshal(sent, &b) != nil || !jsonSameButTags(a, b) { - return err - } - - ia.Body = sent - - return match(req, ia) - })) - - t.Cleanup(func() { - if unused := rec.Unused(); len(unused) > 0 { - t.Errorf("%d recorded interactions were never replayed, the first: %s %s", len(unused), unused[0].Request.Method, &unused[0].Request.URL) - } - }) - - return rec -} - -// lastBody passes requests on to next, and keeps the body of the last response, so that a test can compare what a call -// decoded with what was sent. -type lastBody struct { - next http.RoundTripper - body []byte -} - -func (l *lastBody) RoundTrip(req *http.Request) (*http.Response, error) { - rsp, err := l.next.RoundTrip(req) - if err != nil { - return nil, err - } - - defer rsp.Body.Close() - - if l.body, err = io.ReadAll(rsp.Body); err != nil { - return nil, err - } - - rsp.Body = io.NopCloser(bytes.NewReader(l.body)) - - return rsp, nil -} - -// decodedAsSent fails unless out, what a call decoded from body, encodes to what body holds. A member one side lacks is -// fine where the other holds nothing there (null, false, 0, "", [], an object of nothing but such members, or the zero -// text of a date, a time or a UUID), as an optional value left out is, and so is a tag one side leaves out (see -// jsonInferredTag); members may come in another order. A value may be written another way, as long as it -// is the same: a time as the same instant, a UUID with or without dashes, a number as a string of it. -func decodedAsSent(t *testing.T, op string, out any, body []byte) { - t.Helper() - - encoded, err := json.Marshal(out, jsonOpts) - if err != nil { - t.Fatalf("%s: encoding what was decoded: %v", op, err) - } - - var sent, got any - if err := json.Unmarshal(body, &sent); err != nil { - t.Fatalf("%s: the recorded body: %v", op, err) - } - - if err := json.Unmarshal(encoded, &got); err != nil { - t.Fatalf("%s: %v", op, err) - } - - if at, same := jsonSame(sent, got, ""); !same { - t.Errorf("%s: decoded something else than was sent, at %q:\nsent %s\ngot %s", op, at, body, encoded) - } -} - -// jsonSame reports whether the JSON values a and b, decoded into any, hold the same, as decodedAsSent compares them, -// and where they first differ if not. -func jsonSame(a, b any, at string) (string, bool) { - if jsonEmpty(a) && jsonEmpty(b) || jsonSameInstant(a, b) || jsonSameInstant(b, a) || - jsonSameNumber(a, b) || jsonSameNumber(b, a) { - return "", true - } - - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return at, false - } - - names := slices.Sorted(maps.Keys(a)) - for name := range b { - if _, ok := a[name]; !ok { - names = append(names, name) - } - } - - for _, name := range names { - if jsonInferredTag(a, b, name) || jsonInferredTag(b, a, name) { - continue - } - - if where, same := jsonSame(a[name], b[name], at+"/"+name); !same { - return where, false - } - } - - return "", true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return at, false - } - - for i := range a { - if where, same := jsonSame(a[i], b[i], at+"/"+strconv.Itoa(i)); !same { - return where, false - } - } - - return "", true - case string: - b, ok := b.(string) - if !ok { - return at, false - } - - if a == b { - return "", true - } - - if ua, ok := jsonUUID(a); ok { - if ub, ok := jsonUUID(b); ok { - return at, ua == ub - } - } - - ta, errA := time.Parse(time.RFC3339Nano, a) - tb, errB := time.Parse(time.RFC3339Nano, b) - - return at, errA == nil && errB == nil && ta.Equal(tb) - default: - return at, a == b - } -} - -// jsonSameInstant reports whether a is a Unix time, in seconds or milliseconds, and b a date-time of the same instant, -// as a type that takes either writes one as the other. -func jsonSameInstant(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - ts, err := time.Parse(time.RFC3339Nano, s) - - return err == nil && (float64(ts.Unix()) == n || float64(ts.UnixMilli()) == n) -} - -// jsonSameNumber reports whether a is a number and b a string of the same number, as a string type writes one. -func jsonSameNumber(a, b any) bool { - n, ok := a.(float64) - if !ok { - return false - } - - s, ok := b.(string) - if !ok { - return false - } - - f, err := strconv.ParseFloat(s, 64) - - return err == nil && f == n -} - -// jsonUUID is s, a UUID with or without dashes, as its 32 hex digits in lower case. -func jsonUUID(s string) (string, bool) { - hex := strings.ToLower(strings.ReplaceAll(s, "-", "")) - if len(hex) != 32 || len(s) != 32 && len(s) != 36 || strings.Trim(hex, "0123456789abcdef") != "" { - return "", false - } - - return hex, true -} - -// jsonEmpty reports whether v, a JSON value decoded into any, holds nothing: null, false, 0, "", [], an object whose -// members hold nothing, or the text a zero date, time or UUID is written as, which is what an empty one decodes into: -// null read into a struct is written back as its members, empty. -func jsonEmpty(v any) bool { - switch v := v.(type) { - case nil: - return true - case bool: - return !v - case float64: - return v == 0 - case string: - return v == "" || v == "0000-00-00" || v == "0001-01-01T00:00:00Z" || v == "00000000-0000-0000-0000-000000000000" - case []any: - return len(v) == 0 - case map[string]any: - for _, m := range v { - if !jsonEmpty(m) { - return false - } - } - - return true - default: - return false - } -} - -// jsonInferredTag reports whether the object a lacks the member name, which b holds as a tag: the name of a member both -// hold. A tagged object may leave its tag out, and decoding it infers the tag from the member that is set, which -// encoding then writes. -func jsonInferredTag(a, b map[string]any, name string) bool { - if _, ok := a[name]; ok { - return false - } - - tag, ok := b[name].(string) - if !ok { - return false - } - - _, inA := a[tag] - _, inB := b[tag] - - return inA && inB -} - -// jsonSameButTags reports whether the JSON values a and b, decoded into any, are the same, but for tags either leaves -// out (see jsonInferredTag): the request a call sends for one that was recorded without them. -func jsonSameButTags(a, b any) bool { - switch a := a.(type) { - case map[string]any: - b, ok := b.(map[string]any) - if !ok { - return false - } - - for name := range a { - if _, ok := b[name]; !ok && !jsonInferredTag(b, a, name) { - return false - } - } - - for name, vb := range b { - va, ok := a[name] - if !ok && !jsonInferredTag(a, b, name) || ok && !jsonSameButTags(va, vb) { - return false - } - } - - return true - case []any: - b, ok := b.([]any) - if !ok || len(a) != len(b) { - return false - } - - for i := range a { - if !jsonSameButTags(a[i], b[i]) { - return false - } - } - - return true - default: - return a == b - } -} - -// mustDecodeBody decodes data, the recorded JSON for one request body value -// (or field of one) an interaction's own literal couldn't be built for, into -// T so a replayed call still carries the value it was recorded with. -func mustDecodeBody[T any](t *testing.T, data string) T { - t.Helper() - - var v T - if err := json.Unmarshal([]byte(data), &v, jsonOpts); err != nil { - t.Fatalf("decoding request body fixture: %v", err) - } - - return v -} - func TestClient_Interactions(t *testing.T) { ctx := t.Context() - last := &lastBody{next: replay(t)} + last := &apitest.LastBody{Next: apitest.Replay(t, "../../api/interactions.json")} c, err := NewClient(WithHTTPClient(&http.Client{Transport: last})) if err != nil { @@ -2461,19 +2092,19 @@ func TestClient_Interactions(t *testing.T) { if out, err := c.GetPage(ctx, "p"); err != nil { t.Fatalf("GetPage: %v", err) } else { - decodedAsSent(t, "GetPage", out, last.body) + apitest.DecodedAsSent(t, "GetPage", out, last.Body, jsonOpts) } if out, err := c.Search(ctx, PropertyFilter{ Property: "x", - Type: mustDecodeBody[PropertyFilterType](t, "\"select\""), + Type: apitest.MustDecode[PropertyFilterType](t, "\"select\"", jsonOpts), Select: new(Condition{ DoesNotEqual: "Done", }), }); err != nil { t.Fatalf("Search: %v", err) } else { - decodedAsSent(t, "Search", out, last.body) + apitest.DecodedAsSent(t, "Search", out, last.Body, jsonOpts) } if out, err := c.UpdateUser(ctx, "u", User{ @@ -2482,13 +2113,13 @@ func TestClient_Interactions(t *testing.T) { }); err != nil { t.Fatalf("UpdateUser: %v", err) } else { - decodedAsSent(t, "UpdateUser", out, last.body) + apitest.DecodedAsSent(t, "UpdateUser", out, last.Body, jsonOpts) } if out, err := c.GetBlock(ctx, "b"); err != nil { t.Fatalf("GetBlock: %v", err) } else { - decodedAsSent(t, "GetBlock", out, last.body) + apitest.DecodedAsSent(t, "GetBlock", out, last.Body, jsonOpts) } if out, err := c.CreateDatabase(ctx, CreateDatabaseParent{ @@ -2497,13 +2128,13 @@ func TestClient_Interactions(t *testing.T) { }); err != nil { t.Fatalf("CreateDatabase: %v", err) } else { - decodedAsSent(t, "CreateDatabase", out, last.body) + apitest.DecodedAsSent(t, "CreateDatabase", out, last.Body, jsonOpts) } if out, err := c.GetProperty(ctx, "abc"); err != nil { t.Fatalf("GetProperty: %v", err) } else { - decodedAsSent(t, "GetProperty", out, last.body) + apitest.DecodedAsSent(t, "GetProperty", out, last.Body, jsonOpts) } if out, err := c.ListReports(ctx, ListReportsParams{ @@ -2514,12 +2145,12 @@ func TestClient_Interactions(t *testing.T) { }); err != nil { t.Fatalf("ListReports: %v", err) } else { - decodedAsSent(t, "ListReports", out, last.body) + apitest.DecodedAsSent(t, "ListReports", out, last.Body, jsonOpts) } if out, err := c.CreateSchedule(ctx, Schedule{ Day: civil.Date{Year: 2026, Month: 10, Day: 8}, - Every: mustDecodeBody[time.Duration](t, "3600"), + Every: apitest.MustDecode[time.Duration](t, "3600", jsonOpts), At: time.Unix(1791453600, 0), Enabled: true, Count: 2, @@ -2533,7 +2164,7 @@ func TestClient_Interactions(t *testing.T) { }); err != nil { t.Fatalf("CreateSchedule: %v", err) } else { - decodedAsSent(t, "CreateSchedule", out, last.body) + apitest.DecodedAsSent(t, "CreateSchedule", out, last.Body, jsonOpts) } if _, err := c.GetStatus(ctx); err != nil { diff --git a/testdata/golden/pkg/golden/types.gen_test.go b/testdata/golden/pkg/golden/types.gen_test.go index e69cdbb3..5f484d99 100644 --- a/testdata/golden/pkg/golden/types.gen_test.go +++ b/testdata/golden/pkg/golden/types.gen_test.go @@ -5,9 +5,9 @@ package golden import ( - "bytes" - "encoding/json/v2" "testing" + + "github.com/go-api-libs/api/apitest" ) // TestEnums_Valid checks that every member of an enum is valid, and that a value of its type none is, is not. @@ -208,122 +208,122 @@ func TestEnums_Valid(t *testing.T) { func TestUnions_RoundTrip(t *testing.T) { t.Run("AgentModel/AgentModelOneOf", func(t *testing.T) { v := AgentModelOneOf{Mode: "auto"} - roundTrip(t, AgentModel{AgentModelOneOf: &v}, func(u AgentModel) bool { return u.AgentModelOneOf != nil }) + apitest.RoundTrip(t, AgentModel{AgentModelOneOf: &v}, func(u AgentModel) bool { return u.AgentModelOneOf != nil }, jsonOpts) }) t.Run("AgentModel/AgentModelOneOf2", func(t *testing.T) { v := AgentModelOneOf2{Mode: "pinned"} - roundTrip(t, AgentModel{AgentModelOneOf2: &v}, func(u AgentModel) bool { return u.AgentModelOneOf2 != nil }) + apitest.RoundTrip(t, AgentModel{AgentModelOneOf2: &v}, func(u AgentModel) bool { return u.AgentModelOneOf2 != nil }, jsonOpts) }) t.Run("Bot/BotAnyOf1", func(t *testing.T) { v := BotAnyOf1{} - roundTrip(t, Bot{BotAnyOf1: &v}, func(u Bot) bool { return u.BotAnyOf1 != nil }) + apitest.RoundTrip(t, Bot{BotAnyOf1: &v}, func(u Bot) bool { return u.BotAnyOf1 != nil }, jsonOpts) }) t.Run("Filter/FilterAnyOf0", func(t *testing.T) { v := FilterAnyOf0{} - roundTrip(t, Filter{FilterAnyOf0: &v}, func(u Filter) bool { return u.FilterAnyOf0 != nil }) + apitest.RoundTrip(t, Filter{FilterAnyOf0: &v}, func(u Filter) bool { return u.FilterAnyOf0 != nil }, jsonOpts) }) t.Run("Filter/FilterAnyOf1", func(t *testing.T) { v := FilterAnyOf1{} - roundTrip(t, Filter{FilterAnyOf1: &v}, func(u Filter) bool { return u.FilterAnyOf1 != nil }) + apitest.RoundTrip(t, Filter{FilterAnyOf1: &v}, func(u Filter) bool { return u.FilterAnyOf1 != nil }, jsonOpts) }) t.Run("GroupBy/GroupByAnyOf0", func(t *testing.T) { v := GroupByAnyOf0{Type: "select"} - roundTrip(t, GroupBy{GroupByAnyOf0: &v}, func(u GroupBy) bool { return u.GroupByAnyOf0 != nil }) + apitest.RoundTrip(t, GroupBy{GroupByAnyOf0: &v}, func(u GroupBy) bool { return u.GroupByAnyOf0 != nil }, jsonOpts) }) t.Run("GroupBy/GroupByAnyOf1", func(t *testing.T) { v := GroupByAnyOf1{Type: "date"} - roundTrip(t, GroupBy{GroupByAnyOf1: &v}, func(u GroupBy) bool { return u.GroupByAnyOf1 != nil }) + apitest.RoundTrip(t, GroupBy{GroupByAnyOf1: &v}, func(u GroupBy) bool { return u.GroupByAnyOf1 != nil }, jsonOpts) }) t.Run("IconResponse/Emoji", func(t *testing.T) { v := Emoji{} - roundTrip(t, IconResponse{Emoji: &v}, func(u IconResponse) bool { return u.Emoji != nil }) + apitest.RoundTrip(t, IconResponse{Emoji: &v}, func(u IconResponse) bool { return u.Emoji != nil }, jsonOpts) }) t.Run("IconResponse/Link", func(t *testing.T) { v := Link{} - roundTrip(t, IconResponse{Link: &v}, func(u IconResponse) bool { return u.Link != nil }) + apitest.RoundTrip(t, IconResponse{Link: &v}, func(u IconResponse) bool { return u.Link != nil }, jsonOpts) }) t.Run("MaybeMember/NestedValue", func(t *testing.T) { v := NestedValue{Type: "number", Number: new(1.5)} - roundTrip(t, MaybeMember{NestedValue: &v}, func(u MaybeMember) bool { return u.NestedValue != nil }) + apitest.RoundTrip(t, MaybeMember{NestedValue: &v}, func(u MaybeMember) bool { return u.NestedValue != nil }, jsonOpts) }) t.Run("MaybeMember/GroupObjectResponse", func(t *testing.T) { v := GroupObjectResponse{Object: "group"} - roundTrip(t, MaybeMember{GroupObjectResponse: &v}, func(u MaybeMember) bool { return u.GroupObjectResponse != nil }) + apitest.RoundTrip(t, MaybeMember{GroupObjectResponse: &v}, func(u MaybeMember) bool { return u.GroupObjectResponse != nil }, jsonOpts) }) t.Run("MemberAllOf1/MemberPerson", func(t *testing.T) { v := MemberPerson{Type: "person", MembershipType: "member"} - roundTrip(t, MemberAllOf1{MemberPerson: &v}, func(u MemberAllOf1) bool { return u.MemberPerson != nil }) + apitest.RoundTrip(t, MemberAllOf1{MemberPerson: &v}, func(u MemberAllOf1) bool { return u.MemberPerson != nil }, jsonOpts) }) t.Run("MemberAllOf1/BotUserObjectResponse", func(t *testing.T) { v := BotUserObjectResponse{Type: "bot"} - roundTrip(t, MemberAllOf1{BotUserObjectResponse: &v}, func(u MemberAllOf1) bool { return u.BotUserObjectResponse != nil }) + apitest.RoundTrip(t, MemberAllOf1{BotUserObjectResponse: &v}, func(u MemberAllOf1) bool { return u.BotUserObjectResponse != nil }, jsonOpts) }) t.Run("Owner/PartialUserObjectResponse", func(t *testing.T) { v := PartialUserObjectResponse{Object: "user"} - roundTrip(t, Owner{PartialUserObjectResponse: &v}, func(u Owner) bool { return u.PartialUserObjectResponse != nil }) + apitest.RoundTrip(t, Owner{PartialUserObjectResponse: &v}, func(u Owner) bool { return u.PartialUserObjectResponse != nil }, jsonOpts) }) t.Run("Owner/GroupObjectResponse", func(t *testing.T) { v := GroupObjectResponse{Object: "group"} - roundTrip(t, Owner{GroupObjectResponse: &v}, func(u Owner) bool { return u.GroupObjectResponse != nil }) + apitest.RoundTrip(t, Owner{GroupObjectResponse: &v}, func(u Owner) bool { return u.GroupObjectResponse != nil }, jsonOpts) }) t.Run("PageOrPartial/PartialPage", func(t *testing.T) { v := PartialPage{Object: "page"} - roundTrip(t, PageOrPartial{PartialPage: &v}, func(u PageOrPartial) bool { return u.PartialPage != nil }) + apitest.RoundTrip(t, PageOrPartial{PartialPage: &v}, func(u PageOrPartial) bool { return u.PartialPage != nil }, jsonOpts) }) t.Run("Tags/String", func(t *testing.T) { v := "sample" - roundTrip(t, Tags{String: v}, func(u Tags) bool { return u.String != "" }) + apitest.RoundTrip(t, Tags{String: v}, func(u Tags) bool { return u.String != "" }, jsonOpts) }) t.Run("Tags/String2", func(t *testing.T) { v := []string{"sample"} - roundTrip(t, Tags{String2: v}, func(u Tags) bool { return u.String2 != nil }) + apitest.RoundTrip(t, Tags{String2: v}, func(u Tags) bool { return u.String2 != nil }, jsonOpts) }) t.Run("UserValueResponse/PartialUserObjectResponse", func(t *testing.T) { v := PartialUserObjectResponse{Object: "user"} - roundTrip(t, UserValueResponse{PartialUserObjectResponse: &v}, func(u UserValueResponse) bool { return u.PartialUserObjectResponse != nil }) + apitest.RoundTrip(t, UserValueResponse{PartialUserObjectResponse: &v}, func(u UserValueResponse) bool { return u.PartialUserObjectResponse != nil }, jsonOpts) }) t.Run("UserValueResponse/UserObjectResponse", func(t *testing.T) { v := UserObjectResponse{UserObjectResponseCommon: UserObjectResponseCommon{Object: "user"}, Type: "person", Person: new(UserOneOfPerson{})} - roundTrip(t, UserValueResponse{UserObjectResponse: &v}, func(u UserValueResponse) bool { return u.UserObjectResponse != nil }) + apitest.RoundTrip(t, UserValueResponse{UserObjectResponse: &v}, func(u UserValueResponse) bool { return u.UserObjectResponse != nil }, jsonOpts) }) t.Run("ValueAllOf1/SimpleOrArray", func(t *testing.T) { v := SimpleOrArray{Type: "number", Number: new(1.5)} - roundTrip(t, ValueAllOf1{SimpleOrArray: &v}, func(u ValueAllOf1) bool { return u.SimpleOrArray != nil }) + apitest.RoundTrip(t, ValueAllOf1{SimpleOrArray: &v}, func(u ValueAllOf1) bool { return u.SimpleOrArray != nil }, jsonOpts) }) t.Run("ValueAllOf1/Rollup", func(t *testing.T) { v := Rollup{Type: "rollup"} - roundTrip(t, ValueAllOf1{Rollup: &v}, func(u ValueAllOf1) bool { return u.Rollup != nil }) + apitest.RoundTrip(t, ValueAllOf1{Rollup: &v}, func(u ValueAllOf1) bool { return u.Rollup != nil }, jsonOpts) }) t.Run("ViewFilter/PropertyFilter", func(t *testing.T) { v := PropertyFilter{Type: "select", Select: new(Condition{})} - roundTrip(t, ViewFilter{PropertyFilter: &v}, func(u ViewFilter) bool { return u.PropertyFilter != nil }) + apitest.RoundTrip(t, ViewFilter{PropertyFilter: &v}, func(u ViewFilter) bool { return u.PropertyFilter != nil }, jsonOpts) }) t.Run("ViewFilter/CompoundFilter", func(t *testing.T) { v := CompoundFilter{} - roundTrip(t, ViewFilter{CompoundFilter: &v}, func(u ViewFilter) bool { return u.CompoundFilter != nil }) + apitest.RoundTrip(t, ViewFilter{CompoundFilter: &v}, func(u ViewFilter) bool { return u.CompoundFilter != nil }, jsonOpts) }) } @@ -331,107 +331,78 @@ func TestUnions_RoundTrip(t *testing.T) { // encodes it and decodes it strictly: the tag must come back, and the struct encode as before. func TestTagged_RoundTrip(t *testing.T) { t.Run("Block/paragraph", func(t *testing.T) { - roundTrip(t, Block{Type: "paragraph", Paragraph: "sample"}, func(v Block) bool { return v.Type == "paragraph" }) + apitest.RoundTrip(t, Block{Type: "paragraph", Paragraph: "sample"}, func(v Block) bool { return v.Type == "paragraph" }, jsonOpts) }) t.Run("Block/child_database", func(t *testing.T) { - roundTrip(t, Block{Type: "child_database", ChildDatabase: "sample"}, func(v Block) bool { return v.Type == "child_database" }) + apitest.RoundTrip(t, Block{Type: "child_database", ChildDatabase: "sample"}, func(v Block) bool { return v.Type == "child_database" }, jsonOpts) }) t.Run("Block/relation", func(t *testing.T) { - roundTrip(t, Block{Type: "relation", Relation: []string{"sample"}}, func(v Block) bool { return v.Type == "relation" }) + apitest.RoundTrip(t, Block{Type: "relation", Relation: []string{"sample"}}, func(v Block) bool { return v.Type == "relation" }, jsonOpts) }) t.Run("CoverResponse/external", func(t *testing.T) { - roundTrip(t, CoverResponse{Type: "external", External: new(Link{})}, func(v CoverResponse) bool { return v.Type == "external" }) + apitest.RoundTrip(t, CoverResponse{Type: "external", External: new(Link{})}, func(v CoverResponse) bool { return v.Type == "external" }, jsonOpts) }) t.Run("CoverResponse/file", func(t *testing.T) { - roundTrip(t, CoverResponse{Type: "file", File: new(Link{})}, func(v CoverResponse) bool { return v.Type == "file" }) + apitest.RoundTrip(t, CoverResponse{Type: "file", File: new(Link{})}, func(v CoverResponse) bool { return v.Type == "file" }, jsonOpts) }) t.Run("CreateDatabaseParent/page_id", func(t *testing.T) { - roundTrip(t, CreateDatabaseParent{Type: "page_id", PageID: IDRequest("sample")}, func(v CreateDatabaseParent) bool { return v.Type == "page_id" }) + apitest.RoundTrip(t, CreateDatabaseParent{Type: "page_id", PageID: IDRequest("sample")}, func(v CreateDatabaseParent) bool { return v.Type == "page_id" }, jsonOpts) }) t.Run("CreateDatabaseParent/workspace", func(t *testing.T) { - roundTrip(t, CreateDatabaseParent{Type: "workspace", Workspace: new(true)}, func(v CreateDatabaseParent) bool { return v.Type == "workspace" }) + apitest.RoundTrip(t, CreateDatabaseParent{Type: "workspace", Workspace: new(true)}, func(v CreateDatabaseParent) bool { return v.Type == "workspace" }, jsonOpts) }) t.Run("NestedValue/number", func(t *testing.T) { - roundTrip(t, NestedValue{Type: "number", Number: new(1.5)}, func(v NestedValue) bool { return v.Type == "number" }) + apitest.RoundTrip(t, NestedValue{Type: "number", Number: new(1.5)}, func(v NestedValue) bool { return v.Type == "number" }, jsonOpts) }) t.Run("NestedValue/url", func(t *testing.T) { - roundTrip(t, NestedValue{Type: "url", URL: "sample"}, func(v NestedValue) bool { return v.Type == "url" }) + apitest.RoundTrip(t, NestedValue{Type: "url", URL: "sample"}, func(v NestedValue) bool { return v.Type == "url" }, jsonOpts) }) t.Run("NestedValue/title", func(t *testing.T) { - roundTrip(t, NestedValue{Type: "title", Title: []string{"sample"}}, func(v NestedValue) bool { return v.Type == "title" }) + apitest.RoundTrip(t, NestedValue{Type: "title", Title: []string{"sample"}}, func(v NestedValue) bool { return v.Type == "title" }, jsonOpts) }) t.Run("PropertyFilter/select", func(t *testing.T) { - roundTrip(t, PropertyFilter{Type: "select", Select: new(Condition{})}, func(v PropertyFilter) bool { return v.Type == "select" }) + apitest.RoundTrip(t, PropertyFilter{Type: "select", Select: new(Condition{})}, func(v PropertyFilter) bool { return v.Type == "select" }, jsonOpts) }) t.Run("PropertyFilter/number", func(t *testing.T) { - roundTrip(t, PropertyFilter{Type: "number", Number: new(Condition{})}, func(v PropertyFilter) bool { return v.Type == "number" }) + apitest.RoundTrip(t, PropertyFilter{Type: "number", Number: new(Condition{})}, func(v PropertyFilter) bool { return v.Type == "number" }, jsonOpts) }) t.Run("PropertyValue/date", func(t *testing.T) { - roundTrip(t, PropertyValue{Type: "date", Date: new(Date{})}, func(v PropertyValue) bool { return v.Type == "date" }) + apitest.RoundTrip(t, PropertyValue{Type: "date", Date: new(Date{})}, func(v PropertyValue) bool { return v.Type == "date" }, jsonOpts) }) t.Run("PropertyValue/number", func(t *testing.T) { - roundTrip(t, PropertyValue{Type: "number", Number: new(1.5)}, func(v PropertyValue) bool { return v.Type == "number" }) + apitest.RoundTrip(t, PropertyValue{Type: "number", Number: new(1.5)}, func(v PropertyValue) bool { return v.Type == "number" }, jsonOpts) }) t.Run("SimpleOrArray/number", func(t *testing.T) { - roundTrip(t, SimpleOrArray{Type: "number", Number: new(1.5)}, func(v SimpleOrArray) bool { return v.Type == "number" }) + apitest.RoundTrip(t, SimpleOrArray{Type: "number", Number: new(1.5)}, func(v SimpleOrArray) bool { return v.Type == "number" }, jsonOpts) }) t.Run("SimpleOrArray/text", func(t *testing.T) { - roundTrip(t, SimpleOrArray{Type: "text", Text: "sample"}, func(v SimpleOrArray) bool { return v.Type == "text" }) + apitest.RoundTrip(t, SimpleOrArray{Type: "text", Text: "sample"}, func(v SimpleOrArray) bool { return v.Type == "text" }, jsonOpts) }) t.Run("SimpleOrArray/relation", func(t *testing.T) { - roundTrip(t, SimpleOrArray{Type: "relation", Relation: []string{"sample"}}, func(v SimpleOrArray) bool { return v.Type == "relation" }) + apitest.RoundTrip(t, SimpleOrArray{Type: "relation", Relation: []string{"sample"}}, func(v SimpleOrArray) bool { return v.Type == "relation" }, jsonOpts) }) t.Run("UserObjectResponse/person", func(t *testing.T) { - roundTrip(t, UserObjectResponse{UserObjectResponseCommon: UserObjectResponseCommon{Object: "user"}, Type: "person", Person: new(UserOneOfPerson{})}, func(v UserObjectResponse) bool { return v.Type == "person" }) + apitest.RoundTrip(t, UserObjectResponse{UserObjectResponseCommon: UserObjectResponseCommon{Object: "user"}, Type: "person", Person: new(UserOneOfPerson{})}, func(v UserObjectResponse) bool { return v.Type == "person" }, jsonOpts) }) t.Run("UserObjectResponse/bot", func(t *testing.T) { - roundTrip(t, UserObjectResponse{UserObjectResponseCommon: UserObjectResponseCommon{Object: "user"}, Type: "bot", Bot: new(EmptyObject{})}, func(v UserObjectResponse) bool { return v.Type == "bot" }) + apitest.RoundTrip(t, UserObjectResponse{UserObjectResponseCommon: UserObjectResponseCommon{Object: "user"}, Type: "bot", Bot: new(EmptyObject{})}, func(v UserObjectResponse) bool { return v.Type == "bot" }, jsonOpts) }) } - -// roundTrip encodes in and decodes it strictly into a new value, which set must report holds the variant in did, and -// which must encode as in did. -func roundTrip[T any](t *testing.T, in T, set func(T) bool) { - t.Helper() - - raw, err := json.Marshal(&in, jsonOpts) - if err != nil { - t.Fatal(err) - } - - var got T - if err := json.Unmarshal(raw, &got, jsonOpts); err != nil { - t.Fatalf("%s: %v", raw, err) - } - - if !set(got) { - t.Fatalf("%s decoded as another variant: %+v", raw, got) - } - - again, err := json.Marshal(&got, jsonOpts) - if err != nil { - t.Fatal(err) - } - - if !bytes.Equal(again, raw) { - t.Errorf("encoded %s, then %s", raw, again) - } -} diff --git a/vendor/github.com/go-api-libs/api/README.md b/vendor/github.com/go-api-libs/api/README.md index 60a53b2d..f7085da5 100644 --- a/vendor/github.com/go-api-libs/api/README.md +++ b/vendor/github.com/go-api-libs/api/README.md @@ -1,5 +1,5 @@ -[![Go Reference](https://pkg.go.dev/badge/github.com/go-api-libs/api.svg)](https://pkg.go.dev/github.com/go-api-libs/api) ![Code Coverage](https://img.shields.io/badge/coverage-90%25-brightgreen) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) +[![Go Reference](https://pkg.go.dev/badge/github.com/go-api-libs/api.svg)](https://pkg.go.dev/github.com/go-api-libs/api) ![Code Coverage](https://img.shields.io/badge/coverage-89%25-green) [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) ![Code Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen) diff --git a/vendor/github.com/go-api-libs/api/apitest/apitest.go b/vendor/github.com/go-api-libs/api/apitest/apitest.go new file mode 100644 index 00000000..9ef131e4 --- /dev/null +++ b/vendor/github.com/go-api-libs/api/apitest/apitest.go @@ -0,0 +1,113 @@ +// Package apitest holds what the tests openapi-codegen generates need, as net/http/httptest holds what tests of HTTP +// need: servers that answer as told, the replay of recorded interactions, and the checks of what a client decoded +// and of a type's round trip. It is generated tests', not an API of its own, and changes as the generator needs. +package apitest + +import ( + "encoding/json/v2" + "net/http" + "net/http/httptest" + "net/url" + "testing" +) + +// NewServer is a server that answers every request with status and a JSON content type, but no body, and closes when +// the test ends. +func NewServer(t testing.TB, status int) *httptest.Server { + t.Helper() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + })) + t.Cleanup(srv.Close) + + return srv +} + +// BodyServer is the base URL of a server that answers every request with status, contentType and body, and closes +// when the test ends. +func BodyServer(t testing.TB, status int, contentType string, body []byte) *url.URL { + t.Helper() + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", contentType) + w.WriteHeader(status) + _, _ = w.Write(body) + })) + t.Cleanup(srv.Close) + + u, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + + return u +} + +// RoundTripFunc is a function that is an [http.RoundTripper]. +type RoundTripFunc func(*http.Request) (*http.Response, error) + +// RoundTrip implements [http.RoundTripper]. +func (f RoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// unknownMember is a member no type declares. +const unknownMember = `"not_a_member_of_any_type": true` + +// WithUnknownMember is v as JSON, encoded as opts say, with a member no type declares added to it. +func WithUnknownMember(t testing.TB, v any, opts json.Options) []byte { + t.Helper() + + b, err := json.Marshal(v, opts) + if err != nil { + t.Fatal(err) + } + + if string(b) == "{}" { + return []byte("{" + unknownMember + "}") + } + + return append([]byte("{"+unknownMember+", "), b[1:]...) +} + +// MustDecode decodes data, recorded JSON, into a T as opts say: a value a test builds from a recording it has no +// literal for. +func MustDecode[T any](t testing.TB, data string, opts json.Options) T { + t.Helper() + + var v T + if err := json.Unmarshal([]byte(data), &v, opts); err != nil { + t.Fatalf("decoding %s: %v", data, err) + } + + return v +} + +// RoundTrip encodes in and decodes it strictly into a new value, both as opts say. set must report that the new value +// holds the variant in did, and it must encode as in did. +func RoundTrip[T any](t testing.TB, in T, set func(T) bool, opts json.Options) { + t.Helper() + + raw, err := json.Marshal(&in, opts) + if err != nil { + t.Fatal(err) + } + + var got T + if err := json.Unmarshal(raw, &got, opts); err != nil { + t.Fatalf("%s: %v", raw, err) + } + + if !set(got) { + t.Fatalf("%s decoded as another variant: %+v", raw, got) + } + + again, err := json.Marshal(&got, opts) + if err != nil { + t.Fatal(err) + } + + if string(again) != string(raw) { + t.Errorf("encoded %s, then %s", raw, again) + } +} diff --git a/vendor/github.com/go-api-libs/api/apitest/compare.go b/vendor/github.com/go-api-libs/api/apitest/compare.go new file mode 100644 index 00000000..c120e670 --- /dev/null +++ b/vendor/github.com/go-api-libs/api/apitest/compare.go @@ -0,0 +1,243 @@ +package apitest + +import ( + "encoding/json/v2" + "maps" + "slices" + "strconv" + "strings" + "testing" + "time" +) + +// DecodedAsSent fails unless out, what a call decoded from body, encodes as opts say to what body holds. A member one side lacks is +// fine where the other holds nothing there (null, false, 0, "", [], an object of nothing but such members, or the zero +// text of a date, a time or a UUID), as an optional value left out is, and so is a tag one side leaves out (see +// jsonInferredTag); members may come in another order. A value may be written another way, as long as it +// is the same: a time as the same instant, a UUID with or without dashes, a number as a string of it. +func DecodedAsSent(t testing.TB, op string, out any, body []byte, opts json.Options) { + t.Helper() + + encoded, err := json.Marshal(out, opts) + if err != nil { + t.Fatalf("%s: encoding what was decoded: %v", op, err) + } + + var sent, got any + if err := json.Unmarshal(body, &sent); err != nil { + t.Fatalf("%s: the recorded body: %v", op, err) + } + + if err := json.Unmarshal(encoded, &got); err != nil { + t.Fatalf("%s: %v", op, err) + } + + if at, same := jsonSame(sent, got, ""); !same { + t.Errorf("%s: decoded something else than was sent, at %q:\nsent %s\ngot %s", op, at, body, encoded) + } +} + +// jsonSame reports whether the JSON values a and b, decoded into any, hold the same, as DecodedAsSent compares them, +// and where they first differ if not. +func jsonSame(a, b any, at string) (string, bool) { + if jsonEmpty(a) && jsonEmpty(b) || jsonSameInstant(a, b) || jsonSameInstant(b, a) || + jsonSameNumber(a, b) || jsonSameNumber(b, a) { + return "", true + } + + switch a := a.(type) { + case map[string]any: + b, ok := b.(map[string]any) + if !ok { + return at, false + } + + names := slices.Sorted(maps.Keys(a)) + for name := range b { + if _, ok := a[name]; !ok { + names = append(names, name) + } + } + + for _, name := range names { + if jsonInferredTag(a, b, name) || jsonInferredTag(b, a, name) { + continue + } + + if where, same := jsonSame(a[name], b[name], at+"/"+name); !same { + return where, false + } + } + + return "", true + case []any: + b, ok := b.([]any) + if !ok || len(a) != len(b) { + return at, false + } + + for i := range a { + if where, same := jsonSame(a[i], b[i], at+"/"+strconv.Itoa(i)); !same { + return where, false + } + } + + return "", true + case string: + b, ok := b.(string) + if !ok { + return at, false + } + + if a == b { + return "", true + } + + if ua, ok := jsonUUID(a); ok { + if ub, ok := jsonUUID(b); ok { + return at, ua == ub + } + } + + ta, errA := time.Parse(time.RFC3339Nano, a) + tb, errB := time.Parse(time.RFC3339Nano, b) + + return at, errA == nil && errB == nil && ta.Equal(tb) + default: + return at, a == b + } +} + +// jsonSameInstant reports whether a is a Unix time, in seconds or milliseconds, and b a date-time of the same instant, +// as a type that takes either writes one as the other. +func jsonSameInstant(a, b any) bool { + n, ok := a.(float64) + if !ok { + return false + } + + s, ok := b.(string) + if !ok { + return false + } + + ts, err := time.Parse(time.RFC3339Nano, s) + + return err == nil && (float64(ts.Unix()) == n || float64(ts.UnixMilli()) == n) +} + +// jsonSameNumber reports whether a is a number and b a string of the same number, as a string type writes one. +func jsonSameNumber(a, b any) bool { + n, ok := a.(float64) + if !ok { + return false + } + + s, ok := b.(string) + if !ok { + return false + } + + f, err := strconv.ParseFloat(s, 64) + + return err == nil && f == n +} + +// jsonUUID is s, a UUID with or without dashes, as its 32 hex digits in lower case. +func jsonUUID(s string) (string, bool) { + hex := strings.ToLower(strings.ReplaceAll(s, "-", "")) + if len(hex) != 32 || len(s) != 32 && len(s) != 36 || strings.Trim(hex, "0123456789abcdef") != "" { + return "", false + } + + return hex, true +} + +// jsonEmpty reports whether v, a JSON value decoded into any, holds nothing: null, false, 0, "", [], an object whose +// members hold nothing, or the text a zero date, time or UUID is written as, which is what an empty one decodes into: +// null read into a struct is written back as its members, empty. +func jsonEmpty(v any) bool { + switch v := v.(type) { + case nil: + return true + case bool: + return !v + case float64: + return v == 0 + case string: + return v == "" || v == "0000-00-00" || v == "0001-01-01T00:00:00Z" || v == "00000000-0000-0000-0000-000000000000" + case []any: + return len(v) == 0 + case map[string]any: + for _, m := range v { + if !jsonEmpty(m) { + return false + } + } + + return true + default: + return false + } +} + +// jsonInferredTag reports whether the object a lacks the member name, which b holds as a tag: the name of a member both +// hold. A tagged object may leave its tag out, and decoding it infers the tag from the member that is set, which +// encoding then writes. +func jsonInferredTag(a, b map[string]any, name string) bool { + if _, ok := a[name]; ok { + return false + } + + tag, ok := b[name].(string) + if !ok { + return false + } + + _, inA := a[tag] + _, inB := b[tag] + + return inA && inB +} + +// jsonSameButTags reports whether the JSON values a and b, decoded into any, are the same, but for tags either leaves +// out (see jsonInferredTag): the request a call sends for one that was recorded without them. +func jsonSameButTags(a, b any) bool { + switch a := a.(type) { + case map[string]any: + b, ok := b.(map[string]any) + if !ok { + return false + } + + for name := range a { + if _, ok := b[name]; !ok && !jsonInferredTag(b, a, name) { + return false + } + } + + for name, vb := range b { + va, ok := a[name] + if !ok && !jsonInferredTag(a, b, name) || ok && !jsonSameButTags(va, vb) { + return false + } + } + + return true + case []any: + b, ok := b.([]any) + if !ok || len(a) != len(b) { + return false + } + + for i := range a { + if !jsonSameButTags(a[i], b[i]) { + return false + } + } + + return true + default: + return a == b + } +} diff --git a/vendor/github.com/go-api-libs/api/apitest/replay.go b/vendor/github.com/go-api-libs/api/apitest/replay.go new file mode 100644 index 00000000..f6b8e997 --- /dev/null +++ b/vendor/github.com/go-api-libs/api/apitest/replay.go @@ -0,0 +1,97 @@ +package apitest + +import ( + "bytes" + "context" + "encoding/json/v2" + "io" + "net/http" + "testing" + + "github.com/MarkRosemaker/cassette" +) + +// optionalAuthKey marks the context of a call to an operation whose credentials are optional. +type optionalAuthKey struct{} + +// OptionalAuth is ctx for a call to an operation whose credentials are optional, whose recording may lack them, see +// [Replay]. +func OptionalAuth(ctx context.Context) context.Context { + return context.WithValue(ctx, optionalAuthKey{}, true) +} + +// Replay is a transport that answers calls with the interactions recorded in the file at path. Every call must be the +// next recording, with its headers as recorded but the User-Agent, which names whatever tool made the recording; a +// call marked with [OptionalAuth] may have credentials its recording lacks. A request body may hold a tag its +// recording leaves out, which a client fills in (see jsonSameButTags). The test fails if a recording was never called. +func Replay(t testing.TB, path string) http.RoundTripper { + t.Helper() + + interactions, err := cassette.InteractionsReadFile(path) + if err != nil { + t.Fatal(err) + } + + match := cassette.MatchRequest( + cassette.CompareHeaders("User-Agent"), + cassette.OptionalAuthorization(func(req *http.Request) bool { return req.Context().Value(optionalAuthKey{}) != nil }), + ) + + rec := cassette.Replay(interactions, cassette.InOrder(), cassette.WithMatcher(func(req *http.Request, ia cassette.Request) error { + err := match(req, ia) + if err == nil || req.Body == nil { + return err + } + + // matching drained the body and put it back to be read again + sent, rerr := io.ReadAll(req.Body) + if rerr != nil { + return err + } + + req.Body = io.NopCloser(bytes.NewReader(sent)) + + // the body is the one recorded but for the tags the client fills in: match the rest as it is sent + var a, b any + if json.Unmarshal(ia.Body, &a) != nil || json.Unmarshal(sent, &b) != nil || !jsonSameButTags(a, b) { + return err + } + + ia.Body = sent + + return match(req, ia) + })) + + t.Cleanup(func() { + if unused := rec.Unused(); len(unused) > 0 { + t.Errorf("%d recorded interactions were never replayed, the first: %s %s", len(unused), unused[0].Request.Method, &unused[0].Request.URL) + } + }) + + return rec +} + +// LastBody passes requests on to Next, and keeps the body of the last response, so that a test can compare what a call +// decoded with what was sent, see [DecodedAsSent]. +type LastBody struct { + Next http.RoundTripper + Body []byte +} + +// RoundTrip implements [http.RoundTripper]. +func (l *LastBody) RoundTrip(req *http.Request) (*http.Response, error) { + rsp, err := l.Next.RoundTrip(req) + if err != nil { + return nil, err + } + + defer rsp.Body.Close() + + if l.Body, err = io.ReadAll(rsp.Body); err != nil { + return nil, err + } + + rsp.Body = io.NopCloser(bytes.NewReader(l.Body)) + + return rsp, nil +} diff --git a/vendor/github.com/go-api-libs/api/devtool.json b/vendor/github.com/go-api-libs/api/devtool.json index fd311065..0da670bd 100644 --- a/vendor/github.com/go-api-libs/api/devtool.json +++ b/vendor/github.com/go-api-libs/api/devtool.json @@ -1,6 +1,6 @@ { - "coverage": 90.9, - "devtoolVersion": "v0.0.0-20261112182037-b3e66cbb05d2", + "coverage": 89.8, + "devtoolVersion": "v0.0.0-20261112195051-ee9871757373", "kind": "apilib", "tools": { "golangci-lint": "v2.15.0", diff --git a/vendor/modules.txt b/vendor/modules.txt index 5b256d46..ac3ac6c4 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -40,9 +40,10 @@ github.com/MarkRosemaker/yaml2json # github.com/ettle/strcase v0.2.0 ## explicit; go 1.12 github.com/ettle/strcase -# github.com/go-api-libs/api v0.0.0-20261112190634-bde25c574d51 +# github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 ## explicit; go 1.27 github.com/go-api-libs/api +github.com/go-api-libs/api/apitest github.com/go-api-libs/api/server github.com/go-api-libs/api/union # github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971 From 33d0ac2651f8b49c2f1a808b33cfa8acaff0b0e0 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:04:03 +0000 Subject: [PATCH 2/2] chore: go-api-libs/api at master, which holds package apitest Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019QCb1AfnATvpBQCH3PrX7Y --- go.mod | 2 +- go.sum | 4 ++-- vendor/modules.txt | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/go.mod b/go.mod index 3bcbbc50..5ab1f898 100644 --- a/go.mod +++ b/go.mod @@ -11,7 +11,7 @@ require ( github.com/MarkRosemaker/openapi-flatten v0.0.0-20261112181512-46b453b2a7e8 github.com/MarkRosemaker/ordmap v0.0.0-20261112181350-ce24cb2b5e89 github.com/ettle/strcase v0.2.0 - github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 + github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 github.com/spf13/afero v1.15.0 mvdan.cc/gofumpt v0.12.0 ) diff --git a/go.sum b/go.sum index d4c91d43..678da541 100644 --- a/go.sum +++ b/go.sum @@ -30,8 +30,8 @@ github.com/MarkRosemaker/yaml2json v0.0.0-20261109120453-1b901dbf7e8f h1:Z3r19i6 github.com/MarkRosemaker/yaml2json v0.0.0-20261109120453-1b901dbf7e8f/go.mod h1:DxNA9SDFrzw+RHsnxjIxjUzHy0I4+3hZg7R13u3SBvE= github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= -github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 h1:RFKpEFiUdwh2G9RVUyopW9pskMNkMJXNn+Z+u727Bww= -github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622/go.mod h1:nJuMPHY4qEhbWBvTdDFOPK+LC3Uo8RM9kPhIQfzXv4s= +github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 h1:jHic3tOf6/vtJHZKB5niLbzXcXwl1kcIq1424Wc9xJc= +github.com/go-api-libs/api v0.0.0-20261113130130-277524695333/go.mod h1:nJuMPHY4qEhbWBvTdDFOPK+LC3Uo8RM9kPhIQfzXv4s= github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971 h1:SAGMMY0sujlZjekNUL4cvoACSOKdOj55CrikCTFzAdU= github.com/go-api-libs/types v0.0.0-20261109120451-6cd1daca4971/go.mod h1:z0z6qkZc45AvoRnluq7PkVSlSSF25sT0diJ+vrubYfA= github.com/go-quicktest/qt v1.102.0 h1:HSQxCeh5YZH3EL3W39ixjtyaEhcWSXQHtHnMBzSs474= diff --git a/vendor/modules.txt b/vendor/modules.txt index ac3ac6c4..d97332c4 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -40,7 +40,7 @@ github.com/MarkRosemaker/yaml2json # github.com/ettle/strcase v0.2.0 ## explicit; go 1.12 github.com/ettle/strcase -# github.com/go-api-libs/api v0.0.0-20261113110337-1a210da70622 +# github.com/go-api-libs/api v0.0.0-20261113130130-277524695333 ## explicit; go 1.27 github.com/go-api-libs/api github.com/go-api-libs/api/apitest