1
0
mirror of https://github.com/pocketbase/pocketbase.git synced 2025-01-10 00:43:36 +02:00
pocketbase/tools/security/random_test.go

90 lines
2.3 KiB
Go
Raw Normal View History

2022-07-06 23:19:05 +02:00
package security_test
import (
"regexp"
"testing"
"github.com/pocketbase/pocketbase/tools/security"
)
func TestRandomString(t *testing.T) {
2022-11-06 15:26:34 +02:00
testRandomString(t, security.RandomString)
}
2022-07-06 23:19:05 +02:00
2022-11-06 15:26:34 +02:00
func TestRandomStringWithAlphabet(t *testing.T) {
testRandomStringWithAlphabet(t, security.RandomStringWithAlphabet)
}
2022-07-06 23:19:05 +02:00
2022-11-06 15:28:41 +02:00
func TestPseudorandomString(t *testing.T) {
testRandomString(t, security.PseudorandomString)
2022-11-06 15:26:34 +02:00
}
2022-07-06 23:19:05 +02:00
2022-11-06 15:28:41 +02:00
func TestPseudorandomStringWithAlphabet(t *testing.T) {
testRandomStringWithAlphabet(t, security.PseudorandomStringWithAlphabet)
2022-07-06 23:19:05 +02:00
}
2022-11-06 15:26:34 +02:00
// -------------------------------------------------------------------
func testRandomStringWithAlphabet(t *testing.T, randomFunc func(n int, alphabet string) string) {
scenarios := []struct {
alphabet string
expectPattern string
}{
{"0123456789_", `[0-9_]+`},
2022-12-12 19:19:31 +02:00
{"abcdef123", `[abcdef123]+`},
{"!@#$%^&*()", `[\!\@\#\$\%\^\&\*\(\)]+`},
}
for i, s := range scenarios {
2022-11-06 15:26:34 +02:00
generated := make([]string, 0, 1000)
length := 10
2022-11-06 15:26:34 +02:00
for j := 0; j < 1000; j++ {
result := randomFunc(length, s.alphabet)
if len(result) != length {
t.Fatalf("(%d:%d) Expected the length of the string to be %d, got %d", i, j, length, len(result))
}
reg := regexp.MustCompile(s.expectPattern)
if match := reg.MatchString(result); !match {
t.Fatalf("(%d:%d) The generated string should have only %s characters, got %q", i, j, s.expectPattern, result)
}
for _, str := range generated {
if str == result {
t.Fatalf("(%d:%d) Repeating random string - found %q in %q", i, j, result, generated)
}
}
generated = append(generated, result)
}
}
}
2022-11-06 15:26:34 +02:00
func testRandomString(t *testing.T, randomFunc func(n int) string) {
generated := make([]string, 0, 1000)
reg := regexp.MustCompile(`[a-zA-Z0-9]+`)
length := 10
for i := 0; i < 1000; i++ {
result := randomFunc(length)
if len(result) != length {
t.Fatalf("(%d) Expected the length of the string to be %d, got %d", i, length, len(result))
}
if match := reg.MatchString(result); !match {
t.Fatalf("(%d) The generated string should have only [a-zA-Z0-9]+ characters, got %q", i, result)
}
for _, str := range generated {
if str == result {
t.Fatalf("(%d) Repeating random string - found %q in \n%v", i, result, generated)
}
}
generated = append(generated, result)
}
}