PageRenderTime 1138ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/vendor/github.com/gophercloud/gophercloud/acceptance/tools/tools.go

https://gitlab.com/unofficial-mirrors/openshift-origin
Go | 73 lines | 53 code | 9 blank | 11 comment | 8 complexity | 2a87ed9f3ed45869a532b0a1c5066131 MD5 | raw file
  1. package tools
  2. import (
  3. "crypto/rand"
  4. "encoding/json"
  5. "errors"
  6. mrand "math/rand"
  7. "testing"
  8. "time"
  9. )
  10. // ErrTimeout is returned if WaitFor takes longer than 300 second to happen.
  11. var ErrTimeout = errors.New("Timed out")
  12. // WaitFor polls a predicate function once per second to wait for a certain state to arrive.
  13. func WaitFor(predicate func() (bool, error)) error {
  14. for i := 0; i < 300; i++ {
  15. time.Sleep(1 * time.Second)
  16. satisfied, err := predicate()
  17. if err != nil {
  18. return err
  19. }
  20. if satisfied {
  21. return nil
  22. }
  23. }
  24. return ErrTimeout
  25. }
  26. // MakeNewPassword generates a new string that's guaranteed to be different than the given one.
  27. func MakeNewPassword(oldPass string) string {
  28. randomPassword := RandomString("", 16)
  29. for randomPassword == oldPass {
  30. randomPassword = RandomString("", 16)
  31. }
  32. return randomPassword
  33. }
  34. // RandomString generates a string of given length, but random content.
  35. // All content will be within the ASCII graphic character set.
  36. // (Implementation from Even Shaw's contribution on
  37. // http://stackoverflow.com/questions/12771930/what-is-the-fastest-way-to-generate-a-long-random-string-in-go).
  38. func RandomString(prefix string, n int) string {
  39. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  40. var bytes = make([]byte, n)
  41. rand.Read(bytes)
  42. for i, b := range bytes {
  43. bytes[i] = alphanum[b%byte(len(alphanum))]
  44. }
  45. return prefix + string(bytes)
  46. }
  47. // RandomInt will return a random integer between a specified range.
  48. func RandomInt(min, max int) int {
  49. mrand.Seed(time.Now().Unix())
  50. return mrand.Intn(max-min) + min
  51. }
  52. // Elide returns the first bit of its input string with a suffix of "..." if it's longer than
  53. // a comfortable 40 characters.
  54. func Elide(value string) string {
  55. if len(value) > 40 {
  56. return value[0:37] + "..."
  57. }
  58. return value
  59. }
  60. // PrintResource returns a resource as a readable structure
  61. func PrintResource(t *testing.T, resource interface{}) {
  62. b, _ := json.MarshalIndent(resource, "", " ")
  63. t.Logf(string(b))
  64. }