Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test the randstr.go RandomString function #820

Merged
merged 1 commit into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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(testCase.name, 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)
AaronH88 marked this conversation as resolved.
Show resolved Hide resolved
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")
resoluteCoder marked this conversation as resolved.
Show resolved Hide resolved
}
charsetIndex = currentCharsetIndex
}
}