用 Go 1.25 的 testing/synctest 测试重试和取消

星期日, 8月 17, 2025 | 3分钟阅读 | 更新于 星期日, 8月 17, 2025

@

在 《Go 通道》 里,worker 可以等定时器或等取消信号。测试这种代码时,经常先 time.Sleep 一小段,再猜 worker 已经运行到了哪里。Go 1.25 正式提供 testing/synctest,可以在隔离环境里让定时器用虚拟时钟,并等待其他 goroutine 进入明确的阻塞状态。 Go 1.25 发布说明

实验环境 Go 1.25.0。使用 -race 时需要该系统上支持 CGO 的 C 编译器。Linux 示例可用 GCC 13.2.0。 Go 1.25.0 发行记录

一、先确定重试规则

下面的例子最多调用三次。第一次立即执行,两次间隔分别为 100 ms 和 200 ms。取消发生后会从退避等待中返回。传入的操作也要接收该上下文,才能中断已经开始的 I/O。示例中的操作都是可重试的,实际 HTTP 客户端可以在 operation 里区分临时错误与永久错误。

package retry

import (
    "context"
    "time"
)

func run(ctx context.Context, operation func(context.Context) error) error {
    delay := 100 * time.Millisecond
    for attempt := 1; ; attempt++ {
        if err := ctx.Err(); err != nil {
            return err
        }
        err := operation(ctx)
        if err == nil || attempt == 3 {
            return err
        }

        timer := time.NewTimer(delay)
        select {
        case <-ctx.Done():
            timer.Stop()
            return ctx.Err()
        case <-timer.C:
            delay *= 2
        }
    }
}

二、测试发生在第几毫秒

synctest.Test 在隔离环境里运行测试。时钟只有在所有 goroutine 都进入可确定的阻塞后才会前进。下面同时推进重试的定时器与测试里的 time.Sleep。synctest.Wait 等待其他 goroutine 完成这一步该做的工作,并让测试能安全地读取 attempts。

package retry

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

func TestRetrySchedule(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        start := time.Now()
        var attempts []time.Duration
        done := make(chan error, 1)
        go func() {
            done <- run(t.Context(), func(context.Context) error {
                attempts = append(attempts, time.Since(start))
                if len(attempts) < 3 {
                    return errors.New("try again")
                }
                return nil
            })
        }()

        synctest.Wait()
        if !slices.Equal(attempts, []time.Duration{0}) {
            t.Fatalf("initial attempts: %v", attempts)
        }
        time.Sleep(299 * time.Millisecond)
        synctest.Wait()
        if !slices.Equal(attempts, []time.Duration{0, 100 * time.Millisecond}) {
            t.Fatalf("attempts before 300ms: %v", attempts)
        }
        time.Sleep(time.Millisecond)
        if err := <-done; err != nil {
            t.Fatal(err)
        }
        if !slices.Equal(attempts, []time.Duration{0, 100 * time.Millisecond, 300 * time.Millisecond}) {
            t.Fatalf("all attempts: %v", attempts)
        }
    })
}

func TestCancelDuringBackoff(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        ctx, cancel := context.WithCancel(t.Context())
        defer cancel()
        attempts := 0
        done := make(chan error, 1)
        go func() {
            done <- run(ctx, func(context.Context) error {
                attempts++
                return errors.New("try again")
            })
        }()

        synctest.Wait()
        cancel()
        if err := <-done; !errors.Is(err, context.Canceled) {
            t.Fatalf("run returned %v", err)
        }
        if attempts != 1 {
            t.Fatalf("got %d attempts, want 1", attempts)
        }
    })
}

将两段代码分别保存为 retry.go 和 retry_test.go。用 Go 1.25.0 执行 go mod init retry-example,再运行 go test -race -count=20。第一个测试固定检查 0、100ms、300ms 三个时间点,第二个测试等 worker 确实开始等定时器以后再取消。

三、哪些阻塞适合放进这个测试

隔离环境里创建的 channel 可以用来观察 worker 进入某个阶段。真实网络 socket、文件 I/O 和隔离环境之外发来的事件不适合充当虚拟时钟的推进条件。可以把 HTTP 传输通过接口注入,给退避测试传一个确定性的函数,再用普通 httptest 测请求与连接行为。这样能分别定位重试时序和网络交互的问题。 Go 1.25 的 synctest 文档

四、验证最后一次失败会立即返回

前面验证了成功路径和退避中的取消。还可以用一条始终失败的操作验证最大尝试次数。这个用例不需要手动推动虚拟时钟,当前 goroutine 等返回值时,定时器会在其余工作都阻塞后自动向前推进。把这个测试追加到已有的 retry_test.go,沿用原来的导入。

func TestRetryExhausted(t *testing.T) {
    synctest.Test(t, func(t *testing.T) {
        failure := errors.New("upstream unavailable")
        started := time.Now()
        attempts := 0

        err := run(t.Context(), func(context.Context) error {
            attempts++
            return failure
        })

        if !errors.Is(err, failure) {
            t.Fatalf("final error = %v", err)
        }
        if attempts != 3 {
            t.Fatalf("attempts = %d, want 3", attempts)
        }
        if elapsed := time.Since(started); elapsed != 300*time.Millisecond {
            t.Fatalf("elapsed = %v, want 300ms", elapsed)
        }
    })
}

如果实现错误地在最后一次失败后又等了 400 ms,虚拟时间会变成 700 ms,这条测试就会失败。真实耗时仍然很短。以后如果给重试加入随机抖动,可以把计算延迟的函数注入,让测试传入固定值,再单独检查抖动是否落在约定范围。测试内的并发交互仍用同一套 channel 和上下文,避免碰到真实网络调度。 Go 1.25.0 的 synctest

© 2026 我的博客

🌱 Powered by Hugo with theme Dream.