github.com/rsyabuta/packer@v1.1.4-0.20180119234903-5ef0c2280f0b/common/retry_test.go (about) 1 package common 2 3 import ( 4 "fmt" 5 "testing" 6 ) 7 8 func TestRetry(t *testing.T) { 9 numTries := uint(0) 10 // Test that a passing function only gets called once. 11 err := Retry(0, 0, 0, func(i uint) (bool, error) { 12 numTries++ 13 return true, nil 14 }) 15 if numTries != 1 { 16 t.Fatal("Passing function should not have been retried.") 17 } 18 if err != nil { 19 t.Fatalf("Passing function should not have returned a retry error. Error: %s", err) 20 } 21 22 // Test that a failing function gets retried (once in this example). 23 numTries = 0 24 results := []bool{false, true} 25 err = Retry(0, 0, 0, func(i uint) (bool, error) { 26 result := results[numTries] 27 numTries++ 28 return result, nil 29 }) 30 if numTries != 2 { 31 t.Fatalf("Retried function should have been tried twice. Tried %d times.", numTries) 32 } 33 if err != nil { 34 t.Fatalf("Successful retried function should not have returned a retry error. Error: %s", err) 35 } 36 37 // Test that a function error gets returned, and the function does not get called again. 38 numTries = 0 39 funcErr := fmt.Errorf("This function had an error!") 40 err = Retry(0, 0, 0, func(i uint) (bool, error) { 41 numTries++ 42 return false, funcErr 43 }) 44 if numTries != 1 { 45 t.Fatal("Errant function should not have been retried.") 46 } 47 if err != funcErr { 48 t.Fatalf("Errant function did not return the right error %s. Error: %s", funcErr, err) 49 } 50 51 // Test when a function exhausts its retries. 52 numTries = 0 53 expectedTries := uint(3) 54 err = Retry(0, 0, expectedTries, func(i uint) (bool, error) { 55 numTries++ 56 return false, nil 57 }) 58 if numTries != expectedTries { 59 t.Fatalf("Unsuccessful retry function should have been called %d times. Only called %d times.", expectedTries, numTries) 60 } 61 if err != RetryExhaustedError { 62 t.Fatalf("Unsuccessful retry function should have returned a retry exhausted error. Actual error: %s", err) 63 } 64 }