コンテンツにスキップ

Go/goコマンド/fix/testingcontext

出典: フリー教科書『ウィキブックス(Wikibooks)』

go fix の testingcontext は、Go 1.24 で追加された t.Context() を使って、テスト内の手動コンテキスト管理を簡潔に書き換えるリファクタリングです。

背景:テストでの定型コンテキスト管理
テストでキャンセル可能なコンテキストを使うたびに、毎回同じボイラープレートを書く必要がありました。
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
t.Context() はテストの終了時に自動でキャンセルされるコンテキストを返すため、この定型文が不要になります。

置き換えパターン

[編集]

基本パターン

[編集]
// Before
func TestFoo(t *testing.T) {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    use(ctx)
}

// After
func TestFoo(t *testing.T) {
    ctx := t.Context()
    use(ctx)
}

サブテストも対象

[編集]
// Before
func TestFoo(t *testing.T) {
    t.Run("sub", func(t *testing.T) {
        ctx, cancel := context.WithCancel(context.Background())
        defer cancel()
        use(ctx)
    })
}

// After
func TestFoo(t *testing.T) {
    t.Run("sub", func(t *testing.T) {
        ctx := t.Context()
        use(ctx)
    })
}

ベンチマークも対象

[編集]
// Before
func BenchmarkFoo(b *testing.B) {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()
    for b.Loop() {
        use(ctx)
    }
}

// After
func BenchmarkFoo(b *testing.B) {
    ctx := b.Context()
    for b.Loop() {
        use(ctx)
    }
}

fix されないケース

[編集]

cancel を defer 以外の目的で使っている場合は対象外です。

// ❌ cancel を別の目的で使っている
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
    <-done
    cancel() // ← defer 以外で呼んでいる
}()

t.Context() はテスト終了時に自動キャンセルされるだけなので、途中で明示的にキャンセルしたいケースは自動変換できません。

t.Context() の挙動

[編集]
テスト開始
   ↓
t.Context() → キャンセル可能なコンテキストを返す
   ↓
テスト終了(成功・失敗・タイムアウト問わず)
   ↓
コンテキストが自動キャンセルされる

defer cancel() の書き忘れによるリソースリークも防げます。

適用方法

[編集]
go fix -run testingcontext ./...
まとめ
項目 内容
対象バージョン Go 1.24 以降
変更の種類 可読性改善 + リークリスク低減(動作は変わらない)
対象 testing.T・testing.B 内の定型コンテキスト生成
対象外 cancel を defer 以外で使っているケース

bloop と同じく Go 1.24 のテスト改善を活かす変換です。defer cancel() の書き忘れはテストでのコンテキストリークという気づきにくいバグにつながることがあり、t.Context() への移行でそのリスクを根本から取り除けます。