github.com/huaweicloud/golangsdk@v0.0.0-20210831081626-d823fe11ceba/acceptance/tools/tools.go (about)

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