Skip to content

Commit 38fb6cb

Browse files
authored
test: Try again in unit test if user already exists (#2730)
1 parent 03fd063 commit 38fb6cb

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

coderd/coderdtest/coderdtest.go

+14
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import (
3333
"github.com/spf13/afero"
3434
"github.com/stretchr/testify/assert"
3535
"github.com/stretchr/testify/require"
36+
"golang.org/x/xerrors"
3637
"google.golang.org/api/idtoken"
3738
"google.golang.org/api/option"
3839

@@ -265,13 +266,26 @@ func CreateFirstUser(t *testing.T, client *codersdk.Client) codersdk.CreateFirst
265266

266267
// CreateAnotherUser creates and authenticates a new user.
267268
func CreateAnotherUser(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, roles ...string) *codersdk.Client {
269+
return createAnotherUserRetry(t, client, organizationID, 5, roles...)
270+
}
271+
272+
func createAnotherUserRetry(t *testing.T, client *codersdk.Client, organizationID uuid.UUID, retries int, roles ...string) *codersdk.Client {
268273
req := codersdk.CreateUserRequest{
269274
Email: namesgenerator.GetRandomName(1) + "@coder.com",
270275
Username: randomUsername(),
271276
Password: "testpass",
272277
OrganizationID: organizationID,
273278
}
279+
274280
user, err := client.CreateUser(context.Background(), req)
281+
var apiError *codersdk.Error
282+
// If the user already exists by username or email conflict, try again up to "retries" times.
283+
if err != nil && retries >= 0 && xerrors.As(err, &apiError) {
284+
if apiError.StatusCode() == http.StatusConflict {
285+
retries--
286+
return createAnotherUserRetry(t, client, organizationID, retries, roles...)
287+
}
288+
}
275289
require.NoError(t, err)
276290

277291
login, err := client.LoginWithPassword(context.Background(), codersdk.LoginWithPasswordRequest{

0 commit comments

Comments
 (0)