From 602a5597e944186d6030789b6c3c9be429d838fa Mon Sep 17 00:00:00 2001 From: Claude Code Date: Fri, 27 Nov 2026 17:34:06 -0500 Subject: [PATCH] Add rerun, retry, parameters, issue type and finish flags to the atomic report commands - start-launch: --rerun, --rerun-of (implies --rerun) - start-test: --test-case-id, --param key=value, --retry-of, --has-stats - finish-test: --issue-type, --attr, --description - finish-launch: --attr, --description; prints the launch link after the UUID - --mode and --type are checked against the known values (case-insensitive) before any request Part of #26 Co-Authored-By: Claude Fable 5.2 --- .claude/skills/reportportal/SKILL.md | 22 +- README.md | 48 +++- internal/commands/report_steps.go | 178 +++++++++++++- internal/commands/report_steps_test.go | 314 ++++++++++++++++++++++++- 4 files changed, 547 insertions(+), 15 deletions(-) diff --git a/.claude/skills/reportportal/SKILL.md b/.claude/skills/reportportal/SKILL.md index f428af1..379d74c 100644 --- a/.claude/skills/reportportal/SKILL.md +++ b/.claude/skills/reportportal/SKILL.md @@ -66,7 +66,14 @@ LAUNCH_UUID=$(gorp report start-launch \ | `--name` | `-n` | | | **Required.** Launch name | | `--description` | | | | Launch description | | `--attr` | `-a` | | | Attribute `key:value` or `value` (repeatable) | -| `--mode` | | | `DEFAULT` | `DEFAULT` or `DEBUG` | +| `--mode` | | | `DEFAULT` | `DEFAULT` or `DEBUG` (case-insensitive; anything else is rejected) | +| `--rerun` | | | `false` | Rerun the latest launch with the same name | +| `--rerun-of` | | | | UUID of the launch to rerun (implies `--rerun`) | + +On a rerun the printed UUID is the one of the launch being rerun (ReportPortal 5.13.5+); always use the printed UUID. +Items are matched to the existing ones by test case ID (derived from code ref or tree position when not given); +a matched test becomes the latest attempt, the earlier one its retry. +No launch to rerun → 404 error. --- @@ -94,11 +101,15 @@ TEST_UUID=$(gorp report start-test \ |------|-------|-----|---------|-------------| | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--name` | `-n` | | | **Required.** Item name | -| `--type` | `-t` | | `TEST` | `SUITE`, `TEST`, `STEP`, `SCENARIO`, etc. | +| `--type` | `-t` | | `TEST` | `SUITE`, `STORY`, `TEST`, `SCENARIO`, `STEP`, `BEFORE_*`/`AFTER_*` (`CLASS`, `GROUPS`, `METHOD`, `SUITE`, `TEST`); case-insensitive, anything else is rejected | | `--parent-uuid` | | `PARENT_UUID` | | Parent UUID (creates child item) | | `--description` | | | | Description | | `--code-ref` | | | | Source code reference | | `--attr` | `-a` | | | Attribute (repeatable) | +| `--test-case-id` | | | | Test case ID (default: derived by the server from `--code-ref`) | +| `--param` | | | | Parameter `key=value` (repeatable; a comma separates parameters) | +| `--retry-of` | | | | UUID of the previous attempt; the item becomes its retry. Requires `--parent-uuid` | +| `--has-stats` | | | `true` | `--has-stats=false` (with `=`) makes a nested step, not counted in statistics | --- @@ -158,12 +169,15 @@ gorp report finish-test \ | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--item-uuid` | | `ITEM_UUID` | | **Required.** Test item UUID | | `--status` | | | | Optional. `PASSED`, `FAILED`, `SKIPPED`, etc. | +| `--issue-type` | | | | Defect type locator (`pb001`, `ab001`, `si001`, `ti001`, `nd001`, custom) or `NOT_ISSUE`. Applied only to `FAILED`/`SKIPPED` items with statistics; an unknown locator leaves the item unfinished without an error | +| `--description` | | | | Replaces the description given at start | +| `--attr` | `-a` | | | Attribute (repeatable), added to the ones given at start | --- ## 6. finish-launch -Close the launch with a final status. +Close the launch with a final status. Prints the launch UUID, then the link to the launch in the UI on the next line. ```sh gorp report finish-launch \ @@ -175,6 +189,8 @@ gorp report finish-launch \ |------|-------|-----|---------|-------------| | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--status` | | | | Optional. `PASSED`, `FAILED`, `STOPPED`, etc. | +| `--description` | | | | Appended to the description given at start | +| `--attr` | `-a` | | | Attribute (repeatable), added to the ones given at start | --- diff --git a/README.md b/README.md index b7bc454..113cf29 100644 --- a/README.md +++ b/README.md @@ -261,7 +261,19 @@ LAUNCH_UUID=$(gorp report start-launch --name "Nightly run" --attr "branch:main" | `--name` | `-n` | | | **Required.** Launch name | | `--description` | | | | Launch description | | `--attr` | `-a` | | | Attribute, format `key:value` or `value`. Repeatable. | -| `--mode` | | | `DEFAULT` | Launch mode: `DEFAULT` or `DEBUG` | +| `--mode` | | | `DEFAULT` | Launch mode: `DEFAULT` or `DEBUG` (case-insensitive; anything else is rejected) | +| `--rerun` | | | `false` | Rerun the latest launch with the same name instead of starting a new one | +| `--rerun-of` | | | | UUID of the launch to rerun. Implies `--rerun`. | + +With `--rerun` or `--rerun-of` the command prints the UUID of the launch being rerun (ReportPortal 5.13.5 or newer), so +the following commands report into that launch. ReportPortal matches the items to the existing ones by test case ID +(derived from the code reference or the item's place in the tree when not given): a matched test becomes the latest +attempt and the earlier one is kept as its retry. If there is no launch to rerun, the command +fails with a 404 error. + +```sh +LAUNCH_UUID=$(gorp report start-launch --name "Nightly run" --rerun-of "$PREVIOUS_LAUNCH_UUID") +``` --- @@ -284,11 +296,27 @@ TEST_UUID=$(gorp report start-test \ |------|-------|---------|---------|-------------| | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--name` | `-n` | | | **Required.** Test item name | -| `--type` | `-t` | | `TEST` | Item type: `SUITE`, `TEST`, `STEP`, `SCENARIO`, etc. | +| `--type` | `-t` | | `TEST` | Item type: `SUITE`, `STORY`, `TEST`, `SCENARIO`, `STEP`, `BEFORE_CLASS`, `BEFORE_GROUPS`, `BEFORE_METHOD`, `BEFORE_SUITE`, `BEFORE_TEST`, `AFTER_CLASS`, `AFTER_GROUPS`, `AFTER_METHOD`, `AFTER_SUITE`, `AFTER_TEST` (case-insensitive; anything else is rejected) | | `--parent-uuid` | | `PARENT_UUID` | | Parent item UUID (creates a child item) | | `--description` | | | | Item description | | `--code-ref` | | | | Source code reference | | `--attr` | `-a` | | | Attribute. Repeatable. | +| `--test-case-id` | | | | Test case ID: identifies the same test across launches. By default the server derives it from `--code-ref`. | +| `--param` | | | | Test parameter, format `key=value`. Repeatable. A comma separates several parameters, so a value can't contain one. | +| `--retry-of` | | | | UUID of the previous attempt: reports the item as its retry. Requires `--parent-uuid`. | +| `--has-stats` | | | `true` | Count the item in statistics. Pass `--has-stats=false` (with `=`) for a nested step. | + +```sh +# Second attempt of a failed test: ReportPortal shows the first one as its retry +RETRY_UUID=$(gorp report start-test \ + --launch-uuid "$LAUNCH_UUID" --parent-uuid "$SUITE_UUID" \ + --name "TestBar" --type STEP --param "browser=chrome" --retry-of "$TEST_UUID") + +# Nested step: shown inside the test, not counted in statistics +STEP_UUID=$(gorp report start-test \ + --launch-uuid "$LAUNCH_UUID" --parent-uuid "$TEST_UUID" \ + --name "open page" --type STEP --has-stats=false) +``` --- @@ -330,12 +358,24 @@ gorp report finish-test \ | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--item-uuid` | | `ITEM_UUID` | | **Required.** Test item UUID | | `--status` | | | | Item status: `PASSED`, `FAILED`, `SKIPPED`, etc. | +| `--issue-type` | | | | Defect type locator: `pb001` (product bug), `ab001` (automation bug), `si001` (system issue), `ti001` (to investigate), `nd001` (no defect), a custom locator of the project, or `NOT_ISSUE` | +| `--description` | | | | Item description. Replaces the one given at start. | +| `--attr` | `-a` | | | Attribute. Repeatable. Added to the ones given at start. | + +ReportPortal applies `--issue-type` only to `FAILED` or `SKIPPED` items that are counted in statistics and are not +an earlier attempt of a retry. Without it such an item gets "To Investigate"; `NOT_ISSUE` leaves it without a defect. +An unknown locator is not reported back by the command: the item is not finished and stays in progress. + +```sh +gorp report finish-test \ + --launch-uuid "$LAUNCH_UUID" --item-uuid "$TEST_UUID" --status FAILED --issue-type pb001 +``` --- ### report finish-launch -Finish a launch. +Finish a launch. Prints the launch UUID and, on the next line, the link to the launch in the ReportPortal UI. ```sh gorp report finish-launch --launch-uuid "$LAUNCH_UUID" --status PASSED @@ -345,6 +385,8 @@ gorp report finish-launch --launch-uuid "$LAUNCH_UUID" --status PASSED |------|-------|---------|---------|-------------| | `--launch-uuid` | | `LAUNCH_UUID` | | **Required.** Launch UUID | | `--status` | | | | Launch status: `PASSED`, `FAILED`, `STOPPED`, etc. | +| `--description` | | | | Text appended to the launch description given at start | +| `--attr` | `-a` | | | Attribute. Repeatable. Added to the ones given at start. | --- diff --git a/internal/commands/report_steps.go b/internal/commands/report_steps.go index 9ebc330..3a87fba 100644 --- a/internal/commands/report_steps.go +++ b/internal/commands/report_steps.go @@ -2,9 +2,12 @@ package commands import ( "context" + "errors" "fmt" "os" "path/filepath" + "slices" + "strings" "time" "github.com/urfave/cli/v3" @@ -36,6 +39,15 @@ var ( Usage: "Launch mode: DEFAULT or DEBUG", Value: "DEFAULT", }, + &cli.BoolFlag{ + Name: "rerun", + Usage: "Rerun a launch instead of starting a new one: the latest launch with the same name, " + + "or the one given by --rerun-of. Prints the UUID of the launch being rerun.", + }, + &cli.StringFlag{ + Name: "rerun-of", + Usage: "UUID of the launch to rerun (implies --rerun)", + }, }, Action: withConfig(startLaunchStep), } @@ -54,7 +66,7 @@ var ( &cli.StringFlag{ Name: "type", Aliases: []string{"t"}, - Usage: "Test item type: SUITE, TEST, STEP, SCENARIO, etc.", + Usage: "Test item type: " + strings.Join(testItemTypes(), ", "), Value: "TEST", }, &cli.StringFlag{ @@ -71,6 +83,23 @@ var ( Usage: "Code reference (e.g. package/TestName)", }, attrFlag("Test item attribute with format 'key:value'"), + &cli.StringFlag{ + Name: "test-case-id", + Usage: "Test case ID: identifies the same test across launches (by default the server derives it from --code-ref)", + }, + &cli.StringSliceFlag{ + Name: "param", + Usage: "Test parameter with format 'key=value'. Repeatable.", + }, + &cli.StringFlag{ + Name: "retry-of", + Usage: "UUID of the previous attempt: reports this item as its retry. Requires --parent-uuid.", + }, + &cli.BoolFlag{ + Name: "has-stats", + Usage: "Count the item in statistics. Use --has-stats=false for a nested step.", + Value: true, + }, }, Action: withConfig(startTestStep), } @@ -108,6 +137,18 @@ var ( launchUUIDFlag(), itemUUIDFlag(true), statusFlag("Test item status: PASSED, FAILED, SKIPPED, etc."), + &cli.StringFlag{ + Name: "issue-type", + Usage: "Defect type locator (e.g. pb001, ab001, si001, ti001, nd001, or a custom one) or NOT_ISSUE. " + + "The server applies it only to FAILED or SKIPPED items.", + }, + &cli.StringFlag{ + Name: "description", + Usage: "Test item description (replaces the one given at start)", + }, + attrFlag( + "Test item attribute with format 'key:value', added to the ones given at start", + ), }, Action: withConfig(adaptNoResult(finishTestStep)), } @@ -118,6 +159,11 @@ var ( Flags: []cli.Flag{ launchUUIDFlag(), statusFlag("Launch status: PASSED, FAILED, STOPPED, etc."), + &cli.StringFlag{ + Name: "description", + Usage: "Text appended to the launch description given at start", + }, + attrFlag("Launch attribute with format 'key:value', added to the ones given at start"), }, Action: withConfig(adaptNoResult(finishLaunchStep)), } @@ -132,17 +178,86 @@ func adaptNoResult( } } +func launchModes() []string { + return []string{string(gorppkg.LaunchModes.Default), string(gorppkg.LaunchModes.Debug)} +} + +func testItemTypes() []string { + t := gorppkg.TestItemTypes + types := []gorppkg.TestItemType{ + 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, + } + names := make([]string, len(types)) + for i, itemType := range types { + names[i] = string(itemType) + } + + return names +} + +// parseEnumFlag returns the value in upper case if it is one of the allowed values, ignoring case. +func parseEnumFlag(flag, value string, allowed []string) (string, error) { + upper := strings.ToUpper(strings.TrimSpace(value)) + if !slices.Contains(allowed, upper) { + return "", fmt.Errorf( + "invalid --%s %q: must be one of %s", + flag, + value, + strings.Join(allowed, ", "), + ) + } + + return upper, nil +} + +// parseParameters converts 'key=value' arguments to test item parameters. The value may be empty and +// may contain '='; the key is required. +func parseParameters( + paramArgs []string, +) ([]openapi.ComEpamReportportalBaseReportingParameterResource, error) { + if len(paramArgs) == 0 { + return nil, nil + } + params := make([]openapi.ComEpamReportportalBaseReportingParameterResource, len(paramArgs)) + for i, raw := range paramArgs { + key, value, ok := strings.Cut(raw, "=") + if !ok || key == "" { + return nil, fmt.Errorf("invalid --param %q: expected 'key=value'", raw) + } + params[i] = openapi.ComEpamReportportalBaseReportingParameterResource{ + Key: key, + Value: openapi.PtrString(value), + } + } + + return params, nil +} + // --------------------------------------------------------------------------- // Step functions — testable core logic // --------------------------------------------------------------------------- func startLaunchStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) (string, error) { + mode, err := parseEnumFlag("mode", cmd.String("mode"), launchModes()) + if err != nil { + return "", err + } + client := buildReportingClient(ctx, cfg) rq := &openapi.StartLaunchRQ{ Name: cmd.String("name"), StartTime: time.Now(), - Mode: openapi.PtrString(cmd.String("mode")), + Mode: openapi.PtrString(mode), + } + // The server ignores rerunOf unless rerun is set, so --rerun-of alone would silently start a new launch. + if rerunOf := cmd.String("rerun-of"); rerunOf != "" { + rq.Rerun = openapi.PtrBool(true) + rq.RerunOf = openapi.PtrString(rerunOf) + } else if cmd.Bool("rerun") { + rq.Rerun = openapi.PtrBool(true) } if desc := cmd.String("description"); desc != "" { rq.Description = openapi.PtrString(desc) @@ -160,15 +275,44 @@ func startLaunchStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) ( } func startTestStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) (string, error) { + if args := cmd.Args(); args != nil && args.Present() { + // "--has-stats false" leaves "false" as an argument and would report the item with statistics. + return "", fmt.Errorf( + "unexpected argument %q: a boolean flag takes its value with '=', e.g. --has-stats=false", + args.First(), + ) + } + itemType, err := parseEnumFlag("type", cmd.String("type"), testItemTypes()) + if err != nil { + return "", err + } + params, err := parseParameters(cmd.StringSlice("param")) + if err != nil { + return "", err + } + parentUUID := cmd.String("parent-uuid") + retryOf := cmd.String("retry-of") + if retryOf != "" && parentUUID == "" { + // The server refuses a root retry, but only after the asynchronous API has answered 201. + return "", errors.New("--retry-of requires --parent-uuid: a root item can't be a retry") + } + client := buildReportingClient(ctx, cfg) rq := &openapi.StartTestItemRQ{ LaunchUuid: cmd.String("launch-uuid"), Name: cmd.String("name"), - Type: cmd.String("type"), + Type: itemType, StartTime: time.Now(), - HasStats: openapi.PtrBool(true), - Retry: openapi.PtrBool(false), + HasStats: openapi.PtrBool(cmd.Bool("has-stats")), + Retry: openapi.PtrBool(retryOf != ""), + Parameters: params, + } + if retryOf != "" { + rq.RetryOf = openapi.PtrString(retryOf) + } + if testCaseID := cmd.String("test-case-id"); testCaseID != "" { + rq.TestCaseId = openapi.PtrString(testCaseID) } if desc := cmd.String("description"); desc != "" { rq.Description = openapi.PtrString(desc) @@ -181,8 +325,7 @@ func startTestStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) (st } var rs *openapi.EntryCreatedAsyncRS - var err error - if parentUUID := cmd.String("parent-uuid"); parentUUID != "" { + if parentUUID != "" { rs, err = client.StartChildTest(ctx, parentUUID, rq) } else { rs, err = client.StartTest(ctx, rq) @@ -258,6 +401,15 @@ func finishTestStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) er if status := cmd.String("status"); status != "" { rq.Status = openapi.PtrString(status) } + if desc := cmd.String("description"); desc != "" { + rq.Description = openapi.PtrString(desc) + } + if attrs := parseAttributes(cmd.StringSlice("attr")); len(attrs) > 0 { + rq.Attributes = attrs + } + if issueType := cmd.String("issue-type"); issueType != "" { + rq.Issue = &openapi.ComEpamReportportalBaseReportingIssue{IssueType: issueType} + } _, err := client.FinishTest(ctx, cmd.String("item-uuid"), rq) if err != nil { @@ -278,13 +430,23 @@ func finishLaunchStep(ctx context.Context, cfg *clientConfig, cmd *cli.Command) if status := cmd.String("status"); status != "" { rq.Status = openapi.PtrString(status) } + if desc := cmd.String("description"); desc != "" { + rq.Description = openapi.PtrString(desc) + } + if attrs := parseAttributes(cmd.StringSlice("attr")); len(attrs) > 0 { + rq.Attributes = attrs + } - _, err := client.FinishLaunch(ctx, cmd.String("launch-uuid"), rq) + rs, err := client.FinishLaunch(ctx, cmd.String("launch-uuid"), rq) if err != nil { return err } + // The UUID stays on the first line, so scripts that read it keep working. _, _ = fmt.Fprintln(cmd.Writer, cmd.String("launch-uuid")) + if link := rs.GetLink(); link != "" { + _, _ = fmt.Fprintln(cmd.Writer, link) + } return nil } diff --git a/internal/commands/report_steps_test.go b/internal/commands/report_steps_test.go index af464ac..d3df23c 100644 --- a/internal/commands/report_steps_test.go +++ b/internal/commands/report_steps_test.go @@ -148,6 +148,7 @@ func TestStartTestStep_Root(t *testing.T) { &cli.StringFlag{Name: "description"}, &cli.StringFlag{Name: "code-ref"}, &cli.StringSliceFlag{Name: "attr"}, + &cli.BoolFlag{Name: "has-stats", Value: true}, }) id, err := startTestStep(context.Background(), stepCfg(srv.URL, project), cmd) @@ -176,6 +177,7 @@ func TestStartTestStep_Child(t *testing.T) { &cli.StringFlag{Name: "description"}, &cli.StringFlag{Name: "code-ref", Value: "my/package/TestFoo"}, &cli.StringSliceFlag{Name: "attr"}, + &cli.BoolFlag{Name: "has-stats", Value: true}, }) id, err := startTestStep(context.Background(), stepCfg(srv.URL, project), cmd) @@ -307,7 +309,12 @@ func TestFinishLaunchStep(t *testing.T) { require.NoError(t, err) assert.Equal(t, int32(1), launchFinishes.Load()) - assert.Equal(t, "launch-uuid-1\n", buf.String()) + assert.Equal( + t, + "launch-uuid-1\nhttps://rp/launch/1\n", + buf.String(), + "UUID first, then the launch link", + ) } // --------------------------------------------------------------------------- @@ -345,6 +352,7 @@ func TestFullReportingLifecycle(t *testing.T) { &cli.StringFlag{Name: "description"}, &cli.StringFlag{Name: "code-ref"}, &cli.StringSliceFlag{Name: "attr"}, + &cli.BoolFlag{Name: "has-stats", Value: true}, }) testUUID, err := startTestStep(ctx, cfg, testCmd) require.NoError(t, err) @@ -410,3 +418,307 @@ func TestParseAttributes_Empty(t *testing.T) { assert.Nil(t, parseAttributes(nil)) assert.Nil(t, parseAttributes([]string{})) } + +// --------------------------------------------------------------------------- +// Real flag parsing: command line → request body +// --------------------------------------------------------------------------- + +type recordedRequest struct { + Method string + Path string + Body map[string]any +} + +// runReportCommand runs `gorp report ` with the real flag definitions against a server that records +// the request. The tests using it are not parallel: flag instances belong to the package-level commands. +func runReportCommand( + t *testing.T, + response string, + args ...string, +) (stdout string, rqs []recordedRequest, err error) { + t.Helper() + t.Setenv("HOME", t.TempDir()) // no ~/.gorp + for _, env := range []string{"LAUNCH_UUID", "PARENT_UUID", "ITEM_UUID"} { + t.Setenv(env, "") // the flags read them + } + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + rq := recordedRequest{Method: r.Method, Path: r.URL.Path} + assert.NoError(t, json.NewDecoder(r.Body).Decode(&rq.Body)) + rqs = append(rqs, rq) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(response)) + })) + defer srv.Close() + + // Copies, so that a command does not keep the writer it inherited from the root of an earlier run. + var steps []*cli.Command + for _, step := range []*cli.Command{startLaunchCommand, startTestCommand, finishTestCommand, finishLaunchCommand} { + steps = append(steps, &cli.Command{Name: step.Name, Flags: step.Flags, Action: step.Action}) + } + + var buf bytes.Buffer + root := &cli.Command{ + Name: "gorp", + Writer: &buf, + Flags: connectionFlags(srv.URL), + Commands: []*cli.Command{{Name: "report", Commands: steps}}, + } + err = root.Run(t.Context(), append([]string{"gorp", "report"}, args...)) + + return buf.String(), rqs, err +} + +func TestReportStepFlags(t *testing.T) { + t.Run( + "start-launch --rerun-of implies rerun and prints the UUID from the response", + func(t *testing.T) { + out, rqs, err := runReportCommand(t, `{"id":"original-launch"}`, + "start-launch", "--name", "L", "--mode", "debug", "--rerun-of", "original-launch") + + require.NoError(t, err) + require.Len(t, rqs, 1) + assert.Equal(t, "/api/v2/proj/launch", rqs[0].Path) + assert.Equal(t, true, rqs[0].Body["rerun"]) + assert.Equal(t, "original-launch", rqs[0].Body["rerunOf"]) + assert.Equal(t, "DEBUG", rqs[0].Body["mode"], "mode is sent in upper case") + assert.Equal(t, "original-launch\n", out) + }, + ) + + t.Run("start-launch --rerun reruns by name", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"id":"x"}`, "start-launch", "--name", "L", "--rerun") + + require.NoError(t, err) + require.Len(t, rqs, 1) + assert.Equal(t, true, rqs[0].Body["rerun"]) + assert.NotContains(t, rqs[0].Body, "rerunOf") + }) + + t.Run("start-launch without rerun flags sends neither field", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"id":"x"}`, "start-launch", "--name", "L") + + require.NoError(t, err) + require.Len(t, rqs, 1) + assert.NotContains(t, rqs[0].Body, "rerun") + assert.NotContains(t, rqs[0].Body, "rerunOf") + assert.Equal(t, "DEFAULT", rqs[0].Body["mode"]) + }) + + t.Run("start-launch rejects an unknown mode before any request", func(t *testing.T) { + _, rqs, err := runReportCommand( + t, + `{"id":"x"}`, + "start-launch", + "--name", + "L", + "--mode", + "DEBAG", + ) + + require.EqualError(t, err, `invalid --mode "DEBAG": must be one of DEFAULT, DEBUG`) + assert.Empty(t, rqs) + }) + + t.Run("start-test sends test case id, parameters, retry and hasStats", func(t *testing.T) { + _, rqs, err := runReportCommand( + t, + `{"id":"item"}`, + "start-test", + "--launch-uuid", + "l1", + "--parent-uuid", + "p1", + "--name", + "T", + "--type", + "step", + "--test-case-id", + "pkg.T", + "--param", + "browser=chrome", + "--param", + "url=http://x?a=b", + "--param", + "empty=", + "--retry-of", + "prev-attempt", + "--has-stats=false", + ) + + require.NoError(t, err) + require.Len(t, rqs, 1) + body := rqs[0].Body + assert.Equal(t, "/api/v2/proj/item/p1", rqs[0].Path) + assert.Equal(t, "STEP", body["type"], "type is sent in upper case") + assert.Equal(t, "pkg.T", body["testCaseId"]) + assert.Equal(t, []any{ + map[string]any{"key": "browser", "value": "chrome"}, + map[string]any{"key": "url", "value": "http://x?a=b"}, + map[string]any{"key": "empty", "value": ""}, + }, body["parameters"]) + assert.Equal(t, true, body["retry"]) + assert.Equal(t, "prev-attempt", body["retryOf"]) + assert.Equal(t, false, body["hasStats"]) + }) + + t.Run("start-test splits a --param value on commas, like --attr", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"id":"item"}`, + "start-test", "--launch-uuid", "l1", "--name", "T", "--param", "a=1,b=2") + + require.NoError(t, err) + require.Len(t, rqs, 1) + assert.Equal(t, []any{ + map[string]any{"key": "a", "value": "1"}, + map[string]any{"key": "b", "value": "2"}, + }, rqs[0].Body["parameters"]) + }) + + t.Run("start-test rejects '--has-stats false': the value needs '='", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"id":"item"}`, + "start-test", "--launch-uuid", "l1", "--name", "T", "--has-stats", "false") + + require.EqualError( + t, + err, + `unexpected argument "false": a boolean flag takes its value with '=', e.g. --has-stats=false`, + ) + assert.Empty(t, rqs) + }) + + t.Run("start-test defaults are unchanged", func(t *testing.T) { + _, rqs, err := runReportCommand( + t, + `{"id":"item"}`, + "start-test", + "--launch-uuid", + "l1", + "--name", + "T", + ) + + require.NoError(t, err) + require.Len(t, rqs, 1) + body := rqs[0].Body + assert.Equal(t, "TEST", body["type"]) + assert.Equal(t, true, body["hasStats"]) + assert.Equal(t, false, body["retry"]) + for _, field := range []string{"retryOf", "testCaseId", "parameters"} { + assert.NotContains(t, body, field) + } + }) + + for name, tc := range map[string]struct { + args []string + wantErr string + }{ + "unknown type": { + args: []string{"--type", "CASE"}, + wantErr: `invalid --type "CASE": must be one of SUITE, STORY, TEST, SCENARIO, STEP, BEFORE_CLASS, BEFORE_GROUPS, ` + + `BEFORE_METHOD, BEFORE_SUITE, BEFORE_TEST, AFTER_CLASS, AFTER_GROUPS, AFTER_METHOD, AFTER_SUITE, AFTER_TEST`, + }, + "parameter without '='": { + args: []string{"--param", "chrome"}, + wantErr: `invalid --param "chrome": expected 'key=value'`, + }, + "parameter without a key": { + args: []string{"--param", "=chrome"}, + wantErr: `invalid --param "=chrome": expected 'key=value'`, + }, + "parameter value with a comma": { + args: []string{"--param", "list=a,b"}, + wantErr: `invalid --param "b": expected 'key=value'`, + }, + "retry of a root item": { + args: []string{"--retry-of", "prev"}, + wantErr: "--retry-of requires --parent-uuid: a root item can't be a retry", + }, + } { + t.Run("start-test rejects "+name+" before any request", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"id":"item"}`, + append([]string{"start-test", "--launch-uuid", "l1", "--name", "T"}, tc.args...)...) + + require.EqualError(t, err, tc.wantErr) + assert.Empty(t, rqs) + }) + } + + t.Run("finish-test sends issue type, description and attributes", func(t *testing.T) { + out, rqs, err := runReportCommand( + t, + `{"message":"ok"}`, + "finish-test", + "--launch-uuid", + "l1", + "--item-uuid", + "i1", + "--status", + "FAILED", + "--issue-type", + "pb001", + "--description", + "why", + "--attr", + "owner:qa", + "--attr", + "flaky", + ) + + require.NoError(t, err) + require.Len(t, rqs, 1) + body := rqs[0].Body + assert.Equal(t, "/api/v2/proj/item/i1", rqs[0].Path) + assert.Equal(t, map[string]any{"issueType": "pb001"}, body["issue"]) + assert.Equal(t, "why", body["description"]) + assert.Equal(t, []any{ + map[string]any{"key": "owner", "value": "qa", "system": false}, + map[string]any{"value": "flaky", "system": false}, + }, body["attributes"]) + assert.Equal(t, "i1\n", out) + }) + + t.Run("finish-test without the new flags sends none of the fields", func(t *testing.T) { + _, rqs, err := runReportCommand(t, `{"message":"ok"}`, + "finish-test", "--launch-uuid", "l1", "--item-uuid", "i1", "--status", "PASSED") + + require.NoError(t, err) + require.Len(t, rqs, 1) + for _, field := range []string{"issue", "description", "attributes"} { + assert.NotContains(t, rqs[0].Body, field) + } + }) + + t.Run("finish-launch sends description and attributes and prints the link", func(t *testing.T) { + out, rqs, err := runReportCommand( + t, + `{"id":"l1","link":"https://rp/ui/#proj/launches/all/l1"}`, + "finish-launch", + "--launch-uuid", + "l1", + "--status", + "PASSED", + "--description", + "done", + "--attr", + "build:42", + ) + + require.NoError(t, err) + require.Len(t, rqs, 1) + assert.Equal(t, "/api/v2/proj/launch/l1/finish", rqs[0].Path) + assert.Equal(t, "done", rqs[0].Body["description"]) + assert.Equal( + t, + []any{map[string]any{"key": "build", "value": "42", "system": false}}, + rqs[0].Body["attributes"], + ) + assert.Equal(t, "l1\nhttps://rp/ui/#proj/launches/all/l1\n", out) + }) + + t.Run("finish-launch prints only the UUID when the server returns no link", func(t *testing.T) { + out, _, err := runReportCommand(t, `{"id":"l1"}`, "finish-launch", "--launch-uuid", "l1") + + require.NoError(t, err) + assert.Equal(t, "l1\n", out) + }) +}