blob: 4771ebbd2ca778d387e0f21cac73b1adb3d90704 [file] [log] [blame]
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07001// +build acceptance
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07002package tools
3
4import (
5 "crypto/rand"
Ash Wilsonfd566482014-09-23 15:47:35 -04006 "errors"
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07007 "time"
8)
9
Ash Wilsonfd566482014-09-23 15:47:35 -040010// ErrTimeout is returned if WaitFor takes longer than 300 second to happen.
11var ErrTimeout = errors.New("Timed out")
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070012
Ash Wilsonfd566482014-09-23 15:47:35 -040013// WaitFor polls a predicate function once per second to wait for a certain state to arrive.
14func WaitFor(predicate func() (bool, error)) error {
15 for i := 0; i < 300; i++ {
16 time.Sleep(1 * time.Second)
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070017
Ash Wilsonfd566482014-09-23 15:47:35 -040018 satisfied, err := predicate()
19 if err != nil {
20 return err
21 }
22 if satisfied {
23 return nil
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070024 }
25 }
Ash Wilsonfd566482014-09-23 15:47:35 -040026 return ErrTimeout
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070027}
28
Ash Wilsonfd566482014-09-23 15:47:35 -040029// MakeNewPassword generates a new string that's guaranteed to be different than the given one.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070030func MakeNewPassword(oldPass string) string {
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070031 randomPassword := RandomString("", 16)
32 for randomPassword == oldPass {
33 randomPassword = RandomString("", 16)
34 }
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070035 return randomPassword
36}
37
Ash Wilsonfd566482014-09-23 15:47:35 -040038// RandomString generates a string of given length, but random content.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070039// All content will be within the ASCII graphic character set.
40// (Implementation from Even Shaw's contribution on
41// http://stackoverflow.com/questions/12771930/what-is-the-fastest-way-to-generate-a-long-random-string-in-go).
42func RandomString(prefix string, n int) string {
43 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
44 var bytes = make([]byte, n)
45 rand.Read(bytes)
46 for i, b := range bytes {
47 bytes[i] = alphanum[b%byte(len(alphanum))]
48 }
49 return prefix + string(bytes)
50}