forked from posener/context
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_test.go
110 lines (87 loc) · 1.99 KB
/
context_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
package context
import (
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type testContext int
func (testContext) Deadline() (deadline time.Time, ok bool) { return }
func (testContext) Done() <-chan struct{} { return make(<-chan struct{}) }
func (testContext) Err() error { return nil }
func (testContext) Value(key interface{}) interface{} { return nil }
func TestSet(t *testing.T) {
t.Parallel()
ctx1 := Init()
ctx2 := testContext(2)
ctx3 := testContext(3)
unset := Set(ctx2)
var wg sync.WaitGroup
wg.Add(4)
Go(func() {
assert.Equal(t, Get(), ctx2)
wg.Done()
})
GoCtx(ctx2, func() {
assert.Equal(t, Get(), ctx2)
wg.Done()
})
GoCtx(ctx3, func() {
assert.Equal(t, Get(), ctx3)
wg.Done()
})
unset()
Go(func() {
assert.Equal(t, Get(), ctx1)
wg.Done()
})
wg.Wait()
}
func TestSetNested(t *testing.T) {
t.Parallel()
ctx1 := Init()
ctx2 := testContext(2)
ctx3 := testContext(3)
assert.Equal(t, Get(), ctx1)
unset2 := Set(ctx2)
assert.Equal(t, Get(), ctx2)
unset3 := Set(ctx3)
assert.Equal(t, Get(), ctx3)
unset3()
assert.Equal(t, Get(), ctx2)
unset2()
assert.Equal(t, Get(), ctx1)
}
func TestFunctionScope(t *testing.T) {
t.Parallel()
ctx1 := Init()
ctx2 := testContext(2)
func() {
assert.Equal(t, Get(), ctx1)
defer Set(ctx2)()
assert.Equal(t, Get(), ctx2)
}()
assert.Equal(t, Get(), ctx1)
}
func TestPanic(t *testing.T) {
t.Parallel()
Init()
t.Run("Using context.Get inside non-context goroutine", func(t *testing.T) {
assert.Panics(t, func() { Get() })
})
t.Run("Using context.Go inside non-context goroutine", func(t *testing.T) {
assert.Panics(t, func() { Go(func() {}) })
})
t.Run("Invoking unset twice", func(t *testing.T) {
unset := Set(testContext(1))
unset()
assert.Panics(t, unset)
})
t.Run("Invoking unset unordered", func(t *testing.T) {
unset1 := Set(testContext(1))
unset2 := Set(testContext(2))
assert.Panics(t, unset1)
unset2()
unset1()
})
}