forked from yaojingguo/geekbang-zk-course
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watch_test.go
68 lines (56 loc) · 1.31 KB
/
watch_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
package etcd_code
import (
"context"
"fmt"
v3 "go.etcd.io/etcd/clientv3"
"testing"
)
var end = []byte("end")
// After start the test, run:
// etcdctl put TestOneWatch 1
func TestOneWatch(t *testing.T) {
cli := newClient(t)
defer cli.Close()
rch := cli.Watch(context.Background(), "TestOneWatch")
for wresp := range rch {
printEvents(&wresp)
}
}
// After start the test, run:
// etcdctl put TestTwoWatches1 1
// etcdctl put TestTwoWatches2 2
func TestTwoWatches(t *testing.T) {
cli := newClient(t)
keys := []string{"TestTwoWatches1", "TestTwoWatches2"}
rch1 := cli.Watch(context.Background(), keys[0])
rch2 := cli.Watch(context.Background(), keys[1])
for {
select {
case wresp1 := <-rch1:
printEvents(&wresp1)
case wresp2 := <-rch2:
printEvents(&wresp2)
}
}
}
func TestWatchFromPast(t *testing.T) {
cli := newClient(t)
defer cli.Close()
key := "TestWatchFromPast"
ctx := context.Background()
presp, err := cli.Put(ctx, key, "1")
if err != nil {
t.Fatal(err)
}
rev := presp.Header.Revision
rch := cli.Watch(ctx, key, v3.WithRev(rev))
for wresp := range rch {
printEvents(&wresp)
}
// Output: PUT event TestWatchFromPast: 1
}
func printEvents(resp *v3.WatchResponse) {
for _, ev := range resp.Events {
fmt.Printf("%s event key-value %s: %s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
}
}