diff --git a/test/helpers/data.go b/test/helpers/data.go index bd2d73088..e982b2c33 100644 --- a/test/helpers/data.go +++ b/test/helpers/data.go @@ -20,12 +20,13 @@ import ( "math/rand" "strings" "time" + "unicode" ) const ( letterBytes = "abcdefghijklmnopqrstuvwxyz" randSuffixLen = 8 - sep = "-" + sep = '-' ) func init() { @@ -45,5 +46,32 @@ func AppendRandomString(prefix string) string { suffix[i] = letterBytes[rand.Intn(len(letterBytes))] } - return strings.Join([]string{prefix, string(suffix)}, sep) + return strings.Join([]string{prefix, string(suffix)}, string(sep)) +} + +// MakeK8sNamePrefix converts each chunk of non-alphanumeric character into a single dash +// and also convert camelcase tokens into dash-delimited lowercase tokens. +func MakeK8sNamePrefix(s string) string { + var sb strings.Builder + newToken := false + for _, c := range s { + if !(unicode.IsLetter(c) || unicode.IsNumber(c)) { + newToken = true + continue + } + if sb.Len() > 0 && (newToken || unicode.IsUpper(c)) { + sb.WriteRune(sep) + } + sb.WriteRune(unicode.ToLower(c)) + newToken = false + } + return sb.String() +} + +// GetBaseFuncName returns the baseFuncName parsed from the fullFuncName. +// eg. test/e2e.TestMain will return TestMain. +func GetBaseFuncName(fullFuncName string) string { + baseFuncName := fullFuncName[strings.LastIndex(fullFuncName, "/")+1:] + baseFuncName = baseFuncName[strings.LastIndex(baseFuncName, ".")+1:] + return baseFuncName } diff --git a/test/helpers/data_test.go b/test/helpers/data_test.go index 815b8e761..8a161923e 100644 --- a/test/helpers/data_test.go +++ b/test/helpers/data_test.go @@ -17,16 +17,53 @@ limitations under the License. package helpers import ( - "fmt" "regexp" + "testing" ) var matcher = regexp.MustCompile("abcd-[a-z]{8}") -func ExampleAppendRandomString() { +func TestAppendRandomString(t *testing.T) { const s = "abcd" - t := AppendRandomString(s) + w := AppendRandomString(s) o := AppendRandomString(s) - fmt.Println(matcher.MatchString(t), matcher.MatchString(o), o != t) - // Output: true true true + if !matcher.MatchString(w) || !matcher.MatchString(o) || o == w { + t.Fatalf("Generated string(s) are incorrect: %q, %q", w, o) + } +} + +func TestMakeK8sNamePrefix(t *testing.T) { + testCases := []struct { + input string + expected string + }{ + {"abcd123", "abcd123"}, + {"AbCdef", "ab-cdef"}, + {"ABCD", "a-b-c-d"}, + {"aBc*ef&d", "a-bc-ef-d"}, + } + for _, v := range testCases { + actual := MakeK8sNamePrefix(v.input) + if v.expected != actual { + t.Fatalf("Expect %q but actual is %q", v.expected, actual) + } + } +} + +func TestGetBaseFuncName(t *testing.T) { + testCases := []struct { + input string + expected string + }{ + {"test/e2e.TestMain", "TestMain"}, + {"e2e.TestMain", "TestMain"}, + {"test/TestMain", "TestMain"}, + {"TestMain", "TestMain"}, + } + for _, v := range testCases { + actual := GetBaseFuncName(v.input) + if v.expected != actual { + t.Fatalf("Expect %q but actual is %q", v.expected, actual) + } + } }