Testing concurrent code with testing/synctest

suggest change

Code that uses timeouts, tickers, retries and background goroutines is hard to test. Real time makes tests slow (a 30 second timeout needs a 30 second test) and flaky (time.Sleep(10 * time.Millisecond) "to let the goroutine finish" works on your laptop and fails on a loaded CI machine).

Package testing/synctest fixes both problems. It runs a test in an isolated bubble that has a fake clock. Time in the bubble moves forward only when every goroutine in it is blocked, and then it jumps straight to the next timer. A test of a 30 second timeout finishes in microseconds and gives the same result every time.

Versions:

This article covers:

The basics of writing tests are in Testing.

The problem: tests that wait for real time

Here's a cache whose entries expire after a fixed time-to-live:

package cache

import (
	"sync"
	"time"
)

type entry struct {
	val     string
	expires time.Time
}

// Cache stores values for a fixed time-to-live.
type Cache struct {
	mu  sync.Mutex
	ttl time.Duration
	m   map[string]entry
}

func New(ttl time.Duration) *Cache {
	return &Cache{ttl: ttl, m: map[string]entry{}}
}

func (c *Cache) Set(key, val string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.m[key] = entry{val: val, expires: time.Now().Add(c.ttl)}
}

func (c *Cache) Get(key string) (string, bool) {
	c.mu.Lock()
	defer c.mu.Unlock()
	e, ok := c.m[key]
	if !ok || time.Now().After(e.expires) {
		return "", false
	}
	return e.val, true
}

The obvious test sleeps for real:

func TestExpirySlow(t *testing.T) {
	c := New(2 * time.Second)
	c.Set("k", "v")
	time.Sleep(1900 * time.Millisecond)
	if _, ok := c.Get("k"); !ok {
		t.Fatal("expired too early")
	}
	time.Sleep(200 * time.Millisecond)
	if _, ok := c.Get("k"); ok {
		t.Fatal("did not expire")
	}
}

It takes over 2 seconds and the 100 ms margins are a guess. If the machine stalls for 100 ms between Set and the first Get, the test fails.

The same test in a bubble:

func TestExpiry(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		c := New(2 * time.Second)
		c.Set("k", "v")

		time.Sleep(2*time.Second - time.Nanosecond)
		if _, ok := c.Get("k"); !ok {
			t.Fatal("expired too early")
		}
		time.Sleep(time.Nanosecond)
		// exactly 2s: After(expires) is still false
		if _, ok := c.Get("k"); !ok {
			t.Fatal("expired at exactly ttl")
		}
		time.Sleep(time.Nanosecond)
		if _, ok := c.Get("k"); ok {
			t.Fatal("did not expire")
		}
	})
}
$ go test -v
=== RUN   TestExpirySlow
--- PASS: TestExpirySlow (2.10s)
=== RUN   TestExpiry
--- PASS: TestExpiry (0.00s)
PASS

The fake clock is exact, so the test can check the boundary to the nanosecond: the entry is still valid at exactly 2s and gone 1 ns later. A real-time test can't do that.

The cache itself didn't change. Inside a bubble time.Now, time.Sleep, time.After, time.NewTimer, time.NewTicker and everything built on them (like context.WithTimeout) use the bubble's clock. You don't need to inject a fake clock interface into your code.

The fake clock

synctest.Test(t, f) runs f in a new bubble and waits for every goroutine started in the bubble to exit. Goroutines started from inside the bubble belong to it too.

func TestFakeClock(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		start := time.Now()
		t.Log("start:", start.UTC())

		go func() {
			time.Sleep(time.Hour)
			t.Log("goroutine woke after", time.Since(start))
		}()

		time.Sleep(24 * time.Hour)
		t.Log("test woke after", time.Since(start))
		t.Log("now:  ", time.Now().UTC())
	})
}
=== RUN   TestFakeClock
    basic_test.go:12: start: 2000-01-01 00:00:00 +0000 UTC
    basic_test.go:16: goroutine woke after 1h0m0s
    basic_test.go:20: test woke after 24h0m0s
    basic_test.go:21: now:   2000-01-02 00:00:00 +0000 UTC
--- PASS: TestFakeClock (0.00s)

The rules:

The *testing.T passed to f is a new one, tied to the bubble. Use it, not the outer t. t.Cleanup functions run inside the bubble, and t.Context() returns a context whose Done channel belongs to the bubble. You can't call t.Run, t.Parallel or t.Deadline on it; to run several bubbles, call synctest.Test from each subtest.

Waiting for goroutines with synctest.Wait

The other big source of flakiness is waiting for a goroutine to get to a certain point. synctest.Wait() blocks until every other goroutine in the bubble is durably blocked (defined below). When it returns, the goroutines have done everything they can do without outside input.

func TestWait(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		results := make(chan int)
		var got []int
		go func() {
			for v := range results {
				got = append(got, v)
			}
		}()

		results <- 1
		results <- 2
		synctest.Wait() // the receiver is blocked on an empty channel again
		t.Log("got:", got)
		close(results)
	})
}
=== RUN   TestWait
    basic_test.go:38: got: [1 2]
--- PASS: TestWait (0.00s)

Without Wait, the second send can complete before the receiver has appended 2, and got could be [1]. With Wait, the result is always [1 2]. The race detector knows about synctest.Wait, so reading got after it isn't reported as a race (see Detecting races).

Wait must be called from inside a bubble, and only one goroutine at a time may call it.

Testing timeouts

A function that waits for a result with a timeout, written with select as in Timeout reading from a channel with select:

package deadline

import (
	"context"
	"errors"
	"time"
)

var ErrTimeout = errors.New("timed out")

// FirstResult returns the first value from results, or ErrTimeout
// if nothing arrives within timeout.
func FirstResult(results <-chan string, timeout time.Duration) (string, error) {
	select {
	case r := <-results:
		return r, nil
	case <-time.After(timeout):
		return "", ErrTimeout
	}
}

// Work simulates a slow operation that respects cancellation.
func Work(ctx context.Context, d time.Duration) error {
	select {
	case <-time.After(d):
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

Testing both paths, the result arriving in time and the timeout:

func TestFirstResult(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		results := make(chan string)
		go func() {
			time.Sleep(4 * time.Second)
			results <- "fast enough"
		}()
		start := time.Now()
		r, err := FirstResult(results, 5*time.Second)
		if err != nil {
			t.Fatal(err)
		}
		t.Logf("got %q after %v", r, time.Since(start))
	})
}

func TestFirstResultTimeout(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		results := make(chan string) // nobody ever sends
		start := time.Now()
		_, err := FirstResult(results, 5*time.Second)
		if !errors.Is(err, ErrTimeout) {
			t.Fatalf("got %v, want ErrTimeout", err)
		}
		t.Log("timed out after", time.Since(start))
	})
}
=== RUN   TestFirstResult
    fetch_test.go:23: got "fast enough" after 4s
--- PASS: TestFirstResult (0.00s)
=== RUN   TestFirstResultTimeout
    fetch_test.go:35: timed out after 5s
--- PASS: TestFirstResultTimeout (0.00s)

In TestFirstResultTimeout the only goroutine is blocked in a select on two bubble channels, so the clock jumps 5 seconds to the time.After timer.

Testing context deadlines

Contexts with a timeout use the same timers, so they work too. This tests a cancellable function like the ones in Writing cancellable functions:

func TestWorkDeadline(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
		defer cancel()

		start := time.Now()
		err := Work(ctx, time.Minute)
		t.Logf("err=%v after %v", err, time.Since(start))
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Fatalf("got %v, want DeadlineExceeded", err)
		}
	})
}
=== RUN   TestWorkDeadline
    fetch_test.go:46: err=context deadline exceeded after 30s
--- PASS: TestWorkDeadline (0.00s)

To check that the context expires at exactly the right moment, sleep to just before the deadline, then past it. synctest.Wait after each sleep lets the goroutine that cancels the context run before we look at ctx.Err():

func TestContextDeadlineExact(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		const timeout = 5 * time.Second
		ctx, cancel := context.WithTimeout(t.Context(), timeout)
		defer cancel()

		time.Sleep(timeout - time.Nanosecond)
		synctest.Wait()
		if err := ctx.Err(); err != nil {
			t.Fatalf("before timeout: ctx.Err() = %v", err)
		}

		time.Sleep(time.Nanosecond)
		synctest.Wait()
		if err := ctx.Err(); err != context.DeadlineExceeded {
			t.Fatalf("after timeout: ctx.Err() = %v", err)
		}
		t.Log("ctx.Err() =", ctx.Err())
	})
}
=== RUN   TestContextDeadlineExact
    fetch_test.go:70: ctx.Err() = context deadline exceeded
--- PASS: TestContextDeadlineExact (0.00s)

Testing tickers, and why synctest.Sleep exists

A heartbeat that counts ticks in a background goroutine:

package ticker

import (
	"sync/atomic"
	"time"
)

// Heartbeat counts beats every interval until Stop is called.
type Heartbeat struct {
	beats atomic.Int64
	stop  chan struct{}
	done  chan struct{}
}

func Start(interval time.Duration) *Heartbeat {
	h := &Heartbeat{stop: make(chan struct{}), done: make(chan struct{})}
	go func() {
		defer close(h.done)
		t := time.NewTicker(interval)
		defer t.Stop()
		for {
			select {
			case <-t.C:
				h.beats.Add(1)
			case <-h.stop:
				return
			}
		}
	}()
	return h
}

func (h *Heartbeat) Beats() int64 { return h.beats.Load() }

func (h *Heartbeat) Stop() {
	close(h.stop)
	<-h.done
}

A first try at a test, using time.Sleep in the bubble:

func TestHeartbeatSleep(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		h := Start(10 * time.Second)
		defer h.Stop()

		for i := 1; i <= 6; i++ {
			time.Sleep(10 * time.Second)
			t.Logf("after %ds: %d beats", i*10, h.Beats())
		}
	})
}

Three runs give three different results:

after 10s: 1 beats  after 20s: 2 beats  after 30s: 2 beats  after 40s: 4 beats  after 50s: 4 beats  after 60s: 5 beats
after 10s: 0 beats  after 20s: 1 beats  after 30s: 3 beats  after 40s: 4 beats  after 50s: 4 beats  after 60s: 5 beats
after 10s: 1 beats  after 20s: 2 beats  after 30s: 2 beats  after 40s: 3 beats  after 50s: 5 beats  after 60s: 6 beats

The test's time.Sleep and the ticker fire at exactly the same fake instant. Both goroutines become runnable at once, and which one runs first is up to the scheduler. Sometimes the test reads Beats() before the heartbeat goroutine has incremented it.

The fix is to wait for the bubble to settle after sleeping: time.Sleep(d) followed by synctest.Wait(). Go 1.27 added synctest.Sleep(d), which does exactly that:

func TestHeartbeat(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		h := Start(10 * time.Second)
		defer h.Stop()

		synctest.Sleep(9 * time.Second)
		if got := h.Beats(); got != 0 {
			t.Fatalf("after 9s: %d beats, want 0", got)
		}
		synctest.Sleep(1 * time.Second)
		if got := h.Beats(); got != 1 {
			t.Fatalf("after 10s: %d beats, want 1", got)
		}
		synctest.Sleep(time.Hour)
		if got := h.Beats(); got != 361 {
			t.Fatalf("after 1h10s: %d beats, want 361", got)
		}
		t.Log("beats after", time.Since(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)), "=", h.Beats())
	})
}
=== RUN   TestHeartbeat
    heartbeat_test.go:38: beats after 1h0m10s = 361
--- PASS: TestHeartbeat (0.00s)

An hour of ticks, 361 of them, simulated instantly and always with the same result. As a rule, in the test goroutine use synctest.Sleep rather than time.Sleep. Code under test keeps using the normal time functions.

What "durably blocked" means

The whole mechanism depends on knowing when a goroutine can't make progress. A goroutine is durably blocked when it's blocked and only another goroutine in the same bubble can unblock it. These operations durably block:

These block, but not durably, because something outside the bubble could unblock them:

When every goroutine is durably blocked, one of three things happens:

  1. If someone called synctest.Wait, it returns.
  2. Otherwise, the clock advances to the next timer that wakes a goroutine.
  3. If there's no such timer, it's a deadlock and the test fails.

Deadlocks are detected

func TestChannelDeadlock(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		ch := make(chan int)
		go func() { ch <- 1 }()
		t.Log(<-ch)
		t.Log(<-ch) // nobody sends a second value
	})
}
--- FAIL: TestChannelDeadlock (0.00s)
    nd_test.go:13: 1
panic: deadlock: all goroutines in bubble are blocked [recovered, repanicked]
...
goroutine 9 [chan receive (durable), synctest bubble 1]:
example.com/st/notdurable.TestChannelDeadlock.func1(0x2966d90f2600)
	.../notdurable/nd_test.go:14 +0xdf

Outside a bubble this test would hang until go test kills it after 10 minutes. In a bubble it fails right away and the stack trace points to the receive that can never complete. Goroutine states in the trace are marked (durable) when they're durably blocked, which helps when debugging a bubble that won't advance.

Mutexes are not durably blocking

func TestMutexNotDurable(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		var mu sync.Mutex
		mu.Lock()
		go func() {
			mu.Lock() // blocked, but not durably
			mu.Unlock()
		}()
		synctest.Wait() // never returns: the goroutine isn't durably blocked
		mu.Unlock()
	})
}
$ go test -timeout 3s -run Mutex
panic: test timed out after 3s
	running tests:
		TestMutexNotDurable (3s)

This is rarely a problem in practice. Mutexes are normally held for a short time, so a goroutine waiting on one is just about to run again. It only bites when code holds a lock while it waits for something, which is usually a bug anyway.

Testing HTTP clients with httptest.NewTestServer

The classic httptest.NewServer (see Testing HTTP requests) listens on a real loopback socket. Network I/O isn't durably blocking, so in a bubble a client waiting for the response blocks the clock forever and the test hangs.

Go 1.27 added httptest.NewTestServer(t, handler). It uses an in-memory network made of bubble channels, so it works with synctest. It also shuts the server down with t.Cleanup, and fails the test if the handler panics. The client from srv.Client() sends every request to the server, whatever host name is in the URL.

A client function with a 5 second timeout:

package httpt

import (
	"fmt"
	"io"
	"net/http"
	"time"
)

// FetchStatus GETs url with a 5 second timeout and returns the body.
func FetchStatus(c *http.Client, url string) (string, error) {
	c.Timeout = 5 * time.Second
	resp, err := c.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return "", fmt.Errorf("unexpected status %s", resp.Status)
	}
	b, err := io.ReadAll(resp.Body)
	return string(b), err
}

The test uses a handler that waits for as long as the URL says. It stops waiting when the client gives up, so no handler goroutine is left behind at the end of the test:

package httpt

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"testing/synctest"
	"time"
)

// slowHandler responds after the delay given in the URL path, e.g. /delay/3s.
func slowHandler(w http.ResponseWriter, r *http.Request) {
	d, err := time.ParseDuration(strings.TrimPrefix(r.URL.Path, "/delay/"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	select {
	case <-time.After(d):
		fmt.Fprintf(w, "waited %v", d)
	case <-r.Context().Done(): // client gave up
	}
}

func TestFetchTimeout(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		srv := httptest.NewTestServer(t, http.HandlerFunc(slowHandler))
		client := srv.Client()

		start := time.Now()
		body, err := FetchStatus(client, "http://api.example.com/delay/3s")
		if err != nil {
			t.Fatal(err)
		}
		t.Logf("body=%q after %v", body, time.Since(start))

		start = time.Now()
		_, err = FetchStatus(client, "http://api.example.com/delay/10s")
		if err == nil {
			t.Fatal("expected a timeout")
		}
		t.Logf("err=%v after %v", err, time.Since(start))
	})
}
=== RUN   TestFetchTimeout
    client_test.go:37: body="waited 3s" after 3s
    client_test.go:44: err=Get "http://api.example.com/delay/10s": context deadline exceeded after 5s
--- PASS: TestFetchTimeout (0.00s)

Both the slow server and the client's timeout run on the fake clock. Testing a 5 second timeout takes no time, and there are no ports to allocate.

Code under test must use the client from srv.Client() (or its Transport). A function that uses http.DefaultClient sends real network requests, so make the client a parameter or a field.

To get a server on a real loopback port instead, call srv.Start() after NewTestServer. That's for tests outside a bubble.

Common mistakes

Channels created outside the bubble

A channel, time.Timer or time.Ticker belongs to the bubble it was created in. A goroutine blocked on a channel from outside its bubble isn't durably blocked, because something outside could send on it:

package outside

import "time"

// Poll calls f every interval until quit is closed.
func Poll(interval time.Duration, quit <-chan struct{}, f func()) {
	t := time.NewTicker(interval)
	defer t.Stop()
	for {
		select {
		case <-t.C:
			f()
		case <-quit:
			return
		}
	}
}
func TestPollWrong(t *testing.T) {
	quit := make(chan struct{}) // created OUTSIDE the bubble
	synctest.Test(t, func(t *testing.T) {
		var n atomic.Int32
		go Poll(time.Second, quit, func() { n.Add(1) })
		synctest.Sleep(5 * time.Second) // hangs: time never advances
		t.Log("calls:", n.Load())
		close(quit)
	})
}

The test hangs. The goroutine dump shows why: the Poll goroutine is in select, without the (durable) mark, so the clock never moves:

goroutine 9 [sleep (durable), synctest bubble 1]:
time.Sleep(0x12a05f200)
...
goroutine 10 [select, synctest bubble 1]:
example.com/st/outside.Poll(0x0?, 0x19eabb1343f0, 0x19eabb13e350)
	.../outside/worker.go:10 +0xb2

Create everything the test uses inside the function passed to synctest.Test:

func TestPoll(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		quit := make(chan struct{}) // created inside the bubble
		var n atomic.Int32
		go Poll(time.Second, quit, func() { n.Add(1) })
		synctest.Sleep(5 * time.Second)
		t.Log("calls:", n.Load())
		close(quit)
	})
}
=== RUN   TestPoll
    worker_test.go:27: calls: 5
--- PASS: TestPoll (0.00s)

The same applies to package-level state created in init or shared between tests, like a global worker pool or a cached time.Ticker. The opposite direction is an error too: using a bubble's channel from outside the bubble crashes the program:

var shared chan int

func TestLeakChannel(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		shared = make(chan int, 1) // belongs to this bubble
	})
	shared <- 1 // used outside the bubble
}
fatal error: send on synctest channel from outside bubble

One more limitation: a sync.WaitGroup declared as a package variable (var wg sync.WaitGroup) can't be associated with a bubble, so wg.Wait() on it isn't durably blocking. A *sync.WaitGroup in a package variable (var wg = new(sync.WaitGroup)) is fine.

Leaking goroutines

synctest.Test waits for all goroutines in the bubble to exit. Once the test function returns, time stops advancing, so a background goroutine that's still running is reported:

func TestLeak(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		h := ticker.Start(time.Second)
		synctest.Sleep(3 * time.Second)
		t.Log("beats:", h.Beats())
		// forgot h.Stop()
	})
}
=== RUN   TestLeak
    leak_test.go:15: beats: 3
--- FAIL: TestLeak (0.00s)
panic: deadlock: main bubble goroutine has exited but blocked goroutines remain [recovered, repanicked]
...
goroutine 23 [select (durable), synctest bubble 1]:
example.com/st/ticker.Start.func1()

This is a useful check: it finds goroutine leaks that a normal test never notices. Stop background work before the test returns, with defer or with t.Cleanup, which runs inside the bubble:

func TestCleanup(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		h := ticker.Start(time.Second)
		t.Cleanup(h.Stop) // runs inside the bubble, before Test returns
		synctest.Sleep(3 * time.Second)
		t.Log("beats:", h.Beats())
	})
}
=== RUN   TestCleanup
    leak_test.go:25: beats: 3
--- PASS: TestCleanup (0.00s)

Goroutines that stop when a context is canceled can use t.Context(), which is canceled just before cleanup functions run.

Real I/O and external processes

Anything that waits on the operating system, like a real network connection, a database driver talking to a server, os/exec, or reading a file that is slow, isn't durably blocking. The bubble's clock stops until it returns, and synctest.Wait keeps waiting. Use fakes inside bubbles: httptest.NewTestServer for HTTP, net.Pipe for raw connections (its reads and writes block on channels), and in-memory implementations of your own interfaces for everything else.

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents