Add length limit for the generated names used in tests (#2217)

* add limit

* typo

* remove childname
This commit is contained in:
Yanwei Guo 2021-08-25 00:00:25 -07:00 committed by GitHub
parent a4ed097995
commit a70bb26767
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 42 additions and 8 deletions

View File

@ -21,16 +21,15 @@ import (
"strings"
"time"
"unicode"
"knative.dev/pkg/kmeta"
)
const (
letterBytes = "abcdefghijklmnopqrstuvwxyz"
randSuffixLen = 8
sep = '-'
sepS = "-"
testNamePrefix = "Test"
letterBytes = "abcdefghijklmnopqrstuvwxyz"
randSuffixLen = 8
nameLengthLimit = 50
sep = '-'
sepS = "-"
testNamePrefix = "Test"
)
func init() {
@ -52,7 +51,14 @@ func ObjectPrefixForTest(t named) string {
// ObjectNameForTest generates a random object name based on the test name.
func ObjectNameForTest(t named) string {
return kmeta.ChildName(ObjectPrefixForTest(t), string(sep)+RandomString())
prefix := ObjectPrefixForTest(t)
suffix := string(sep) + RandomString()
limit := nameLengthLimit - len(suffix)
if len(prefix) < limit {
limit = len(prefix)
}
return prefix[:limit] + suffix
}
// AppendRandomString will generate a random string that begins with prefix.

View File

@ -18,6 +18,7 @@ package helpers
import (
"regexp"
"strings"
"testing"
)
@ -74,3 +75,30 @@ func TestGetBaseFuncName(t *testing.T) {
}
}
}
func TestObjectNameForTest(t *testing.T) {
testCases := []struct {
input testNamed
expectedPrefix string
}{
{testNamed{name: "TestFooBar"}, "foo-bar-"},
{testNamed{name: "Foo-bar"}, "foo-bar-"},
{testNamed{name: "with_underscore"}, "with-underscore-"},
{testNamed{name: "WithHTTP"}, "with-http-"},
{testNamed{name: "ANameExceedingTheLimitLength-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, "a-name-exceeding-the-limit-length-aaaaaaa-"},
}
for _, v := range testCases {
actual := ObjectNameForTest(&v.input)
if !strings.HasPrefix(actual, v.expectedPrefix) {
t.Fatalf("Expect prefix %q but actual is %q", v.expectedPrefix, actual)
}
}
}
type testNamed struct {
name string
}
func (n *testNamed) Name() string {
return n.name
}