github.com/lfch/etcd-io/tests/v3@v3.0.0-20221004140520-eac99acd3e9d/common/watch_test.go (about) 1 package common 2 3 import ( 4 "context" 5 "testing" 6 "time" 7 8 clientv3 "github.com/lfch/etcd-io/client/v3" 9 "github.com/lfch/etcd-io/tests/v3/framework" 10 "github.com/lfch/etcd-io/tests/v3/framework/config" 11 "github.com/lfch/etcd-io/tests/v3/framework/testutils" 12 "github.com/stretchr/testify/assert" 13 ) 14 15 func TestWatch(t *testing.T) { 16 testRunner.BeforeTest(t) 17 watchTimeout := 1 * time.Second 18 for _, tc := range clusterTestCases { 19 t.Run(tc.name, func(t *testing.T) { 20 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) 21 defer cancel() 22 clus := testRunner.NewCluster(ctx, t, tc.config) 23 24 defer clus.Close() 25 cc := framework.MustClient(clus.Client(clientv3.AuthConfig{})) 26 testutils.ExecuteUntil(ctx, t, func() { 27 tests := []struct { 28 puts []testutils.KV 29 watchKey string 30 opts config.WatchOptions 31 wanted []testutils.KV 32 }{ 33 { // watch by revision 34 puts: []testutils.KV{{Key: "bar", Val: "revision_1"}, {Key: "bar", Val: "revision_2"}, {Key: "bar", Val: "revision_3"}}, 35 watchKey: "bar", 36 opts: config.WatchOptions{Revision: 3}, 37 wanted: []testutils.KV{{Key: "bar", Val: "revision_2"}, {Key: "bar", Val: "revision_3"}}, 38 }, 39 { // watch 1 key 40 puts: []testutils.KV{{Key: "sample", Val: "value"}}, 41 watchKey: "sample", 42 opts: config.WatchOptions{Revision: 1}, 43 wanted: []testutils.KV{{Key: "sample", Val: "value"}}, 44 }, 45 { // watch 3 keys by prefix 46 puts: []testutils.KV{{Key: "foo1", Val: "val1"}, {Key: "foo2", Val: "val2"}, {Key: "foo3", Val: "val3"}}, 47 watchKey: "foo", 48 opts: config.WatchOptions{Revision: 1, Prefix: true}, 49 wanted: []testutils.KV{{Key: "foo1", Val: "val1"}, {Key: "foo2", Val: "val2"}, {Key: "foo3", Val: "val3"}}, 50 }, 51 { // watch 3 keys by range 52 puts: []testutils.KV{{Key: "key1", Val: "val1"}, {Key: "key3", Val: "val3"}, {Key: "key2", Val: "val2"}}, 53 watchKey: "key", 54 opts: config.WatchOptions{Revision: 1, RangeEnd: "key3"}, 55 wanted: []testutils.KV{{Key: "key1", Val: "val1"}, {Key: "key2", Val: "val2"}}, 56 }, 57 } 58 59 for _, tt := range tests { 60 wCtx, wCancel := context.WithCancel(ctx) 61 wch := cc.Watch(wCtx, tt.watchKey, tt.opts) 62 if wch == nil { 63 t.Fatalf("failed to watch %s", tt.watchKey) 64 } 65 66 for j := range tt.puts { 67 if err := cc.Put(ctx, tt.puts[j].Key, tt.puts[j].Val, config.PutOptions{}); err != nil { 68 t.Fatalf("can't not put key %q, err: %s", tt.puts[j].Key, err) 69 } 70 } 71 72 kvs, err := testutils.KeyValuesFromWatchChan(wch, len(tt.wanted), watchTimeout) 73 if err != nil { 74 wCancel() 75 t.Fatalf("failed to get key-values from watch channel %s", err) 76 } 77 78 wCancel() 79 assert.Equal(t, tt.wanted, kvs) 80 } 81 }) 82 }) 83 } 84 }