This repository has been archived by the owner on Jul 29, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher_test.go
105 lines (91 loc) · 2.33 KB
/
watcher_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
package netstate
import (
"context"
"fmt"
"sync"
"testing"
"github.com/google/go-cmp/cmp"
)
func TestWatcherWatch(t *testing.T) {
// Test invariants for subscribed interfaces and their bitmasks.
const (
ifi0 = "test0"
changes0 = LinkAny
ifi1 = "test1"
changes1 = LinkUp | LinkDown
)
tests := []struct {
name string
in changeSet
check func(t *testing.T, oneC, twoC <-chan Change)
}{
{
name: "no changes",
check: func(t *testing.T, oneC <-chan Change, twoC <-chan Change) {
_, ok1 := <-oneC
_, ok2 := <-twoC
if ok1 || ok2 {
t.Fatalf("expected both channels to be closed: (%v, %v)", ok1, ok2)
}
},
},
{
name: "change one interface",
in: changeSet{
ifi0: []Change{LinkUp},
// Not subscribed to these changes.
ifi1: []Change{LinkLowerLayerDown, LinkNotPresent},
// Not subscribed on this interface.
"test999": []Change{LinkUp},
},
check: func(t *testing.T, oneC <-chan Change, twoC <-chan Change) {
if diff := cmp.Diff(LinkUp, <-oneC); diff != "" {
t.Fatalf("unexpected up on first link (-want +got):\n%s", diff)
}
if _, ok := <-twoC; ok {
t.Fatal("expected second channel to be closed")
}
},
},
{
name: "change both interfaces",
in: changeSet{
ifi0: []Change{LinkLowerLayerDown},
ifi1: []Change{LinkUp},
},
check: func(t *testing.T, oneC <-chan Change, twoC <-chan Change) {
if diff := cmp.Diff(LinkLowerLayerDown, <-oneC); diff != "" {
t.Fatalf("unexpected lower layer down on first link (-want +got):\n%s", diff)
}
if diff := cmp.Diff(LinkUp, <-twoC); diff != "" {
t.Fatalf("unexpected up on second link (-want +got):\n%s", diff)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
w := NewWatcher()
w.watch = func(_ context.Context, notify func(changeSet)) error {
// One shot notify with any changes we specify.
notify(tt.in)
return nil
}
oneC := w.Subscribe(ifi0, changes0)
twoC := w.Subscribe(ifi1, changes1)
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
if err := w.Watch(context.Background()); err != nil {
panicf("failed to watch: %v", err)
}
}()
wg.Wait()
tt.check(t, oneC, twoC)
})
}
}
func panicf(format string, a ...interface{}) {
panic(fmt.Sprintf(format, a...))
}