-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwith_cancel_test.go
86 lines (60 loc) · 1.6 KB
/
with_cancel_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package byo_context
import (
"testing"
"github.com/stretchr/testify/require"
)
func Test_WithCancel(t *testing.T) {
ctx, cancel := WithCancel(Background())
require.Nil(t, ctx.Err())
_, ok := ctx.Deadline()
require.False(t, ok)
require.NotNil(t, ctx.Done())
require.Nil(t, ctx.Value(nil))
cancel()
require.ErrorIs(t, ctx.Err(), Canceled)
// test that cancel() is idempotent
cancel()
require.ErrorIs(t, ctx.Err(), Canceled)
select {
case <-ctx.Done():
t.Log("ctx.Done() is closed after cancel()")
default:
t.Error("ctx.Done() should be closed after cancel()")
}
}
func Test_WithCancel_propogation(t *testing.T) {
parent, cancel := WithCancel(Background())
child, _ := WithCancel(parent)
require.Nil(t, child.Err())
cancel()
require.ErrorIs(t, child.Err(), Canceled)
}
func Test_WithCancel_propogation2(t *testing.T) {
/*
Creates a context tree like this:
Background-root
|
|---cancelCtx1---cancelCtx3---cancelCtx5
| |
| |---cancelCtx4
|
|
|---cancelCtx2---cancelCtx6
*/
root := Background()
cancelCtx1, cancel1 := WithCancel(root)
cancelCtx2, _ := WithCancel(root)
cancelCtx3, _ := WithCancel(cancelCtx1)
cancelCtx4, _ := WithCancel(cancelCtx1)
cancelCtx5, _ := WithCancel(cancelCtx3)
cancelCtx6, cancel6 := WithCancel(cancelCtx2)
cancel1()
require.ErrorIs(t, cancelCtx1.Err(), Canceled)
require.ErrorIs(t, cancelCtx3.Err(), Canceled)
require.ErrorIs(t, cancelCtx5.Err(), Canceled)
require.ErrorIs(t, cancelCtx4.Err(), Canceled)
require.Nil(t, cancelCtx2.Err())
cancel6()
require.ErrorIs(t, cancelCtx6.Err(), Canceled)
require.Nil(t, cancelCtx2.Err())
}