Use global, sync'ed random source
Almost unbelievably it appears tests on AppVeyor get the same value when seeding the random generator. See https://ci.appveyor.com/project/otoolep/rqlite/builds/47853399master
parent
ad3a29de16
commit
c1a8b4a13a
@ -0,0 +1,29 @@
|
||||
package random
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var r *rand.Rand
|
||||
var mu sync.Mutex
|
||||
|
||||
func init() {
|
||||
r = rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
}
|
||||
|
||||
// RandomString returns a random string of 20 characters
|
||||
func RandomString() string {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
var output strings.Builder
|
||||
chars := "abcdedfghijklmnopqrstABCDEFGHIJKLMNOP"
|
||||
for i := 0; i < 20; i++ {
|
||||
random := r.Intn(len(chars))
|
||||
randomChar := chars[random]
|
||||
output.WriteString(string(randomChar))
|
||||
}
|
||||
return output.String()
|
||||
}
|
@ -0,0 +1,25 @@
|
||||
package random
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func Test_RandomStringLength(t *testing.T) {
|
||||
str := RandomString()
|
||||
if len(str) != 20 {
|
||||
t.Errorf("RandomString() returned a string of length %d; want 20", len(str))
|
||||
}
|
||||
}
|
||||
|
||||
func Test_RandomStringUniqueness(t *testing.T) {
|
||||
const numStrings = 100
|
||||
strs := make(map[string]bool, numStrings)
|
||||
|
||||
for i := 0; i < numStrings; i++ {
|
||||
str := RandomString()
|
||||
if strs[str] {
|
||||
t.Errorf("RandomString() returned a non-unique string: %s", str)
|
||||
}
|
||||
strs[str] = true
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue