### Install tparse using go install Source: https://github.com/mfridman/tparse/blob/main/README.md Install the tparse tool using the go install command. Ensure your Go environment is set up correctly. ```bash go install github.com/mfridman/tparse@latest ``` -------------------------------- ### Programmatic CLI Entry Point with app.Run Source: https://context7.com/mfridman/tparse/llms.txt Use app.Run to programmatically execute tparse functionality. Configure output, sorting, filtering, and file input/output via the app.Options struct. ```go package main import ( "fmt" "io" "os" "github.com/mfridman/tparse/internal/app" "github.com/mfridman/tparse/parse" ) func main() { opts := app.Options{ Output: os.Stdout, DisableColor: false, Format: app.OutputFormatBasic, Sorter: parse.SortByPackageName, ShowNoTests: false, FileName: "results.out", // read from file; omit to read from stdin pipe TestTableOptions: app.TestTableOptions{ Pass: true, Skip: true, Trim: false, Slow: 10, // show only 10 slowest passed tests }, SummaryTableOptions: app.SummaryTableOptions{ TrimPath: "auto", }, FollowOutput: false, FollowOutputWriter: io.NopCloser(io.Discard), Progress: false, } exitCode, err := app.Run(opts) if err != nil { fmt.Fprintf(os.Stderr, "tparse error: %v\n", err) } os.Exit(exitCode) } ``` -------------------------------- ### parse.Process with OptionsFunc Source: https://context7.com/mfridman/tparse/llms.txt Demonstrates using `parse.Process` with functional options to configure its behavior, such as enabling follow output, setting a writer for output, enabling debug mode, and controlling timestamp inclusion. ```APIDOC ## parse.Process with OptionsFunc ### Description Configures the `parse.Process` function using functional options to customize its behavior, including enabling follow output, specifying a writer for output, activating debug logging, and controlling the inclusion of timestamps. ### Method `parse.Process(reader io.Reader, opts ...parse.OptionsFunc) (*parse.GoTestSummary, error)` ### Parameters - `reader io.Reader`: The input stream of `go test -json` output. - `opts ...parse.OptionsFunc`: - `parse.WithFollowOutput(bool)`: Enables streaming of plain text `go test` output. - `parse.WithWriter(io.Writer)`: Sets the destination writer for follow output. - `parse.WithDebug()`: Enables surfacing of JSON parse errors to stderr. - `parse.WithIncludeTimestamp(bool)`: Prefixes follow output lines with RFC3339 timestamps. ``` -------------------------------- ### Configure parse.Process with OptionsFunc Source: https://context7.com/mfridman/tparse/llms.txt Use `OptionsFunc` with `parse.Process` to customize behavior like streaming follow output, setting the writer for follow output, enabling debug logging for parse errors, and including timestamps. Ensure all necessary imports are present. ```go package main import ( "os" "strings" "github.com/mfridman/tparse/parse" ) func main() { jsonOutput := strings.NewReader(`{"Action":"run","Package":"example/pkg","Test":"TestFoo"} {"Action":"output","Package":"example/pkg","Test":"TestFoo","Output":" log line\n"} {"Action":"pass","Package":"example/pkg","Test":"TestFoo","Elapsed":0.01} {"Action":"pass","Package":"example/pkg","Elapsed":0.01} `) // WithFollowOutput streams the plain text go test output to the provided writer // WithWriter sets the destination writer for follow output // WithDebug surfaces JSON parse errors to stderr // WithIncludeTimestamp prefixes follow output lines with RFC3339 timestamps summary, err := parse.Process( jsonOutput, parse.WithFollowOutput(true), parse.WithWriter(os.Stdout), parse.WithDebug(), parse.WithIncludeTimestamp(false), ) if err != nil { panic(err) } _ = summary } ``` -------------------------------- ### Process Go Test JSON Output Source: https://context7.com/mfridman/tparse/llms.txt Use `parse.Process` as the main entry point to read `go test -json` output line-by-line. It aggregates results per package and returns a `*GoTestSummary`. Configure behavior with `OptionsFunc`. Returns `ErrNotParsable` if no valid JSON events are found within the first 50 lines. ```go package main import ( "fmt" "os" "strings" "github.com/mfridman/tparse/parse" ) func main() { // Simulate go test -json output jsonOutput := strings.NewReader(` {"Time":"2024-01-01T00:00:00Z","Action":"run","Package":"example/pkg","Test":"TestAdd"} {"Time":"2024-01-01T00:00:00Z","Action":"output","Package":"example/pkg","Test":"TestAdd","Output":"--- PASS: TestAdd (0.00s)\n"} {"Time":"2024-01-01T00:00:00Z","Action":"pass","Package":"example/pkg","Test":"TestAdd","Elapsed":0.001} {"Time":"2024-01-01T00:00:01Z","Action":"output","Package":"example/pkg","Output":"ok \texample/pkg\t0.123s\tcoverage: 87.5% of statements\n"} {"Time":"2024-01-01T00:00:01Z","Action":"pass","Package":"example/pkg","Elapsed":0.123} `) summary, err := parse.Process(jsonOutput) if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } for name, pkg := range summary.Packages { fmt.Printf("Package: %s\n", name) fmt.Printf(" Action: %s\n", pkg.Summary.Action) fmt.Printf(" Elapsed: %.2fs\n", pkg.Summary.Elapsed) fmt.Printf(" Cached: %v\n", pkg.Cached) fmt.Printf(" Coverage: %.1f%%\n", pkg.Coverage) fmt.Printf(" Tests: %d passed, %d failed, %d skipped\n", len(pkg.TestsByAction(parse.ActionPass)), len(pkg.TestsByAction(parse.ActionFail)), len(pkg.TestsByAction(parse.ActionSkip)), ) } // Output: // Package: example/pkg // Action: pass // Elapsed: 0.12s // Cached: false // Coverage: 87.5% // Tests: 1 passed, 0 failed, 0 skipped } ``` -------------------------------- ### Choose output format with -format Source: https://context7.com/mfridman/tparse/llms.txt The `-format` flag selects the output table format. Options include `plain` (no borders), `markdown` (GitHub-flavored tables), and `basic` (rounded borders, default). ```bash # Plain (no borders) — good for narrow terminals go test ./... -json | tparse -all -format plain # Markdown — renders as GitHub-flavored tables; good for PR comments go test ./... -json | tparse -all -format markdown # Basic (rounded borders, default) go test ./... -json | tparse -all -format basic ``` -------------------------------- ### Basic tparse CLI Usage Source: https://context7.com/mfridman/tparse/llms.txt Pipe Go test output to tparse for formatted results. Use the -format flag to select output style. ```bash # Basic — rounded box borders, colored status, default terminal output go test ./... -json | tparse -format basic ``` ```bash # Plain — no borders, space-separated columns, ideal for log files go test ./... -json | tparse -format plain ``` ```bash # Markdown — GitHub-flavored markdown tables, emoji status indicators # Best used in CI pipelines that post results as PR comments go test ./... -json | tparse -format markdown -all ``` -------------------------------- ### Use -follow to mirror raw go test output Source: https://context7.com/mfridman/tparse/llms.txt The `-follow` flag allows `tparse` to print the raw test output to stdout while still collecting data for the summary table. Use `-follow-output` to redirect the raw output to a file. ```bash set -o pipefail && go test ./... -json | tparse -follow -all ``` ```bash # Write raw follow output to a file instead of stdout go test ./... -json | tparse -follow-output=raw.txt -all ``` -------------------------------- ### Use -progress for incremental feedback Source: https://context7.com/mfridman/tparse/llms.txt The `-progress` flag provides one-line-per-package progress updates, useful for long test suites in CI environments. ```bash go test ./... -json | tparse -progress ``` -------------------------------- ### Analyze saved go test -json output with -file Source: https://context7.com/mfridman/tparse/llms.txt Save `go test -json` output to a file and then analyze it using `tparse -file`. Supports different output formats like markdown for CI reports. ```bash # Save output first go test ./... -json > results.out # Then analyze tparse -all -file results.out # With markdown output format for CI reports tparse -all -format markdown -file results.out ``` -------------------------------- ### parse.GoTestSummary Source: https://context7.com/mfridman/tparse/llms.txt Represents the overall result of parsing `go test -json` output. It contains a map of package names to `*Package` details and provides methods for sorting packages and determining the process exit code. ```APIDOC ## parse.GoTestSummary ### Description The main result structure returned by `parse.Process`. It holds a collection of parsed package information and offers utility methods for analysis. ### Methods - `GetSortedPackages(sorter func(*parse.Package) string) []*parse.Package`: Returns packages sorted according to the provided sorter function (e.g., `parse.SortByPackageName`). - `ExitCode() int`: Determines the process exit code based on test results: - `0`: All packages passed. - `1`: One or more failures, panics, or data races occurred. - `2`: A build or setup failure was encountered. ``` -------------------------------- ### Include packages without test files with -notests Source: https://context7.com/mfridman/tparse/llms.txt Use the `-notests` flag to include packages that do not have any test files in the summary output. ```bash go test ./... -json | tparse -notests ``` -------------------------------- ### parse.Process Source: https://context7.com/mfridman/tparse/llms.txt Processes a stream of `go test -json` output to aggregate events into packages and tests, providing a summary of the test run. ```APIDOC ## parse.Process ### Description Processes a stream of `go test -json` output to aggregate events into packages and tests, providing a summary of the test run. It returns a `GoTestSummary` object containing aggregated package and test information. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (io.Reader) - Required - An `io.Reader` providing the `go test -json` output. ### Response #### Success Response (200) - **summary** (*parse.GoTestSummary) - A pointer to the `GoTestSummary` object containing aggregated test results. - **err** (error) - An error if the input could not be processed. ### Request Example ```go import ( "strings" "github.com/mfridman/tparse/parse" ) input := strings.NewReader(` {"Action":"pass","Package":"example/aaa","Elapsed":0.9} {"Action":"pass","Package":"example/bbb","Elapsed":0.1} `) summary, err := parse.Process(input) ``` ### Response Example ```go // Assuming successful processing // summary will be a *parse.GoTestSummary object // err will be nil ``` ``` -------------------------------- ### Sort packages by name, elapsed time, or coverage Source: https://context7.com/mfridman/tparse/llms.txt The `GoTestSummary.GetSortedPackages` method accepts `PackageSorter` functions to order packages. Built-in sorters include `SortByPackageName`, `SortByElapsed` (descending), and `SortByCoverage` (descending). ```go package main import ( "fmt" "strings" "github.com/mfridman/tparse/parse" ) func main() { input := strings.NewReader(` {"Action":"pass","Package":"example/aaa","Elapsed":0.9} {"Action":"pass","Package":"example/bbb","Elapsed":0.1} {"Action":"pass","Package":"example/ccc","Elapsed":0.5} `) summary, _ := parse.Process(input) // Sort by elapsed time descending (slowest first) for _, pkg := range summary.GetSortedPackages(parse.SortByElapsed) { fmt.Printf("%.1fs %s\n", pkg.Summary.Elapsed, pkg.Summary.Package) } // 0.9s example/aaa // 0.5s example/ccc // 0.1s example/bbb // Sort alphabetically for _, pkg := range summary.GetSortedPackages(parse.SortByPackageName) { fmt.Printf("%s\n", pkg.Summary.Package) } // example/aaa // example/bbb // example/ccc } ``` -------------------------------- ### Aggregate and process test results Source: https://context7.com/mfridman/tparse/llms.txt Use `parse.Process` to aggregate `go test -json` output into a `GoTestSummary`. The `Package` struct holds aggregated events for a single package, and `Test` represents individual test functions within a package. You can retrieve tests by action type using `TestsByAction`. ```go package main import ( "fmt" "strings" "github.com/mfridman/tparse/parse" ) func main() { input := strings.NewReader(` {"Action":"run","Package":"example/svc","Test":"TestCreate"} {"Action":"output","Package":"example/svc","Test":"TestCreate","Output":"--- PASS: TestCreate (0.05s)\n"} {"Action":"pass","Package":"example/svc","Test":"TestCreate","Elapsed":0.05} {"Action":"run","Package":"example/svc","Test":"TestDelete"} {"Action":"output","Package":"example/svc","Test":"TestDelete","Output":" db_test.go:42: connection refused\n"} {"Action":"output","Package":"example/svc","Test":"TestDelete","Output":"--- FAIL: TestDelete (0.12s)\n"} {"Action":"fail","Package":"example/svc","Test":"TestDelete","Elapsed":0.12} {"Action":"fail","Package":"example/svc","Elapsed":0.17} `) summary, _ := parse.Process(input) pkg := summary.Packages["example/svc"] fmt.Printf("HasPanic: %v\n", pkg.HasPanic) fmt.Printf("HasDataRace: %v\n", pkg.HasDataRace) for _, t := range pkg.Tests { fmt.Printf(" Test: %-20s Status: %-4s Elapsed: %.2fs\n", t.Name, t.Status(), t.Elapsed()) } // Test: TestCreate Status: pass Elapsed: 0.05s // Test: TestDelete Status: fail Elapsed: 0.12s passed := pkg.TestsByAction(parse.ActionPass) failed := pkg.TestsByAction(parse.ActionFail) fmt.Printf("Passed: %d, Failed: %d\n", len(passed), len(failed)) // Passed: 1, Failed: 1 } ``` -------------------------------- ### Analyze saved go test output with tparse Source: https://github.com/mfridman/tparse/blob/main/README.md Save the JSON output of 'go test' to a file and then use tparse with the '-file' option to analyze it. This is useful for reviewing test results later. ```bash go test fmt -json > fmt.out tparse -all -file=fmt.out ``` -------------------------------- ### Accessing GoTestSummary and Exit Code Source: https://context7.com/mfridman/tparse/llms.txt The `*GoTestSummary` returned by `parse.Process` contains package information and methods to retrieve sorted packages and compute the process exit code. Use `GetSortedPackages` with a sorter like `SortByPackageName` and `ExitCode` to determine the overall test status. ```go package main import ( "fmt" "strings" "github.com/mfridman/tparse/parse" ) func main() { input := strings.NewReader(`{"Action":"fail","Package":"example/bad","Elapsed":0.5}`) summary, err := parse.Process(input) if err != nil { panic(err) } // GetSortedPackages returns packages in the order defined by the provided sorter. packages := summary.GetSortedPackages(parse.SortByPackageName) for _, pkg := range packages { fmt.Printf("%s => %s\n", pkg.Summary.Package, pkg.Summary.Action) } // ExitCode returns: // 0 — all packages passed // 1 — one or more failures, panics, or data races // 2 — build or setup failure code := summary.ExitCode() fmt.Printf("Exit code: %d\n", code) } ``` -------------------------------- ### Prefix follow output with timestamps Source: https://context7.com/mfridman/tparse/llms.txt The `-include-timestamp` flag prefixes output lines from `-follow` mode with RFC3339 timestamps. ```bash go test ./... -json | tparse -follow -include-timestamp ``` -------------------------------- ### Pipe go test -json output to tparse Source: https://context7.com/mfridman/tparse/llms.txt Pipe the JSON output from `go test ./... -json` directly to `tparse`. Use flags like `-all`, `-pass`, or `-skip` to control which test results are displayed. ```bash go test ./... -json | tparse ``` ```bash set -o pipefail && go test ./... -json | tparse -all ``` ```bash go test ./... -json | tparse -pass ``` ```bash go test ./... -json | tparse -skip ``` -------------------------------- ### Pipe go test output to tparse Source: https://github.com/mfridman/tparse/blob/main/README.md Analyze go test output in real-time by piping the JSON output directly to tparse. The pipefail option ensures that the pipeline will exit with a non-zero status if any command fails. ```bash set -o pipefail && go test fmt -json | tparse -all ``` -------------------------------- ### Diff coverage with -compare Source: https://context7.com/mfridman/tparse/llms.txt The experimental `-compare` flag allows diffing current test coverage against a saved baseline file. The coverage column will show changes like "78.3% (+2.1%)" or "78.3% (-1.0%)". ```bash # Save a baseline go test ./... -json > baseline.out # Later, compare current run against baseline go test ./... -json | tparse -compare baseline.out ``` -------------------------------- ### GitHub Actions CI Integration with tparse Source: https://context7.com/mfridman/tparse/llms.txt Integrate tparse into GitHub Actions workflows to display test results. Ensure Go tests are run with the -json flag and pipe the output to tparse. ```yaml # .github/workflows/ci.yaml name: CI on: [push, pull_request] jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: actions/setup-go@v5 with: go-version: stable - name: Install tparse run: go install github.com/mfridman/tparse@latest - name: Run tests run: | set -o pipefail go test ./... -json -cover -race | tparse -all -format markdown # Alternative: save output and analyze separately - name: Run tests (save output) run: go test ./... -json -cover -race > test-output.json || true - name: Analyze with tparse run: tparse -all -format markdown -file test-output.json ``` -------------------------------- ### Shorten package names with -trimpath Source: https://context7.com/mfridman/tparse/llms.txt Use `-trimpath auto` to automatically strip the longest common prefix from package names, or specify a prefix explicitly. Can be combined with `-smallscreen`. ```bash # Auto-detect and strip the longest common prefix from all package names go test ./... -json | tparse -trimpath auto # Strip a specific prefix explicitly go test ./... -json | tparse -trimpath github.com/myorg/myrepo/ # Combine with smallscreen for very narrow displays go test ./... -json | tparse -smallscreen -trimpath auto ``` -------------------------------- ### Detect special conditions in test events Source: https://context7.com/mfridman/tparse/llms.txt The `Event` struct provides boolean methods like `IsPanic()`, `IsRace()`, `IsCached()`, `NoTestFiles()`, and `NoTestsToRun()` to classify events. The `Cover()` method returns coverage percentage and a boolean indicating if coverage information is present. ```go package main import ( "fmt" "github.com/mfridman/tparse/parse" ) func main() { cases := [][]byte{ []byte(`{"Action":"output","Package":"p","Output":"panic: runtime error: index out of range\n"}`), []byte(`{"Action":"output","Package":"p","Output":"WARNING: DATA RACE\n"}`), []byte(`{"Action":"output","Package":"p","Output":"ok \tp\t(cached)\tcoverage: 55.0% of statements\n"}`), []byte(`{"Action":"output","Package":"p","Output":"? \tp/internal\t[no test files]\n"}`), []byte(`{"Action":"output","Package":"p","Output":"ok \tp\t1.2s\t[no tests to run]\n"}`), } for _, raw := range cases { e, _ := parse.NewEvent(raw) cov, hasCov := e.Cover() fmt.Printf("output=%-55q panic=%-5v race=%-5v cached=%-5v noFiles=%-5v noTests=%-5v cover=%.1f hascover=%v\n", e.Output, e.IsPanic(), e.IsRace(), e.IsCached(), e.NoTestFiles(), e.NoTestsToRun(), cov, hasCov) } // panic=true race=false cached=false ... // panic=false race=true ... // panic=false race=false cached=true cover=55.0 hascover=true // noFiles=true ... // noTests=true ... } ``` -------------------------------- ### Decode a single line of `go test -json` output Source: https://context7.com/mfridman/tparse/llms.txt Use `parse.NewEvent` to decode a single line of `go test -json` output into an `*Event`. This is useful for processing events one at a time. Ensure the input is a valid JSON line. ```go package main import ( "fmt" "github.com/mfridman/tparse/parse" ) func main() { line := []byte(`{"Time":"2024-06-01T10:00:00Z","Action":"fail","Package":"example/pkg","Test":"TestDB","Elapsed":2.345}`) event, err := parse.NewEvent(line) if err != nil { panic(err) } fmt.Printf("Action: %s\n", event.Action) // fail fmt.Printf("Package: %s\n", event.Package) // example/pkg fmt.Printf("Test: %s\n", event.Test) // TestDB fmt.Printf("Elapsed: %.3fs\n", event.Elapsed) // 2.345s fmt.Printf("IsFail: %v\n", event.Action == parse.ActionFail) // true fmt.Printf("IsLast: %v\n", event.LastLine()) // false (has Test name) } ``` -------------------------------- ### parse.Process Source: https://context7.com/mfridman/tparse/llms.txt The primary function to process `go test -json` output. It reads a stream, decodes JSON events, aggregates results, and returns a `GoTestSummary`. It returns `ErrNotParsable` if no valid JSON is found in the first 50 lines. ```APIDOC ## parse.Process ### Description Processes `go test -json` output from a stream, aggregates results per package, and returns a `*GoTestSummary`. Accepts variadic `OptionsFunc` for configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `io.Reader`: A stream of `go test -json` output. - `...parse.OptionsFunc`: Variadic functional options to configure the parsing process (e.g., follow output, progress, timestamps, debug mode). ### Returns - `*parse.GoTestSummary`: A summary of the test results. - `error`: Returns `ErrNotParsable` if no valid JSON events are detected within the first 50 lines, or other errors during processing. ``` -------------------------------- ### Package and Test Aggregation Source: https://context7.com/mfridman/tparse/llms.txt The `Package` type aggregates events for a single Go test package, while `Test` represents a single named test function within a package, storing its events and computed status. ```APIDOC ## Package and Test Aggregation ### Description `Package` aggregates all events for a single Go test package. `Test` represents a single named test function within a package, with its events and computed status. ### Package Methods - **HasPanic**: bool - Indicates if the package had any panic events. - **HasDataRace**: bool - Indicates if the package had any data race events. - **TestsByAction(action string)** []*Test - Returns a slice of `Test` pointers that match the specified action (e.g., `parse.ActionPass`, `parse.ActionFail`). ### Test Methods - **Name**: string - The name of the test function. - **Status()**: string - Returns the status of the test (e.g., "pass", "fail"). - **Elapsed()**: time.Duration - Returns the elapsed time for the test. ### Request Example ```go // Assuming 'pkg' is a *parse.Package object hasPanic := pkg.HasPanic hasDataRace := pkg.HasDataRace passedTests := pkg.TestsByAction(parse.ActionPass) // Assuming 't' is a *parse.Test object testName := t.Name testStatus := t.Status() testElapsed := t.Elapsed() ``` ### Response Example ```go // For a package: hasPanic = true hasDataRace = false // For a test: testName = "TestMyFeature" testStatus = "pass" testElapsed = 0.05s ``` ``` -------------------------------- ### Event Detection Methods Source: https://context7.com/mfridman/tparse/llms.txt `Event` provides several boolean methods to classify special conditions, such as identifying panic, data races, cached test results, or missing test files. ```APIDOC ## Event Detection Methods ### Description `Event` exposes several boolean methods used by `Process` to classify special conditions. These can also be used directly when processing events. ### Methods - **IsPanic()** bool: Returns true if the event indicates a panic. - **IsRace()** bool: Returns true if the event indicates a data race. - **IsCached()** bool: Returns true if the event indicates a cached test result. - **NoTestFiles()** bool: Returns true if the event indicates no test files were found for the package. - **NoTestsToRun()** bool: Returns true if the event indicates there are no tests to run. - **Cover()** (float64, bool): Returns the coverage percentage and a boolean indicating if coverage information is present. ### Request Example ```go // Assuming 'e' is a *parse.Event object isPanic := e.IsPanic() isRace := e.IsRace() cov, hasCov := e.Cover() ``` ### Response Example ```go // For a panic event: isPanic = true // For a data race event: isRace = true // For a coverage event: cov = 55.0 hasCov = true ``` ``` -------------------------------- ### parse.NewEvent Source: https://context7.com/mfridman/tparse/llms.txt Decodes a single line of `go test -json` output into an `*Event`. This function is useful for programs that need to handle events individually. ```APIDOC ## parse.NewEvent ### Description Decodes a single line of `go test -json` output into an `*Event`. Used internally by `Process` but available for programs that need to handle events one at a time. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **line** ([]byte) - Required - A byte slice representing a single line of `go test -json` output. ### Response #### Success Response (200) - **event** (*parse.Event) - A pointer to the parsed Event object. - **err** (error) - An error if the line could not be parsed. ### Request Example ```go line := []byte(`{"Time":"2024-06-01T10:00:00Z","Action":"fail","Package":"example/pkg","Test":"TestDB","Elapsed":2.345}`) event, err := parse.NewEvent(line) ``` ### Response Example ```go // Assuming successful parsing // event will be a *parse.Event object // err will be nil ``` ``` -------------------------------- ### Control table sort order with -sort Source: https://context7.com/mfridman/tparse/llms.txt The `-sort` flag allows controlling the sort order of the summary table. Options include `elapsed` (descending), `cover` (descending), and `name` (alphabetical, default). ```bash # Sort summary table by elapsed time descending (slowest first) go test ./... -json | tparse -sort elapsed # Sort by coverage descending (highest coverage first) go test ./... -json | tparse -sort cover # Sort alphabetically by package name (default) go test ./... -json | tparse -sort name ``` -------------------------------- ### Package Sorters Source: https://context7.com/mfridman/tparse/llms.txt Provides built-in `PackageSorter` functions for ordering the package list returned by `GoTestSummary.GetSortedPackages`. ```APIDOC ## Package Sorters ### Description Three built-in `PackageSorter` functions for ordering the package list returned by `GoTestSummary.GetSortedPackages`. These allow sorting packages by name, elapsed time, or coverage. ### Sorters - **SortByPackageName**: `func(p1, p2 *PackageSummary) bool` - Sorts packages alphabetically by name. - **SortByElapsed**: `func(p1, p2 *PackageSummary) bool` - Sorts packages by elapsed time in descending order (slowest first). - **SortByCoverage**: `func(p1, p2 *PackageSummary) bool` - Sorts packages by coverage percentage in descending order (highest first). ### Request Example ```go import ( "github.com/mfridman/tparse/parse" ) // Assuming 'summary' is a *parse.GoTestSummary object // Sort by elapsed time sortedByElapsed := summary.GetSortedPackages(parse.SortByElapsed) // Sort by name sortedByName := summary.GetSortedPackages(parse.SortByPackageName) ``` ### Response Example ```go // sortedByElapsed and sortedByName will be slices of *parse.PackageSummary // Each *parse.PackageSummary contains details like Package name, Elapsed time, and Coverage. ``` ``` -------------------------------- ### Display slowest passed tests with -slow N Source: https://context7.com/mfridman/tparse/llms.txt Use the `-slow N` flag to display only the N slowest passing tests per package. ```bash # Show the 5 slowest passing tests per package go test ./... -json | tparse -pass -slow 5 ``` -------------------------------- ### Disable colors with -nocolor or NO_COLOR Source: https://context7.com/mfridman/tparse/llms.txt ANSI colors can be disabled using the `-nocolor` flag or by setting the `NO_COLOR` environment variable. ```bash # Via flag go test ./... -json | tparse -nocolor # Via environment variable (standard NO_COLOR spec) NO_COLOR=1 go test ./... -json | tparse ``` -------------------------------- ### Check for ErrNotParsable in Go Source: https://context7.com/mfridman/tparse/llms.txt Use errors.Is to check for parse.ErrNotParsable when processing input. This helps distinguish between non-JSON input and other I/O errors. ```go package main import ( "errors" "fmt" "strings" "github.com/mfridman/tparse/parse" ) func main() { // Plain text go test output — missing -json flag plainOutput := strings.NewReader("ok \tfmt\t0.144s\nFAIL\tio\t0.012s\n") _, err := parse.Process(plainOutput) if err != nil { if errors.Is(err, parse.ErrNotParsable) { fmt.Println("hint: run go test with the -json flag") } else { fmt.Printf("unexpected error: %v\n", err) } } // hint: run go test with the -json flag } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.