-
Notifications
You must be signed in to change notification settings - Fork 1
/
sources_test.go
128 lines (103 loc) · 2.33 KB
/
sources_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
// SPDX-License-Identifier: Apache-2.0
// Copyright Authors of Cilium
package stream_test
import (
"context"
"errors"
"fmt"
"sync/atomic"
"testing"
"time"
. "github.com/cilium/stream"
)
func TestMulticast(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
numSubs := 3
expected := []int{1, 2, 3, 4, 5}
in := make(chan int)
// Create an unbuffered broadcast of 'in'
src, connect := ToMulticast(FromChannel(in))
subErrs := make(chan error, numSubs)
defer close(subErrs)
var numReady atomic.Uint32
for i := 0; i < numSubs; i++ {
go func() {
errs := make(chan error)
items := ToChannel(ctx, src, WithErrorChan(errs))
index := 0
ready := false
for {
select {
case item := <-items:
if item == 0 {
if !ready {
numReady.Add(1)
ready = true
}
} else {
if item != expected[index] {
subErrs <- fmt.Errorf("%d != %d", item, expected[index])
return
}
index++
}
case err := <-errs:
subErrs <- err
return
}
}
}()
}
connect(ctx)
// Synchronize with the subscriptions
for numReady.Load() != uint32(numSubs) {
in <- 0
}
// Feed in the actual test data.
for _, i := range expected {
in <- i
}
close(in)
// Process errors from the subscribers
for i := 0; i < numSubs; i++ {
err := <-subErrs
if err != nil {
t.Errorf("error: %s", err)
}
}
// Cancel the context and check that observing now completes immediately.
cancel()
items, err := ToSlice(context.TODO(), src)
if len(items) != 0 || err != nil {
t.Fatalf("Unexpected result after cancel(): items=%v, err=%v", items, err)
}
}
func TestMulticastCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
numSubs := 10
src, connect := ToMulticast(Range(0, 10000))
subErrs := make(chan error, numSubs)
defer close(subErrs)
for i := 0; i < numSubs; i++ {
src.Observe(
context.TODO(), // We don't care about cancelling the subs
func(item int) {
time.Sleep(time.Millisecond)
},
func(err error) {
subErrs <- err
})
}
connect(ctx)
time.Sleep(10 * time.Millisecond)
cancel()
// Process errors from the subscribers
for i := 0; i < numSubs; i++ {
err := <-subErrs
if err != nil && !errors.Is(err, context.Canceled) {
t.Fatalf("error: %s", err)
}
}
}