Coverage

Purpose and Scope

Coverage answers a practical testing question: after a test run, which parts of the program were exercised, and which paths still need attention? In Go workflows, developers usually encounter coverage through the same go command family used for building, running, and testing packages. The official Go documentation frames the go tool as the standard way to fetch, build, install, and test modules and packages, so coverage belongs naturally beside ordinary test execution rather than as a separate build system. This page uses the supplied repository evidence to orient the workflow and to distinguish coverage from nearby diagnostic artifacts such as CPU, heap, and contention profiles.

The source evidence for this page is intentionally narrower than the full coverage implementation. It shows two important neighboring ideas. First, Go examples and tests live in ordinary package source trees and can include realistic command-line behavior, context cancellation, and external resource setup. Second, the Go distribution vendors pprof, a profile reporting tool whose command table and CLI parser demonstrate how diagnostic data is turned into reports, annotated listings, web views, or raw output. Coverage reports are not pprof profiles, but both are developer feedback loops generated by running code under tooling. Sources: src/database/sql/example_cli_test.go, src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go, src/cmd/vendor/github.com/google/pprof/internal/driver/cli.go

A useful mental model is to separate three phases. The test phase executes package tests or examples. The measurement phase records observations about that execution, such as coverage counters or profiling samples. The reporting phase renders those observations into something a human can act on. The provided pprof files are strongest evidence for the reporting side: they define command names, output formats, post-processing hooks, and CLI flags that select profile sources and reports. The database/sql example test is strongest evidence for the test side: it shows how example-style code can parse flags, open resources, use contexts, and call functions that would be executed by a test harness or example runner.

Relevant Source Files

  • src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go - Defines the pprof command registry, command metadata, help rendering, extension points, and built-in report commands such as list, text, top, raw, tags, and disasm. It is relevant because coverage users often compare coverage output with other source-annotated diagnostics, and this file shows how the bundled pprof tool models report generation.
  • src/cmd/vendor/github.com/google/pprof/internal/driver/cli.go - Defines the source struct and parseFlags path for pprof command-line operation, including profile source selection, symbolization, timeout, HTTP UI, profile-kind flags, and generated report command flags. It grounds the CLI/reporting vocabulary used in this page.
  • src/database/sql/example_cli_test.go - Provides an example test file in the standard library. It demonstrates command-line flags, connection-pool setup, context cancellation, PingContext, QueryRowContext, and Scan, which are representative of the kind of executable behavior developers may want tests and coverage to exercise.

System-to-Code Mapping

The testing side of this page is represented by src/database/sql/example_cli_test.go. The file is in package sql_test, which is the conventional form for examples that exercise a package through its exported API rather than private internals. The example declares a package-level pool *sql.DB, parses id and dsn flags, validates required inputs, calls sql.Open, configures connection-pool limits, and then delegates to Ping and Query. From a coverage perspective, the interesting point is not that this example is itself a coverage engine. It is that realistic code paths are often made measurable only when tests and examples drive public behavior with real inputs, cancellation paths, and error handling. Sources: src/database/sql/example_cli_test.go

The reporting side is represented by the vendored pprof driver. In commands.go, the command type records the report format, optional post-processing, optional visualization, whether a command expects a regular-expression parameter, a single-line description, and longer usage text. The map named pprofCommands then binds user-facing command names to those definitions. That table includes commands that produce raw output, textual summaries, call trees, annotated source, assembly listings, tags, comments, and DOT graphs. Coverage reports use different data, but the structure illustrates the same repository pattern: tooling turns collected execution data into named report formats with help text and consistent invocation behavior. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go

The pprof CLI parser in cli.go fills in the command-line story. The source struct holds profile inputs and report-control fields such as Sources, ExecName, BuildID, Base, DiffBase, Normalize, Seconds, Timeout, Symbolize, HTTPHostport, HTTPDisableBrowser, Comment, and AllFrames. The parseFlags function installs flags for comparison profiles, source options, CPU duration, heap display modes, contention display modes, object tools, and an interactive HTTP UI. It also derives command-specific flags from the command registry. For readers learning coverage, this is a useful contrast: coverage is commonly requested as part of test execution, while pprof is commonly pointed at an existing or dynamically collected profile source and then asked for a selected report. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/cli.go, src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go

Execution Flow

A coverage-oriented workflow begins with code that can be exercised deterministically. The database/sql example shows several practices that make execution observable and bounded. It parses input once, fails fast when required values are missing, opens the database through the standard sql.Open API, and defers cleanup with pool.Close. It then configures the connection pool with SetConnMaxLifetime, SetMaxIdleConns, and SetMaxOpenConns. For coverage readers, the lesson is that testable code often separates setup from the operations being measured. The exported-looking helper functions Ping and Query each take a context.Context, create a timeout, and perform exactly one database operation, making the paths easier to call from tests or examples. Sources: src/database/sql/example_cli_test.go

Once code is executable under the test tool, coverage measurement can tell you which statements were reached, but it cannot by itself prove correctness. The example makes that distinction clear. Ping verifies that the data source name is usable and that the server is accessible, while Query checks the query path by calling QueryRowContext with a named SQL parameter and scanning the result into a string. A coverage result that reaches those lines says that the path ran; the assertions, error handling, and log-fatal behavior decide whether the path behaved acceptably. Treat coverage as a map of exercised code, then pair it with checks that validate the outcome.

The pprof flow is different but complementary. A user supplies a profile source, optional executable information, and flags that select how to symbolize and display the data. parseFlags rejects an invocation with no profile source, recognizes profile and executable inputs, and creates command flags based on the registry in pprofCommands. That registry then determines whether a command produces report.Text, report.List, report.Raw, report.Tags, report.Dot, or another format. Developers often use coverage first to find untested regions and profiling later to understand where exercised code spends time or memory. The supplied source files show how these diagnostic surfaces can coexist as command-driven workflows. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/cli.go, src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go

A compact local workflow, using the public go tool terminology from the official docs, is to keep code in a module, write tests or examples beside the package, run the tests, and request coverage output as part of that run. A typical command sequence looks like this:

go test ./...
go test -cover ./...

The first command establishes the correctness baseline. The second asks the test workflow to include coverage information. When coverage highlights a missing path, add or refine a test that drives the behavior, not merely a superficial call. If the program also needs runtime diagnosis after the covered path is exercised, collect a profile and use pprof commands such as top, list, text, or raw to inspect profile data.

API Components and Reference

The pprof command registry is a concrete reference point for report-oriented tooling in this repository. AddCommand(cmd string, format int, post PostProcessor, desc, usage string) allows extensions to add or replace a command in the pprof command set. SetVariableDefault(variable, value string) changes default pprof configuration. PostProcessor is a function type with the shape func(input io.Reader, output io.Writer, ui plugin.UI) error, giving commands a hook for transforming generated report output. These names are not coverage APIs, but they are source-backed examples of how Go-distributed tools expose extensibility and reporting contracts. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go

The built-in pprof command table also provides useful vocabulary for interpreting diagnostic outputs. comments emits profile comments. disasm prints assembly listings annotated with samples and expects a function regexp parameter. dot writes graph output. list prints annotated source for functions matching a regexp. peek displays callers and callees. raw writes a text form of the raw profile. tags, text, and top provide tag listings and textual summaries. Coverage output is typically statement-oriented rather than sample-oriented, but readers will often move between these commands and coverage reports while improving tests and performance. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/commands.go

The pprof flag parser exposes source and display controls that are worth distinguishing from coverage flags. It includes diff_base, base, symbolize, buildid, timeout, add_comment, all_frames, seconds, heap mode flags such as inuse_space and alloc_objects, contention flags such as total_delay, contentions, and mean_delay, plus tools, http, and no_browser. These options describe how to fetch, compare, symbolize, and render profiles. Coverage users should not confuse these profile-source controls with test coverage generation; instead, treat them as the next diagnostic layer after tests have executed code paths of interest. Sources: src/cmd/vendor/github.com/google/pprof/internal/driver/cli.go

The database example offers a small API checklist for coverage-friendly code under test. It uses flag.Int64, flag.String, and flag.Parse for command-line inputs; sql.Open for creating a *sql.DB; SetConnMaxLifetime, SetMaxIdleConns, and SetMaxOpenConns for pool configuration; context.WithCancel and context.WithTimeout for shutdown and per-operation deadlines; PingContext for connectivity; and QueryRowContext(...).Scan(&name) for a single-row query. When adding tests around similar code, aim to cover success, missing configuration, cancellation, query error, and scan behavior rather than only the happy path. Sources: src/database/sql/example_cli_test.go

Testing Signals and Next Steps

Coverage is most valuable when interpreted with the rest of the test signal. A high percentage can hide weak assertions, while a low percentage can reveal important behavior that has never been executed by automated tests. The supplied example underscores this: exercising Query without checking the selected name would cover the call but would not verify the result. Conversely, a well-scoped test that covers an error path may be more valuable than broad execution with little validation. Use coverage to choose where to write the next test, then use ordinary Go assertions, examples, table tests, or integration checks to decide whether the code behaved correctly.

For next steps, start from the package or module you maintain and run the ordinary test workflow before adding coverage. Then inspect uncovered code and ask whether each gap is dead code, hard-to-test integration behavior, or an important branch that deserves a focused test. If a covered path is slow or allocates unexpectedly, switch mental models from coverage to profiling and use the pprof command surface described above. Related pages in this OpenWiki should be read in this order: testing for go test behavior, go-command for command dispatch, pprof for profile reporting, and diagnostics for how Go’s runtime and tools fit together.