From bad870dc6874d1b143c189ea2960630d8a24844a Mon Sep 17 00:00:00 2001 From: Frank Schroeder Date: Tue, 24 Oct 2017 15:02:25 +0200 Subject: [PATCH] watch: convert TestKeyWatch to use channels --- watch/funcs_test.go | 53 ++++++++++++++++++++++----------------------- 1 file changed, 26 insertions(+), 27 deletions(-) diff --git a/watch/funcs_test.go b/watch/funcs_test.go index 2e9e992e98..5e61ac3af4 100644 --- a/watch/funcs_test.go +++ b/watch/funcs_test.go @@ -18,54 +18,53 @@ func TestKeyWatch(t *testing.T) { a := agent.NewTestAgent(t.Name(), ``) defer a.Shutdown() + invoke := make(chan error) plan := mustParse(t, `{"type":"key", "key":"foo/bar/baz"}`) - invoke := 0 plan.Handler = func(idx uint64, raw interface{}) { - if invoke == 0 { - if raw == nil { - return - } - v, ok := raw.(*consulapi.KVPair) - if !ok || v == nil || string(v.Value) != "test" { - t.Fatalf("Bad: %#v", raw) - } - invoke++ + if raw == nil { + return // ignore + } + v, ok := raw.(*consulapi.KVPair) + if !ok || v == nil { + return // ignore + } + if string(v.Value) != "test" { + invoke <- errBadContent + return } + invoke <- nil } + var wg sync.WaitGroup + wg.Add(1) go func() { - defer plan.Stop() - time.Sleep(20 * time.Millisecond) - + defer wg.Done() kv := a.Client().KV() + + time.Sleep(20 * time.Millisecond) pair := &consulapi.KVPair{ Key: "foo/bar/baz", Value: []byte("test"), } - _, err := kv.Put(pair, nil) - if err != nil { + if _, err := kv.Put(pair, nil); err != nil { t.Fatalf("err: %v", err) } + }() - // Wait for the query to run - time.Sleep(20 * time.Millisecond) - plan.Stop() - - // Delete the key - _, err = kv.Delete("foo/bar/baz", nil) - if err != nil { + wg.Add(1) + go func() { + defer wg.Done() + if err := plan.Run(a.HTTPAddr()); err != nil { t.Fatalf("err: %v", err) } }() - err := plan.Run(a.HTTPAddr()) - if err != nil { + if err := <-invoke; err != nil { t.Fatalf("err: %v", err) } - if invoke == 0 { - t.Fatalf("bad: %v", invoke) - } + plan.Stop() + wg.Wait() } func TestKeyWatch_With_PrefixDelete(t *testing.T) {