testing/synctest

最後更新


testing/synctest 套件讓你在隔離的「泡泡」裡測試併發與時間相關的程式碼:時間是假的、可以瞬間前進,還能等到所有 goroutine 都停下來再檢查結果。Go 1.25 起提供。

這個套件做什麼


測試併發程式碼有兩個老問題:
  1. 跟時間有關的邏輯很慢:要測「快取 5 分鐘後過期」,難道真的等 5 分鐘?把時間縮短成 50 毫秒,又容易在忙碌的 CI 機器上偶發失敗
  2. 不知道背景 goroutine 做完了沒:只好 time.Sleep(100 * time.Millisecond) 碰運氣

synctest 的解法是把測試放進一個泡泡(bubble)裡執行:
  • 假時鐘:泡泡裡的 time.Now、time.Sleep、time.After、計時器都使用假時間,起點固定為 2000-01-01 00:00:00 UTC
  • 時間只在大家都卡住時才前進:當泡泡裡每個 goroutine 都「持久阻塞」(durably blocked,只能被泡泡內的其他 goroutine 喚醒)時,假時間會直接跳到下一個會喚醒某個 goroutine 的時間點。所以 time.Sleep(5 * time.Minute) 瞬間完成
  • Wait:等到泡泡裡其他 goroutine 全部持久阻塞或結束,再繼續往下檢查

會讓 goroutine「持久阻塞」的操作:泡泡內建立的 channel 收送、只含這類 channel 的 select、time.Sleep、sync.Cond.Wait、在泡泡內 Add 過的 sync.WaitGroup.Wait。
注意:等待 sync.Mutex、網路 I/O、系統呼叫都不算持久阻塞,因為它們可能被泡泡外的事件喚醒。需要網路時改用 net.Pipe 這類程序內的假連線。
基礎測試寫法見 單元測試 與 testing;goroutine 與 channel 的觀念見 Goroutine、Channel。
本頁範例都是「被測檔+測試檔+go test 指令」的形式,目錄中另有以 go mod init example.com/demo 建立的 go.mod(go 版本須為 1.25 以上)。輸出最後一行的秒數依機器而異。

匯入


  1. import "testing/synctest"

常用 API


Test 與假時鐘


synctest.Test(t, f) 在新泡泡中執行 f,並等泡泡裡所有 goroutine 都結束才返回。傳給 f 的 *testing.T 跟一般測試一樣使用,另外:
  • t.Cleanup 註冊的函式在泡泡內、Test 返回前執行
  • t.Context() 的 context 屬於這個泡泡

注意:f 裡面不能呼叫 t.Run、t.Parallel、t.Deadline;Test 也不能在另一個泡泡裡呼叫。若泡泡內的 goroutine 全部卡死、沒有任何計時器能喚醒它們,就是死結,測試會失敗。
簽名:
  1. func Test(t *testing.T, f func(*testing.T))

被測檔 cache.go:
  1. package demo
  2. import "time"
  3. type entry struct {
  4. value string
  5. expires time.Time
  6. }
  7. type Cache struct {
  8. ttl time.Duration
  9. data map[string]entry
  10. }
  11. func NewCache(ttl time.Duration) *Cache {
  12. return &Cache{ttl: ttl, data: map[string]entry{}}
  13. }
  14. func (c *Cache) Set(key, value string) {
  15. c.data[key] = entry{value: value, expires: time.Now().Add(c.ttl)}
  16. }
  17. func (c *Cache) Get(key string) (string, bool) {
  18. e, ok := c.data[key]
  19. if !ok || time.Now().After(e.expires) {
  20. return "", false
  21. }
  22. return e.value, true
  23. }

測試檔 cache_test.go:
  1. package demo
  2. import (
  3. "testing"
  4. "testing/synctest"
  5. "time"
  6. )
  7. func TestCacheExpire(t *testing.T) {
  8. synctest.Test(t, func(t *testing.T) {
  9. t.Log("起始時間:", time.Now().UTC())
  10. c := NewCache(5 * time.Minute)
  11. c.Set("token", "abc")
  12. time.Sleep(4 * time.Minute)
  13. if _, ok := c.Get("token"); !ok {
  14. t.Fatal("4 分鐘時不應過期")
  15. }
  16. time.Sleep(2 * time.Minute)
  17. if _, ok := c.Get("token"); ok {
  18. t.Fatal("6 分鐘時應該已過期")
  19. }
  20. t.Log("目前時間:", time.Now().UTC())
  21. })
  22. }

執行:
  1. go test -count=1 -v

輸出:
  1. === RUN TestCacheExpire
  2. cache_test.go:11: 起始時間: 2000-01-01 00:00:00 +0000 UTC
  3. cache_test.go:25: 目前時間: 2000-01-01 00:06:00 +0000 UTC
  4. --- PASS: TestCacheExpire (0.00s)
  5. PASS
  6. ok example.com/demo 0.050s

測試裡總共「睡」了 6 分鐘,實際只花了不到 1 秒(大部分是編譯時間)。起始時間固定,所以時間相關的輸出每次都一樣。

Wait


synctest.Wait() 會阻塞,直到泡泡裡「除了自己以外」的所有 goroutine 都持久阻塞或已結束。用它取代「睡一下等背景工作做完」的寫法:背景 goroutine 處理完事件、回到等待 channel 的狀態時,Wait 就返回,結果不會因機器快慢而不同。
注意:Wait 只能在泡泡內呼叫,否則會 panic。
簽名:
  1. func Wait()

被測檔 counter.go:
  1. package demo
  2. import "sync/atomic"
  3. type Counter struct {
  4. events chan string
  5. count atomic.Int64
  6. }
  7. func NewCounter() *Counter {
  8. c := &Counter{events: make(chan string)}
  9. go func() {
  10. for range c.events {
  11. c.count.Add(1)
  12. }
  13. }()
  14. return c
  15. }
  16. func (c *Counter) Send(name string) {
  17. go func() { c.events <- name }()
  18. }
  19. func (c *Counter) Count() int64 { return c.count.Load() }
  20. func (c *Counter) Close() { close(c.events) }

測試檔 counter_test.go:
  1. package demo
  2. import (
  3. "testing"
  4. "testing/synctest"
  5. )
  6. func TestCounter(t *testing.T) {
  7. synctest.Test(t, func(t *testing.T) {
  8. c := NewCounter()
  9. defer c.Close()
  10. c.Send("click")
  11. c.Send("click")
  12. c.Send("scroll")
  13. synctest.Wait()
  14. t.Log("Wait 後:", c.Count())
  15. if got := c.Count(); got != 3 {
  16. t.Errorf("Count() = %d, want 3", got)
  17. }
  18. })
  19. }

執行:
  1. go test -count=1 -v

輸出:
  1. === RUN TestCounter
  2. counter_test.go:18: Wait 後: 3
  3. --- PASS: TestCounter (0.00s)
  4. PASS
  5. ok example.com/demo 0.040s

Send 在背景送出事件,剛呼叫完時計數多半還沒更新,而且值不固定;Wait 返回時,送事件的 goroutine 都已結束,處理 goroutine 也回到等待 channel 的狀態,計數必定是 3。defer c.Close() 關閉 channel 讓處理 goroutine 結束,否則它會一直卡著,Test 會判定為死結。

測試逾時與 context


泡泡裡的 context.WithTimeout、time.After 同樣使用假時鐘。要測「上游太慢時應該在 2 秒後放棄」,不必真的等 2 秒,也能精確驗證放棄的時間點。觀念見 取消與逾時。
這個小節用的仍是 synctest.Test 與 synctest.Wait,示範的是最常見的應用情境。
簽名:
  1. func Test(t *testing.T, f func(*testing.T))
  2. func Wait()

被測檔 fetch.go:
  1. package demo
  2. import (
  3. "context"
  4. "time"
  5. )
  6. func Fetch(ctx context.Context, timeout time.Duration, slow <-chan string) (string, error) {
  7. ctx, cancel := context.WithTimeout(ctx, timeout)
  8. defer cancel()
  9. select {
  10. case v := <-slow:
  11. return v, nil
  12. case <-ctx.Done():
  13. return "", ctx.Err()
  14. }
  15. }

測試檔 fetch_test.go:
  1. package demo
  2. import (
  3. "context"
  4. "errors"
  5. "sync/atomic"
  6. "testing"
  7. "testing/synctest"
  8. "time"
  9. )
  10. func TestFetchTimeout(t *testing.T) {
  11. synctest.Test(t, func(t *testing.T) {
  12. start := time.Now()
  13. _, err := Fetch(t.Context(), 2*time.Second, make(chan string))
  14. if !errors.Is(err, context.DeadlineExceeded) {
  15. t.Fatalf("err = %v, want DeadlineExceeded", err)
  16. }
  17. t.Log("放棄前等待:", time.Since(start))
  18. })
  19. }
  20. func TestFetchInTime(t *testing.T) {
  21. synctest.Test(t, func(t *testing.T) {
  22. slow := make(chan string)
  23. go func() {
  24. time.Sleep(1500 * time.Millisecond)
  25. slow <- "ok"
  26. }()
  27. start := time.Now()
  28. v, err := Fetch(t.Context(), 2*time.Second, slow)
  29. if err != nil || v != "ok" {
  30. t.Fatalf("Fetch() = %q, %v", v, err)
  31. }
  32. t.Log("取得結果耗時:", time.Since(start))
  33. })
  34. }
  35. func TestTimerNotFired(t *testing.T) {
  36. synctest.Test(t, func(t *testing.T) {
  37. var fired atomic.Bool
  38. time.AfterFunc(time.Second, func() { fired.Store(true) })
  39. time.Sleep(time.Second - time.Nanosecond)
  40. synctest.Wait()
  41. t.Log("差 1 奈秒時觸發了嗎:", fired.Load())
  42. time.Sleep(time.Nanosecond)
  43. synctest.Wait()
  44. t.Log("滿 1 秒時觸發了嗎:", fired.Load())
  45. })
  46. }

執行:
  1. go test -count=1 -v

輸出:
  1. === RUN TestFetchTimeout
  2. fetch_test.go:19: 放棄前等待: 2s
  3. --- PASS: TestFetchTimeout (0.00s)
  4. === RUN TestFetchInTime
  5. fetch_test.go:35: 取得結果耗時: 1.5s
  6. --- PASS: TestFetchInTime (0.00s)
  7. === RUN TestTimerNotFired
  8. fetch_test.go:46: 差 1 奈秒時觸發了嗎: false
  9. fetch_test.go:50: 滿 1 秒時觸發了嗎: true
  10. --- PASS: TestTimerNotFired (0.00s)
  11. PASS
  12. ok example.com/demo 0.225s

time.Since(start) 剛好是 2s 與 1.5s,不會有毫秒級的誤差;TestTimerNotFired 甚至能精確到奈秒驗證計時器的觸發時間點。

重點整理


  • testing/synctest 於 Go 1.25 起提供,只有 Test 與 Wait 兩個函式
  • synctest.Test 建立泡泡:假時鐘從 2000-01-01 UTC 開始,只有在所有 goroutine 都持久阻塞時才前進
  • 測試裡的 time.Sleep、context.WithTimeout 都瞬間完成,結果也完全可重現
  • synctest.Wait 取代「睡一下等背景工作」,等到其他 goroutine 都停下來再檢查
  • Mutex、網路 I/O、系統呼叫不算持久阻塞;網路測試改用 net.Pipe 等程序內實作
  • 泡泡裡的 goroutine 要能結束,否則 Test 會判定死結而失敗

資料來源