Files
coder/testutil/names.go
T
Ethan a71e5cc8b0 test: add increasing integer to GetRandomNameHyphenated (#19481)
Fixes flakes like the following:
```
workspaces_test.go:4938: 
	Error Trace:	/home/runner/work/coder/coder/coderd/coderdtest/coderdtest.go:1279
											/home/runner/work/coder/coder/coderd/workspaces_test.go:4938
											/home/runner/work/coder/coder/coderd/workspaces_test.go:5044
	Error:      	Received unexpected error:
								POST http://127.0.0.1:42597/api/v2/users/me/workspaces: unexpected status code 409: Workspace "romantic-mcclintock" already exists.
									name: This value is already in use and should be unique.
	Test:       	TestWorkspaceCreateWithImplicitPreset/SinglePresetWithParameters
```

https://github.com/coder/coder/actions/runs/17142665868/job/48633017007?pr=19464
 
Which are caused by insufficient randomness when creating multiple
workspaces with random names. Two words is not enough to avoid flakes.
We have a `testutil.GetRandomName` function that appends a monotonically
increasing integer, but this alternative function that uses hyphens
doesn't add that integer. This PR fixes that by just
`testutil.GetRandomName`
2025-08-22 12:20:03 +10:00

50 lines
1.3 KiB
Go

package testutil
import (
"strconv"
"strings"
"sync/atomic"
"testing"
"github.com/moby/moby/pkg/namesgenerator"
)
var n atomic.Int64
const maxNameLen = 32
// GetRandomName returns a random name using moby/pkg/namesgenerator.
// namesgenerator.GetRandomName exposes a retry parameter that appends
// a pseudo-random number between 1 and 10 to its return value.
// While this reduces the probability of collisions, it does not negate them.
// This function calls namesgenerator.GetRandomName without the retry
// parameter and instead increments a monotonically increasing integer
// to the return value.
func GetRandomName(t testing.TB) string {
t.Helper()
name := namesgenerator.GetRandomName(0)
return incSuffix(name, n.Add(1), maxNameLen)
}
// GetRandomNameHyphenated is as GetRandomName but uses a hyphen "-" instead of
// an underscore.
func GetRandomNameHyphenated(t testing.TB) string {
t.Helper()
name := GetRandomName(t)
return strings.ReplaceAll(name, "_", "-")
}
func incSuffix(s string, num int64, maxLen int) string {
suffix := strconv.FormatInt(num, 10)
if len(s)+len(suffix) <= maxLen {
return s + suffix
}
stripLen := (len(s) + len(suffix)) - maxLen
stripIdx := len(s) - stripLen
if stripIdx < 0 {
return ""
}
s = s[:stripIdx]
return s + suffix
}