blob: ffade126a7979ab63577606b6404fde2d77badfc [file] [log] [blame]
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07001// +build acceptance
Ash Wilson15e0f272014-10-21 15:33:02 -04002
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07003package tools
4
5import (
6 "crypto/rand"
Ash Wilsonfd566482014-09-23 15:47:35 -04007 "errors"
Samuel A. Falvo II43d83532014-07-31 14:34:48 -07008 "time"
9)
10
Ash Wilsonfd566482014-09-23 15:47:35 -040011// ErrTimeout is returned if WaitFor takes longer than 300 second to happen.
12var ErrTimeout = errors.New("Timed out")
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070013
Ash Wilsonfd566482014-09-23 15:47:35 -040014// WaitFor polls a predicate function once per second to wait for a certain state to arrive.
15func WaitFor(predicate func() (bool, error)) error {
16 for i := 0; i < 300; i++ {
17 time.Sleep(1 * time.Second)
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070018
Ash Wilsonfd566482014-09-23 15:47:35 -040019 satisfied, err := predicate()
20 if err != nil {
21 return err
22 }
23 if satisfied {
24 return nil
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070025 }
26 }
Ash Wilsonfd566482014-09-23 15:47:35 -040027 return ErrTimeout
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070028}
29
Ash Wilsonfd566482014-09-23 15:47:35 -040030// MakeNewPassword generates a new string that's guaranteed to be different than the given one.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070031func MakeNewPassword(oldPass string) string {
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070032 randomPassword := RandomString("", 16)
33 for randomPassword == oldPass {
34 randomPassword = RandomString("", 16)
35 }
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070036 return randomPassword
37}
38
Ash Wilsonfd566482014-09-23 15:47:35 -040039// RandomString generates a string of given length, but random content.
Samuel A. Falvo II43d83532014-07-31 14:34:48 -070040// All content will be within the ASCII graphic character set.
41// (Implementation from Even Shaw's contribution on
42// http://stackoverflow.com/questions/12771930/what-is-the-fastest-way-to-generate-a-long-random-string-in-go).
43func RandomString(prefix string, n int) string {
44 const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
45 var bytes = make([]byte, n)
46 rand.Read(bytes)
47 for i, b := range bytes {
48 bytes[i] = alphanum[b%byte(len(alphanum))]
49 }
50 return prefix + string(bytes)
51}