Skip to content

Commit

Permalink
Test random string generator
Browse files Browse the repository at this point in the history
Signed-off-by: Jo Vandeginste <[email protected]>
  • Loading branch information
jovandeginste committed Feb 20, 2024
1 parent 4466f6a commit 23744af
Show file tree
Hide file tree
Showing 10 changed files with 3,746 additions and 15 deletions.
15 changes: 0 additions & 15 deletions pkg/util/random.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,6 @@ import (

const letters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-"

// GenerateRandomBytes returns securely generated random bytes.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
// case the caller should not continue.
func GenerateRandomBytes(n int) ([]byte, error) {
b := make([]byte, n)

// Note that err == nil only if we read len(b) bytes.
if _, err := rand.Read(b); err != nil {
return nil, err
}

return b, nil
}

// GenerateRandomString returns a securely generated random string.
// It will return an error if the system's secure random
// number generator fails to function correctly, in which
Expand Down
30 changes: 30 additions & 0 deletions pkg/util/random_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package util

import (
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func TestGenerateRandomString(t *testing.T) {
for _, l := range []int{
4, 8, 16, 32,
} {
s, err := GenerateRandomString(l)
require.NoError(t, err)
assert.Len(t, s, l)
}
}

func TestGenerateRandomStringIsRandom(t *testing.T) {
s1, err := GenerateRandomString(32)
require.NoError(t, err)

for i := 0; i < 100; i++ {
s2, err := GenerateRandomString(32)
require.NoError(t, err)

assert.NotEqual(t, s1, s2)
}
}
29 changes: 29 additions & 0 deletions vendor/github.com/stretchr/testify/require/doc.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions vendor/github.com/stretchr/testify/require/forward_requirements.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 23744af

Please sign in to comment.