go / expert
Snippet
LIFO Resource Deallocation Order via t.Cleanup in Subtests
The t.Cleanup method registers functions that are executed when the test or subtest completes. Functions registered via t.Cleanup are invoked in Last-In-First-Out (LIFO) order, guaranteeing that subtest resources are released prior to parent test cleanups.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package mainimport "testing"func TestResourceLifecycle(t *testing.T) {t.Cleanup(func() {t.Log("Primary cleanup executed last (LIFO)")})t.Run("Subtest", func(t *testing.T) {t.Cleanup(func() {t.Log("Subtest specific cleanup executed first")})t.Log("Running subtest assertions")})}
Breakdown
1
t.Cleanup(func() {
Registers a cleanup callback scoped strictly to the lifecycle of the current testing context.
2
t.Run("Subtest", func(t *testing.T) {
Spawns a isolated subtest with its own independent cleanup stack.