github.com/emate/nomad@v0.8.2-wo-binpacking/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(500*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 4 60 } 61 62 return 1 63 } 64 65 // Timeout takes the desired timeout and increases it if running in Travis 66 func Timeout(original time.Duration) time.Duration { 67 return original * time.Duration(TestMultiplier()) 68 } 69 70 func IsTravis() bool { 71 _, ok := os.LookupEnv(TravisRunEnv) 72 return ok 73 } 74 75 type rpcFn func(string, interface{}, interface{}) error 76 77 func WaitForLeader(t testing.T, rpc rpcFn) { 78 WaitForResult(func() (bool, error) { 79 args := &structs.GenericRequest{} 80 var leader string 81 err := rpc("Status.Leader", args, &leader) 82 return leader != "", err 83 }, func(err error) { 84 t.Fatalf("failed to find leader: %v", err) 85 }) 86 }