github.com/vnpaycloud-console/gophercloud/v2@v2.0.5/internal/acceptance/tools/tools.go (about) 1 package tools 2 3 import ( 4 "context" 5 "encoding/json" 6 "math/rand" 7 "strings" 8 "testing" 9 "time" 10 11 "github.com/vnpaycloud-console/gophercloud/v2" 12 ) 13 14 // WaitFor uses WaitForTimeout to poll a predicate function once per second to 15 // wait for a certain state to arrive, with a default timeout of 600 seconds. 16 func WaitFor(predicate func(context.Context) (bool, error)) error { 17 return WaitForTimeout(predicate, 600*time.Second) 18 } 19 20 // WaitForTimeout polls a predicate function once per second to wait for a 21 // certain state to arrive, or until the given timeout is reached. 22 func WaitForTimeout(predicate func(context.Context) (bool, error), timeout time.Duration) error { 23 ctx, cancel := context.WithTimeout(context.TODO(), timeout) 24 defer cancel() 25 26 return gophercloud.WaitFor(ctx, predicate) 27 } 28 29 // MakeNewPassword generates a new string that's guaranteed to be different than the given one. 30 func MakeNewPassword(oldPass string) string { 31 randomPassword := RandomString("", 16) 32 for randomPassword == oldPass { 33 randomPassword = RandomString("", 16) 34 } 35 return randomPassword 36 } 37 38 // RandomString generates a string of given length, but random content. 39 // All content will be within the ASCII graphic character set. 40 func RandomString(prefix string, n int) string { 41 charset := []rune("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz") 42 return prefix + randomString(charset, n) 43 } 44 45 // RandomFunnyString returns a random string of the given length filled with 46 // funny Unicode code points. 47 func RandomFunnyString(length int) string { 48 charset := []rune("012abc \n\t🤖👾👩🏾🚀+.,;:*`~|\"'/\\]êà²×c師☷") 49 return randomString(charset, length) 50 } 51 52 // RandomFunnyStringNoSlash returns a random string of the given length filled with 53 // funny Unicode code points, but no forward slash. 54 func RandomFunnyStringNoSlash(length int) string { 55 charset := []rune("012abc \n\t🤖👾👩🏾🚀+.,;:*`~|\"'\\]êà²×c師☷") 56 return randomString(charset, length) 57 } 58 59 func randomString(charset []rune, length int) string { 60 var s strings.Builder 61 for i := 0; i < length; i++ { 62 s.WriteRune(charset[rand.Intn(len(charset))]) 63 } 64 return s.String() 65 } 66 67 // RandomInt will return a random integer between a specified range. 68 func RandomInt(min, max int) int { 69 return rand.Intn(max-min) + min 70 } 71 72 // Elide returns the first bit of its input string with a suffix of "..." if it's longer than 73 // a comfortable 40 characters. 74 func Elide(value string) string { 75 if len(value) > 40 { 76 return value[0:37] + "..." 77 } 78 return value 79 } 80 81 // PrintResource returns a resource as a readable structure 82 func PrintResource(t *testing.T, resource any) { 83 b, _ := json.MarshalIndent(resource, "", " ") 84 t.Log(string(b)) 85 }