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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .claude/skills/reportportal/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ 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 |
| `oauth2.go` | Password-grant token source, `WithPasswordOwnerGrantAuth` |
| `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

Expand Down
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 9 additions & 11 deletions pkg/gorp/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"golang.org/x/oauth2"
"resty.dev/v3"

"github.com/reportportal/goRP/v5/pkg/openapi"
)
Expand Down Expand Up @@ -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)
}
5 changes: 4 additions & 1 deletion pkg/gorp/model_api.go
Original file line number Diff line number Diff line change
@@ -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
Expand Down
53 changes: 53 additions & 0 deletions pkg/gorp/model_parse.go
Original file line number Diff line number Diff line change
@@ -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, ", "),
)
}
86 changes: 86 additions & 0 deletions pkg/gorp/model_parse_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
107 changes: 107 additions & 0 deletions pkg/gorp/options.go
Original file line number Diff line number Diff line change
@@ -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
}
}
Loading
Loading