From cfb8ad09a5a10873eb7f4c193b79eaa30a342d9a Mon Sep 17 00:00:00 2001 From: Claude Code Date: Fri, 27 Nov 2026 17:32:52 -0500 Subject: [PATCH] Add client options, WARN/TRACE/FATAL log levels and enum parsers NewClient and NewReportingClient take variadic options after the authentication option. WithResponseMiddleware adds a hook that is called with every response and its body before the client's own error handling; hooks are chained and the first error stops the chain. The same hook serves the Resty-based methods and the generated client. ParseLaunchMode, ParseItemType and ParseStatus convert user input to the typed values. Part of #27 Co-Authored-By: Claude Fable 5.2 --- .claude/skills/reportportal/SKILL.md | 4 + AGENTS.md | 2 + README.md | 20 +++ pkg/gorp/client.go | 20 ++- pkg/gorp/model_api.go | 5 +- pkg/gorp/model_parse.go | 53 ++++++++ pkg/gorp/model_parse_test.go | 86 ++++++++++++ pkg/gorp/options.go | 107 +++++++++++++++ pkg/gorp/options_test.go | 190 +++++++++++++++++++++++++++ pkg/gorp/reporting_client.go | 16 ++- 10 files changed, 484 insertions(+), 19 deletions(-) create mode 100644 pkg/gorp/model_parse.go create mode 100644 pkg/gorp/model_parse_test.go create mode 100644 pkg/gorp/options.go create mode 100644 pkg/gorp/options_test.go diff --git a/.claude/skills/reportportal/SKILL.md b/.claude/skills/reportportal/SKILL.md index f428af1..df06a4b 100644 --- a/.claude/skills/reportportal/SKILL.md +++ b/.claude/skills/reportportal/SKILL.md @@ -391,6 +391,10 @@ func WithApiKeyAuth(ctx context.Context, apiKey string) ClientOption func WithPasswordOwnerGrantAuth(ctx context.Context, cfg *oauth2.Config, username, password string) ClientOption ``` +Both constructors also take optional `gorp.Option` values after the auth option, e.g. +`gorp.WithResponseMiddleware(func(resp *http.Response, body []byte) error)`: called with every response +before the client's own error handling; middlewares are chained and the first error stops the chain. + --- ## Statuses diff --git a/AGENTS.md b/AGENTS.md index 63a52c5..b1f1d9f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ A Go CLI tool (`gorp`) and library (`pkg/gorp`) for [ReportPortal](https://repor | File | Contents | |------|----------| | `client.go` | `Client` — embeds generated OpenAPI client + launch helpers; `ClientOption`, `WithApiKeyAuth` | +| `options.go` | `Option` (variadic settings of `NewClient`/`NewReportingClient`), `WithResponseMiddleware` | | `reporting_client.go` | `ReportingClient` — v2 reporting API (launches, test items, logs) via Resty | | `launches.go` | Launch list/merge helpers (Resty, `/api/v1/…`) | | `filters.go` | User-filter lookup for launch queries | @@ -41,6 +42,7 @@ A Go CLI tool (`gorp`) and library (`pkg/gorp`) for [ReportPortal](https://repor | `quality_gate.go` | `ParseQualityGate` from launch metadata | | `multipart.go` | `Multipart` interface + `FileMultipart`/`ReaderMultipart` | | `model_api.go`, `model_enums.go` | Hand-written request/response types, `Statuses`, `TestItemTypes`, `LaunchModes`, log levels | +| `model_parse.go` | `ParseLaunchMode`, `ParseItemType`, `ParseStatus` | ### CLI command tree diff --git a/README.md b/README.md index b7bc454..dec3ed4 100644 --- a/README.md +++ b/README.md @@ -517,6 +517,26 @@ all, err := client.GetAllLaunchesByFilterString(ctx, "my_project", | `gorp.WithApiKeyAuth(ctx, apiKey)` | API key (user token) — recommended | | `gorp.WithPasswordOwnerGrantAuth(ctx, cfg, user, pass)` | OAuth2 resource-owner password grant | +### Client options + +`NewClient` and `NewReportingClient` take optional settings after the authentication helper: + +```go +client := gorp.NewReportingClient(host, project, gorp.WithApiKeyAuth(ctx, apiKey), + gorp.WithResponseMiddleware(func(resp *http.Response, body []byte) error { + slog.Debug("reportportal", "url", resp.Request.URL.Path, "status", resp.StatusCode) + return nil // an error returned here becomes the error of the call + }), +) +``` + +| Option | Description | +|--------|-------------| +| `gorp.WithResponseMiddleware(fn)` | Called with every response and its body, before the client's own error handling. Middlewares are chained in the order they were added; the first error stops the chain | + +`gorp.ParseLaunchMode`, `gorp.ParseItemType` and `gorp.ParseStatus` convert user input (any case) to the +typed values and report an unknown value with an error wrapping `gorp.ErrUnknownValue`. + --- ## Environment Variables diff --git a/pkg/gorp/client.go b/pkg/gorp/client.go index 170b19b..a5b640a 100644 --- a/pkg/gorp/client.go +++ b/pkg/gorp/client.go @@ -8,7 +8,6 @@ import ( "time" "golang.org/x/oauth2" - "resty.dev/v3" "github.com/reportportal/goRP/v5/pkg/openapi" ) @@ -69,26 +68,25 @@ type Client struct { } // NewClient creates new instance of Client -// host - server hostname -// project - name of the project -// apiKey - User Token (see user profile page) -func NewClient(u *url.URL, clientOption ClientOption) *Client { +// u - URL of the server +// clientOption - authentication, see [WithApiKeyAuth] and [WithPasswordOwnerGrantAuth] +// opts - optional settings, see [Option] +func NewClient(u *url.URL, clientOption ClientOption, opts ...Option) *Client { + o := newClientOptions(opts) httpClient := clientOption() - httpResty := resty.NewWithClient(httpClient). - SetBaseURL(u.String()). - AddResponseMiddleware(defaultHTTPErrorHandler) return &Client{ launchClient: &launchClient{ - http: httpResty, + http: o.newResty(httpClient, u.String()), }, - APIClient: newAPIClient(u, httpClient), + APIClient: newAPIClient(u, httpClient, o), } } -func newAPIClient(u *url.URL, httpClient *http.Client) *openapi.APIClient { +func newAPIClient(u *url.URL, httpClient *http.Client, o *clientOptions) *openapi.APIClient { conf := openapi.NewConfiguration() conf.HTTPClient = httpClient conf.Scheme = u.Scheme conf.Host = u.Host + o.configureOpenAPI(conf) return openapi.NewAPIClient(conf) } diff --git a/pkg/gorp/model_api.go b/pkg/gorp/model_api.go index 12ef749..2e924d4 100644 --- a/pkg/gorp/model_api.go +++ b/pkg/gorp/model_api.go @@ -1,10 +1,13 @@ package gorp -// Client constants +// Log levels the server knows by name, from the least to the most severe const ( + LogLevelTrace = "TRACE" LogLevelDebug = "DEBUG" LogLevelInfo = "INFO" + LogLevelWarn = "WARN" LogLevelError = "ERROR" + LogLevelFatal = "FATAL" ) // PAYLOADS diff --git a/pkg/gorp/model_parse.go b/pkg/gorp/model_parse.go new file mode 100644 index 0000000..fe46d3f --- /dev/null +++ b/pkg/gorp/model_parse.go @@ -0,0 +1,53 @@ +package gorp + +import ( + "errors" + "fmt" + "strings" +) + +// ErrUnknownValue is wrapped by the errors of [ParseLaunchMode], [ParseItemType] and [ParseStatus] +var ErrUnknownValue = errors.New("unknown value") + +// ParseLaunchMode converts a string such as "debug" to a [LaunchMode]. +// Case and surrounding spaces are ignored. An unknown value gives an error that wraps [ErrUnknownValue]. +func ParseLaunchMode(s string) (LaunchMode, error) { + return parseEnum("launch mode", s, LaunchModes.Default, LaunchModes.Debug) +} + +// ParseItemType converts a string such as "before_suite" to a [TestItemType]. +// Case and surrounding spaces are ignored. An unknown value gives an error that wraps [ErrUnknownValue]. +func ParseItemType(s string) (TestItemType, error) { + t := TestItemTypes + return parseEnum("test item type", s, + t.Suite, t.Story, t.Test, t.Scenario, t.Step, + t.BeforeClass, t.BeforeGroups, t.BeforeMethod, t.BeforeSuite, t.BeforeTest, + t.AfterClass, t.AfterGroups, t.AfterMethod, t.AfterSuite, t.AfterTest) +} + +// ParseStatus converts a string such as "passed" to a [Status]. +// Case and surrounding spaces are ignored. An unknown value gives an error that wraps [ErrUnknownValue]. +func ParseStatus(s string) (Status, error) { + st := Statuses + return parseEnum("status", s, + st.Passed, st.Failed, st.Stopped, st.Skipped, st.Interrupted, st.Canceled, st.Info, st.Warn) +} + +func parseEnum[T ~string](kind, s string, values ...T) (T, error) { + normalized := strings.ToUpper(strings.TrimSpace(s)) + names := make([]string, 0, len(values)) + for _, v := range values { + if string(v) == normalized { + return v, nil + } + names = append(names, string(v)) + } + + return "", fmt.Errorf( + "%w: %s %q, expected one of %s", + ErrUnknownValue, + kind, + s, + strings.Join(names, ", "), + ) +} diff --git a/pkg/gorp/model_parse_test.go b/pkg/gorp/model_parse_test.go new file mode 100644 index 0000000..1b98616 --- /dev/null +++ b/pkg/gorp/model_parse_test.go @@ -0,0 +1,86 @@ +package gorp + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseLaunchMode(t *testing.T) { + t.Parallel() + + for in, want := range map[string]LaunchMode{ + "DEFAULT": LaunchModes.Default, + "debug": LaunchModes.Debug, + " Debug ": LaunchModes.Debug, + } { + got, err := ParseLaunchMode(in) + require.NoError(t, err, in) + assert.Equal(t, want, got, in) + } + + for _, in := range []string{"", "DEBUGGING", "de bug"} { + got, err := ParseLaunchMode(in) + require.ErrorIs(t, err, ErrUnknownValue, in) + assert.Empty(t, got) + } + _, err := ParseLaunchMode("x") + assert.EqualError(t, err, `unknown value: launch mode "x", expected one of DEFAULT, DEBUG`) +} + +func TestParseItemType(t *testing.T) { + t.Parallel() + + for in, want := range map[string]TestItemType{ + "suite": TestItemTypes.Suite, + "Story": TestItemTypes.Story, + "TEST": TestItemTypes.Test, + "scenario": TestItemTypes.Scenario, + "step": TestItemTypes.Step, + "before_class": TestItemTypes.BeforeClass, + "before_groups": TestItemTypes.BeforeGroups, + "before_method": TestItemTypes.BeforeMethod, + "before_suite": TestItemTypes.BeforeSuite, + "before_test": TestItemTypes.BeforeTest, + "after_class": TestItemTypes.AfterClass, + "after_groups": TestItemTypes.AfterGroups, + "after_method": TestItemTypes.AfterMethod, + "after_suite": TestItemTypes.AfterSuite, + "\tAFTER_TEST": TestItemTypes.AfterTest, + } { + got, err := ParseItemType(in) + require.NoError(t, err, in) + assert.Equal(t, want, got, in) + } + + for _, in := range []string{"", "before-suite", "BEFORESUITE", "launch"} { + _, err := ParseItemType(in) + require.ErrorIs(t, err, ErrUnknownValue, in) + } +} + +func TestParseStatus(t *testing.T) { + t.Parallel() + + for in, want := range map[string]Status{ + "passed": Statuses.Passed, + "Failed": Statuses.Failed, + "STOPPED": Statuses.Stopped, + "skipped": Statuses.Skipped, + "interrupted": Statuses.Interrupted, + "cancelled": Statuses.Canceled, //nolint:misspell // the server's spelling + "info": Statuses.Info, + "warn": Statuses.Warn, + } { + got, err := ParseStatus(in) + require.NoError(t, err, in) + assert.Equal(t, want, got, in) + } + + // "canceled" is not what the server calls it, IN_PROGRESS is not for clients to set + for _, in := range []string{"", "canceled", "IN_PROGRESS", "ok"} { + _, err := ParseStatus(in) + require.ErrorIs(t, err, ErrUnknownValue, in) + } +} diff --git a/pkg/gorp/options.go b/pkg/gorp/options.go new file mode 100644 index 0000000..0d30c88 --- /dev/null +++ b/pkg/gorp/options.go @@ -0,0 +1,107 @@ +package gorp + +import ( + "net/http" + + "resty.dev/v3" + + "github.com/reportportal/goRP/v5/pkg/openapi" +) + +// Option configures a [Client] or a [ReportingClient]. Pass options to [NewClient] and +// [NewReportingClient] after the authentication [ClientOption]. +type Option func(*clientOptions) + +// ResponseMiddleware is called for every HTTP response a client receives, successful or not, +// with the response and its body. The body argument is the place to read the body from: +// resp.Body may be consumed already. A returned error becomes the error of the API call. +// +// It has the shape of [openapi.ResponseMiddlewareFunction], so one function serves the Resty-based +// methods and the generated client. +type ResponseMiddleware func(resp *http.Response, body []byte) error + +type clientOptions struct { + responseMiddlewares []ResponseMiddleware +} + +func newClientOptions(opts []Option) *clientOptions { + o := &clientOptions{} + for _, opt := range opts { + if opt != nil { + opt(o) + } + } + + return o +} + +// WithResponseMiddleware adds a [ResponseMiddleware]. Middlewares are chained, not replaced: they run +// in the order they were added and before the client's own error handling, which stays in place. +// The first error stops the chain, so a middleware that returns an error also decides what the caller +// gets instead of the client's own error for a failed response. +// +// Typical uses are logging, metrics and mapping particular responses to errors of your own. +// A response that never arrived (network error, canceled context) doesn't reach the middlewares. +func WithResponseMiddleware(m ResponseMiddleware) Option { + return func(o *clientOptions) { + if m != nil { + o.responseMiddlewares = append(o.responseMiddlewares, m) + } + } +} + +// runResponseMiddlewares runs the user's middlewares and stops at the first error. +func (o *clientOptions) runResponseMiddlewares(resp *http.Response, body []byte) error { + for _, m := range o.responseMiddlewares { + if err := m(resp, body); err != nil { + return err + } + } + + return nil +} + +// newResty builds the Resty client all hand-written methods use. +func (o *clientOptions) newResty(httpClient *http.Client, baseURL string) *resty.Client { + c := resty.NewWithClient(httpClient).SetBaseURL(baseURL) + if len(o.responseMiddlewares) == 0 { + return c.AddResponseMiddleware(defaultHTTPErrorHandler) + } + + // Resty hands the body of a successfully parsed response over to the result object; + // buffering keeps it readable for the middlewares as well. + c.SetResponseBodyUnlimitedReads(true) + + // Resty runs every response middleware even after one of them failed, so the user's + // middlewares and the error handler are one middleware: the first error wins. + return c.AddResponseMiddleware(func(c *resty.Client, rs *resty.Response) error { + if rs.RawResponse != nil { + if err := o.runResponseMiddlewares(rs.RawResponse, rs.Bytes()); err != nil { + return err + } + } + + return defaultHTTPErrorHandler(c, rs) + }) +} + +// configureOpenAPI applies the options to the configuration of the generated client. +// The generated client has a single response middleware, so the user's middlewares are put +// in front of the one the configuration already has. +func (o *clientOptions) configureOpenAPI(conf *openapi.Configuration) { + if len(o.responseMiddlewares) == 0 { + return + } + + own := conf.ResponseMiddleware + conf.ResponseMiddleware = func(resp *http.Response, body []byte) error { + if err := o.runResponseMiddlewares(resp, body); err != nil { + return err + } + if own != nil { + return own(resp, body) + } + + return nil + } +} diff --git a/pkg/gorp/options_test.go b/pkg/gorp/options_test.go new file mode 100644 index 0000000..13244c2 --- /dev/null +++ b/pkg/gorp/options_test.go @@ -0,0 +1,190 @@ +package gorp + +import ( + "errors" + "net/http" + "net/http/httptest" + "net/url" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/reportportal/goRP/v5/pkg/openapi" +) + +// seenResponses records what a response middleware was called with +type seenResponses struct { + mu sync.Mutex + calls []string + bodies []string +} + +func (s *seenResponses) middleware(name string) ResponseMiddleware { + return func(resp *http.Response, body []byte) error { + s.mu.Lock() + defer s.mu.Unlock() + s.calls = append( + s.calls, + name+" "+resp.Request.Method+" "+resp.Request.URL.Path+" "+resp.Status, + ) + s.bodies = append(s.bodies, string(body)) + + return nil + } +} + +func jsonServer(t *testing.T, status int, body string) *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) + _, _ = w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + + return srv +} + +func TestResponseMiddlewareReportingClient(t *testing.T) { + t.Parallel() + + srv := jsonServer(t, http.StatusCreated, `{"id":"launch-1"}`) + var seen seenResponses + client := NewReportingClient(srv.URL, "prj", WithApiKeyAuth(t.Context(), "key"), + WithResponseMiddleware(seen.middleware("first")), + nil, // a nil option is ignored + WithResponseMiddleware(nil), + WithResponseMiddleware(seen.middleware("second")), + ) + + rs, err := client.StartLaunch(t.Context(), &openapi.StartLaunchRQ{Name: "n"}) + require.NoError(t, err) + // the middlewares read the body and the client still decodes it + assert.Equal(t, "launch-1", rs.GetId()) + assert.Equal(t, []string{ + "first POST /api/v2/prj/launch 201 Created", + "second POST /api/v2/prj/launch 201 Created", + }, seen.calls) + assert.Equal(t, []string{`{"id":"launch-1"}`, `{"id":"launch-1"}`}, seen.bodies) +} + +func TestResponseMiddlewareKeepsErrorHandling(t *testing.T) { + t.Parallel() + + const body = `{"errorCode":4001,"message":"Incorrect Request"}` + srv := jsonServer(t, http.StatusBadRequest, body) + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + var seen seenResponses + client := NewClient( + u, + WithApiKeyAuth(t.Context(), "key"), + WithResponseMiddleware(seen.middleware("mw")), + ) + + // Resty-based method: the middleware sees the failed response, the client still reports its own error + _, err = client.GetLaunchesByFilterString(t.Context(), "prj", "") + var httpErr *HTTPError + require.ErrorAs(t, err, &httpErr) + assert.Equal(t, http.StatusBadRequest, httpErr.StatusCode) + assert.Equal(t, body, httpErr.Response) + + // generated client: same middleware, the generated error stays + _, _, err = client.LaunchAPI.GetProjectLaunches(t.Context(), "prj").Execute() + var apiErr *openapi.GenericOpenAPIError + require.ErrorAs(t, err, &apiErr) + assert.Equal(t, body, string(apiErr.Body())) + + assert.Equal(t, []string{ + "mw GET /api/v1/prj/launch 400 Bad Request", + "mw GET /api/v1/prj/launch 400 Bad Request", + }, seen.calls) + assert.Equal(t, []string{body, body}, seen.bodies) +} + +func TestResponseMiddlewareErrorStopsChain(t *testing.T) { + t.Parallel() + + srv := jsonServer(t, http.StatusNotFound, `{"errorCode":4041,"message":"not found"}`) + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + errMine := errors.New("mine") + var seen seenResponses + client := NewClient(u, WithApiKeyAuth(t.Context(), "key"), + WithResponseMiddleware(func(*http.Response, []byte) error { return errMine }), + WithResponseMiddleware(seen.middleware("never")), + ) + + _, err = client.GetLaunchesByFilterString(t.Context(), "prj", "") + require.ErrorIs(t, err, errMine) + var httpErr *HTTPError + assert.NotErrorAs(t, err, &httpErr, "the middleware's error replaces the client's own") + + _, _, err = client.LaunchAPI.GetProjectLaunches(t.Context(), "prj").Execute() + require.ErrorIs(t, err, errMine) + + assert.Empty(t, seen.calls) +} + +func TestResponseMiddlewareCanFailSuccessfulResponse(t *testing.T) { + t.Parallel() + + srv := jsonServer(t, http.StatusOK, `{"id":"x"}`) + errMine := errors.New("mine") + client := NewReportingClient(srv.URL, "prj", WithApiKeyAuth(t.Context(), "key"), + WithResponseMiddleware(func(*http.Response, []byte) error { return errMine })) + + _, err := client.StartLaunch(t.Context(), &openapi.StartLaunchRQ{Name: "n"}) + assert.ErrorIs(t, err, errMine) +} + +// Constructors must keep compiling for callers that pass no options. +func TestConstructorsWithoutOptions(t *testing.T) { + t.Parallel() + + srv := jsonServer(t, http.StatusOK, `{"id":"x"}`) + u, err := url.Parse(srv.URL) + require.NoError(t, err) + + assert.NotNil(t, NewClient(u, WithApiKeyAuth(t.Context(), "key"))) + rs, err := NewReportingClient(srv.URL, "prj", WithApiKeyAuth(t.Context(), "key")). + StartLaunch(t.Context(), &openapi.StartLaunchRQ{Name: "n"}) + require.NoError(t, err) + assert.Equal(t, "x", rs.GetId()) +} + +// The generated client has one response middleware: the user's ones go in front of it, they don't replace it. +func TestConfigureOpenAPIKeepsExistingMiddleware(t *testing.T) { + t.Parallel() + + errOwn := errors.New("own") + var calls []string + newConf := func() *openapi.Configuration { + conf := openapi.NewConfiguration() + conf.ResponseMiddleware = func(*http.Response, []byte) error { + calls = append(calls, "own") + + return errOwn + } + + return conf + } + + conf := newConf() + newClientOptions(nil).configureOpenAPI(conf) + require.ErrorIs(t, conf.ResponseMiddleware(nil, nil), errOwn, "no options: left as is") + + calls = nil + conf = newConf() + newClientOptions([]Option{WithResponseMiddleware(func(*http.Response, []byte) error { + calls = append(calls, "user") + + return nil + })}).configureOpenAPI(conf) + require.ErrorIs(t, conf.ResponseMiddleware(nil, nil), errOwn) + assert.Equal(t, []string{"user", "own"}, calls) +} diff --git a/pkg/gorp/reporting_client.go b/pkg/gorp/reporting_client.go index 4bdd4df..4d7f2e2 100644 --- a/pkg/gorp/reporting_client.go +++ b/pkg/gorp/reporting_client.go @@ -19,16 +19,18 @@ type ReportingClient struct { } // NewReportingClient creates new instance of ReportingClient -// host - server hostname +// host - URL of the server // project - name of the project -// apiKey - User Token (see user profile page) -func NewReportingClient(host, project string, clientOption ClientOption) *ReportingClient { - http := resty.NewWithClient(clientOption()). - SetBaseURL(host). - AddResponseMiddleware(defaultHTTPErrorHandler) +// clientOption - authentication, see [WithApiKeyAuth] and [WithPasswordOwnerGrantAuth] +// opts - optional settings, see [Option] +func NewReportingClient( + host, project string, + clientOption ClientOption, + opts ...Option, +) *ReportingClient { return &ReportingClient{ project: project, - http: http, + http: newClientOptions(opts).newResty(clientOption(), host), } }