# 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-unit) 與 [`testing`](/pkg-testing)；goroutine 與 channel 的觀念見 [Goroutine](/concurrency-goroutines)、[Channel](/concurrency-channels)。

本頁範例都是「被測檔＋測試檔＋`go test` 指令」的形式，目錄中另有以 `go mod init example.com/demo` 建立的 `go.mod`（`go` 版本須為 1.25 以上）。輸出最後一行的秒數依機器而異。

## 匯入

```go
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 全部卡死、沒有任何計時器能喚醒它們，就是死結，測試會失敗。

簽名：

```go
func Test(t *testing.T, f func(*testing.T))
```

被測檔 `cache.go`：

```go
package demo

import "time"

type entry struct {
	value   string
	expires time.Time
}

type Cache struct {
	ttl  time.Duration
	data map[string]entry
}

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

func (c *Cache) Set(key, value string) {
	c.data[key] = entry{value: value, expires: time.Now().Add(c.ttl)}
}

func (c *Cache) Get(key string) (string, bool) {
	e, ok := c.data[key]
	if !ok || time.Now().After(e.expires) {
		return "", false
	}
	return e.value, true
}
```

測試檔 `cache_test.go`：

```go
package demo

import (
	"testing"
	"testing/synctest"
	"time"
)

func TestCacheExpire(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		t.Log("起始時間:", time.Now().UTC())

		c := NewCache(5 * time.Minute)
		c.Set("token", "abc")

		time.Sleep(4 * time.Minute)
		if _, ok := c.Get("token"); !ok {
			t.Fatal("4 分鐘時不應過期")
		}

		time.Sleep(2 * time.Minute)
		if _, ok := c.Get("token"); ok {
			t.Fatal("6 分鐘時應該已過期")
		}
		t.Log("目前時間:", time.Now().UTC())
	})
}
```

執行：

```bash
go test -count=1 -v
```

輸出：

```text
=== RUN   TestCacheExpire
    cache_test.go:11: 起始時間: 2000-01-01 00:00:00 +0000 UTC
    cache_test.go:25: 目前時間: 2000-01-01 00:06:00 +0000 UTC
--- PASS: TestCacheExpire (0.00s)
PASS
ok  	example.com/demo	0.050s
```

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

### Wait

`synctest.Wait()` 會阻塞，直到泡泡裡「除了自己以外」的所有 goroutine 都持久阻塞或已結束。用它取代「睡一下等背景工作做完」的寫法：背景 goroutine 處理完事件、回到等待 channel 的狀態時，`Wait` 就返回，結果不會因機器快慢而不同。

注意：`Wait` 只能在泡泡內呼叫，否則會 panic。

簽名：

```go
func Wait()
```

被測檔 `counter.go`：

```go
package demo

import "sync/atomic"

type Counter struct {
	events chan string
	count  atomic.Int64
}

func NewCounter() *Counter {
	c := &Counter{events: make(chan string)}
	go func() {
		for range c.events {
			c.count.Add(1)
		}
	}()
	return c
}

func (c *Counter) Send(name string) {
	go func() { c.events <- name }()
}

func (c *Counter) Count() int64 { return c.count.Load() }

func (c *Counter) Close() { close(c.events) }
```

測試檔 `counter_test.go`：

```go
package demo

import (
	"testing"
	"testing/synctest"
)

func TestCounter(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		c := NewCounter()
		defer c.Close()

		c.Send("click")
		c.Send("click")
		c.Send("scroll")

		synctest.Wait()
		t.Log("Wait 後:", c.Count())
		if got := c.Count(); got != 3 {
			t.Errorf("Count() = %d, want 3", got)
		}
	})
}
```

執行：

```bash
go test -count=1 -v
```

輸出：

```text
=== RUN   TestCounter
    counter_test.go:18: Wait 後: 3
--- PASS: TestCounter (0.00s)
PASS
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 秒，也能精確驗證放棄的時間點。觀念見 [取消與逾時](/context-cancel-timeout)。

這個小節用的仍是 `synctest.Test` 與 `synctest.Wait`，示範的是最常見的應用情境。

簽名：

```go
func Test(t *testing.T, f func(*testing.T))
func Wait()
```

被測檔 `fetch.go`：

```go
package demo

import (
	"context"
	"time"
)

func Fetch(ctx context.Context, timeout time.Duration, slow <-chan string) (string, error) {
	ctx, cancel := context.WithTimeout(ctx, timeout)
	defer cancel()
	select {
	case v := <-slow:
		return v, nil
	case <-ctx.Done():
		return "", ctx.Err()
	}
}
```

測試檔 `fetch_test.go`：

```go
package demo

import (
	"context"
	"errors"
	"sync/atomic"
	"testing"
	"testing/synctest"
	"time"
)

func TestFetchTimeout(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		start := time.Now()
		_, err := Fetch(t.Context(), 2*time.Second, make(chan string))
		if !errors.Is(err, context.DeadlineExceeded) {
			t.Fatalf("err = %v, want DeadlineExceeded", err)
		}
		t.Log("放棄前等待:", time.Since(start))
	})
}

func TestFetchInTime(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		slow := make(chan string)
		go func() {
			time.Sleep(1500 * time.Millisecond)
			slow <- "ok"
		}()
		start := time.Now()
		v, err := Fetch(t.Context(), 2*time.Second, slow)
		if err != nil || v != "ok" {
			t.Fatalf("Fetch() = %q, %v", v, err)
		}
		t.Log("取得結果耗時:", time.Since(start))
	})
}

func TestTimerNotFired(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		var fired atomic.Bool
		time.AfterFunc(time.Second, func() { fired.Store(true) })

		time.Sleep(time.Second - time.Nanosecond)
		synctest.Wait()
		t.Log("差 1 奈秒時觸發了嗎:", fired.Load())

		time.Sleep(time.Nanosecond)
		synctest.Wait()
		t.Log("滿 1 秒時觸發了嗎:", fired.Load())
	})
}
```

執行：

```bash
go test -count=1 -v
```

輸出：

```text
=== RUN   TestFetchTimeout
    fetch_test.go:19: 放棄前等待: 2s
--- PASS: TestFetchTimeout (0.00s)
=== RUN   TestFetchInTime
    fetch_test.go:35: 取得結果耗時: 1.5s
--- PASS: TestFetchInTime (0.00s)
=== RUN   TestTimerNotFired
    fetch_test.go:46: 差 1 奈秒時觸發了嗎: false
    fetch_test.go:50: 滿 1 秒時觸發了嗎: true
--- PASS: TestTimerNotFired (0.00s)
PASS
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` 會判定死結而失敗

## 資料來源

- [dsxwk/go-docs（標準庫分類架構參考）](https://github.com/dsxwk/go-docs)
- [pkg.go.dev：testing/synctest](https://pkg.go.dev/testing/synctest)
- [Go 1.26.0 原始碼：src/testing/synctest](https://github.com/golang/go/tree/go1.26.0/src/testing/synctest)
