-
Notifications
You must be signed in to change notification settings - Fork 4
/
values_test.go
81 lines (63 loc) · 2.04 KB
/
values_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
package ctxutil
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type key string
func TestWithValuesCancel(t *testing.T) {
t.Parallel()
// Create main context with key value and cancel
ctxOrig, cancel := context.WithCancel(context.Background())
ctxOrig = context.WithValue(ctxOrig, key("key1"), "value1")
ctxOrig = context.WithValue(ctxOrig, key("key2"), "value2")
// Create a copy of the context
ctxCopy := WithValues(context.Background(), ctxOrig)
ctxCopy = context.WithValue(ctxCopy, key("key2"), "value2-2")
ctxCopy = context.WithValue(ctxCopy, key("key3"), "value3")
// Test copy of key and values of the copied context and the original context
assert.Equal(t, "value1", ctxCopy.Value(key("key1")).(string))
assert.Equal(t, "value2-2", ctxCopy.Value(key("key2")).(string))
assert.Equal(t, "value3", ctxCopy.Value(key("key3")).(string))
assert.Equal(t, "value1", ctxOrig.Value(key("key1")).(string))
assert.Equal(t, "value2", ctxOrig.Value(key("key2")).(string))
assert.Nil(t, ctxOrig.Value(key("key3")))
// Cancel the original context
cancel()
assertCancelled(t, ctxOrig)
assertValid(t, ctxCopy)
}
func TestWithValuesDeadline(t *testing.T) {
t.Parallel()
// Create main context with timeout
ctxOrig, cancel := context.WithTimeout(context.Background(), shortDuration)
defer cancel()
// Create a copy of the context
ctxCopy := WithValues(context.Background(), ctxOrig)
// Wait for deadline
time.Sleep(2 * shortDuration)
assertDeadlined(t, ctxOrig)
assertValid(t, ctxCopy)
}
func assertValid(t *testing.T, ctx context.Context) {
t.Helper()
_, deadline := ctx.Deadline()
assert.False(t, deadline)
assertNotDone(t, ctx)
assert.Nil(t, ctx.Err())
}
func assertCancelled(t *testing.T, ctx context.Context) {
t.Helper()
_, deadline := ctx.Deadline()
assert.False(t, deadline)
assertDone(t, ctx)
assert.NotNil(t, ctx.Err())
}
func assertDeadlined(t *testing.T, ctx context.Context) {
t.Helper()
_, deadline := ctx.Deadline()
assert.True(t, deadline)
assertDone(t, ctx)
assert.NotNil(t, ctx.Err())
}