From b1769f057d07942ae90a4e5d93e660e654fa9d9a Mon Sep 17 00:00:00 2001 From: Claude Code Date: Thu, 26 Nov 2026 21:07:38 -0500 Subject: [PATCH 1/2] report test2json: report tests as STEPs, handle skips, send system attributes ReportPortal counts execution statistics and assigns "To Investigate" only for STEP items without children. test2json reported every test as TEST, so its launches had no statistics at all, and subtests were flat next to their parent. - Report each test as a STEP and nest subtests under their running parent test, so every test case is counted exactly once. A test that already finished or is paused in t.Parallel() is never taken as the parent of a test named like it. - Handle the skip action: t.Skip() tests are SKIPPED instead of taking the package status. --skipped-issue (default true, as rp.skipped.issue in the Java agents) can mark them No Defect, and the launch carries the skippedIssue system attribute. - Send the agent, os and go system attributes (new pkg/gorp helpers SystemAttributes, SkippedIssueAttribute, NotIssue). - Print the launch link returned by the server with --print-launch-uuid. - Send SaveLog as a one-entry multipart batch: JSON on /log is deprecated in ReportPortal 6.x. - e2e: assert launch statistics, subtest nesting and skipped status. Fixes #22, #23, #24, #25 Co-Authored-By: Claude Opus 5.5 --- .claude/skills/reportportal/SKILL.md | 13 +- AGENTS.md | 10 +- README.md | 11 +- e2e/reporting_test.go | 63 ++++ internal/commands/actions_test.go | 1 + internal/commands/report.go | 51 ++- internal/commands/report_hierarchy_test.go | 348 ++++++++++++++++++++ internal/commands/report_robustness_test.go | 14 +- internal/commands/report_test.go | 9 +- internal/commands/reporter.go | 129 ++++++-- pkg/gorp/attributes.go | 47 +++ pkg/gorp/attributes_test.go | 48 +++ pkg/gorp/reporting_client.go | 11 +- pkg/gorp/reporting_client_test.go | 12 +- 14 files changed, 701 insertions(+), 66 deletions(-) create mode 100644 internal/commands/report_hierarchy_test.go create mode 100644 pkg/gorp/attributes.go create mode 100644 pkg/gorp/attributes_test.go diff --git a/.claude/skills/reportportal/SKILL.md b/.claude/skills/reportportal/SKILL.md index f428af1..a3ffbda 100644 --- a/.claude/skills/reportportal/SKILL.md +++ b/.claude/skills/reportportal/SKILL.md @@ -238,11 +238,20 @@ go test -json ./... | gorp report test2json --quality-gate-check | `--launchName` | `-ln` | `LAUNCH_NAME` | `"gorp launch"` | Launch name | | `--reportEmptyPkg` | `-ep` | `REPORT_EMPTY_PKG` | `false` | Report packages with no test files as a launch item | | `--attr` | `-a` | | | Launch attribute `key:value` or `value` (repeatable) | -| `--print-launch-uuid` | | | `false` | Print the launch UUID after reporting completes | +| `--skipped-issue` | | `SKIPPED_ISSUE` | `true` | Skipped tests are "To Investigate" (`true`) or "No Defect" (`false`) | +| `--print-launch-uuid` | | | `false` | Print the launch UUID and link after reporting completes | | `--quality-gate-check` | `-qgc` | `QUALITY_GATE_CHECK` | `false` | Poll the quality gate after reporting; exits **10** on non-`PASSED` status | | `--quality-gate-timeout` | `-qgt` | `QUALITY_GATE_TIMEOUT` | `1m` | Shared with `quality-gate check` | | `--quality-gate-check-interval` | `-qgci` | `QUALITY_GATE_CHECK_INTERVAL` | `3s` | Shared with `quality-gate check` | +### Reported hierarchy + +Each package is a `SUITE`, each test a `STEP`, and each subtest (`t.Run`) a `STEP` nested under its +parent test. ReportPortal counts executions only for `STEP` items without children, so every test case is +counted once (a test with subtests is not counted itself). `t.Skip` tests are `SKIPPED`; they are +"To Investigate" unless `--skipped-issue=false`. The launch gets the system attributes `agent`, `os`, `go` +and `skippedIssue`. With `--print-launch-uuid` the launch link is printed as well (`ReportPortal Launch: `). + ### Go 1.27+ output handling Starting with Go 1.27, `go test -json` annotates `"action":"output"` events with an `OutputType` @@ -257,7 +266,7 @@ field: `"frame"` (test framing like `=== RUN`/`--- FAIL:`), `"error"` (first chu so older Go toolchains still work. No flags are needed to enable this — it's automatic based on whether the incoming stream has -`OutputType` set. See `internal/commands/report.go` (`logLevelForOutputType`, `shouldMergeOutput`) +`OutputType` set. See `internal/commands/reporter.go` (`logLevelForOutputType`, `shouldMergeOutput`) and `internal/commands/report_log_test.go` for the exact behavior and test fixtures. --- diff --git a/AGENTS.md b/AGENTS.md index 63a52c5..c950eb4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,8 @@ A Go CLI tool (`gorp`) and library (`pkg/gorp`) for [ReportPortal](https://repor |------|----------| | `commands.go` | `init`, config loading (`~/.gorp`), client builders (`buildClient`, `buildReportingClient`) | | `launch.go` | `launch list`, `launch merge` | -| `report.go` | `report test2json` pipeline (test2json event stream → RP); `reporter`/`testEvent` types | +| `report.go` | `report test2json` command: flags, input scanning, feeding events to the reporter | +| `reporter.go` | `reporter`/`testEvent` types: test2json events → launch, `SUITE` per package, `STEP` per test, subtests nested under their parent | | `report_steps.go` | Atomic report commands: `start-launch`, `start-test`, `log`, `finish-test`, `finish-launch` | | `quality_gate.go` | `quality-gate check` (polls launch metadata until QG resolves) | | `util.go` | Shared CLI helpers (config file path, validation, stdin checks) | @@ -39,6 +40,7 @@ A Go CLI tool (`gorp`) and library (`pkg/gorp`) for [ReportPortal](https://repor | `filters.go` | User-filter lookup for launch queries | | `oauth2.go` | Password-grant token source, `WithPasswordOwnerGrantAuth` | | `quality_gate.go` | `ParseQualityGate` from launch metadata | +| `attributes.go` | `SystemAttributes` (agent/os/go), `SkippedIssueAttribute`, `NotIssue` | | `multipart.go` | `Multipart` interface + `FileMultipart`/`ReaderMultipart` | | `model_api.go`, `model_enums.go` | Hand-written request/response types, `Statuses`, `TestItemTypes`, `LaunchModes`, log levels | @@ -121,7 +123,9 @@ The suite skips itself when no credentials are configured. - Quality gate polling uses a ticker (`time.NewTicker`) — the channel must be selected on, never `default`. The caller's `ctx` must be forwarded into each poll iteration. A failed/non-PASSED quality gate exits with **exit code 10** (`cli.Exit(..., 10)` in `quality_gate.go`); this is depended on by CI pipelines — do not change it casually. - Log batch goroutines inside the `test2json` reporter are managed with `errgroup.Group` (not `sync.WaitGroup`). Errors surface at `errGroup.Wait()` in `receive()`. - `pkg/openapi/` is regenerated from `openapi-modified.json`. `openapi-modified.json` is a git-ignored derived file: never edit it, change `reportportal-api-docs.json` or `scripts/openapi-preprocess.jq` instead. -- `report test2json` parses `go test -json` output (see `internal/commands/report.go`'s `testEvent` struct). As of **Go 1.27**, `test2json` annotates `"action":"output"` events with an `OutputType` field (`"frame"`, `"error"`, `"error-continue"`, or blank) and `"action":"fail"` events with `FailedBuild` when the failure was a build failure. The repo's `testEvent` struct captures both fields; `logLevelForOutputType` promotes `error`/`error-continue` output to `ERROR`-level RP logs, and `shouldMergeOutput` merges `error-continue` (or, for pre-1.27 streams with no `OutputType`, tab-indented) chunks into the previous log entry. `FailedBuild` is parsed but not currently acted on. See `report.go` and `report_log_test.go` for the full logic and test coverage. **Note:** despite the pre-existing fields (`time`, `action`, etc.) being tagged with lowercase `json:"..."` names while `OutputType`/`FailedBuild` use exact-case tags, `encoding/json.Unmarshal`'s case-insensitive fallback makes both work correctly against the real (PascalCase) `go test -json` wire format — this is a cosmetic inconsistency, not a bug. +- `report test2json` parses `go test -json` output (see `internal/commands/reporter.go`'s `testEvent` struct). As of **Go 1.27**, `test2json` annotates `"action":"output"` events with an `OutputType` field (`"frame"`, `"error"`, `"error-continue"`, or blank) and `"action":"fail"` events with `FailedBuild` when the failure was a build failure. The repo's `testEvent` struct captures both fields; `logLevelForOutputType` promotes `error`/`error-continue` output to `ERROR`-level RP logs, and `shouldMergeOutput` merges `error-continue` (or, for pre-1.27 streams with no `OutputType`, tab-indented) chunks into the previous log entry. `FailedBuild` is parsed but not currently acted on. See `reporter.go` and `report_log_test.go` for the full logic and test coverage. **Note:** despite the pre-existing fields (`time`, `action`, etc.) being tagged with lowercase `json:"..."` names while `OutputType`/`FailedBuild` use exact-case tags, `encoding/json.Unmarshal`'s case-insensitive fallback makes both work correctly against the real (PascalCase) `go test -json` wire format — this is a cosmetic inconsistency, not a bug. +- `report test2json` reports tests as `STEP` items (subtests nested under their parent `STEP`), not `TEST`: ReportPortal counts execution statistics and assigns "To Investigate" only for `STEP` items without children. Don't switch them back to `TEST`. +- `ReportingClient.SaveLog` sends a one-entry multipart batch: a plain JSON body on `/log` is deprecated in ReportPortal 6.x. - `Statuses.Canceled` (Go identifier, American spelling) serializes to the string `"CANCELLED"` (British spelling, matching the ReportPortal API) — don't "fix" the string value to match the identifier. - Generated types use long fully-qualified names (`ComEpamReportportal...`); short names (`StartLaunchRQ`, `PageMetadata`, …) are type aliases kept for backward compatibility in `scripts/openapi-compat/compat.go.tmpl`, which `task generate-openapi-client` copies to `pkg/openapi/compat.go`. If a regenerated spec renames a type, `go build` fails in `compat.go` — fix the template. An alias must point to the type with the same meaning, not just one that compiles: e.g. `LaunchResource` is the reporting model, while launch list/get endpoints return `LaunchViewModel` / `PageLaunchViewModel`. @@ -145,4 +149,4 @@ Before considering a change done: 2. `task test` (or `go test -cover ./...` if Docker/Task aren't available) 3. `task e2e` when the change affects what is sent to ReportPortal (needs credentials, writes to the configured project) 4. `task lint` (or `golangci-lint run ./...` if you have it installed locally with the pinned config) -5. For anything touching `report test2json` / `internal/commands/report.go`: generate real `go test -json` output from the installed Go toolchain and diff its shape against the `testEvent` struct and `report_log_test.go` fixtures rather than relying on release notes alone — Go's JSON stream format is a better source of truth than prose docs. +5. For anything touching `report test2json` / `internal/commands/report.go` / `reporter.go`: generate real `go test -json` output from the installed Go toolchain and diff its shape against the `testEvent` struct and `report_log_test.go` fixtures rather than relying on release notes alone — Go's JSON stream format is a better source of truth than prose docs. diff --git a/README.md b/README.md index b7bc454..b9e0408 100644 --- a/README.md +++ b/README.md @@ -236,12 +236,18 @@ go test -json ./... | gorp report test2json --quality-gate-check | `--file` | `-f` | `FILE` | stdin | Input file (test2json format). Reads stdin if omitted. | | `--launchName` | `--ln` | `LAUNCH_NAME` | `gorp launch` | Launch name in ReportPortal | | `--attr` | `-a` | | | Launch attribute, format `key:value` or `value`. Repeatable. | -| `--reportEmptyPkg` | `--ep` | `REPORT_EMPTY_PKG` | `false` | Report packages with no test cases | -| `--print-launch-uuid` | | | `false` | Print `ReportPortal Launch UUID: ` to stdout after reporting | +| `--reportEmptyPkg` | `--ep` | `REPORT_EMPTY_PKG` | `false` | Report packages with no test files | +| `--skipped-issue` | | `SKIPPED_ISSUE` | `true` | Whether skipped tests are "To Investigate" (`true`, ReportPortal's default) or "No Defect" (`false`) | +| `--print-launch-uuid` | | | `false` | Print `ReportPortal Launch UUID: ` and `ReportPortal Launch: ` to stdout after reporting | | `--quality-gate-check` | `--qgc` | `QUALITY_GATE_CHECK` | `false` | Poll for quality gate result after reporting; exits `10` on failure | | `--quality-gate-timeout` | `--qgt` | `QUALITY_GATE_TIMEOUT` | `1m` | Maximum time to wait for quality gate | | `--quality-gate-check-interval` | `--qgci` | `QUALITY_GATE_CHECK_INTERVAL` | `3s` | How often to poll for quality gate status | +Each package is a `SUITE`. Each test is a `STEP`, and a subtest (`t.Run`) is a `STEP` nested under its parent test, +so ReportPortal counts every test case once: a test with subtests is not counted itself. Tests skipped with +`t.Skip` are reported as `SKIPPED`. The launch carries the system attributes `agent` (`gorp|`), `os`, `go` +and `skippedIssue`. With `--print-launch-uuid`, the launch link is printed too, as `ReportPortal Launch: `. + The launch finishes as `FAILED` if any test or package failed, otherwise `PASSED`. If the run is interrupted (Ctrl-C, `SIGTERM`) or the input stream breaks midway, items that are still running are finished as `INTERRUPTED`, followed by the launch, so nothing is left `IN_PROGRESS`. A second Ctrl-C terminates immediately. @@ -530,6 +536,7 @@ all, err := client.GetAllLaunchesByFilterString(ctx, "my_project", | `LAUNCH_NAME` | `--launchName` | Launch name for `report test2json` | | `FILE` | `--file` | Input file for `report test2json` | | `REPORT_EMPTY_PKG` | `--reportEmptyPkg` | Report packages with no tests | +| `SKIPPED_ISSUE` | `--skipped-issue` | Skipped tests are "To Investigate" (`true`) or "No Defect" (`false`) | | `QUALITY_GATE_CHECK` | `--quality-gate-check` | Enable quality gate check after report | | `QUALITY_GATE_TIMEOUT` | `--quality-gate-timeout` | Quality gate poll timeout (e.g. `2m`) | | `QUALITY_GATE_CHECK_INTERVAL` | `--quality-gate-check-interval` | Quality gate poll interval (e.g. `5s`) | diff --git a/e2e/reporting_test.go b/e2e/reporting_test.go index 0f39f93..3b33863 100644 --- a/e2e/reporting_test.go +++ b/e2e/reporting_test.go @@ -8,6 +8,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/reportportal/goRP/v5/pkg/openapi" ) // test2json stream of a package with a passing and a failing test (Go 1.27 OutputType annotations). @@ -88,6 +90,67 @@ func TestReportTest2JSON_PassingRunPassesLaunch(t *testing.T) { assert.Equal(t, "PASSED", launch.GetStatus()) } +// ReportPortal counts executions only for STEP items without children, so this checks the launch +// statistics themselves: subtests are nested under their parent test, the parent is not counted, and a +// skipped test is SKIPPED. +func TestReportTest2JSON_StatisticsSubtestsAndSkip(t *testing.T) { + e := newEnv(t) + name := uniqueName(t) + input := writeFile(t, "events.jsonl", strings.Join([]string{ + `{"Time":"2026-01-01T10:00:00Z","Action":"run","Package":"example.com/e2e","Test":"TestPass"}`, + `{"Time":"2026-01-01T10:00:01Z","Action":"pass","Package":"example.com/e2e","Test":"TestPass"}`, + `{"Time":"2026-01-01T10:00:01Z","Action":"run","Package":"example.com/e2e","Test":"TestSkip"}`, + `{"Time":"2026-01-01T10:00:02Z","Action":"skip","Package":"example.com/e2e","Test":"TestSkip"}`, + `{"Time":"2026-01-01T10:00:02Z","Action":"run","Package":"example.com/e2e","Test":"TestTable"}`, + `{"Time":"2026-01-01T10:00:02Z","Action":"run","Package":"example.com/e2e","Test":"TestTable/ok"}`, + `{"Time":"2026-01-01T10:00:03Z","Action":"pass","Package":"example.com/e2e","Test":"TestTable/ok"}`, + `{"Time":"2026-01-01T10:00:03Z","Action":"run","Package":"example.com/e2e","Test":"TestTable/bad"}`, + `{"Time":"2026-01-01T10:00:04Z","Action":"fail","Package":"example.com/e2e","Test":"TestTable/bad"}`, + `{"Time":"2026-01-01T10:00:04Z","Action":"fail","Package":"example.com/e2e","Test":"TestTable"}`, + `{"Time":"2026-01-01T10:00:05Z","Action":"fail","Package":"example.com/e2e"}`, + }, "\n")+"\n") + + res := runGorp( + t, + "report", + "test2json", + "--file", + input, + "--launchName", + name, + "--print-launch-uuid", + ). + requireOK(t) + assert.Contains(t, res.stdout, "ReportPortal Launch: ", "the launch link is printed") + + launch := e.findLaunch(t, name, func(l *openapi.LaunchViewModel) bool { + return finished(l) && l.GetStatistics().Executions != nil + }) + executions := *launch.GetStatistics().Executions + assert.Equal( + t, + int32(4), + executions["total"], + "TestPass, TestSkip and two subtests; TestTable itself is not counted", + ) + assert.Equal(t, int32(2), executions["passed"]) + assert.Equal(t, int32(1), executions["failed"]) + assert.Equal(t, int32(1), executions["skipped"]) + + items := e.items(t, launch.Id, 6) // the suite, three tests and two subtests + assert.Equal(t, "SKIPPED", items["TestSkip"].Status) + assert.Equal( + t, + items["TestTable"].ID, + items["ok"].Parent, + "subtests belong to their parent test", + ) + assert.Equal(t, items["TestTable"].ID, items["bad"].Parent) + for _, n := range []string{"TestPass", "TestSkip", "TestTable", "ok", "bad"} { + assert.Equal(t, "STEP", items[n].Type, n) + } +} + // The atomic commands are what shell-based integrations use: each prints the ID it created. func TestAtomicSteps(t *testing.T) { e := newEnv(t) diff --git a/internal/commands/actions_test.go b/internal/commands/actions_test.go index f07fbd9..a7a256b 100644 --- a/internal/commands/actions_test.go +++ b/internal/commands/actions_test.go @@ -92,6 +92,7 @@ func test2jsonCmd(host, file string, extra ...cli.Flag) (*cli.Command, *bytes.Bu &cli.StringFlag{Name: "launchName", Value: "launch"}, &cli.BoolFlag{Name: "reportEmptyPkg"}, &cli.StringSliceFlag{Name: "attr"}, + &cli.BoolFlag{Name: "skipped-issue", Value: true}, &cli.BoolFlag{Name: "print-launch-uuid", Value: true}, ) diff --git a/internal/commands/report.go b/internal/commands/report.go index 44af9b4..b04744b 100644 --- a/internal/commands/report.go +++ b/internal/commands/report.go @@ -9,10 +9,14 @@ import ( "log/slog" "os" "path/filepath" + "strings" "github.com/urfave/cli/v3" ) +// agentName identifies gorp in the "agent" system attribute of the launches it reports. +const agentName = "gorp" + // scannerMaxLine bounds a single test2json line; output events can be larger than bufio's 64 KB default. const scannerMaxLine = 10 * 1024 * 1024 @@ -57,9 +61,16 @@ var ( attrFlag( "Launch attribute with format 'key:value'. Omitting a ':' separator will tag the launch with the value.", ), + &cli.BoolFlag{ + Name: "skipped-issue", + Usage: "Whether skipped tests are 'To Investigate' (true, ReportPortal's default) " + + "or 'No Defect' (false)", + Sources: cli.EnvVars("SKIPPED_ISSUE"), + Value: true, + }, &cli.BoolFlag{ Name: "print-launch-uuid", - Usage: "Print launch UUID to console", + Usage: "Print launch UUID and link to console", Value: false, }, &cli.BoolFlag{ @@ -83,13 +94,16 @@ func reportTest2Json(ctx context.Context, cmd *cli.Command) error { } // start reporting of the launch - launchID, err := reportLaunch(ctx, cfg, cmd) + launchID, launchLink, err := reportLaunch(ctx, cfg, cmd) if err != nil { return err } - // check if we need to print launch UUID + // check if we need to print launch UUID (and the link, if the server returned one) if cmd.Bool("print-launch-uuid") && launchID != "" { _, _ = fmt.Fprintf(cmd.Writer, "ReportPortal Launch UUID: %s\n", launchID) + if launchLink != "" { + _, _ = fmt.Fprintf(cmd.Writer, "ReportPortal Launch: %s\n", launchLink) + } } // check if we need to check quality gate if cmd.Bool("quality-gate-check") { @@ -108,15 +122,22 @@ func reportTest2Json(ctx context.Context, cmd *cli.Command) error { return nil } -func reportLaunch(ctx context.Context, cfg *clientConfig, cmd *cli.Command) (string, error) { +// reportLaunch reports the test2json input as a launch and returns its UUID and UI link. +func reportLaunch( + ctx context.Context, + cfg *clientConfig, + cmd *cli.Command, +) (string, string, error) { rpClient := buildReportingClient(ctx, cfg) input := make(chan *testEvent) - launchNameArg := cmd.String("launchName") - reportEmptyPkgArg := cmd.Bool("reportEmptyPkg") - attrArgs := cmd.StringSlice("attr") - rep := newReporter(ctx, input, rpClient, launchNameArg, reportEmptyPkgArg, attrArgs...) + rep := newReporter(ctx, input, rpClient, cmd.String("launchName"), reporterOptions{ + reportEmpty: cmd.Bool("reportEmptyPkg"), + skippedIssue: cmd.Bool("skipped-issue"), + agentVersion: agentVersion(cmd), + attributes: cmd.StringSlice("attr"), + }) // start reporting in a separate goroutine. // recvErr is written before done is closed, so it is safe to read once done is closed. @@ -135,12 +156,20 @@ func reportLaunch(ctx context.Context, cfg *clientConfig, cmd *cli.Command) (str // reporter errors take precedence: they are the reason the input might have been abandoned if recvErr != nil { slog.Error("input processing interrupted", "error", recvErr) - return "", recvErr + return "", "", recvErr } if readErr != nil { - return "", readErr + return "", "", readErr + } + return rep.launchUUID, rep.launchLink, nil +} + +// agentVersion is gorp's version as set on the root command ("1.2.3 (date)"), without the date. +func agentVersion(cmd *cli.Command) string { + if fields := strings.Fields(cmd.Root().Version); len(fields) > 0 { + return fields[0] } - return rep.launchUUID, nil + return "dev" } // feedEventsFrom feeds the reporter from the --file argument, or from stdin if it is not set. diff --git a/internal/commands/report_hierarchy_test.go b/internal/commands/report_hierarchy_test.go new file mode 100644 index 0000000..9afe827 --- /dev/null +++ b/internal/commands/report_hierarchy_test.go @@ -0,0 +1,348 @@ +package commands + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// recordedItem is a test item start as seen by hierarchyServer. +type recordedItem struct { + ID string + ParentID string // empty for a root item + Body map[string]any +} + +// hierarchyServer is a ReportPortal fake that gives every started item its own ID and records the +// requests, so tests can check the reported hierarchy and request bodies. +type hierarchyServer struct { + mu sync.Mutex + items []recordedItem + finishes map[string]map[string]any // item ID -> finish body + launchStart map[string]any +} + +func newHierarchyServer(t *testing.T, project string) (*hierarchyServer, *httptest.Server) { + t.Helper() + rec := &hierarchyServer{finishes: map[string]map[string]any{}} + decode := func(r *http.Request) map[string]any { + var body map[string]any + require.NoError(t, json.NewDecoder(r.Body).Decode(&body)) + return body + } + reply := func(w http.ResponseWriter, v any) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(v) + } + + mux := http.NewServeMux() + mux.HandleFunc("POST /api/v2/"+project+"/launch", func(w http.ResponseWriter, r *http.Request) { + rec.mu.Lock() + rec.launchStart = decode(r) + rec.mu.Unlock() + reply(w, map[string]string{"id": "launch-1"}) + }) + mux.HandleFunc( + "PUT /api/v2/"+project+"/launch/launch-1/finish", + func(w http.ResponseWriter, _ *http.Request) { + reply( + w, + map[string]string{"id": "launch-1", "link": "http://rp.example/ui/#launches/all/1"}, + ) + }, + ) + mux.HandleFunc("POST /api/v2/"+project+"/item/", func(w http.ResponseWriter, r *http.Request) { + body := decode(r) + rec.mu.Lock() + id := fmt.Sprintf("item-%d", len(rec.items)+1) + rec.items = append(rec.items, recordedItem{ + ID: id, + ParentID: strings.TrimPrefix(r.URL.Path, "/api/v2/"+project+"/item/"), + Body: body, + }) + rec.mu.Unlock() + reply(w, map[string]string{"id": id}) + }) + mux.HandleFunc( + "PUT /api/v2/"+project+"/item/{id}", + func(w http.ResponseWriter, r *http.Request) { + body := decode(r) + rec.mu.Lock() + rec.finishes[r.PathValue("id")] = body + rec.mu.Unlock() + reply(w, map[string]string{"message": "finished"}) + }, + ) + mux.HandleFunc("POST /api/v2/"+project+"/log", func(w http.ResponseWriter, _ *http.Request) { + reply(w, map[string]any{"responses": []map[string]string{{"id": "log-1"}}}) + }) + + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return rec, srv +} + +// item returns the recorded start of the item with the given name. +func (rec *hierarchyServer) item(t *testing.T, name string) recordedItem { + t.Helper() + rec.mu.Lock() + defer rec.mu.Unlock() + for _, it := range rec.items { + if it.Body["name"] == name { + return it + } + } + require.Failf(t, "item not reported", "no item named %q", name) + return recordedItem{} +} + +func writeEventLines(t *testing.T, lines ...string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "events.jsonl") + require.NoError(t, os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600)) + return path +} + +func event(action, test string) string { + if test == "" { + return fmt.Sprintf( + `{"time":"2025-01-01T00:00:00Z","action":%q,"package":"example/pkg"}`, + action, + ) + } + return fmt.Sprintf( + `{"time":"2025-01-01T00:00:00Z","action":%q,"package":"example/pkg","test":%q}`, + action, + test, + ) +} + +func TestReportLaunch_TestsAreStepsAndSubtestsNest(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, + event("run", "TestTable"), + event("run", "TestTable/a"), + event("run", "TestTable/a/deep"), + event("pass", "TestTable/a/deep"), + event("pass", "TestTable/a"), + event("run", "TestTable/b"), + event("fail", "TestTable/b"), + event("fail", "TestTable"), + event("run", "TestPlain"), + event("pass", "TestPlain"), + event("fail", ""), + ) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, link, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + require.NoError(t, err) + assert.Equal( + t, + "http://rp.example/ui/#launches/all/1", + link, + "the server's launch link is returned", + ) + + suite := rec.item(t, "example/pkg") + assert.Equal(t, "SUITE", suite.Body["type"]) + + table := rec.item(t, "TestTable") + assert.Equal(t, suite.ID, table.ParentID, "a top-level test is a child of the package suite") + + a := rec.item(t, "a") + assert.Equal(t, table.ID, a.ParentID, "a subtest is a child of its parent test") + assert.Equal( + t, + "example/pkg/TestTable/a", + a.Body["testCaseId"], + "the identity keeps the full test path", + ) + + deep := rec.item(t, "deep") + assert.Equal(t, a.ID, deep.ParentID, "a nested subtest is a child of its own parent") + + b := rec.item(t, "b") + assert.Equal(t, table.ID, b.ParentID) + + plain := rec.item(t, "TestPlain") + assert.Equal(t, suite.ID, plain.ParentID) + + // ReportPortal counts executions only for STEP items, so every test must be a STEP. + for _, it := range []recordedItem{table, a, deep, b, plain} { + assert.Equal(t, "STEP", it.Body["type"], "item %v", it.Body["name"]) + assert.Equal(t, true, it.Body["hasStats"], "item %v", it.Body["name"]) + } +} + +func TestReportLaunch_SkippedTest(t *testing.T) { + t.Parallel() + + for _, tc := range []struct { + name string + skippedIssue bool + wantIssue any + }{ + {name: "skipped tests stay To Investigate by default", skippedIssue: true, wantIssue: nil}, + { + name: "skipped tests are No Defect with --skipped-issue=false", + skippedIssue: false, + wantIssue: map[string]any{"issueType": "NOT_ISSUE"}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, + event("run", "TestSkip"), + event("skip", "TestSkip"), + event("pass", ""), + ) + cmd := reportCmd(file, "launch", false) + require.NoError(t, cmd.Set("skipped-issue", fmt.Sprint(tc.skippedIssue))) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, cmd) + require.NoError(t, err) + + skipped := rec.item(t, "TestSkip") + rec.mu.Lock() + finish := rec.finishes[skipped.ID] + rec.mu.Unlock() + require.NotNil(t, finish, "the skipped test must be finished by the reporter") + assert.Equal(t, "SKIPPED", finish["status"]) + assert.Equal(t, tc.wantIssue, finish["issue"]) + + assert.Contains(t, rec.launchStart["attributes"], map[string]any{ + "key": "skippedIssue", "value": fmt.Sprint(tc.skippedIssue), "system": true, + }) + }) + } +} + +func TestReportLaunch_SystemAttributes(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, event("run", "TestOne"), event("pass", "TestOne"), event("pass", "")) + cmd := reportCmd(file, "launch", false) + require.NoError(t, cmd.Set("attr", "build:42")) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, cmd) + require.NoError(t, err) + + attrs, ok := rec.launchStart["attributes"].([]any) + require.True(t, ok) + byKey := map[string]map[string]any{} + for _, a := range attrs { + m, isMap := a.(map[string]any) + require.True(t, isMap) + key, _ := m["key"].(string) + byKey[key] = m + } + assert.Equal(t, "42", byKey["build"]["value"], "user attributes are kept") + assert.NotEqual(t, true, byKey["build"]["system"], "user attributes are not system attributes") + for _, key := range []string{"agent", "os", "go"} { + require.Contains(t, byKey, key) + assert.Equal(t, true, byKey[key]["system"], "%s is a system attribute", key) + } + assert.True(t, strings.HasPrefix(byKey["agent"]["value"].(string), "gorp|")) +} + +func TestTest2JSON_PrintsLaunchLink(t *testing.T) { + t.Setenv("HOME", t.TempDir()) // no ~/.gorp + + _, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, event("run", "TestOne"), event("pass", "TestOne"), event("pass", "")) + cmd, out := test2jsonCmd(srv.URL, file) + + require.NoError(t, reportTest2Json(t.Context(), cmd)) + assert.Contains(t, out.String(), "ReportPortal Launch: http://rp.example/ui/#launches/all/1") +} + +func TestReportLaunch_SubtestParentMustBeRunning(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, + event("run", "TestX"), + // t.Run("c") finishes, then a sibling t.Run("c/d") runs: "TestX/c/d" is not a child of "c" + event("run", "TestX/c"), + event("pass", "TestX/c"), + event("run", "TestX/c/d"), + event("pass", "TestX/c/d"), + // t.Run("a") calls t.Parallel() and pauses, then a sibling t.Run("a/b") runs + event("run", "TestX/a"), + event("pause", "TestX/a"), + event("run", "TestX/a/b"), + event("pass", "TestX/a/b"), + event("cont", "TestX/a"), + // a real subtest of the resumed "a" + event("run", "TestX/a/real"), + event("pass", "TestX/a/real"), + event("pass", "TestX/a"), + event("pass", "TestX"), + event("pass", ""), + ) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + require.NoError(t, err) + + x := rec.item(t, "TestX") + assert.Equal( + t, + x.ID, + rec.item(t, "c/d").ParentID, + "a sibling named like a finished test is not its child", + ) + assert.Equal( + t, + x.ID, + rec.item(t, "a/b").ParentID, + "a sibling named like a paused test is not its child", + ) + assert.Equal( + t, + rec.item(t, "a").ID, + rec.item(t, "real").ParentID, + "a resumed test can have subtests", + ) +} + +func TestReportLaunch_PackageWithoutTestFilesWithReportEmpty(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + // before Go 1.20 a package without test files produced a lone "skip" with no "start" + file := writeEventLines( + t, + event("skip", ""), + `{"time":"2025-01-01T00:00:00Z","action":"start","package":"example/other"}`, + `{"time":"2025-01-01T00:00:00Z","action":"run","package":"example/other","test":"TestOne"}`, + `{"time":"2025-01-01T00:00:00Z","action":"pass","package":"example/other","test":"TestOne"}`, + `{"time":"2025-01-01T00:00:00Z","action":"pass","package":"example/other"}`, + ) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", true)) + require.NoError(t, err, "a package-level skip without a suite must not interrupt the launch") + assert.Equal( + t, + "SUITE", + rec.item(t, "example/other").Body["type"], + "the other package is still reported", + ) +} diff --git a/internal/commands/report_robustness_test.go b/internal/commands/report_robustness_test.go index 6de514a..8a6b3d9 100644 --- a/internal/commands/report_robustness_test.go +++ b/internal/commands/report_robustness_test.go @@ -131,7 +131,7 @@ func TestReportLaunch_LogFailureDoesNotHangAndInterruptsLaunch(t *testing.T) { errCh := make(chan error, 1) go func() { - _, err := reportLaunch(t.Context(), cfg, cmd) + _, _, err := reportLaunch(t.Context(), cfg, cmd) errCh <- err }() @@ -165,7 +165,7 @@ func TestReportLaunch_LargeAndMalformedLines(t *testing.T) { }) cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - launchID, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + launchID, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) require.NoError(t, err) assert.Equal(t, "launch-uuid-1", launchID) @@ -188,7 +188,7 @@ func TestReportLaunch_NoEmptyLogBatch(t *testing.T) { }) cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) require.NoError(t, err) srv.mu.Lock() @@ -220,7 +220,7 @@ func TestReportLaunch_LaunchStatusFollowsResults(t *testing.T) { }) cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) require.NoError(t, err) srv.mu.Lock() @@ -244,7 +244,7 @@ func TestReportLaunch_PackageWithoutTestsIsSkipped(t *testing.T) { }) cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) require.NoError(t, err) srv.mu.Lock() @@ -447,7 +447,7 @@ func TestReportLaunch_CancelledContextInterruptsLaunch(t *testing.T) { srv.onItemStart = cancel cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - _, err := reportLaunch(ctx, cfg, reportCmd(file, "launch", false)) + _, _, err := reportLaunch(ctx, cfg, reportCmd(file, "launch", false)) require.Error(t, err) srv.mu.Lock() @@ -468,7 +468,7 @@ func TestReportLaunch_InterruptFinishesOpenItemsBeforeLaunch(t *testing.T) { }) cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} - _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) require.Error(t, err) srv.mu.Lock() diff --git a/internal/commands/report_test.go b/internal/commands/report_test.go index 853d463..ad35636 100644 --- a/internal/commands/report_test.go +++ b/internal/commands/report_test.go @@ -337,6 +337,7 @@ func reportCmd(filePath, launchName string, reportEmpty bool) *cli.Command { &cli.StringFlag{Name: "launchName", Value: launchName}, &cli.BoolFlag{Name: "reportEmptyPkg", Value: reportEmpty}, &cli.StringSliceFlag{Name: "attr"}, + &cli.BoolFlag{Name: "skipped-issue", Value: true}, } return cmd } @@ -364,7 +365,7 @@ func TestReportLaunch_SingleTest(t *testing.T) { cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} cmd := reportCmd(f.Name(), "my-launch", false) - launchID, err := reportLaunch(context.Background(), cfg, cmd) + launchID, _, err := reportLaunch(context.Background(), cfg, cmd) require.NoError(t, err) assert.Equal(t, "launch-uuid-1", launchID) @@ -398,7 +399,7 @@ func TestReportLaunch_MultipleTests(t *testing.T) { cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} cmd := reportCmd(f.Name(), "multi-launch", false) - launchID, err := reportLaunch(context.Background(), cfg, cmd) + launchID, _, err := reportLaunch(context.Background(), cfg, cmd) require.NoError(t, err) assert.Equal(t, "launch-uuid-1", launchID) @@ -423,7 +424,7 @@ func TestReportLaunch_EmptyInput(t *testing.T) { cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} cmd := reportCmd(f.Name(), "empty-launch", false) - launchID, err := reportLaunch(context.Background(), cfg, cmd) + launchID, _, err := reportLaunch(context.Background(), cfg, cmd) // No events — no launch was started, launchUUID stays empty. require.NoError(t, err) @@ -483,7 +484,7 @@ func TestReportLaunch_OutputTypeErrorLevels(t *testing.T) { cfg := &clientConfig{URL: srv.URL, Project: project, ApiKey: "tok"} cmd := reportCmd(f.Name(), "outputtype-launch", false) - _, err = reportLaunch(context.Background(), cfg, cmd) + _, _, err = reportLaunch(context.Background(), cfg, cmd) require.NoError(t, err) require.NotEmpty(t, logBodies) diff --git a/internal/commands/reporter.go b/internal/commands/reporter.go index 7f6b24d..c8f8f3c 100644 --- a/internal/commands/reporter.go +++ b/internal/commands/reporter.go @@ -27,6 +27,9 @@ const ( testActionOutput = "output" testActionPass = "pass" testActionFail = "fail" + testActionSkip = "skip" + testActionPause = "pause" + testActionCont = "cont" ) // test2json OutputType values (Go 1.27+); see cmd/test2json documentation. @@ -72,11 +75,26 @@ type reporter struct { openItems []string launchAttributes []openapi.ItemAttributesRQ tests map[string]string - suites map[string]string - logs []*openapi.SaveLogRQ - logsBatchSize int - errGroup errgroup.Group - reportEmpty bool + // paused are the tests that called t.Parallel() and wait for their turn; they cannot have subtests + // started while paused, so a test named like them ("a/b" next to a paused "a") is not their child + paused map[string]bool + suites map[string]string + logs []*openapi.SaveLogRQ + logsBatchSize int + errGroup errgroup.Group + reportEmpty bool + // skippedIssue keeps skipped tests "To Investigate" (true, ReportPortal's default) or marks them "No Defect" + skippedIssue bool + // launchLink is the UI link of the finished launch, as returned by ReportPortal + launchLink string +} + +// reporterOptions are the optional settings of the test2json reporter. +type reporterOptions struct { + reportEmpty bool + skippedIssue bool + agentVersion string + attributes []string } func newReporter( @@ -84,20 +102,24 @@ func newReporter( input <-chan *testEvent, client *gorppkg.ReportingClient, launchName string, - reportEmpty bool, - launchAttrArgs ...string, + opts reporterOptions, ) *reporter { + attributes := parseAttributes(opts.attributes) + attributes = append(attributes, gorppkg.SystemAttributes(agentName, opts.agentVersion)...) + attributes = append(attributes, gorppkg.SkippedIssueAttribute(opts.skippedIssue)) r := &reporter{ ctx: ctx, input: input, launchName: launchName, - launchAttributes: parseAttributes(launchAttrArgs), + launchAttributes: attributes, client: client, tests: map[string]string{}, + paused: map[string]bool{}, suites: map[string]string{}, logs: []*openapi.SaveLogRQ{}, logsBatchSize: logsBatchSize, - reportEmpty: reportEmpty, + reportEmpty: opts.reportEmpty, + skippedIssue: opts.skippedIssue, } r.errGroup.SetLimit(maxLogBatchesInFlight) @@ -119,6 +141,12 @@ func (r *reporter) reportEvent(ev *testEvent) error { err = r.finish(ev, gorppkg.Statuses.Passed) case testActionFail: err = r.finish(ev, gorppkg.Statuses.Failed) + case testActionSkip: + err = r.finish(ev, gorppkg.Statuses.Skipped) + case testActionPause: + r.paused[r.getTestName(ev)] = true + case testActionCont: + delete(r.paused, r.getTestName(ev)) } return err } @@ -220,28 +248,36 @@ func (r *reporter) startSuite(ev *testEvent) (string, error) { return id, nil } +// startTest starts a test as a STEP: ReportPortal counts executions (total, passed, failed, skipped) +// only for STEP items without children, and only those get "To Investigate". A subtest is started +// as a child of its parent test, so the parent stops being counted once it has subtests and every +// test case is counted exactly once. func (r *reporter) startTest(ev *testEvent) error { testID := r.getTestName(ev) - suiteID, found := r.suites[ev.Package] - if !found { - if r.reportEmpty { - return fmt.Errorf("unable to find suiteID for package: %s", ev.Package) - } - var err error - suiteID, err = r.startSuite(ev) - if err != nil { - return err + parentID, name := r.parentOf(ev) + if parentID == "" { + suiteID, found := r.suites[ev.Package] + if !found { + if r.reportEmpty { + return fmt.Errorf("unable to find suiteID for package: %s", ev.Package) + } + var err error + suiteID, err = r.startSuite(ev) + if err != nil { + return err + } } + parentID = suiteID } - rs, err := r.client.StartChildTest(r.ctx, suiteID, &openapi.StartTestItemRQ{ - Name: ev.Test, + rs, err := r.client.StartChildTest(r.ctx, parentID, &openapi.StartTestItemRQ{ + Name: name, StartTime: ev.Time, LaunchUuid: r.launchUUID, HasStats: openapi.PtrBool(true), UniqueId: openapi.PtrString(testID), CodeRef: openapi.PtrString(testID), TestCaseId: openapi.PtrString(testID), - Type: string(gorppkg.TestItemTypes.Test), + Type: string(gorppkg.TestItemTypes.Step), Retry: openapi.PtrBool(false), }) if err != nil { @@ -256,6 +292,23 @@ func (r *reporter) startTest(ev *testEvent) error { return nil } +// parentOf finds the running test that ev is a subtest of and returns its item ID together with the +// name of ev relative to it ("TestA/b/c" under "TestA/b" is "c"). Subtest names may contain "/" +// themselves, so the longest prefix that names a running test wins. A test that already finished or +// is paused in t.Parallel() cannot be the parent: t.Run("c/d") after a finished t.Run("c") is a +// sibling of "c". For a top-level test, or when no running parent is found, the ID is empty and the +// name is the full test name. +func (r *reporter) parentOf(ev *testEvent) (string, string) { + for i := strings.LastIndex(ev.Test, "/"); i > 0; i = strings.LastIndex(ev.Test[:i], "/") { + name := ev.Package + "/" + ev.Test[:i] + id, ok := r.tests[name] + if ok && !r.paused[name] && slices.Contains(r.openItems, id) { + return id, ev.Test[i+1:] + } + } + return "", ev.Test +} + func logLevelForOutputType(outputType string) string { switch outputType { case testOutputTypeError, testOutputTypeErrorContinue: @@ -353,10 +406,13 @@ func (r *reporter) finishLaunch( status gorppkg.Status, endTime time.Time, ) error { - _, err := r.client.FinishLaunch(ctx, r.launchUUID, &openapi.FinishExecutionRQ{ + rs, err := r.client.FinishLaunch(ctx, r.launchUUID, &openapi.FinishExecutionRQ{ Status: status.Ptr(), EndTime: endTime, }) + if err == nil && rs != nil { + r.launchLink = rs.GetLink() + } return err } @@ -364,7 +420,15 @@ func (r *reporter) finishTest(ev *testEvent, status gorppkg.Status) error { testName := r.getTestName(ev) testID := r.tests[testName] - return r.finishItem(r.ctx, testID, ev.Time, status) + rq := &openapi.FinishTestItemRQ{ + EndTime: ev.Time, + Status: status.Ptr(), + LaunchUuid: r.launchUUID, + } + if status == gorppkg.Statuses.Skipped && !r.skippedIssue { + rq.Issue = gorppkg.NotIssue() + } + return r.finishItemRQ(r.ctx, testID, rq) } // finishItem finishes a suite or a test. The item is not open anymore even if the request fails: @@ -375,13 +439,21 @@ func (r *reporter) finishItem( endTime time.Time, status gorppkg.Status, ) error { - r.openItems = slices.DeleteFunc(r.openItems, func(open string) bool { return open == id }) - - _, err := r.client.FinishTest(ctx, id, &openapi.FinishTestItemRQ{ + return r.finishItemRQ(ctx, id, &openapi.FinishTestItemRQ{ EndTime: endTime, Status: status.Ptr(), LaunchUuid: r.launchUUID, }) +} + +func (r *reporter) finishItemRQ( + ctx context.Context, + id string, + rq *openapi.FinishTestItemRQ, +) error { + r.openItems = slices.DeleteFunc(r.openItems, func(open string) bool { return open == id }) + + _, err := r.client.FinishTest(ctx, id, rq) return err } @@ -399,8 +471,9 @@ func (r *reporter) finish(ev *testEvent, status gorppkg.Status) error { func (r *reporter) finishSuite(ev *testEvent, status gorppkg.Status) error { suiteID, found := r.suites[ev.Package] if !found { - if !r.reportEmpty { - // the package had no tests, so no suite was started and there is nothing to finish + // the package had no tests (or, for "skip", no test files), so no suite was started and + // there is nothing to finish + if !r.reportEmpty || status == gorppkg.Statuses.Skipped { return nil } return fmt.Errorf("unable to find suiteID for package: %s", ev.Package) diff --git a/pkg/gorp/attributes.go b/pkg/gorp/attributes.go new file mode 100644 index 0000000..af41c2a --- /dev/null +++ b/pkg/gorp/attributes.go @@ -0,0 +1,47 @@ +package gorp + +import ( + "runtime" + "strconv" + + "github.com/reportportal/goRP/v5/pkg/openapi" +) + +// IssueTypeNotIssue is the locator of the "No Defect" issue type. A FAILED or SKIPPED item finished +// with it is not counted as "To Investigate". +const IssueTypeNotIssue = "NOT_ISSUE" + +// SkippedIssueAttributeKey is the key of the system launch attribute that tells ReportPortal whether +// skipped items are treated as issues ("To Investigate") or not. The server reads it when it finishes +// items on its own, for example the open children of a finished parent. +const SkippedIssueAttributeKey = "skippedIssue" + +// NotIssue returns an issue that marks a FAILED or SKIPPED item as "No Defect". +func NotIssue() *openapi.ComEpamReportportalBaseReportingIssue { + return openapi.NewComEpamReportportalBaseReportingIssue(IssueTypeNotIssue) +} + +// SystemAttributes returns the system launch attributes that describe the reporting agent and its +// environment, like the ones ReportPortal's Java agents send: agent=|, +// os=| and go=. +func SystemAttributes(agentName, agentVersion string) []openapi.ItemAttributesRQ { + return []openapi.ItemAttributesRQ{ + systemAttribute("agent", agentName+"|"+agentVersion), + systemAttribute("os", runtime.GOOS+"|"+runtime.GOARCH), + systemAttribute("go", runtime.Version()), + } +} + +// SkippedIssueAttribute returns the system launch attribute that tells ReportPortal whether skipped +// items are "To Investigate" (true) or "No Defect" (false). +func SkippedIssueAttribute(skippedIssue bool) openapi.ItemAttributesRQ { + return systemAttribute(SkippedIssueAttributeKey, strconv.FormatBool(skippedIssue)) +} + +func systemAttribute(key, value string) openapi.ItemAttributesRQ { + return openapi.ItemAttributesRQ{ + Key: openapi.PtrString(key), + Value: value, + System: openapi.PtrBool(true), + } +} diff --git a/pkg/gorp/attributes_test.go b/pkg/gorp/attributes_test.go new file mode 100644 index 0000000..ab34656 --- /dev/null +++ b/pkg/gorp/attributes_test.go @@ -0,0 +1,48 @@ +package gorp + +import ( + "runtime" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestSystemAttributes(t *testing.T) { + t.Parallel() + + attrs := SystemAttributes("gorp", "1.2.3") + + require.Len(t, attrs, 3) + got := map[string]string{} + for _, a := range attrs { + require.NotNil(t, a.Key) + require.NotNil(t, a.System) + assert.True(t, *a.System, "%s must be a system attribute", *a.Key) + got[*a.Key] = a.Value + } + assert.Equal(t, map[string]string{ + "agent": "gorp|1.2.3", + "os": runtime.GOOS + "|" + runtime.GOARCH, + "go": runtime.Version(), + }, got) +} + +func TestSkippedIssueAttribute(t *testing.T) { + t.Parallel() + + for _, v := range []bool{true, false} { + a := SkippedIssueAttribute(v) + require.NotNil(t, a.Key) + assert.Equal(t, "skippedIssue", *a.Key) + assert.Equal(t, map[bool]string{true: "true", false: "false"}[v], a.Value) + require.NotNil(t, a.System) + assert.True(t, *a.System) + } +} + +func TestNotIssue(t *testing.T) { + t.Parallel() + + assert.Equal(t, "NOT_ISSUE", NotIssue().IssueType) +} diff --git a/pkg/gorp/reporting_client.go b/pkg/gorp/reporting_client.go index 4bdd4df..8310113 100644 --- a/pkg/gorp/reporting_client.go +++ b/pkg/gorp/reporting_client.go @@ -221,14 +221,9 @@ func (c *ReportingClient) SaveLog( ctx context.Context, log *openapi.SaveLogRQ, ) (*openapi.EntryCreatedAsyncRS, error) { - var rs openapi.EntryCreatedAsyncRS - _, err := c.http.R(). - SetContext(ctx). - SetPathParam("project", c.project). - SetBody(log). - SetResult(&rs). - Post("/api/v2/{project}/log") - return &rs, err + // A single log is sent as a one-entry multipart batch: a plain JSON body on /log is deprecated + // in ReportPortal 6.x, while the multipart form works on every server version. + return c.SaveLogMultipart(ctx, []*openapi.SaveLogRQ{log}, nil) } // SaveLogs saves logs as batch request diff --git a/pkg/gorp/reporting_client_test.go b/pkg/gorp/reporting_client_test.go index ea29631..f437879 100644 --- a/pkg/gorp/reporting_client_test.go +++ b/pkg/gorp/reporting_client_test.go @@ -2,6 +2,7 @@ package gorp import ( "bytes" + "encoding/json" "fmt" "io" "net/http" @@ -24,7 +25,16 @@ func TestSaveLog(t *testing.T) { assert.Equal(t, "/api/v2/prj/log", r.URL.Path) assert.Equal(t, http.MethodPost, r.Method) - response := `{"id": "log123"}` + // A single log is sent as a one-entry multipart batch, not as the JSON body deprecated in 6.x. + assert.Contains(t, r.Header.Get("Content-Type"), "multipart/form-data") + part := r.FormValue("json_request_part") + var logs []map[string]any + if assert.NoError(t, json.Unmarshal([]byte(part), &logs)) && assert.Len(t, logs, 1) { + assert.Equal(t, "Test log message", logs[0]["message"]) + assert.Equal(t, "item123", logs[0]["itemUuid"]) + } + + response := `{"responses": [{"id": "log123"}]}` w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) _, _ = w.Write([]byte(response)) From d4d2e5ed648c1b34f4ae3bdfb56d14823fca3e15 Mon Sep 17 00:00:00 2001 From: Claude Code Date: Thu, 26 Nov 2026 21:23:01 -0500 Subject: [PATCH 2/2] report test2json: skip parent candidates that have a running subtest A running test with a running subtest is blocked in t.Run (or its body returned and its parallel subtests run), so it cannot start a new subtest. parentOf now drops such candidates before taking the longest running prefix. Document the remaining case test2json cannot decide (parallel siblings "a" and "a/b" both running) and why the longest prefix is kept there: test cases are still counted exactly once. Co-Authored-By: Claude Opus 5.5 --- internal/commands/report_hierarchy_test.go | 67 +++++++++++++++++++++ internal/commands/reporter.go | 68 +++++++++++++++++----- 2 files changed, 121 insertions(+), 14 deletions(-) diff --git a/internal/commands/report_hierarchy_test.go b/internal/commands/report_hierarchy_test.go index 9afe827..73f9d14 100644 --- a/internal/commands/report_hierarchy_test.go +++ b/internal/commands/report_hierarchy_test.go @@ -322,6 +322,73 @@ func TestReportLaunch_SubtestParentMustBeRunning(t *testing.T) { ) } +// TestReportLaunch_AmbiguousSubtestParent replays the real "go test -json" stream of parallel siblings +// "a" and "a/b" that both resumed when "TestX/a/b/c" starts. It is the same whether "a" called +// t.Run("b/c") or "a/b" called t.Run("c"), so the longest running prefix is the parent: every test +// case is still counted once, as a leaf. +func TestReportLaunch_AmbiguousSubtestParent(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, + event("run", "TestX"), + event("run", "TestX/a"), + event("pause", "TestX/a"), + event("run", "TestX/a/b"), + event("pause", "TestX/a/b"), + event("cont", "TestX/a"), + event("cont", "TestX/a/b"), + event("run", "TestX/a/b/c"), + event("pass", "TestX/a/b/c"), + event("pass", "TestX/a"), + event("pass", "TestX/a/b"), + event("pass", "TestX"), + event("pass", ""), + ) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + require.NoError(t, err) + + x := rec.item(t, "TestX") + assert.Equal(t, x.ID, rec.item(t, "a").ParentID) + assert.Equal(t, x.ID, rec.item(t, "a/b").ParentID) + assert.Equal(t, rec.item(t, "a/b").ID, rec.item(t, "c").ParentID) +} + +// TestReportLaunch_SubtestParentHasNoRunningSubtest checks that a running test with a running subtest +// is not a parent candidate: it is blocked in t.Run, so "TestX/a/b/c" can only be t.Run("b/c") of "a". +func TestReportLaunch_SubtestParentHasNoRunningSubtest(t *testing.T) { + t.Parallel() + + rec, srv := newHierarchyServer(t, "proj") + file := writeEventLines(t, + event("run", "TestX"), + event("run", "TestX/a"), + event("pause", "TestX/a"), + event("run", "TestX/a/b"), + event("pause", "TestX/a/b"), + event("cont", "TestX/a"), + event("cont", "TestX/a/b"), + // "a/b" runs a subtest and waits for it + event("run", "TestX/a/b/z"), + event("run", "TestX/a/b/c"), + event("pass", "TestX/a/b/c"), + event("pass", "TestX/a/b/z"), + event("pass", "TestX/a"), + event("pass", "TestX/a/b"), + event("pass", "TestX"), + event("pass", ""), + ) + + cfg := &clientConfig{URL: srv.URL, Project: "proj", ApiKey: "tok"} + _, _, err := reportLaunch(t.Context(), cfg, reportCmd(file, "launch", false)) + require.NoError(t, err) + + assert.Equal(t, rec.item(t, "a/b").ID, rec.item(t, "z").ParentID) + assert.Equal(t, rec.item(t, "a").ID, rec.item(t, "b/c").ParentID) +} + func TestReportLaunch_PackageWithoutTestFilesWithReportEmpty(t *testing.T) { t.Parallel() diff --git a/internal/commands/reporter.go b/internal/commands/reporter.go index c8f8f3c..7cc234a 100644 --- a/internal/commands/reporter.go +++ b/internal/commands/reporter.go @@ -77,7 +77,9 @@ type reporter struct { tests map[string]string // paused are the tests that called t.Parallel() and wait for their turn; they cannot have subtests // started while paused, so a test named like them ("a/b" next to a paused "a") is not their child - paused map[string]bool + paused map[string]bool + // parents maps a started test to its parent test ("" when its parent is the package suite) + parents map[string]string suites map[string]string logs []*openapi.SaveLogRQ logsBatchSize int @@ -115,6 +117,7 @@ func newReporter( client: client, tests: map[string]string{}, paused: map[string]bool{}, + parents: map[string]string{}, suites: map[string]string{}, logs: []*openapi.SaveLogRQ{}, logsBatchSize: logsBatchSize, @@ -254,8 +257,9 @@ func (r *reporter) startSuite(ev *testEvent) (string, error) { // test case is counted exactly once. func (r *reporter) startTest(ev *testEvent) error { testID := r.getTestName(ev) - parentID, name := r.parentOf(ev) - if parentID == "" { + parentTest, name := r.parentOf(ev) + parentID := r.tests[parentTest] + if parentTest == "" { suiteID, found := r.suites[ev.Package] if !found { if r.reportEmpty { @@ -288,25 +292,61 @@ func (r *reporter) startTest(ev *testEvent) error { return err } r.tests[testID] = id + r.parents[testID] = parentTest r.openItems = append(r.openItems, id) return nil } -// parentOf finds the running test that ev is a subtest of and returns its item ID together with the -// name of ev relative to it ("TestA/b/c" under "TestA/b" is "c"). Subtest names may contain "/" -// themselves, so the longest prefix that names a running test wins. A test that already finished or -// is paused in t.Parallel() cannot be the parent: t.Run("c/d") after a finished t.Run("c") is a -// sibling of "c". For a top-level test, or when no running parent is found, the ID is empty and the -// name is the full test name. +// parentOf finds the running test that ev is a subtest of and returns its name (package-qualified, as +// in r.tests) together with the name of ev relative to it ("TestA/b/c" under "TestA/b" is "c"). For a +// top-level test, or when no running parent is found, the parent is empty and the name is the full +// test name. +// +// Subtest names may contain "/" themselves, so every running test whose name is a prefix of ev's is a +// candidate. A test that already finished or is paused in t.Parallel() cannot be the parent: +// t.Run("c/d") after a finished t.Run("c") is a sibling of "c". Neither can a test that has a running +// subtest: it is blocked in t.Run, or its body has returned and its parallel subtests run. Of the +// remaining candidates the longest wins. +// +// test2json cannot always tell more: with parallel siblings "a" and "a/b" both running, "a/b/c" is +// either t.Run("b/c") of "a" or t.Run("c") of "a/b", and the stream is the same for both. The +// longest prefix picks "a/b". When that is wrong, the test is shown under its sibling, but every +// test case is still counted exactly once; any other choice would count one test case too many. func (r *reporter) parentOf(ev *testEvent) (string, string) { + var candidates []int // indexes of "/" in ev.Test that end the name of a candidate, longest first for i := strings.LastIndex(ev.Test, "/"); i > 0; i = strings.LastIndex(ev.Test[:i], "/") { - name := ev.Package + "/" + ev.Test[:i] - id, ok := r.tests[name] - if ok && !r.paused[name] && slices.Contains(r.openItems, id) { - return id, ev.Test[i+1:] + if r.isRunning(ev.Package + "/" + ev.Test[:i]) { + candidates = append(candidates, i) + } + } + if len(candidates) == 0 { + return "", ev.Test + } + parent := candidates[0] + for _, i := range candidates { + if !r.hasRunningSubtest(ev.Package + "/" + ev.Test[:i]) { + parent = i + break + } + } + // when every candidate has a running subtest (t.Run called from a goroutine), the longest one stays + return ev.Package + "/" + ev.Test[:parent], ev.Test[parent+1:] +} + +// isRunning reports whether the test is started, not finished and not paused in t.Parallel(). +func (r *reporter) isRunning(test string) bool { + id, ok := r.tests[test] + return ok && !r.paused[test] && slices.Contains(r.openItems, id) +} + +// hasRunningSubtest reports whether one of the test's direct subtests is running. +func (r *reporter) hasRunningSubtest(test string) bool { + for child, parent := range r.parents { + if parent == test && r.isRunning(child) { + return true } } - return "", ev.Test + return false } func logLevelForOutputType(outputType string) string {