From f9bc1b1f876ec6cf640efe28edb02d035938a51a Mon Sep 17 00:00:00 2001 From: Chris Santiago Date: Tue, 22 Aug 2023 04:55:02 -0500 Subject: [PATCH] Test the randstr.go RandomString function (#820) --- pkg/randstr/randstr.go | 3 ++ pkg/randstr/randstr_test.go | 71 +++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 pkg/randstr/randstr_test.go diff --git a/pkg/randstr/randstr.go b/pkg/randstr/randstr.go index cab585e9f..8fd69883f 100644 --- a/pkg/randstr/randstr.go +++ b/pkg/randstr/randstr.go @@ -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++ { diff --git a/pkg/randstr/randstr_test.go b/pkg/randstr/randstr_test.go new file mode 100644 index 000000000..b1ddd66b8 --- /dev/null +++ b/pkg/randstr/randstr_test.go @@ -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) + 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 + } +}