Skip to content

Commit

Permalink
Test the randstr.go RandomString function
Browse files Browse the repository at this point in the history
  • Loading branch information
resoluteCoder committed Aug 17, 2023
1 parent ff0ff07 commit 2e5509b
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pkg/randstr/randstr.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (

// RandomString returns a random string of a given length.
func RandomString(length int) string {
if length < 0 {
return ""
}
charset := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
randbytes := make([]byte, 0, length)
for i := 0; i < length; i++ {
Expand Down
71 changes: 71 additions & 0 deletions pkg/randstr/randstr_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package randstr_test

import (
"strings"
"testing"

"github.com/ansible/receptor/pkg/randstr"
)

func TestRandStrLength(t *testing.T) {
randStringTestCases := []struct {
name string
inputLength int
expectedLength int
}{
{
name: "length of 100",
inputLength: 100,
expectedLength: 100,
},
{
name: "length of 0",
inputLength: 0,
expectedLength: 0,
},
{
name: "length of -1",
inputLength: -1,
expectedLength: 0,
},
}

for _, testCase := range randStringTestCases {
t.Run("Test the random string length", func(t *testing.T) {
randomStr := randstr.RandomString(testCase.inputLength)

if len(randomStr) != testCase.expectedLength {
t.Errorf("%s - expected: %+v, received: %+v", testCase.name, testCase.expectedLength, len(randomStr))
}
})
}
}

func TestRandStrHasDifferentOutputThanCharset(t *testing.T) {
charset := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
randomStr := randstr.RandomString(len(charset))

if randomStr == charset {
t.Errorf("output should be different than charset. charset: %+v, received: %+v", charset, randomStr)
}
}

func TestRandStrHasNoContinuousSubStringOfCharset(t *testing.T) {
randomStr := randstr.RandomString(10)
charset := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

charsetIndex := strings.Index(charset, string(randomStr[0]))
for index, char := range randomStr {
if index == 0 {
continue
}
currentCharsetIndex := strings.Index(charset, string(char))
if charsetIndex+1 != currentCharsetIndex {
break
}
if index+1 == len(randomStr) {
t.Error("rand str is continuous")
}
charsetIndex = currentCharsetIndex
}
}

0 comments on commit 2e5509b

Please sign in to comment.