Go

What does this test print, and in what order?

Question 379HardGo 1.22 to 1.25
func TestOrder(t *testing.T) {
    defer fmt.Println("defer")
    t.Cleanup(func() { fmt.Println("cleanup") })
    for i := range 2 {
        t.Run(fmt.Sprint(i), func(t *testing.T) {
            t.Parallel()
            fmt.Println("sub", i)
        })
    }
    fmt.Println("end")
}

Output:

end
defer
sub 0   // these two in nondeterministic order
sub 1
cleanup

When a subtest calls t.Parallel(), it pauses and t.Run returns immediately. Paused parallel subtests are released only after the parent test function returns. So "end" prints, then the parent's defer runs, then the subtests run concurrently, and finally t.Cleanup runs after all subtests complete.

The practical consequence: never tear down shared fixtures with defer in a test that has parallel subtests — the DB would be closed before the subtests use it. Use t.Cleanup, or wrap the parallel subtests in a group t.Run("group", ...), which doesn't return until its parallel children finish. Since Go 1.22, i is per-iteration, so each subtest prints its own value; before 1.22 both would likely have printed sub 2 (with the old for i := 0; i < 2; i++ form) unless you wrote i := i.

More on Performance, Profiling & Testing

All 38 Performance, Profiling & Testing questions