feat: random string
This commit is contained in:
17
rand/rand.go
17
rand/rand.go
@@ -59,18 +59,17 @@ func RandomInt64(min, max int64) int64 {
|
|||||||
|
|
||||||
// RandomString 随机字符串,包含大小写字母和数字
|
// RandomString 随机字符串,包含大小写字母和数字
|
||||||
func RandomString(l int) string {
|
func RandomString(l int) string {
|
||||||
|
if l <= 0 {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||||
|
|
||||||
bytes := make([]byte, l)
|
bytes := make([]byte, l)
|
||||||
for i := 0; i < l; i++ {
|
for i := 0; i < l; i++ {
|
||||||
x := Intn(3)
|
bytes[i] = charset[Intn(len(charset))]
|
||||||
switch x {
|
|
||||||
case 0:
|
|
||||||
bytes[i] = byte(RandomInt(65, 90)) //大写字母
|
|
||||||
case 1:
|
|
||||||
bytes[i] = byte(RandomInt(97, 122))
|
|
||||||
case 2:
|
|
||||||
bytes[i] = byte(Intn(10))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(bytes)
|
return string(bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -208,11 +208,13 @@ func TestRandomInt64_ZeroRange(t *testing.T) {
|
|||||||
func TestRandomString_LengthZero(t *testing.T) {
|
func TestRandomString_LengthZero(t *testing.T) {
|
||||||
result := RandomString(0)
|
result := RandomString(0)
|
||||||
assert.Equal(t, "", result)
|
assert.Equal(t, "", result)
|
||||||
|
t.Logf("LengthZero: %s", result)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRandomString_PositiveLength(t *testing.T) {
|
func TestRandomString_PositiveLength(t *testing.T) {
|
||||||
result := RandomString(10)
|
result := RandomString(10)
|
||||||
assert.Len(t, result, 10)
|
assert.Len(t, result, 10)
|
||||||
|
t.Logf("PositiveLength: %s", result)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRandomString_ContainsOnlyValidCharacters(t *testing.T) {
|
func TestRandomString_ContainsOnlyValidCharacters(t *testing.T) {
|
||||||
@@ -220,6 +222,7 @@ func TestRandomString_ContainsOnlyValidCharacters(t *testing.T) {
|
|||||||
for _, char := range result {
|
for _, char := range result {
|
||||||
assert.True(t, (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9'))
|
assert.True(t, (char >= 'A' && char <= 'Z') || (char >= 'a' && char <= 'z') || (char >= '0' && char <= '9'))
|
||||||
}
|
}
|
||||||
|
t.Logf("ContainsOnlyValidCharacters: %s", result)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRandomString_NegativeLength(t *testing.T) {
|
func TestRandomString_NegativeLength(t *testing.T) {
|
||||||
|
|||||||
Reference in New Issue
Block a user