-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwith_deadline_test.go
128 lines (92 loc) · 2.38 KB
/
with_deadline_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
package byo_context
import (
"testing"
"time"
"github.com/stretchr/testify/require"
)
func after(dur time.Duration) time.Time {
return time.Now().Add(dur)
}
func Test_WithDeadline(t *testing.T) {
root := Background()
deadline := after(100 * time.Millisecond)
ctx, cancel := WithDeadline(root, deadline)
time.Sleep(50 * time.Millisecond)
select {
case <-ctx.Done():
t.Error("context should not be done")
default:
}
expectDeadline(t, ctx, deadline)
time.Sleep(50 * time.Millisecond)
select {
case <-ctx.Done():
default:
t.Error("context should be done")
}
expectDeadline(t, ctx, deadline)
// no effect of cancel after deadline
cancel()
select {
case <-ctx.Done():
default:
t.Error("context should be done")
}
expectDeadline(t, ctx, deadline)
require.ErrorIs(t, ctx.Err(), DeadlineExceeded)
}
func expectDeadline(t *testing.T, ctx Context, deadline time.Time) {
t.Helper()
d, ok := ctx.Deadline()
require.True(t, ok)
require.Equal(t, deadline, d)
}
func Test_Deadline_override_deadline(t *testing.T) {
root := Background()
deadline1 := after(100 * time.Millisecond)
ctx1, _ := WithDeadline(root, deadline1)
// new deadline is before the parent deadline
deadline2 := after(50 * time.Millisecond)
ctx2, _ := WithDeadline(ctx1, deadline2)
expectDeadline(t, ctx2, deadline2)
expectDeadline(t, ctx1, deadline1)
dealine3 := after(150 * time.Millisecond)
ctx3, _ := WithDeadline(ctx1, dealine3) // dedline is after the parent deadline
expectDeadline(t, ctx3, deadline1) // deadline is the parent deadline, as it is before the new deadline
}
func Test_Deadline_early_cancel(t *testing.T) {
root := Background()
deadline := after(100 * time.Millisecond)
ctx, cancel := WithDeadline(root, deadline)
cancel()
select {
case <-ctx.Done():
default:
t.Error("context should be done")
}
require.ErrorIs(t, ctx.Err(), Canceled)
}
func Test_WithTimeout(t *testing.T) {
root := Background()
ctx, cancel := WithTimeout(root, 100*time.Millisecond)
time.Sleep(50 * time.Millisecond)
select {
case <-ctx.Done():
t.Error("context should not be done")
default:
}
time.Sleep(51 * time.Millisecond)
select {
case <-ctx.Done():
default:
t.Error("context should be done")
}
// no effect of cancel after deadline
cancel()
select {
case <-ctx.Done():
default:
t.Error("context should be done")
}
require.ErrorIs(t, ctx.Err(), DeadlineExceeded)
}