Go 1.25 用 testing/synctest 给超时与并发逻辑写确定性测试,不再靠 sleep 碰运气

未来之星2026-11-1616 次阅读

靠真实时间写的测试,又慢又飘

测一个三秒超时的重试逻辑,最朴素的做法是真等三秒。一个用例三秒,几十个用例跑下来 CI 就慢得没人愿意等。把超时常量改成可注入的参数能缩短等待,却又走进了另一个坑:睡眠时间设短了,负载一高 goroutine 还没调度到断言就执行了,测试偶发失败;设长了又回到慢。这类 flaky 测试最消耗信任,重跑一次就过了,谁也说不清到底有没有 bug。Go 1.25 稳定下来的 testing/synctest 提供了一个隔离气泡与假时钟,气泡内所有 goroutine 都持久阻塞时,时间直接跳到下一个该唤醒的时刻,三秒的超时在测试里瞬时完成,并且结果完全确定。

先写一个被测的重试函数

下面这段逻辑很常见:按固定间隔重试一个可能失败的操作,超时或上下文取消就退出。把它存成 retry.go,传统的测试只能靠缩短 interval 加 sleep 去碰,恰恰是 synctest 最擅长覆盖的类型。

package retry

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

var errTemporary = errors.New("temporary failure")

// Retry 每隔 interval 调用一次 op,直到成功、超时或 ctx 被取消
func Retry(ctx context.Context, interval time.Duration, op func() (bool, error)) error {
    ticker := time.NewTicker(interval)
    defer ticker.Stop()

    for {
        if ok, err := op(); err != nil {
            return err
        } else if ok {
            return nil
        }

        select {
        case <-ctx.Done():
            return ctx.Err()
        case <-ticker.C:
        }
    }
}

气泡与假时钟怎么用

synctest.Test 接收 *testing.T 与一个函数,函数体内启动的所有 goroutine 都属于这个气泡。气泡内的 time 使用假时钟,初始时间固定为 UTC 2000 年 1 月 1 日零点,只有当气泡内所有 goroutine 都处于持久阻塞状态时,时钟才会推进到下一个能唤醒某个 goroutine 的时刻。于是 time.Sleep 不再消耗真实时间,而是一次确定性的时间跳跃。下面这个测试执行耗时接近零,却完整覆盖了三次重试的时序。

package retry

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

func TestRetrySucceedsOnThirdAttempt(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        calls := 0
        ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
        defer cancel()

        err := Retry(ctx, time.Second, func() (bool, error) {
            calls++
            return calls == 3, nil
        })
        if err != nil {
            t.Fatalf("Retry: %v", err)
        }
        if calls != 3 {
            t.Fatalf("calls = %d, want 3", calls)
        }
    })
}

func TestRetryStopsOnDeadline(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ctx, cancel := context.WithTimeout(t.Context(), 2500*time.Millisecond)
        defer cancel()

        calls := 0
        err := Retry(ctx, time.Second, func() (bool, error) {
            calls++
            return false, nil
        })
        if err != context.DeadlineExceeded {
            t.Fatalf("err = %v, want DeadlineExceeded", err)
        }
        if calls != 3 {
            t.Fatalf("calls = %d, want 3", calls)
        }
    })
}

注意这里用的是 t.Context() 而不是 context.Background(),因为传给回调的 T 所提供的 Context,其 Done 通道与气泡关联,取消与超时都由假时钟驱动。用外部创建的 Context 会让 goroutine 有可能被气泡外的事件唤醒,破坏持久阻塞的判定。

用 Wait 断言「此刻还没发生」

超时类测试最想验证的其实是边界:时间没到之前不该发生,时间到了之后必须发生。synctest.Wait 会阻塞到气泡内除当前 goroutine 之外的所有 goroutine 都持久阻塞,正好用来在中间时刻切片检查。下面的例子先睡到超时前一纳秒,断言上下文仍有效,再补一纳秒断言已超时,两段断言都不依赖调度运气。

package retry

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

func TestTimeoutBoundary(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, want nil", err)
        }

        time.Sleep(time.Nanosecond)
        synctest.Wait()
        if err := ctx.Err(); err != context.DeadlineExceeded {
            t.Fatalf("after timeout: ctx.Err() = %v, want DeadlineExceeded", err)
        }
    })
}

同样的手法适合验证延迟回调:注册一个 context.AfterFunc,先用 Wait 确认还没执行,再 cancel 并 Wait 确认已执行,全程不需要任何真实睡眠。

func TestContextAfterFunc(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ctx, cancel := context.WithCancel(t.Context())
        called := false
        context.AfterFunc(ctx, func() { called = true })

        synctest.Wait()
        if called {
            t.Fatal("before cancel: AfterFunc was called")
        }

        cancel()
        synctest.Wait()
        if !called {
            t.Fatal("after cancel: AfterFunc was not called")
        }
    })
}

什么算持久阻塞

这个概念决定了假时钟何时推进,是使用时最容易踩坑的地方。只有当 goroutine 被阻塞、且只能由同一个气泡内的其他 goroutine 唤醒时,才算持久阻塞:气泡内创建的 channel 上的收发、全由气泡内 channel 组成的 select、sync.Cond.Wait、在气泡内调用过 Add 的 WaitGroup.Wait,以及 time.Sleep 都算。反过来,加解锁 Mutex、网络 IO、系统调用都不算,因为它们可能被气泡外的事件唤醒。

实践含义很直接:不要在气泡里用真实网络。哪怕是本机回环连接,阻塞在 socket 上的 goroutine 也不算持久阻塞,气泡可能永远无法进入空闲状态。标准库文档给出的做法是改用 net.Pipe 这类进程内的假连接,或者把网络层抽象成接口注入一个内存实现。另外,气泡内创建的 channel、Timer、Ticker 与气泡绑定,从气泡外操作会 panic;测试之间别共享这类对象,每个用例都在自己的 Test 回调里重新创建。

版本与工程化细节

synctest.Test 与 synctest.Wait 自 Go 1.25 起进入标准库,go.mod 里把 go 指令设到 1.25 即可,不需要 GOEXPERIMENT。更早的 1.24 曾是实验版本,API 也不一致,不建议照着老教程写。Go 1.27 又新增了 synctest.Sleep,等价于 time.Sleep 后紧跟一次 Wait,用来避免测试协程与被测协程睡同样时长时的先后不确定;要兼容 1.25 就继续用 time.Sleep 加 Wait 的组合。

module example.com/retry

go 1.25

还有几条关于 T 的限制:回调里的 Cleanup 会在气泡内、Test 返回前执行,适合做收尾断言;但 T.Run、T.Parallel 与 T.Deadline 都不允许调用,气泡内的测试不能并行。气泡根协程退出后时间停止推进,Test 会等气泡内所有 goroutine 退出才返回,若它们互相等死会直接判定测试失败,这比传统测试里悄悄泄漏 goroutine 要好排查得多。

工程化注意点

  • synctest.Test 与 Wait 需要 Go 1.25 及以上,go.mod 里同步把 go 指令升到 1.25。
  • 测试内一律用 t.Context() 派生上下文,用 context.Background() 会破坏气泡隔离。
  • 气泡内避免真实网络与系统调用,改用 net.Pipe 或注入内存实现,否则气泡无法进入空闲。
  • channel、Timer、Ticker 在气泡内创建就与气泡绑定,跨气泡操作会 panic,每个用例独立创建。
  • T.Run、T.Parallel、T.Deadline 在回调提供的 T 上禁止调用,需要拆成多个顶层 synctest.Test。
  • Go 1.27 起可用 synctest.Sleep 替代 time.Sleep 加 Wait,兼容 1.25 时保持后者。
  • 把气泡内的假时钟仅用于时间相关逻辑,普通并发正确性仍应配合 -race 一起跑。

把这类测试迁到 synctest 之后,最直观的变化是 CI 时长:原来几十秒的超时用例集群压缩到几毫秒,而且不再有那种重跑一次就通过的红点。更实质的收益是断言能力变强了,过去只能验证「最终成功」,现在可以精确切在超时前后那一刻,确认不该发生的确实没发生。

未

未来之星

文章作者

靠真实时间写的测试,又慢又飘 测一个三秒超时的重试逻辑,最朴素的做法是真等三秒。一个用例三秒,几十个用例跑下来 CI...

分类
技术
发布时间
2026-11-16
字数
约 5469 字
阅读
16 次