### Install gotestsum with go install Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Install gotestsum globally using the go install command. This makes the gotestsum executable available in your system's PATH. ```bash go install gotest.tools/gotestsum@latest ``` -------------------------------- ### Combine Post-Run Command with Test Summary Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md This example demonstrates combining --jsonfile with --post-run-command to print the slowest tests after the main test run. It uses bash to execute a secondary gotestsum command. ```bash gotestsum \ --jsonfile tmp.json.log \ --post-run-command "bash -c \ 'echo; echo Slowest tests;\ gotestsum tool slowest --num 10 --jsonfile tmp.json.log'" ``` -------------------------------- ### Run gotestsum with go run Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Execute gotestsum directly using 'go run' without installing it globally. This is useful for quick tests or when you don't want to add it to your global environment. ```bash go run gotest.tools/gotestsum@latest ``` -------------------------------- ### Hide skipped tests in summary Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Customize the test summary output by hiding specific sections. This example hides the 'skipped' tests count and details from the summary. ```bash gotestsum --hide-summary=skipped ``` -------------------------------- ### Parse Go Test Output with testjson.ScanTestOutput Source: https://context7.com/gotestyourself/gotestsum/llms.txt The `testjson.ScanTestOutput` function parses `test2json` streams, invoking an `EventHandler` for each event. This example demonstrates a custom handler to process failed tests and iterate through execution results. ```go import ( "os" "strings" "fmt" "gotest.tools/gotestsum/testjson" ) // Custom event handler type myHandler struct{} func (h myHandler) Event(event testjson.TestEvent, exec *testjson.Execution) error { if event.Action == testjson.ActionFail && !event.PackageEvent() { fmt.Printf("FAILED: %s/%s (%.2fs)\n", event.Package, event.Test, event.Elapsed) } return nil } func (h myHandler) Err(text string) error { fmt.Fprintln(os.Stderr, "stderr:", text) return nil } func main() { // Parse a saved jsonfile f, err := os.Open("test-output.log") if err != nil { panic(err) } defer f.Close() exec, err := testjson.ScanTestOutput(testjson.ScanConfig{ Stdout: f, Handler: myHandler{}, }) if err != nil { panic(err) } fmt.Printf("Total: %d, Failed: %d, Skipped: %d\n", exec.Total(), len(exec.Failed()), len(exec.Skipped()), ) // Iterate over failed test cases for _, tc := range exec.Failed() { pkg := exec.Package(tc.Package) fmt.Printf("\n--- FAIL: %s/%s\n", tc.Package, tc.Test) for _, line := range pkg.OutputLines(tc) { fmt.Print(line) } } // List all packages for _, name := range exec.Packages() { pkg := exec.Package(name) fmt.Printf("pkg %s: result=%s elapsed=%s\n", name, pkg.Result(), pkg.Elapsed()) } } ``` -------------------------------- ### Find Slow Tests with aggregate.Slowest Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use `aggregate.Slowest` to filter and sort test cases by elapsed time from a `testjson.Execution`. You can specify a time threshold (e.g., 200ms) to find tests slower than that, or a count to get the top N slowest tests, sorted with the slowest first. Both threshold and count can be zero to disable filtering. ```go import ( "fmt" "os" "time" "gotest.tools/gotestsum/internal/aggregate" "gotest.tools/gotestsum/testjson" ) func main() { f, _ := os.Open("test-output.log") defer f.Close() exec, err := testjson.ScanTestOutput(testjson.ScanConfig{Stdout: f}) if err != nil { panic(err) } // Get all tests slower than 200ms, sorted slowest first slow := aggregate.Slowest(exec, 200*time.Millisecond, 0) for _, tc := range slow { fmt.Printf("%s %s %s\n", tc.Package, tc.Test, tc.Elapsed) } // Get only the top 5 slowest regardless of threshold top5 := aggregate.Slowest(exec, 0, 5) for _, tc := range top5 { fmt.Printf("%.2fs %s\n", tc.Elapsed.Seconds(), tc.Test) } } ``` -------------------------------- ### Basic Test Run with Format Selection Source: https://context7.com/gotestyourself/gotestsum/llms.txt Control the output style using the --format flag or GOTESTSUM_FORMAT environment variable. Runs 'go test -json ./...' by default. Flags after '--' are passed directly to 'go test'. ```sh gotestsum ``` ```sh gotestsum --format testname ``` ```sh gotestsum --format dots ``` ```sh gotestsum --format testdox ``` ```sh gotestsum --format standard-verbose ``` ```sh gotestsum --format github-actions ``` ```sh gotestsum --format testname -- -tags=integration -count=2 ./... ``` ```sh gotestsum -- ./internal/junitxml/... ``` ```sh gotestsum -- -coverprofile=cover.out ./... ``` ```sh TEST_DIRECTORY=./cmd gotestsum --format testname ``` -------------------------------- ### Typical Gotestsum Local Development and CI Usage Source: https://context7.com/gotestyourself/gotestsum/llms.txt Illustrates common patterns for using gotestsum during local development with watch mode and in CI for detailed test output. The `--rerun-fails` flag is beneficial for large test suites. ```bash gotestsum --watch --format testname ``` ```bash gotestsum --junitfile unit-tests.xml --jsonfile test-output.log -- -race ./... ``` -------------------------------- ### Execute compiled test binary with gotestsum Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Execute a compiled test binary using --raw-command. Ensure 'go tool test2json' is used to format output for gotestsum, as the -json flag is not available for compiled binaries. The -test.v flag must be included for go tool test2json to capture all output. ```bash gotestsum --raw-command -- go tool test2json -t -p pkgname ./binary.test -test.v ``` -------------------------------- ### Skip slow tests with go test --short Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md This command demonstrates how to skip tests that are slower than a specified threshold when using `go test --short`. Tests slower than 200ms will be modified to include a skip statement. ```go if testing.Short() { t.Skip("too slow for testing.Short") } ``` ```sh go test -json -short ./... | gotestsum tool slowest --skip-stmt "testing.Short" --threshold 200ms ``` -------------------------------- ### Distribute Packages with gotestsum tool ci-matrix Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use `gotestsum tool ci-matrix` to generate a GitHub Actions matrix for distributing Go packages across parallel CI jobs. It reads historical timing data to optimize job distribution and minimize total CI time. ```sh # Capture timing events during CI runs (write per-run logs) gotestsum --jsonfile-timing-events ./logs/run-$(date +%s).log -- ./... ``` ```sh # Generate a 4-partition matrix from timing history echo -n "matrix=" >> $GITHUB_OUTPUT go list ./... | gotestsum tool ci-matrix \ --timing-files './logs/*.log' \ --partitions 4 >> $GITHUB_OUTPUT # Example JSON output: # {"include":[ # {"id":0,"estimatedRuntime":"1m2s","packages":"pkg/a pkg/b","description":"0 - pkg/a and 1 others"}, # {"id":1,"estimatedRuntime":"58s","packages":"pkg/c","description":"1 - pkg/c"}, # ... # ]} ``` ```yaml # GitHub Actions workflow usage: # jobs: # prepare: # outputs: # matrix: ${{ steps.matrix.outputs.matrix }} # steps: # - id: matrix # run: | # echo -n "matrix=" >> $GITHUB_OUTPUT # go list ./... | gotestsum tool ci-matrix --timing-files './logs/*.log' --partitions 4 >> $GITHUB_OUTPUT # test: # needs: prepare # strategy: # matrix: ${{ fromJson(needs.prepare.outputs.matrix) }} # steps: # - run: gotestsum --jsonfile-timing-events ./logs/${{ matrix.id }}.log -- ${{ matrix.packages }} ``` -------------------------------- ### Custom go test command with gotestsum Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Customize the go test command using positional arguments after '--'. The default test directory is './...'. Use --debug to see the command before execution. Environment variable TEST_DIRECTORY can also set the test directory. ```bash gotestsum -- -tags=integration ./... ``` ```bash gotestsum -- ./io/http ``` ```bash gotestsum -- -coverprofile=cover.out ./... ``` ```bash gotestsum --raw-command -- ./scripts/run_tests.sh ``` ```bash cat out.json | gotestsum --raw-command -- cat ``` ```bash #!/usr/bin/env bash set -eu for pkg in $(go list "$@"); do dir="$(go list -f '{{ .Dir }}' $pkg)" go test -json -cpuprofile="$dir/cpu.profile" "$pkg" done ``` ```bash gotestsum --raw-command ./profile.sh ./... ``` ```bash TEST_DIRECTORY=./io/http gotestsum ``` -------------------------------- ### Run tests when a file is saved with gotestsum Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Use the `--watch` flag to automatically run tests when a Go file in a watched directory is modified. By default, all directories under the current directory with at least one `.go` file will be watched. ```sh gotestsum --watch --format testname ``` -------------------------------- ### Use Custom Test Runners with --raw-command Source: https://context7.com/gotestyourself/gotestsum/llms.txt The --raw-command flag bypasses the default `go test -json` invocation, allowing you to use custom scripts or binaries that emit `test2json`-compatible output. This enables advanced scenarios like piping saved logs, running compiled test binaries, or profiling individual packages. ```sh # Run a custom shell script that emits test2json output gotestsum --raw-command -- ./scripts/run_tests.sh ``` ```sh # Accept input from stdin (pipe a saved log) cat out.json | gotestsum --raw-command -- cat ``` ```sh # Run a compiled test binary via go tool test2json gotestsum --raw-command -- go tool test2json -t -p mypkg ./binary.test -test.v ``` ```sh # Profile each package individually gotestsum --raw-command -- ./profile.sh ./... # profile.sh example: # #!/usr/bin/env bash # for pkg in $(go list "$@"); do # dir="$(go list -f '{{ .Dir }}' $pkg)" # go test -json -cpuprofile="$dir/cpu.profile" "$pkg" # done ``` ```sh # Ignore non-JSON lines written to stdout (redirected to stderr) gotestsum --raw-command --ignore-non-json-output-lines -- ./mixed-output-script.sh ``` -------------------------------- ### Generate JUnit XML Reports Source: https://context7.com/gotestyourself/gotestsum/llms.txt Create JUnit XML reports for CI systems using --junitfile. Options include setting project name, package name format, and omitting empty packages or skipped tests. ```sh gotestsum --junitfile unit-tests.xml ``` ```sh gotestsum --junitfile unit-tests.xml --junitfile-project-name "my-service" ``` ```sh gotestsum \ --junitfile unit-tests.xml \ --junitfile-testsuite-name short \ --junitfile-testcase-classname short ``` ```sh gotestsum \ --junitfile unit-tests.xml \ --junitfile-testsuite-name relative \ --junitfile-testcase-classname relative ``` ```sh gotestsum --junitfile unit-tests.xml --junitfile-hide-empty-pkg ``` ```sh gotestsum --junitfile unit-tests.xml --junitfile-hide-skipped-tests ``` ```sh GOVERSION="go1.22.0 linux/amd64" gotestsum --junitfile unit-tests.xml ``` ```sh GOTESTSUM_JUNITFILE=unit-tests.xml gotestsum ``` -------------------------------- ### Gotestsum CI Matrix Integration Source: https://context7.com/gotestyourself/gotestsum/llms.txt Utilize the `ci-matrix` subcommand to integrate with GitHub Actions matrix strategies. This command balances test packages across parallel runners based on historical timing data to optimize CI duration. ```bash gotestsum tool ci-matrix ``` -------------------------------- ### Run Go Tests with Race Detector using Gotestsum Source: https://context7.com/gotestyourself/gotestsum/llms.txt Execute Go tests with the race detector enabled, passing arguments to the underlying `go test` command via gotestsum. This is a common pattern in CI pipelines. ```bash gotestsum -- -race ./... ``` -------------------------------- ### Print Test Summaries with testjson.PrintSummary Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use `PrintSummary` to write the post-run summary (failures, skipped, errors, DONE line) to an `io.Writer`. The `Summary` bitmask controls which sections are included. You can print all sections, only the DONE line, or selectively hide specific sections like skipped tests. ```go import ( "os" "gotest.tools/gotestsum/testjson" ) func printResults(exec *testjson.Execution) { // Print all summary sections (default) testjson.PrintSummary(os.Stdout, exec, testjson.SummarizeAll) // Print only the DONE line (suppress everything else) testjson.PrintSummary(os.Stdout, exec, testjson.SummarizeNone) // Hide skipped tests from summary hide := testjson.SummarizeAll skipped, _ := testjson.NewSummary("skipped") hide -= skipped testjson.PrintSummary(os.Stdout, exec, hide) } ``` -------------------------------- ### Execute Post-Run Commands with --post-run-command Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use --post-run-command to execute an arbitrary command after each test run. The command can access test statistics via environment variables. This is useful for notifications, generating reports, or triggering other build steps. ```sh # Desktop notification (using contrib/notify) gotestsum --post-run-command notify ``` ```sh # Command with flags (quote the whole command) gotestsum --post-run-command "notify me --date" ``` ```sh # Print slowest 10 tests after the summary gotestsum \ --jsonfile tmp.json.log \ --post-run-command "bash -c ' echo; echo Slowest tests; gotestsum tool slowest --num 10 --jsonfile tmp.json.log'" ``` ```sh # Environment variables available inside the post-run command: # GOTESTSUM_ELAPSED — run time in seconds, e.g. "2.45s" # GOTESTSUM_FORMAT — format name, e.g. "pkgname" # GOTESTSUM_JSONFILE — path to the jsonfile (empty if not set) # GOTESTSUM_JUNITFILE — path to the junitfile (empty if not set) # TESTS_TOTAL — total number of test cases run # TESTS_FAILED — number of failed test cases # TESTS_SKIPPED — number of skipped test cases # TESTS_ERRORS — number of build/package errors ``` -------------------------------- ### Generate JUnit XML with junitxml.Write Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use `junitxml.Write` to serialize a `testjson.Execution` into a JUnit XML document. This function requires an `io.Writer` for the output file and a `junitxml.Config` struct to customize aspects like `ProjectName`, `FormatTestSuiteName`, and whether to `HideEmptyPackages` or `HideSkippedTests`. ```go import ( "os" "gotest.tools/gotestsum/internal/junitxml" "gotest.tools/gotestsum/testjson" ) func writeJUnit(exec *testjson.Execution, path string) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() return junitxml.Write(f, exec, junitxml.Config{ ProjectName: "my-service", FormatTestSuiteName: nil, // nil = full package path (default) FormatTestCaseClassname: nil, HideEmptyPackages: true, HideSkippedTests: false, }) } ``` -------------------------------- ### Create Test Output Formatters with testjson.NewEventFormatter Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use `NewEventFormatter` to create an `EventFormatter` for a specific output format. This formatter can then be used with `ScanTestOutput` to stream formatted test results. Available formats include 'testname', 'dots', 'github-actions', and more. Options like `HideEmptyPackages` and `Icons` can customize the output. ```go import ( "os" "strings" "gotest.tools/gotestsum/testjson" ) func main() { // Available format names: // "pkgname", "testname", "testdox", "dots", "dots-v2", // "standard-verbose", "standard-quiet", "github-actions", "none" formatter := testjson.NewEventFormatter(os.Stdout, "testname", testjson.FormatOptions{ HideEmptyPackages: true, Icons: "hivis", // or "text", "codicons", "octicons", "emoticons" }) // Plug into ScanTestOutput f, _ := os.Open("test-output.log") defer f.Close() _, err := testjson.ScanTestOutput(testjson.ScanConfig{ Stdout: f, Handler: testjson.HandlerFunc(formatter.Format), }) if err != nil { panic(err) } } ``` -------------------------------- ### Environment Variables for Gotestsum Configuration Source: https://context7.com/gotestyourself/gotestsum/llms.txt Configure Gotestsum behavior using environment variables. These variables allow customization of output format, icons, output file paths for JSON and JUnit XML, and JUnit-specific flags like hiding empty packages or skipped tests. They are particularly useful for CI environments. ```sh # Format GOTESTSUM_FORMAT=testname GOTESTSUM_FORMAT_ICONS=hivis # Output files GOTESTSUM_JSONFILE=./logs/test-output.log GOTESTSUM_JSONFILE_TIMING_EVENTS=./logs/timing.log GOTESTSUM_JUNITFILE=./reports/unit-tests.xml GOTESTSUM_JUNITFILE_PROJECT_NAME=my-service # JUnit flags GOTESTSUM_JUNIT_HIDE_EMPTY_PKG=true GOTESTSUM_JUNIT_HIDE_SKIPPED_TESTS=true # Skip go version lookup warning when go is not in PATH GOVERSION="go1.24.0 linux/amd64" # Override the default test directory (./...) TEST_DIRECTORY=./cmd ``` -------------------------------- ### Watch File Changes with --watch Source: https://context7.com/gotestyourself/gotestsum/llms.txt The --watch flag enables file-system watch mode, automatically re-running tests for modified packages. It can be combined with options to run all packages, change directories, clear the screen, or use interactive keys for manual control. ```sh # Watch and run tests for changed packages gotestsum --watch --format testname ``` ```sh # Also run ./... on every change (in addition to the changed package) gotestsum --watch -- "./..." ``` ```sh # Change directory to the modified file's directory before running (multi-module repos) gotestsum --watch --watch-chdir ``` ```sh # Clear screen before each test re-run gotestsum --watch --watch-clear ``` ```sh # Interactive keys while watching: # r - re-run tests for the previous event # u - re-run tests with -update flag # d - debug with delve (requires dlv in PATH) # a - run all packages (./...) # l - rescan directories for new .go files ``` -------------------------------- ### testjson.PrintSummary Source: https://context7.com/gotestyourself/gotestsum/llms.txt Writes the post-run summary (failures, skipped, errors, and DONE line) to an io.Writer. The Summary bitmask controls which sections are included in the output. ```APIDOC ## Go package — `testjson.PrintSummary`: print the post-run summary `PrintSummary` writes the summary block (failures, skipped, errors, and the `DONE` line) to any `io.Writer`. The `Summary` bitmask controls which sections are included. ```go import ( "os" "gotest.tools/gotestsum/testjson" ) func printResults(exec *testjson.Execution) { // Print all summary sections (default) testjson.PrintSummary(os.Stdout, exec, testjson.SummarizeAll) // Print only the DONE line (suppress everything else) testjson.PrintSummary(os.Stdout, exec, testjson.SummarizeNone) // Hide skipped tests from summary hide := testjson.SummarizeAll skipped, _ := testjson.NewSummary("skipped") hide -= skipped testjson.PrintSummary(os.Stdout, exec, hide) } // Example output: // --- FAIL: TestSomething (1.23s) // example_test.go:42: expected foo got bar // DONE 101 tests, 3 skipped, 1 failure in 4.302s ``` ``` -------------------------------- ### Save Raw Test Events with --jsonfile Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use the --jsonfile flag to save all test2json events to a newline-delimited JSON file. This file can be replayed or parsed later. It can be used with default settings or to keep verbose data while showing compact output on screen. ```sh # Save all events to test-output.log gotestsum --jsonfile test-output.log ``` ```sh # Use compact output on screen while keeping verbose data in the file gotestsum --format pkgname --jsonfile test-output.log -- "./..." ``` ```sh # Save only terminal events (pass/fail/skip) — useful for timing analysis gotestsum --jsonfile-timing-events timing.log -- "./..." ``` ```sh # Pipe previously saved output back in (via raw-command + cat) cat test-output.log | gotestsum --raw-command -- cat ``` ```sh # Via environment variable GOTESTSUM_JSONFILE=test-output.log gotestsum ``` -------------------------------- ### Customize Pass/Fail/Skip Icons Source: https://context7.com/gotestyourself/gotestsum/llms.txt Modify icons used in 'pkgname' and 'testdox' formats with --format-icons or GOTESTSUM_FORMAT_ICONS. Supports unicode, emoji, plain text, and various Nerd Fonts. ```sh gotestsum --format testdox ``` ```sh gotestsum --format testdox --format-icons hivis ``` ```sh gotestsum --format testdox --format-icons text ``` ```sh gotestsum --format testdox --format-icons codicons ``` ```sh gotestsum --format testdox --format-icons octicons ``` ```sh gotestsum --format testdox --format-icons emoticons ``` ```sh GOTESTSUM_FORMAT_ICONS=hivis gotestsum --format pkgname ``` -------------------------------- ### Print slow tests with gotestsum Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Use this command to print a list of tests slower than a specified threshold. It requires test2json output, which can be generated with `gotestsum --jsonfile` or `go test -json`. ```sh $ gotestsum --format dots --jsonfile json.log [.]····↷··↷· $ gotestsum tool slowest --jsonfile json.log --threshold 500ms gotest.tools/example TestSomething 1.34s gotest.tools/example TestSomethingElse 810ms ``` -------------------------------- ### Generate JUnit XML Report Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Use the --junitfile flag to generate a JUnit XML report for CI integration. Package names can be customized using --junitfile-testsuite-name or --junitfile-testcase-classname flags. ```bash gotestsum --junitfile unit-tests.xml ``` -------------------------------- ### Export Environment Variables for Gotestsum CI Source: https://context7.com/gotestyourself/gotestsum/llms.txt Set environment variables to configure gotestsum's output format and file destinations for CI environments. This is useful for standardizing test reporting. ```bash export GOTESTSUM_FORMAT=testname export GOTESTSUM_JUNITFILE=unit-tests.xml export GOTESTSUM_JSONFILE=test-output.log ``` -------------------------------- ### Stop Gotestsum Run Early with --max-fails Source: https://context7.com/gotestyourself/gotestsum/llms.txt Use the `--max-fails` flag to limit the number of test failures before stopping the entire test run. This is useful for quickly identifying critical issues. ```sh # Stop after the first 3 failures gotestsum --max-fails=3 -- ./... ``` -------------------------------- ### Execute Post-Run Command Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md The --post-run-command flag executes a command after tests complete, with environment variables like GOTESTSUM_ELAPSED and TESTS_FAILED set. This can be used for notifications or custom reporting. ```bash gotestsum --post-run-command notify ``` -------------------------------- ### Control Post-Run Summary Section Source: https://context7.com/gotestyourself/gotestsum/llms.txt Suppress specific sections (skipped, failed, errors, output) from the summary using --hide-summary or by setting it to 'all'. ```sh gotestsum ``` ```sh gotestsum --hide-summary=skipped ``` ```sh gotestsum --hide-summary=skipped,failed,errors,output ``` ```sh gotestsum --hide-summary=all ``` ```sh gotestsum --hide-summary=output ``` -------------------------------- ### Hide all sections except DONE line in summary Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Completely customize the test summary by hiding all sections except the final 'DONE' line. This provides a minimal summary. ```bash gotestsum --hide-summary=skipped,failed,errors,output ``` ```bash gotestsum --hide-summary=all ``` -------------------------------- ### Generate JSON Report Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Use the --jsonfile flag to generate a line-delimited JSON file with test2json output. This is useful for comparing test runs and identifying flaky tests. ```bash gotestsum --jsonfile test-output.log ``` -------------------------------- ### Re-run failed tests with gotestsum Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Use the --rerun-fails flag to re-run failed tests until they pass or a maximum number of attempts is reached. The maximum attempts defaults to 2 and can be configured with --rerun-fails=n. To prevent re-runs on too many failures, use --rerun-fails-max-failures=n, which defaults to 10. Data races during re-runs can be handled with --rerun-fails-abort-on-data-race. ```bash gotestsum --rerun-fails --packages="./..." -- -count=2 ``` ```bash gotestsum --rerun-fails --packages="./..." -- -count=2 -args -update-golden ``` -------------------------------- ### Pass Flags to Post-Run Command Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md To pass arguments to the post-run command, quote the entire command. This allows for more complex command execution with specific flags. ```bash gotestsum --post-run-command "notify me --date" ``` -------------------------------- ### junitxml.Write Source: https://context7.com/gotestyourself/gotestsum/llms.txt Serializes a completed testjson.Execution as a JUnit XML document to a specified writer. It allows configuration for project name, test suite naming, classname formatting, and options to hide empty packages or skipped tests. ```APIDOC ## Go package — `junitxml.Write`: generate JUnit XML programmatically `junitxml.Write` serializes a completed `testjson.Execution` as a JUnit XML document. ```go import ( "os" "gotest.tools/gotestsum/internal/junitxml" "gotest.tools/gotestsum/testjson" ) func writeJUnit(exec *testjson.Execution, path string) error { f, err := os.Create(path) if err != nil { return err } defer f.Close() return junitxml.Write(f, exec, junitxml.Config{ ProjectName: "my-service", FormatTestSuiteName: nil, // nil = full package path (default) FormatTestCaseClassname: nil, HideEmptyPackages: true, HideSkippedTests: false, }) } // Example XML output (truncated): // // // // // // ... // // ``` ``` -------------------------------- ### testjson.NewEventFormatter Source: https://context7.com/gotestyourself/gotestsum/llms.txt Creates an EventFormatter for a named format, allowing programmatic streaming of formatted test output. It supports various predefined formats and customizable options like hiding empty packages and choosing icon styles. ```APIDOC ## Go package — `testjson.NewEventFormatter`: create output formatters `NewEventFormatter` returns an `EventFormatter` for a named format. Formatters can be used programmatically to stream formatted output. ```go import ( "os" "strings" "gotest.tools/gotestsum/testjson" ) func main() { // Available format names: // "pkgname", "testname", "testdox", "dots", "dots-v2", // "standard-verbose", "standard-quiet", "github-actions", "none" formatter := testjson.NewEventFormatter(os.Stdout, "testname", testjson.FormatOptions{ HideEmptyPackages: true, Icons: "hivis", // or "text", "codicons", "octicons", "emoticons" }) // Plug into ScanTestOutput f, _ := os.Open("test-output.log") defer f.Close() _, err := testjson.ScanTestOutput(testjson.ScanConfig{ Stdout: f, Handler: testjson.HandlerFunc(formatter.Format), }) if err != nil { panic(err) } } ``` ``` -------------------------------- ### Analyze Slow Tests with gotestsum tool slowest Source: https://context7.com/gotestyourself/gotestsum/llms.txt Identify and optionally skip slow tests using `gotestsum tool slowest`. It processes `test2json` output to find tests exceeding a specified threshold or to list the N slowest tests. It can also rewrite source files to add skip statements. ```sh # First capture a JSON log gotestsum --format dots --jsonfile json.log -- ./... ``` ```sh # Print tests slower than 500ms gotestsum tool slowest --jsonfile json.log --threshold 500ms # Output: # gotest.tools/example TestSomething 1.34s # gotest.tools/example TestSomethingElse 810ms ``` ```sh # Print only the 10 slowest tests regardless of threshold gotestsum tool slowest --jsonfile json.log --num 10 ``` ```sh # Add a testing.Short() skip statement to tests slower than 200ms go test -json ./... | gotestsum tool slowest \ --skip-stmt "testing.Short" \ --threshold 200ms # Modifies source files to add: # if testing.Short() { # t.Skip("too slow for testing.Short") # } ``` ```sh # Custom skip statement skip_stmt='if os.Getenv("TEST_FAST") != "" { t.Skip("too slow for TEST_FAST") }' gotestsum tool slowest --skip-stmt "$skip_stmt" --threshold 200ms --jsonfile json.log ``` ```sh # Then skip slow tests in the next run gotestsum -- -short ./... ``` -------------------------------- ### Hide test output in summary Source: https://github.com/gotestyourself/gotestsum/blob/main/README.md Control the verbosity of the test summary by hiding the detailed output of failed and skipped tests, while still showing names and errors. ```bash gotestsum --hide-summary=output ``` -------------------------------- ### Rerun Failed Tests with --rerun-fails Source: https://context7.com/gotestyourself/gotestsum/llms.txt The --rerun-fails flag reruns failing tests individually until they pass or an attempt limit is reached, helping to manage flaky tests. You can specify the maximum number of reruns or configure behavior like rerunning the root test, aborting on data races, or setting a failure threshold. ```sh # Enable with default max 2 reruns gotestsum --rerun-fails ``` ```sh # Allow up to 5 reruns per failing test gotestsum --rerun-fails=5 ``` ```sh # Must supply --packages when passing go test flags after -- gotestsum --rerun-fails --packages="./..." -- -count=2 ``` ```sh # Pass flags to the test binary using -args gotestsum --rerun-fails --packages="./..." -- -count=2 -args -update-golden ``` ```sh # Rerun entire root test when any subtest fails (instead of only the subtest) gotestsum --rerun-fails --rerun-fails-run-root-test --packages="./..." ``` ```sh # Abort reruns if a data race is detected gotestsum --rerun-fails --rerun-fails-abort-on-data-race --packages="./..." ``` ```sh # Increase the failure threshold before reruns are skipped (default 10) gotestsum --rerun-fails --rerun-fails-max-failures=20 --packages="./..." ``` ```sh # Write a report of rerun tests (package.TestName: N runs, N failures) gotestsum --rerun-fails --rerun-fails-report=rerun-report.txt --packages="./..." ``` -------------------------------- ### aggregate.Slowest Source: https://context7.com/gotestyourself/gotestsum/llms.txt Filters and sorts test cases by elapsed time from an Execution object. It can retrieve all tests slower than a specified duration or the top N slowest tests, regardless of duration. ```APIDOC ## Go package — `aggregate.Slowest`: find slow tests programmatically `aggregate.Slowest` filters and sorts test cases by elapsed time from an `Execution`. ```go import ( "fmt" "os" "time" "gotest.tools/gotestsum/internal/aggregate" "gotest.tools/gotestsum/testjson" ) func main() { f, _ := os.Open("test-output.log") defer f.Close() exec, err := testjson.ScanTestOutput(testjson.ScanConfig{Stdout: f}) if err != nil { panic(err) } // Get all tests slower than 200ms, sorted slowest first slow := aggregate.Slowest(exec, 200*time.Millisecond, 0) for _, tc := range slow { fmt.Printf("%s %s %s\n", tc.Package, tc.Test, tc.Elapsed) } // Get only the top 5 slowest regardless of threshold top5 := aggregate.Slowest(exec, 0, 5) for _, tc := range top5 { fmt.Printf("%.2fs %s\n", tc.Elapsed.Seconds(), tc.Test) } } // Output example: // gotest.tools/gotestsum/cmd TestE2E_RerunFails 3.21s // gotest.tools/gotestsum/testjson TestScanTestOutput 820ms ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.