-
Notifications
You must be signed in to change notification settings - Fork 13
/
cancel_test.go
80 lines (69 loc) · 1.71 KB
/
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
package pipeline
import (
"context"
"fmt"
"math"
"strconv"
"strings"
"testing"
"time"
)
func TestCancel(t *testing.T) {
t.Parallel()
const testDuration = time.Second
// Collect logs
var logs []string
logf := func(v string, is ...interface{}) {
logs = append(logs, fmt.Sprintf(v, is...))
}
// Send a stream of ints through the in chan
in := make(chan int)
go func() {
defer close(in)
i := 0
endAt := time.Now().Add(testDuration)
for now := time.Now(); now.Before(endAt); now = time.Now() {
in <- i
i++
time.Sleep(testDuration / 100)
}
logf("ended")
}()
// Create a logger for the cancel func
canceled := func(i int, err error) {
logf("canceled: %d because %s\n", i, err)
}
// Start canceling the pipeline about half way through the test
ctx, cancel := context.WithTimeout(context.Background(), testDuration/2)
defer cancel()
for i := range Cancel(ctx, canceled, in) {
logf("%d", i)
}
// There should be some logs
lenLogs := len(logs)
if lenLogs < 2 {
t.Errorf("len(logs) = %d, wanted > 2", lenLogs)
t.Log(logs)
return
}
// The first half of the logs (+-20%) should be a string representation of the numbers in order
var iCanceled int
for i, log := range logs {
if strconv.Itoa(i) != log {
iCanceled = i
if isAboutHalfWay := math.Abs(float64((lenLogs/2)-i)) <= .2*float64(lenLogs); isAboutHalfWay {
break
}
t.Errorf("got %d, wanted %s", i, log)
for _, l := range logs {
t.Error(l)
}
}
}
// The remaining logs should be prefixed with "canceled:"
for i, log := range logs[iCanceled : lenLogs-1] {
if !strings.Contains(log, "canceled:") {
t.Errorf("got '%s', wanted 'canceled: %d because context deadline exceeded'", log, i+lenLogs/2)
}
}
}