github.com/jrxfive/nomad@v0.6.1-0.20170802162750-1fef470e89bf/testutil/wait.go (about) 1 package testutil 2 3 import ( 4 "os" 5 "time" 6 7 "github.com/hashicorp/nomad/nomad/structs" 8 "github.com/mitchellh/go-testing-interface" 9 ) 10 11 const ( 12 // TravisRunEnv is an environment variable that is set if being run by 13 // Travis. 14 TravisRunEnv = "CI" 15 ) 16 17 type testFn func() (bool, error) 18 type errorFn func(error) 19 20 func WaitForResult(test testFn, error errorFn) { 21 WaitForResultRetries(2000*TestMultiplier(), test, error) 22 } 23 24 func WaitForResultRetries(retries int64, test testFn, error errorFn) { 25 for retries > 0 { 26 time.Sleep(10 * time.Millisecond) 27 retries-- 28 29 success, err := test() 30 if success { 31 return 32 } 33 34 if retries == 0 { 35 error(err) 36 } 37 } 38 } 39 40 // AssertUntil asserts the test function passes throughout the given duration. 41 // Otherwise error is called on failure. 42 func AssertUntil(until time.Duration, test testFn, error errorFn) { 43 deadline := time.Now().Add(until) 44 for time.Now().Before(deadline) { 45 success, err := test() 46 if !success { 47 error(err) 48 return 49 } 50 // Sleep some arbitrary fraction of the deadline 51 time.Sleep(until / 30) 52 } 53 } 54 55 // TestMultiplier returns a multiplier for retries and waits given environment 56 // the tests are being run under. 57 func TestMultiplier() int64 { 58 if IsTravis() { 59 return 3 60 } 61 62 return 1 63 } 64 65 func IsTravis() bool { 66 _, ok := os.LookupEnv(TravisRunEnv) 67 return ok 68 } 69 70 type rpcFn func(string, interface{}, interface{}) error 71 72 func WaitForLeader(t testing.T, rpc rpcFn) { 73 WaitForResult(func() (bool, error) { 74 args := &structs.GenericRequest{} 75 var leader string 76 err := rpc("Status.Leader", args, &leader) 77 return leader != "", err 78 }, func(err error) { 79 t.Fatalf("failed to find leader: %v", err) 80 }) 81 }