diff --git a/consul/catalog_endpoint_test.go b/consul/catalog_endpoint_test.go index 3a174ce45..a553538b8 100644 --- a/consul/catalog_endpoint_test.go +++ b/consul/catalog_endpoint_test.go @@ -2,6 +2,7 @@ package consul import ( "fmt" + "github.com/hashicorp/consul/testutil" "github.com/hashicorp/consul/consul/structs" "net/rpc" "os" @@ -35,12 +36,12 @@ func TestCatalogRegister(t *testing.T) { t.Fatalf("err: %v", err) } - // Wait for leader - time.Sleep(100 * time.Millisecond) - - if err := client.Call("Catalog.Register", &arg, &out); err != nil { + testutil.WaitForResult(func() (bool, error) { + err := client.Call("Catalog.Register", &arg, &out) + return err == nil, err + }, func(err error) { t.Fatalf("err: %v", err) - } + }) } func TestCatalogRegister_ForwardLeader(t *testing.T) { diff --git a/testutil/wait.go b/testutil/wait.go new file mode 100644 index 000000000..6071c94ce --- /dev/null +++ b/testutil/wait.go @@ -0,0 +1,26 @@ +package testutil + +import ( + "time" +) + +type testFn func() (bool, error) +type errorFn func(error) + +func WaitForResult(test testFn, error errorFn) { + retries := 500 // 5 seconds timeout + + for retries > 0 { + time.Sleep(10 * time.Millisecond) + retries-- + + success, err := test() + if success { + return + } + + if retries == 0 { + error(err) + } + } +}