-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathxcontext_test.go
133 lines (94 loc) · 2.41 KB
/
xcontext_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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package xcontext_test
import (
"context"
"testing"
"oss.terrastruct.com/util-go/assert"
"oss.terrastruct.com/util-go/xcontext"
)
func TestWithoutCancel(t *testing.T) {
t.Parallel()
s := "meow"
ctx := context.Background()
ctx = stringWith(ctx, s)
assert.Success(t, ctx.Err())
t.Run("no_cancel", func(t *testing.T) {
t.Parallel()
ctx := xcontext.WithoutCancel(ctx)
assert.Success(t, ctx.Err())
s2 := stringFrom(ctx)
assert.String(t, s, s2)
})
t.Run("cancel_before", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(ctx)
cancel()
assert.Error(t, ctx.Err())
ctx = xcontext.WithoutCancel(ctx)
assert.Success(t, ctx.Err())
s2 := stringFrom(ctx)
assert.String(t, s, s2)
})
t.Run("cancel_after", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(ctx)
ctx = xcontext.WithoutCancel(ctx)
cancel()
assert.Success(t, ctx.Err())
s2 := stringFrom(ctx)
assert.String(t, s, s2)
})
}
func TestWithoutValues(t *testing.T) {
t.Parallel()
ctx := context.Background()
const k = "Death is nature's way of saying `Howdy'."
const exp = "Proposed Additions to the PDP-11 Instruction Set"
const exp2 = "character density, n.:"
t.Run("no_value", func(t *testing.T) {
t.Parallel()
v := ctx.Value(k)
assert.JSON(t, nil, v)
ctx := xcontext.WithoutValues(ctx)
v = ctx.Value(k)
assert.JSON(t, nil, v)
})
t.Run("with_value", func(t *testing.T) {
t.Parallel()
ctxv := context.WithValue(ctx, k, exp)
ctx := xcontext.WithoutValues(ctxv)
// ctxv contains k but ctx doesn't.
v := ctxv.Value(k)
assert.JSON(t, exp, v)
v = ctx.Value(k)
assert.JSON(t, nil, v)
ctx = context.WithValue(ctx, k, exp2)
v = ctx.Value(k)
assert.JSON(t, exp2, v)
})
t.Run("cancel", func(t *testing.T) {
t.Parallel()
t.Run("before", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(ctx)
cancel()
ctx = xcontext.WithoutValues(ctx)
assert.Error(t, ctx.Err())
})
t.Run("after", func(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
ctx = xcontext.WithoutValues(ctx)
assert.Success(t, ctx.Err())
cancel()
assert.Error(t, ctx.Err())
})
})
}
type stringKey struct{}
func stringFrom(ctx context.Context) string {
return ctx.Value(stringKey{}).(string)
}
func stringWith(ctx context.Context, s string) context.Context {
return context.WithValue(ctx, stringKey{}, s)
}