Merge pull request #12044 from reteptilian/11721-remove-randomstring-3

fixes 11721 replace stringutils.GenerateRandomString with stringid.GenerateRandomID
This commit is contained in:
Michael Crosby 2015-04-13 13:47:50 -07:00
commit b15e56b3ef
2 changed files with 39 additions and 19 deletions

View file

@ -1,23 +1,10 @@
package stringutils package stringutils
import ( import (
"crypto/rand"
"encoding/hex"
"io"
mathrand "math/rand" mathrand "math/rand"
"time" "time"
) )
// Generate 32 chars random string
func GenerateRandomString() string {
id := make([]byte, 32)
if _, err := io.ReadFull(rand.Reader, id); err != nil {
panic(err) // This shouldn't happen
}
return hex.EncodeToString(id)
}
// Generate alpha only random stirng with length n // Generate alpha only random stirng with length n
func GenerateRandomAlphaOnlyString(n int) string { func GenerateRandomAlphaOnlyString(n int) string {
// make a really long string // make a really long string

View file

@ -2,18 +2,19 @@ package stringutils
import "testing" import "testing"
func TestRandomString(t *testing.T) { func testLengthHelper(generator func(int) string, t *testing.T) {
str := GenerateRandomString() expectedLength := 20
if len(str) != 64 { s := generator(expectedLength)
t.Fatalf("Id returned is incorrect: %s", str) if len(s) != expectedLength {
t.Fatalf("Length of %s was %d but expected length %d", s, len(s), expectedLength)
} }
} }
func TestRandomStringUniqueness(t *testing.T) { func testUniquenessHelper(generator func(int) string, t *testing.T) {
repeats := 25 repeats := 25
set := make(map[string]struct{}, repeats) set := make(map[string]struct{}, repeats)
for i := 0; i < repeats; i = i + 1 { for i := 0; i < repeats; i = i + 1 {
str := GenerateRandomString() str := generator(64)
if len(str) != 64 { if len(str) != 64 {
t.Fatalf("Id returned is incorrect: %s", str) t.Fatalf("Id returned is incorrect: %s", str)
} }
@ -23,3 +24,35 @@ func TestRandomStringUniqueness(t *testing.T) {
set[str] = struct{}{} set[str] = struct{}{}
} }
} }
func isASCII(s string) bool {
for _, c := range s {
if c > 127 {
return false
}
}
return true
}
func TestGenerateRandomAlphaOnlyStringLength(t *testing.T) {
testLengthHelper(GenerateRandomAlphaOnlyString, t)
}
func TestGenerateRandomAlphaOnlyStringUniqueness(t *testing.T) {
testUniquenessHelper(GenerateRandomAlphaOnlyString, t)
}
func TestGenerateRandomAsciiStringLength(t *testing.T) {
testLengthHelper(GenerateRandomAsciiString, t)
}
func TestGenerateRandomAsciiStringUniqueness(t *testing.T) {
testUniquenessHelper(GenerateRandomAsciiString, t)
}
func TestGenerateRandomAsciiStringIsAscii(t *testing.T) {
str := GenerateRandomAsciiString(64)
if !isASCII(str) {
t.Fatalf("%s contained non-ascii characters", str)
}
}