Skip to content

Commit c952565

Browse files
committed
make let.Context cancel after test execution
This might help cleanup compontents which use context cancellation as shutdown signal
1 parent d75a913 commit c952565

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

let/std.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@ import (
99

1010
func Context(s *testcase.Spec) testcase.Var[context.Context] {
1111
return testcase.Let(s, func(t *testcase.T) context.Context {
12-
return context.Background()
12+
ctx, cancel := context.WithCancel(context.Background())
13+
t.Defer(cancel)
14+
return ctx
1315
})
1416
}
1517

let/std_test.go

+24-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,16 @@ func TestSTD_smoke(t *testing.T) {
3434
}
3535

3636
s.Test("", func(t *testcase.T) {
37-
t.Must.Equal(context.Background(), Context.Get(t))
37+
t.Must.NotNil(Context.Get(t))
38+
t.Must.NoError(Context.Get(t).Err())
39+
t.Must.NotWithin(time.Millisecond, func(ctx context.Context) {
40+
select {
41+
case <-Context.Get(t).Done():
42+
// expect to block
43+
case <-ctx.Done():
44+
// will be done after the assertion
45+
}
46+
})
3847
t.Must.Error(Error.Get(t))
3948
t.Must.NotEmpty(String.Get(t))
4049
t.Must.NotEmpty(StringNC.Get(t))
@@ -53,3 +62,17 @@ func TestSTD_smoke(t *testing.T) {
5362
})
5463
})
5564
}
65+
66+
func TestContext_cancellationDuringCleanup(t *testing.T) {
67+
s := testcase.NewSpec(t)
68+
s.Sequential()
69+
ctxVar := let.Context(s)
70+
var ctx context.Context
71+
s.Test("", func(t *testcase.T) {
72+
ctx = ctxVar.Get(t)
73+
t.Must.NoError(ctx.Err())
74+
})
75+
s.Finish()
76+
assert.NotNil(t, ctx)
77+
assert.ErrorIs(t, context.Canceled, ctx.Err())
78+
}

0 commit comments

Comments
 (0)