github.com/gophercloud/gophercloud@v1.11.0/internal/acceptance/tools/tools.go (about) 1 package tools 2 3 import ( 4 "crypto/rand" 5 "encoding/json" 6 "errors" 7 mrand "math/rand" 8 "testing" 9 "time" 10 ) 11 12 // ErrTimeout is returned if WaitFor/WaitForTimeout take longer than their timeout duration. 13 var ErrTimeout = errors.New("Timed out") 14 15 // WaitFor uses WaitForTimeout to poll a predicate function once per second to 16 // wait for a certain state to arrive, with a default timeout of 300 seconds. 17 func WaitFor(predicate func() (bool, error)) error { 18 return WaitForTimeout(predicate, 600*time.Second) 19 } 20 21 // WaitForTimeout polls a predicate function once per second to wait for a 22 // certain state to arrive, or until the given timeout is reached. 23 func WaitForTimeout(predicate func() (bool, error), timeout time.Duration) error { 24 startTime := time.Now() 25 for time.Since(startTime) < timeout { 26 time.Sleep(2 * time.Second) 27 28 satisfied, err := predicate() 29 if err != nil { 30 return err 31 } 32 if satisfied { 33 return nil 34 } 35 } 36 return ErrTimeout 37 } 38 39 // MakeNewPassword generates a new string that's guaranteed to be different than the given one. 40 func MakeNewPassword(oldPass string) string { 41 randomPassword := RandomString("", 16) 42 for randomPassword == oldPass { 43 randomPassword = RandomString("", 16) 44 } 45 return randomPassword 46 } 47 48 // RandomString generates a string of given length, but random content. 49 // All content will be within the ASCII graphic character set. 50 // (Implementation from Even Shaw's contribution on 51 // http://stackoverflow.com/questions/12771930/what-is-the-fastest-way-to-generate-a-long-random-string-in-go). 52 func RandomString(prefix string, n int) string { 53 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 54 var bytes = make([]byte, n) 55 rand.Read(bytes) 56 for i, b := range bytes { 57 bytes[i] = alphanum[b%byte(len(alphanum))] 58 } 59 return prefix + string(bytes) 60 } 61 62 // RandomInt will return a random integer between a specified range. 63 func RandomInt(min, max int) int { 64 mrand.Seed(time.Now().Unix()) 65 return mrand.Intn(max-min) + min 66 } 67 68 // Elide returns the first bit of its input string with a suffix of "..." if it's longer than 69 // a comfortable 40 characters. 70 func Elide(value string) string { 71 if len(value) > 40 { 72 return value[0:37] + "..." 73 } 74 return value 75 } 76 77 // PrintResource returns a resource as a readable structure 78 func PrintResource(t *testing.T, resource interface{}) { 79 b, _ := json.MarshalIndent(resource, "", " ") 80 t.Logf(string(b)) 81 }