Skip to content

Commit 49a2880

Browse files
authored
fix(testutil): ensure GetRandomName never returns strings greater tha… (#14153)
1 parent 8acc7f2 commit 49a2880

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

testutil/names.go

+18-1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import (
1010

1111
var n atomic.Int64
1212

13+
const maxNameLen = 32
14+
1315
// GetRandomName returns a random name using moby/pkg/namesgenerator.
1416
// namesgenerator.GetRandomName exposes a retry parameter that appends
1517
// a pseudo-random number between 1 and 10 to its return value.
@@ -19,5 +21,20 @@ var n atomic.Int64
1921
// to the return value.
2022
func GetRandomName(t testing.TB) string {
2123
t.Helper()
22-
return namesgenerator.GetRandomName(0) + strconv.FormatInt(n.Add(1), 10)
24+
name := namesgenerator.GetRandomName(0)
25+
return incSuffix(name, n.Add(1), maxNameLen)
26+
}
27+
28+
func incSuffix(s string, num int64, maxLen int) string {
29+
suffix := strconv.FormatInt(num, 10)
30+
if len(s)+len(suffix) <= maxLen {
31+
return s + suffix
32+
}
33+
stripLen := (len(s) + len(suffix)) - maxLen
34+
stripIdx := len(s) - stripLen
35+
if stripIdx < 0 {
36+
return ""
37+
}
38+
s = s[:stripIdx]
39+
return s + suffix
2340
}

testutil/names_internal_test.go

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package testutil
2+
3+
import (
4+
"testing"
5+
6+
"github.com/stretchr/testify/assert"
7+
)
8+
9+
func TestIncSuffix(t *testing.T) {
10+
t.Parallel()
11+
12+
for _, tt := range []struct {
13+
s string
14+
num int64
15+
maxLen int
16+
want string
17+
}{
18+
{
19+
s: "foo",
20+
num: 1,
21+
maxLen: 4,
22+
want: "foo1",
23+
},
24+
{
25+
s: "foo",
26+
num: 42,
27+
maxLen: 3,
28+
want: "f42",
29+
},
30+
{
31+
s: "foo",
32+
num: 3,
33+
maxLen: 2,
34+
want: "f3",
35+
},
36+
{
37+
s: "foo",
38+
num: 4,
39+
maxLen: 1,
40+
want: "4",
41+
},
42+
{
43+
s: "foo",
44+
num: 0,
45+
maxLen: 0,
46+
want: "",
47+
},
48+
} {
49+
actual := incSuffix(tt.s, tt.num, tt.maxLen)
50+
assert.Equal(t, tt.want, actual)
51+
}
52+
}

0 commit comments

Comments
 (0)