github.com/terraform-modules-krish/terratest@v0.29.0/modules/random/random.go (about)

     1  // Package random contains different random generators.
     2  package random
     3  
     4  import (
     5  	"bytes"
     6  	"math/rand"
     7  	"time"
     8  )
     9  
    10  // Random generates a random int between min and max, inclusive.
    11  func Random(min int, max int) int {
    12  	return newRand().Intn(max-min+1) + min
    13  }
    14  
    15  // RandomInt picks a random element in the slice of ints.
    16  func RandomInt(elements []int) int {
    17  	index := Random(0, len(elements)-1)
    18  	return elements[index]
    19  }
    20  
    21  // RandomString picks a random element in the slice of string.
    22  func RandomString(elements []string) string {
    23  	index := Random(0, len(elements)-1)
    24  	return elements[index]
    25  }
    26  
    27  const base62chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
    28  const uniqueIDLength = 6 // Should be good for 62^6 = 56+ billion combinations
    29  
    30  // UniqueId returns a unique (ish) id we can attach to resources and tfstate files so they don't conflict with each other
    31  // Uses base 62 to generate a 6 character string that's unlikely to collide with the handful of tests we run in
    32  // parallel. Based on code here: http://stackoverflow.com/a/9543797/483528
    33  func UniqueId() string {
    34  	var out bytes.Buffer
    35  
    36  	generator := newRand()
    37  	for i := 0; i < uniqueIDLength; i++ {
    38  		out.WriteByte(base62chars[generator.Intn(len(base62chars))])
    39  	}
    40  
    41  	return out.String()
    42  }
    43  
    44  // newRand creates a new random number generator, seeding it with the current system time.
    45  func newRand() *rand.Rand {
    46  	return rand.New(rand.NewSource(time.Now().UnixNano()))
    47  }