Unverified Commit 801b024f authored by bryanl's avatar bryanl
Browse files

Add more test cases to rand string gen



* Exercise random string generation by adding larger test cases
* wrap random number generation with a mutex because math/rand isn't goroutine safe
Signed-off-by: default avatarbryanl <bryanliles@gmail.com>
parent e2ef2b8e
......@@ -28,14 +28,20 @@ const (
letterIdxMax = 63 / letterIdxBits // number of letter indices fitting in 63 bits
)
var randSrc = rand.NewSource(time.Now().UnixNano())
func init() {
rand.Seed(time.Now().UnixNano())
}
// Rand generates a random string of lower and upper case letters n characters long.
func Rand(n int) string {
if n < 1 {
return ""
}
b := make([]byte, n)
for i, cache, remain := n-1, randSrc.Int63(), letterIdxMax; i >= 0; {
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = randSrc.Int63(), letterIdxMax
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
......@@ -50,10 +56,14 @@ func Rand(n int) string {
// LowerRand generates a random string of lower case letters n characters long.
func LowerRand(n int) string {
if n < 1 {
return ""
}
b := make([]byte, n)
for i, cache, remain := n-1, randSrc.Int63(), letterIdxMax; i >= 0; {
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = randSrc.Int63(), letterIdxMax
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterLowerBytes) {
b[i] = letterLowerBytes[idx]
......
......@@ -16,6 +16,7 @@
package strings
import (
"fmt"
"regexp"
"testing"
......@@ -23,19 +24,37 @@ import (
)
func TestRand(t *testing.T) {
got := Rand(5)
for i := 1; i < 45; i++ {
t.Run(fmt.Sprintf("Rand(%d)", i), func(t *testing.T) {
got := Rand(i)
assert.Len(t, got, 5)
assert.Len(t, got, i)
re := regexp.MustCompile(`^[A-Za-z]{5}$`)
assert.True(t, re.MatchString(got))
re := regexp.MustCompile(fmt.Sprintf(`^[A-Za-z]{%d}$`, i))
assert.True(t, re.MatchString(got))
})
}
}
func TestRand_negative(t *testing.T) {
got := Rand(-1)
assert.Len(t, got, 0)
}
func TestLowerRand(t *testing.T) {
got := LowerRand(5)
for i := 1; i < 45; i++ {
t.Run(fmt.Sprintf("LowerRand(%d)", i), func(t *testing.T) {
got := LowerRand(i)
assert.Len(t, got, 5)
assert.Len(t, got, i)
re := regexp.MustCompile(fmt.Sprintf(`^[a-z]{%d}$`, i))
assert.True(t, re.MatchString(got))
})
}
}
re := regexp.MustCompile(`^[a-z]{5}$`)
assert.True(t, re.MatchString(got))
func TestLowerRand_negative(t *testing.T) {
got := LowerRand(-1)
assert.Len(t, got, 0)
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment