go / test
Assertions come from is. Database tests insert fixtures through a test helper, each in a transaction that rolls back. No test reaches the network. CI reuses the Go caches across runs, with two flags that keep the result cache warm.
Assertions
func TestRename(t *testing.T) {
is := is.New(t)
co, err := Rename(id, "Acme")
is.NoErr(err)
is.Eq(co.Name, "Acme")
}
A failure reads:
rename_test.go:9: co.Name = Beta, want Acme
The variable shadows the package so a call site reads as English.
The source label comes from my old Ruby test framework, where
ok { got == 6 } failed by printing the expression with the values
under it:
got == 6
| |
| false
5
Eq,NotEqcompare two values.NoErr,HasErrcheck errors.Nil,NotNilcheck nil.Truechecks a predicate with no want to name, such asis.True(strings.Contains(s, x)).
New(t) fails fatally on the first failure. NewRelaxed(t) records
and continues, for a test that reports every mismatch in a loop.
Eq(x, nil) fails for a nil *T, because a typed nil boxed into
any is a non-nil interface. Nil handles it.
True(got == want) compiles, prints false, want true, and loses
both values.
Eq takes any
A method cannot have type parameters, so Eq takes any and gives up
compile-time type checking:
is.Eq(gotInt64, 3) // builds, then fails: int64 3 against int 3
When the two values format the same, the failure prints %T too. The
fix is a typed literal, int64(3).
Eq uses reflect.Value.Equal where both values are comparable, so
pointers compare by identity. It uses reflect.DeepEqual elsewhere,
so slices and maps compare by contents.
Label from source
co.Name is the source text of the assertion's first argument, read
back from the test file. I write no message.
The values always print. A failed file read degrades to
got X, want Y. A literal argument gets no label, because
[]int{1, 2} = []int{1, 2} is noise.
Under -trimpath, which the cache needs, runtime.Caller
returns a module-relative path that does not open. filepath.Base of
it does open, because go test runs each binary in its package
directory.
The package parses the whole file and takes the call node that covers the line. So a call spread over several lines keeps its label. The node must be a call to the helper. This check rejects a file with the same name from another package.
gotest.tools/v3/assert also reads the source, but opens the path
runtime.Caller returns, so under go test -trimpath its parse
fails. matryer/is prints the trailing comment, which is still a
hand-written message.
Fixtures
I use is beside database test fixtures:
func TestRename(t *testing.T) {
t.Parallel()
is := is.New(t)
db := test.NewDB(t)
co := db.InsertCompany()
err := Rename(t.Context(), db.DB, co.ID, "Acme")
is.NoErr(err)
is.Eq(db.FindCompany(co.ID).Name, "Acme")
}
db wraps the database connection and holds fixture helpers such as
db.InsertCompany(). is holds the assertions.
I keep the two helpers separate. db.Eq reads like a database query
instead of a test assertion.
The test runs the function and checks the result with is. Each
fixture method inserts a row into a test transaction:
type CompanyOpts struct {
Name string
Status string
}
type CompanyRow struct {
ID int64 `db:"id"`
Name string `db:"name"`
}
func (db *DB) InsertCompany(opts ...CompanyOpts) CompanyRow {
db.t.Helper()
var o CompanyOpts
if len(opts) > 0 {
o = opts[0]
}
if o.Name == "" {
o.Name = "Test Co"
}
if o.Status == "" {
o.Status = "active"
}
var row CompanyRow
err := db.QueryRow(db.ctx, `
INSERT INTO companies (name, status)
VALUES ($1, $2)
RETURNING id, name
`, o.Name, o.Status).Scan(&row.ID, &row.Name)
if err != nil {
db.t.Fatalf("insert company: %v", err)
}
return row
}
The options struct sets defaults that satisfy database constraints. A test overrides only the fields it tests.
The method returns the inserted row with its generated ID. If the
insert fails, t.Fatalf stops the test immediately.
The test database runs on a separate cluster. See postgres / dev test clusters.
A transaction, not a database
Each test process opens one pool against one test database. Each test takes a connection, begins a transaction, and rolls it back at cleanup:
func NewDB(t testing.TB) *DB {
t.Helper()
ctx := context.Background()
conn, err := pool.Acquire(ctx)
if err != nil {
t.Fatalf("acquire test conn: %v", err)
}
tx, err := conn.Begin(ctx)
if err != nil {
conn.Release()
t.Fatalf("begin test tx: %v", err)
}
t.Cleanup(func() {
tx.Rollback(ctx)
conn.Release()
})
return &DB{DB: pgdb.NewWithTx(tx), ctx: t.Context(), t: t}
}
The cleanup uses context.Background(), because Go cancels
t.Context() before cleanup functions run.
A test pays for one BEGIN and one ROLLBACK. Another test cannot
see rows that the test has not committed, so the tests run in
parallel against one database.
A CREATE DATABASE ... TEMPLATE copy for each test needs a pool for
each copy and a DROP DATABASE at cleanup. In my small app, each copy
takes 0.1 to 0.2 seconds, and the copies wait for each other. So I use
a transaction for each test. The package runs in 14 seconds.
The code under test must take a database value that a transaction can
stand in for. In my larger app, functions take a *pgdb.DB, which
wraps a pool or a pgx.Tx. Begin on a pgx.Tx opens a savepoint,
so code that opens its own transaction still runs inside the test's
transaction.
The small app passes *sql.DB to about 150 functions, and I did not
change them. go-txdb registers
a database/sql driver whose connections share one transaction for
each name:
txdb.Register("txdb", "pgx", sharedURL)
func memDB(t testing.TB) *sql.DB {
t.Helper()
db, err := sql.Open("txdb", t.Name()+"/"+randHex(6))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() }) // rolls back
return db
}
go-txdb turns a Begin into a savepoint. It also reads each result
set into memory, so code that runs a query inside a rows.Next loop
still works on one connection. The random suffix keeps two tests with
the same name in separate transactions.
A test that needs its own database
A transaction is one Postgres session. Three kinds of test need more than that:
- A test of an advisory lock. A session-level lock is re-entrant, so
inside one session a second
pg_try_advisory_locksucceeds. I use separate sessions to test that a job skips while another run holds the lock. - A migration test that starts from an empty database.
- A test that swaps, drops indexes on, or deletes all rows of a shared
cache table.
NewPrivateDBcopies a template that holds the schema and shared seeds, opens a transaction on the copy, and drops the copy at cleanup.
Those tests still take a copy of the template. Postgres copies a database only while no session connects to it, so the transactions run on a second database: a copy of the template, made once per schema.
One helper call per test
Two calls to the helper in one test open two transactions. When both
write the same unique key, the second waits for the first, and the
first ends only at cleanup. The test hangs until the test binary
times out. So each test calls the helper once. The test connection also
sets lock_timeout = '5s', so a wait like that fails with an error
that names the lock.
Unique values across processes
go test ./... runs one test binary for each package, and the
binaries share one database. A fixture helper fills a unique column,
such as users.email, from a counter in the package. Each binary
starts its counter at zero, so two binaries write the same values.
They wait on each other's uncommitted rows, and Postgres can report a
deadlock.
Each binary reserves its own block of a shared sequence when it opens its pool. An advisory lock serializes the reservation:
SELECT pg_advisory_xact_lock(hashtext('test-fixtures'));
CREATE SEQUENCE IF NOT EXISTS test_fixture_seq;
SELECT nextval('test_fixture_seq');
The counter starts at that value times a stride, so the ranges of two binaries never overlap.
Shared rows
A transaction for each test isolates what a test writes. It does not isolate a row that every test can see, such as a seeded user.
An insert that references a row through a foreign key takes a key-share lock on that row until its transaction ends. A seeded row that many fixtures point at can hold locks from many parallel transactions at once.
An update such as UPDATE users SET team = NULL writes seeded rows
that other tests can reference. It can conflict with their key-share
locks. So a test writes only rows that it inserts. To keep seeded rows
out of a result, the test filters on its own fixtures.
Two checks catch hidden row-lock waits between parallel tests. A push
test reads db/schema.sql for single-column unique indexes and fails
when two tests pass the same literal to a unique fixture field. A
scheduled daily_lockwait check runs the suite with
lock_timeout = '5ms', so any test that waits on another test's lock
fails with SQLSTATE 55P03.
Committed rows
One test must commit. It tests a trigger that sends NOTIFY, and
Postgres delivers a notification only when the transaction commits.
Its rows stand for about a second, and the package test binaries run
at the same time. Another test can read those rows unless it filters
on its own fixtures. An unrelated row can have a NULL where the test
expects an integer, or add to a count that the test expects to be zero.
Each read of jobs in a test names its own rows: by queue, by job
name, or by an id that its own fixture made. A read matches an id in
args by JSONB containment, not by a cast:
SELECT count(*) FROM jobs WHERE args @> jsonb_build_object('company_id', $1::bigint);
A cast such as (args->>'company_id')::bigint reads every row in the
table. A row from another test with a non-numeric id then raises an
error.
A test in the jobs package parses every other test file and fails on
a read of jobs whose WHERE clause names none of the three. An
allow list takes an exception, with one reason for each directory.
Tables
I write a table test when cases differ only in their inputs and wants. The table holds only the differences. A case with its own setup or its own output stays a separate test.
Every row calls t.Parallel():
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
is := is.New(t)
db := test.NewDB(t)
// ...
})
}
A row is a new test. Folding parallel tests into rows that are not parallel trades away concurrency that the suite needs as it grows.
Races
I test http.TimeoutHandler with a 1 ms timeout. A handler that
returns when the request context is cancelled races with that timer.
TimeoutHandler selects on the handler being done and on the context
being done. When both cases are ready, select picks one at random.
The test can read 200 when it expects 503.
The handler blocks until the test ends, so the timer is the only outcome:
done := make(chan struct{})
t.Cleanup(func() { close(done) })
h := http.TimeoutHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-done
}), time.Millisecond, "timeout")
A goroutine that a test starts and does not stop keeps running after the test ends. My web handler warms a cache from scoreboard URLs in a package variable. A test that changes the URLs races with a running warmer. So the constructor starts its background work through one function variable, and a test replaces it:
var startWarmers = func(h *handler) {
refreshScoresOnce()
go refreshScoresLoop()
go h.warmDayCaches()
}
Hermetic tests
A test that reaches a real host is slow, and it fails when that host
or the network does. My HTTP clients use http.DefaultTransport
unless a test gives them another, so TestMain replaces it:
func TestMain(m *testing.M) {
http.DefaultTransport = loopbackOnly{next: http.DefaultTransport}
os.Exit(m.Run())
}
type loopbackOnly struct{ next http.RoundTripper }
func (l loopbackOnly) RoundTrip(r *http.Request) (*http.Response, error) {
host := r.URL.Hostname()
if ip := net.ParseIP(host); host == "localhost" || (ip != nil && ip.IsLoopback()) {
return l.next.RoundTrip(r)
}
return nil, fmt.Errorf("test: network access to %s is blocked", host)
}
A test stubs each provider with an httptest.NewServer on loopback.
See go / http clients. My larger app refuses
every request through the default transport. An httptest server
still works there, because the client from srv.Client() has its own
transport.
The guard makes a missing stub fail at once. A retry loop then sleeps
its full delay after each failure. My scoreboard fetch retries after
300 ms and 600 ms for each league and each day. I keep each retry
delay in a package variable, and TestMain sets it once:
scoreboardRetryDelay = time.Millisecond
A test that sets the variable and restores it races with the tests that run in parallel. Its restore also puts the long delay back for the tests that run after it.
Cache
To reuse the go test cache across CI runs, I persist the cache
directories and make each test binary depend only on its source.
Go keeps two on-disk caches:
GOCACHE: compiled packages and passing test results.GOMODCACHE: downloaded module source.
On a CI VM I put both on the local disk and reuse them across runs:
export GOCACHE=/var/cache/ci/go-cache
export GOMODCACHE=/var/cache/ci/go-mod
The result cache keys on the inputs to each test binary. Two defaults change those inputs on every CI run:
go teststamps the binary with VCS info, so every commit produces a different binary.- The binary embeds the absolute source path, which differs per box.
Two flags remove both:
go test -buildvcs=false -trimpath ./...
Identical source then produces an identical binary, and go test
reuses cached results across commits and across boxes that share a
GOCACHE.
The first run populates the cache. The next run on the same source
reports (cached) for unchanged packages and finishes in seconds.
apps / sockeye runs its CI cache this way.
A cached result includes what the test binary printed, and go test
replays it on a hit. So a check that reads the run's output costs
nothing when nothing changed. My template coverage check works this
way. Each render prints a line to stdout. A command reads the lines
back out of the -v output. See
go / html templates.
The cache also keys on the environment variables the binary read. So a run with the trace on and a run with it off are separate entries.
It also keys on the size and mtime of each file and directory
that a test opens. A fresh checkout gives each file the time of the
checkout. So a test that reads a testdata file runs again in each CI
job, whether or not the file changed. My runner sets the mtime of each
tracked file from its Git object ID:
func objectTime(id string) time.Time {
n, _ := strconv.ParseUint(id[:8], 16, 32)
return time.Unix(315532800+int64(n&(1<<30-1)), 0).UTC()
}
A file whose content changes gets a new ID, and so a new mtime. One
fixed time for every file would give a false pass when a file changes
and keeps its size. The time falls between 1980 and 2014, because
go test caches no result for a file that changed in the last two
seconds.
The runner also mounts each job's directory at one fixed path. HOME,
GOPATH, and the first PATH entry then name the same path in each
job, and a test that reads one of them still hits the cache.
The cache does not key on a database. After a migration, a package whose source did not change replays a pass against the old schema. I embed the schema file in a package that the test helpers import, so a migration changes the binary. See postgres / dev test clusters.