-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathringchan_test.go
More file actions
108 lines (90 loc) · 1.81 KB
/
ringchan_test.go
File metadata and controls
108 lines (90 loc) · 1.81 KB
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
package ringchan
import (
"testing"
"time"
)
func TestRingChanBasic(t *testing.T) {
input := make(chan int, 5)
rc := New(input, 3)
go func() {
for i := 1; i <= 5; i++ {
input <- i
}
close(input)
}()
time.Sleep(50 * time.Millisecond)
l := len(rc.C)
if l != 3 {
t.Fatalf("expected Len()=%v, got %v", 3, l)
}
var got []int
for v := range rc.C {
got = append(got, v)
}
// Only last 3 values should be kept due to overwrite
want := []int{3, 4, 5}
if len(got) != len(want) {
t.Fatalf("expected %v values, got %v", len(want), len(got))
}
if rc.Dropped != 2 {
t.Fatalf("expected %d values to be dropped, got %d", 2, rc.Dropped)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("expected %v at index %d, got %v", want[i], i, got[i])
}
}
}
func TestRingChanBlockingReceive(t *testing.T) {
input := make(chan int, 1)
rc := New(input, 1)
go func() {
time.Sleep(100 * time.Millisecond)
input <- 42
close(input)
}()
val := <-rc.C
if val != 42 {
t.Errorf("expected 42, got %v", val)
}
}
func TestRingChanRangeAfterClose(t *testing.T) {
input := make(chan string, 2)
rc := New(input, 2)
input <- "foo"
input <- "bar"
close(input)
var results []string
for v := range rc.C {
results = append(results, v)
}
if len(results) != 2 || results[0] != "foo" || results[1] != "bar" {
t.Errorf("unexpected results: %v", results)
}
}
func BenchmarkSingleSender(b *testing.B) {
input := make(chan int)
ring := New(input, 1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
input <- i
}
close(input)
for range ring.C {
}
b.StopTimer()
}
func BenchmarkParallelSenders(b *testing.B) {
input := make(chan int)
ring := New(input, 1)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
input <- 1
}
})
close(input)
for range ring.C {
}
b.StopTimer()
}