utils_test.go 774 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package testutils
  2. import (
  3. "math/rand"
  4. "testing"
  5. "time"
  6. )
  7. const chars = "abcdefghijklmnopqrstuvwxyz" +
  8. "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
  9. "~!@#$%^&*()-_+={}[]\\|<,>.?/\"';:` "
  10. // Timeout calls f and waits for 100ms for it to complete.
  11. // If it doesn't, it causes the tests to fail.
  12. // t must be a valid testing context.
  13. func Timeout(t *testing.T, f func()) {
  14. onTimeout := time.After(100 * time.Millisecond)
  15. onDone := make(chan bool)
  16. go func() {
  17. f()
  18. close(onDone)
  19. }()
  20. select {
  21. case <-onTimeout:
  22. t.Fatalf("timeout")
  23. case <-onDone:
  24. }
  25. }
  26. // RandomString returns random string of specified length
  27. func RandomString(length int) string {
  28. res := make([]byte, length)
  29. for i := 0; i < length; i++ {
  30. res[i] = chars[rand.Intn(len(chars))]
  31. }
  32. return string(res)
  33. }