Test context, attributes, and output
suggest changeGo 1.24 to 1.26 added a handful of small methods to testing.T and testing.B that replace boilerplate most test suites used to write by hand:
| API | Go | What it does |
|---|---|---|
t.Context() |
1.24 | a context canceled when the test ends, before Cleanup functions run |
t.Chdir(dir) |
1.24 | changes the working directory for one test |
b.Loop() |
1.24, improved in 1.26 | the new way to write a benchmark loop |
t.Attr(key, value) |
1.25 | attaches metadata to a test, visible to go test -json |
t.Output() |
1.25 | an io.Writer that writes to the test log |
t.ArtifactDir() |
1.26 | a directory for files you want to keep after the test |
All of them are also in the testing.TB interface, so helpers that take a testing.TB can use them. t.Chdir and t.ArtifactDir are shown next to t.TempDir in Temporary files; this article only covers ArtifactDir in more depth.
If you're new to Go tests, start with Basic Test.
t.Context: a context that ends with the test
Code under test often takes a context.Context and runs until it's canceled: a worker goroutine, a server, a polling loop. Before Go 1.24 every test created its own context and had to cancel it at the right moment.
t.Context() returns a context that is canceled when the test function (and its subtests) finish, just before the functions registered with t.Cleanup run. That order is what makes it useful: a cleanup function can wait for a goroutine to stop, because by the time the cleanup runs, the goroutine has already been told to stop.
worker.go:
package ctx
import (
"context"
"time"
)
// Worker processes jobs until ctx is canceled.
type Worker struct {
Jobs chan string
Done chan struct{} // closed when Run returns
Seen []string
}
func NewWorker() *Worker {
return &Worker{Jobs: make(chan string), Done: make(chan struct{})}
}
func (w *Worker) Run(ctx context.Context) {
defer close(w.Done)
for {
select {
case <-ctx.Done():
return
case j := <-w.Jobs:
w.Seen = append(w.Seen, j)
}
}
}
// Fetch pretends to do slow I/O that honors ctx.
func Fetch(ctx context.Context, d time.Duration) error {
select {
case <-time.After(d):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
worker_test.go:
package ctx
import (
"context"
"testing"
"time"
)
func TestWorker(t *testing.T) {
w := NewWorker()
go w.Run(t.Context())
// Cleanup runs after t.Context() is canceled,
// so waiting for Done here can't hang.
t.Cleanup(func() {
<-w.Done
t.Logf("worker stopped, saw %v", w.Seen)
})
w.Jobs <- "a"
w.Jobs <- "b"
}
func TestContextLifetime(t *testing.T) {
ctx := t.Context()
t.Cleanup(func() {
t.Logf("in Cleanup: ctx.Err() = %v", ctx.Err())
})
t.Run("sub", func(t *testing.T) {
sub := t.Context()
t.Cleanup(func() {
t.Logf("sub Cleanup: sub.Err() = %v, parent.Err() = %v", sub.Err(), ctx.Err())
})
})
t.Logf("in test body: ctx.Err() = %v", ctx.Err())
}
func TestFetchTimeout(t *testing.T) {
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Millisecond)
defer cancel()
err := Fetch(ctx, time.Second)
if err != context.DeadlineExceeded {
t.Fatalf("got %v, want DeadlineExceeded", err)
}
}
$ go test -v
=== RUN TestWorker
worker_test.go:17: worker stopped, saw [a b]
--- PASS: TestWorker (0.00s)
=== RUN TestContextLifetime
=== RUN TestContextLifetime/sub
worker_test.go:32: sub Cleanup: sub.Err() = context canceled, parent.Err() = <nil>
=== NAME TestContextLifetime
worker_test.go:35: in test body: ctx.Err() = <nil>
worker_test.go:27: in Cleanup: ctx.Err() = context canceled
--- PASS: TestContextLifetime (0.00s)
--- PASS: TestContextLifetime/sub (0.00s)
=== RUN TestFetchTimeout
--- PASS: TestFetchTimeout (0.01s)
PASS
ok example.com/ctx 1.037s
Things to notice:
- each test and subtest has its own context. A subtest's context is canceled when the subtest ends, while the parent's context is still live.
- the context is canceled however the test ends: pass,
t.Fatal,t.Skip, or a failedt.FailNowin a helper. - derive from it when you need a deadline (
context.WithTimeout(t.Context(), ...)) or extra values. You no longer needcontext.Background()in tests. - benchmarks get the same thing with
b.Context(), and fuzz targets withf.Context().
Compare with what tests had to write before Go 1.24:
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(func() {
cancel()
<-w.Done
})
go w.Run(ctx)
This works, but it's easy to get the order wrong. Cleanup functions run last-in, first-out, so if cancel and the wait are registered as two separate t.Cleanup calls in the wrong order, the test hangs waiting for a goroutine nobody canceled. With t.Context() there is nothing to order.
Don't keep t.Context() after the test ends, for example in a package-level variable used by the next test: it's already canceled. For setup shared by many tests, see Testing using setUp and tearDown function.
t.Attr: metadata for CI tools
t.Attr(key, value) attaches a key/value pair to a test. Go doesn't give any key a meaning: it's for CI systems and test dashboards that read go test -json output. Typical uses are an owning team, a link to a bug tracker, or marking a test as known-flaky so a dashboard can treat its failures differently.
package attr
import "testing"
func TestCheckout(t *testing.T) {
t.Attr("owner", "payments-team")
t.Attr("issue", "https://github.com/acme/shop/issues/42")
t.Run("card", func(t *testing.T) {
t.Attr("flaky", "true")
})
}
With -v the attributes show up as === ATTR lines:
$ go test -v -run TestCheckout
=== RUN TestCheckout
=== ATTR TestCheckout owner payments-team
=== ATTR TestCheckout issue https://github.com/acme/shop/issues/42
=== RUN TestCheckout/card
=== ATTR TestCheckout/card flaky true
--- PASS: TestCheckout (0.00s)
--- PASS: TestCheckout/card (0.00s)
PASS
The real consumer is go test -json (which uses test2json). Each attribute becomes an event with "Action":"attr" and separate Key and Value fields, so tools don't have to parse text:
$ go test -json -run TestCheckout
...
{"Time":"...","Action":"attr","Package":"example.com/attr","Test":"TestCheckout","Key":"owner","Value":"payments-team"}
{"Time":"...","Action":"attr","Package":"example.com/attr","Test":"TestCheckout","Key":"issue","Value":"https://github.com/acme/shop/issues/42"}
{"Time":"...","Action":"attr","Package":"example.com/attr","Test":"TestCheckout/card","Key":"flaky","Value":"true"}
...
Rules:
- the key can't contain whitespace and the value can't contain newlines. Breaking a rule fails the test:
--- FAIL: TestBadKey (0.00s)
testing.go:1759: disallowed whitespace in attribute key "bad key"
- attributes are written to the log immediately but should be treated as unordered.
- attributes are only printed with
-vor-json. Without them, a failing test shows its log but not itsATTRlines.
t.Output: an io.Writer for the test log
t.Log adds a file:line: prefix and a newline to every call. That's right for short messages but awkward for multi-line output, or for libraries that want an io.Writer, like a logger or an HTTP request dump.
t.Output() returns a writer that writes to the same place as t.Log, with the same indentation, but without a source location and without adding newlines. It's line buffered: text is flushed at each newline, by the next t.Log, and at the end of the test.
package attr
import (
"fmt"
"log/slog"
"testing"
)
func TestOutput(t *testing.T) {
t.Log("from t.Log")
// Output has no file:line prefix and doesn't add a newline.
w := t.Output()
fmt.Fprintf(w, "step 1 ")
fmt.Fprintf(w, "done\n")
fmt.Fprintf(w, "table:\n a 1\n b 2\n")
// Send a logger's output to the test log.
log := slog.New(slog.NewTextHandler(w, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.TimeKey && len(groups) == 0 {
return slog.Attr{} // drop time for stable output
}
return a
},
}))
log.Info("connected", "addr", "127.0.0.1:5432")
fmt.Fprint(w, "no trailing newline")
}
$ go test -v -run TestOutput
=== RUN TestOutput
attr_test.go:19: from t.Log
step 1 done
table:
a 1
b 2
level=INFO msg=connected addr=127.0.0.1:5432
no trailing newline
--- PASS: TestOutput (0.00s)
PASS
The most useful pattern is the logger: give the code under test a *slog.Logger that writes to t.Output(). Its log lines are then attached to the test that produced them, appear in order with t.Log output, and, like any test output, are hidden unless the test fails or you run with -v:
$ go test
--- FAIL: TestFails (0.00s)
request body: {"id": 7}
bad_test.go:15: status 500
FAIL
This is better than logging to os.Stdout, which is printed for every test (passing or not) and isn't grouped per test when tests run in parallel.
Don't call t.Output() or write to it after the test and its parents have returned, for example from a goroutine the test didn't wait for. Stop such goroutines first, which is exactly what t.Context() helps with.
t.ArtifactDir: files to keep after the test
t.TempDir() is deleted when the test ends. That's what you want for scratch files, but sometimes a test produces a file you want to look at: a rendered image, an HTML report, a database dump from a failed integration test, a golden file that doesn't match.
t.ArtifactDir() returns a per-test directory for such files. What happens to it depends on the -artifacts flag:
- without
-artifactsit behaves liket.TempDir(): a temporary directory removed after the test - with
-artifactsthe directory is created in_artifactsunder the output directory (-outputdir, by default the directory you rungo testin) and is kept. For a package in the current directory the path is_artifacts/<TestName>/<random>; withgo test -artifacts ./...it includes the package's relative path, e.g._artifacts/sub/TestA/<random>
render.go:
package render
import (
"fmt"
"strings"
)
// Report renders an HTML table.
func Report(rows map[string]int, keys []string) string {
var b strings.Builder
b.WriteString("<table>\n")
for _, k := range keys {
fmt.Fprintf(&b, " <tr><td>%s</td><td>%d</td></tr>\n", k, rows[k])
}
b.WriteString("</table>\n")
return b.String()
}
render_test.go:
package render
import (
"os"
"path/filepath"
"strings"
"testing"
)
func TestReport(t *testing.T) {
got := Report(map[string]int{"apples": 3, "pears": 5}, []string{"apples", "pears"})
// Save the rendered page so a human (or CI) can look at it.
dir := t.ArtifactDir()
path := filepath.Join(dir, "report.html")
if err := os.WriteFile(path, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
if !strings.Contains(got, "<td>pears</td><td>5</td>") {
t.Errorf("pears row missing, see %s", path)
}
}
$ go test -v
=== RUN TestReport
--- PASS: TestReport (0.00s)
PASS
$ go test -v -artifacts
=== RUN TestReport
=== ARTIFACTS TestReport C:\src\render\_artifacts\TestReport\276787349
--- PASS: TestReport (0.00s)
PASS
$ find _artifacts -type f
_artifacts/TestReport/276787349/report.html
Notes:
- the
=== ARTIFACTSline tells you where the files are. Ingo test -jsonoutput it's an event with"Action":"artifacts"and aPathfield, so a CI job can find and upload the files. - every test and subtest gets its own directory; a subtest's directory isn't inside its parent's. Calling
ArtifactDiragain in the same test returns the same directory. -outputdirmust already exist:go test -artifacts -outputdir=outfails with amkdirerror ifoutis missing.- add
_artifacts/to.gitignore.
Because the directory is a temp dir when the flag is absent, tests can call t.ArtifactDir() unconditionally. Developers don't pay for it in normal runs; CI adds -artifacts and uploads the directory when a job fails.
Benchmarks with b.Loop
The classic benchmark loop runs the code b.N times. testing calls the function repeatedly with growing b.N until the run takes long enough (1 second by default). Benchmarks shows that style. Go 1.24 added b.Loop(), and it's now the recommended way:
func BenchmarkX(b *testing.B) {
// setup, not measured
for b.Loop() {
// code to measure
}
// cleanup, not measured
}
b.Loop fixes three problems of for i := 0; i < b.N; i++.
1. The compiler can't optimize the work away. If a benchmarked function is inlined and its result isn't used, the compiler may delete the computation, and you measure an empty loop. Inside for b.Loop() { ... }, function arguments, results and assigned variables are kept alive, so the code really runs.
2. Setup is excluded automatically. b.Loop resets the timer on its first call and stops it when it returns false. You don't need b.ResetTimer().
3. The benchmark function runs once. With b.N, the whole function, setup included, runs once for each b.N the framework tries. With b.Loop, the framework runs the function once and controls the iteration count inside the loop, so expensive setup runs once.
sum.go:
package bench
// mix scrambles the bits of x (a step from a hash function).
func mix(x uint64) uint64 {
x ^= x >> 33
x *= 0xff51afd7ed558ccd
x ^= x >> 33
x *= 0xc4ceb9fe1a85ec53
x ^= x >> 33
return x
}
func Sum(nums []int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum_test.go:
package bench
import (
"testing"
"time"
)
// Old style: the result is thrown away, mix is inlined,
// and the compiler deletes the whole computation.
func BenchmarkMixN(b *testing.B) {
for i := 0; i < b.N; i++ {
mix(uint64(i))
}
}
// b.Loop keeps arguments and results alive, so the work really runs.
func BenchmarkMixLoop(b *testing.B) {
var i uint64
for b.Loop() {
mix(i)
i++
}
}
func makeData() []int {
time.Sleep(100 * time.Millisecond) // pretend this is expensive
nums := make([]int, 10_000)
for i := range nums {
nums[i] = i
}
return nums
}
var runsN, runsLoop int
// Old style: the whole function, setup included, runs once per
// b.N round, and you must remember b.ResetTimer.
func BenchmarkSumN(b *testing.B) {
runsN++
nums := makeData()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Sum(nums)
}
b.Logf("run %d: b.N=%d", runsN, b.N)
}
// New style: the function runs once and setup is never timed.
func BenchmarkSumLoop(b *testing.B) {
runsLoop++
nums := makeData()
for b.Loop() {
Sum(nums)
}
b.Logf("run %d: b.N=%d", runsLoop, b.N)
}
$ go test -bench=.
goos: windows
goarch: amd64
pkg: example.com/bench
cpu: 12th Gen Intel(R) Core(TM) i9-12900F
BenchmarkMixN-24 1000000000 0.1829 ns/op
BenchmarkMixLoop-24 535305555 2.117 ns/op
BenchmarkSumN-24 382420 2720 ns/op
--- BENCH: BenchmarkSumN-24
sum_test.go:45: run 1: b.N=1
sum_test.go:45: run 2: b.N=100
sum_test.go:45: run 3: b.N=10000
sum_test.go:45: run 4: b.N=382420
BenchmarkSumLoop-24 251374 4568 ns/op
--- BENCH: BenchmarkSumLoop-24
sum_test.go:55: run 1: b.N=251374
PASS
ok example.com/bench 6.973s
What the numbers show:
BenchmarkMixNreports 0.18 ns per call, less than one CPU cycle. That's an empty loop: the compiler inlinedmix, saw the result was unused, and removed it.BenchmarkMixLoopmeasures the real cost.BenchmarkSumNlooks faster thanBenchmarkSumLoop, but it's wrong for the same reason: the result of the inlinedSumis unused, so the compiler drops the additions and only the bare loop remains. Assigning the result to a package-levelsinkvariable, the usual workaround beforeb.Loop, makes theb.Nversion as slow as theb.Loopone.BenchmarkSumNwas called 4 times, so the 100 ms setup ran 4 times.BenchmarkSumLoopwas called once.
After the loop, b.N holds the total number of iterations, so you can still use it to compute your own metrics. Here's a sub-benchmark that reports nanoseconds per element:
package bench
import (
"fmt"
"slices"
"testing"
)
func BenchmarkSort(b *testing.B) {
for _, n := range []int{100, 10_000} {
b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) {
orig := make([]int, n)
for i := range orig {
orig[i] = int(mix(uint64(i)))
}
buf := make([]int, n)
for b.Loop() {
copy(buf, orig) // sorting must start from unsorted data
slices.Sort(buf)
}
b.ReportMetric(float64(b.Elapsed().Nanoseconds())/float64(b.N*n), "ns/elem")
})
}
}
$ go test -bench=Sort -benchmem
BenchmarkSort/n=100-24 875005 1328 ns/op 13.28 ns/elem 0 B/op 0 allocs/op
BenchmarkSort/n=10000-24 1042 960143 ns/op 96.01 ns/elem 0 B/op 0 allocs/op
Rules and caveats:
- the condition must be written exactly as
for b.Loop(). The keep-alive behavior is a compiler transformation that only recognizes that form, and only applies to statements between the loop's braces. - use either
b.Loopor ab.Nloop in a benchmark, never both. - in Go 1.24 and 1.25, a
b.Loopbody prevented inlining of the calls in it. That stopped the compiler from deleting them, but it could also add allocations (values escaping to the heap) that the real program doesn't have, so the benchmark measured something different. Go 1.26 inlines them again while still keeping arguments and results alive, so you can convert anyb.Nbenchmark tob.Loopwithout changing what it measures. b.StopTimerandb.StartTimerstill work inside the loop for per-iteration setup you don't want timed, but they're slow. Prefer moving setup out of the loop, asBenchmarkSortdoes with the copy source.
To turn benchmark results into CPU profiles, see Using Benchmarks to Create Profile.
Summary
- pass
t.Context()to code that runs until canceled. It's canceled before cleanups run, so a cleanup can wait for shutdown. - use
t.Attrto tag tests with metadata for CI tools that readgo test -json. - point loggers and other writers at
t.Output()so their output is attached to the right test and hidden when it passes. - save files you want to inspect with
t.ArtifactDir()and rungo test -artifactsin CI. - write new benchmarks with
for b.Loop(), and convert oldb.Nloops, especially ones whose results are unused.