Skip to content

Commit 973df19

Browse files
authored
test: Check created_at for prepareData to ensure user order (#6436)
* test: Check created_at for prepareData to ensure user order * test: Consistent user ordering in dbfake * import order * Linting
1 parent 3cb9b3d commit 973df19

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

coderd/database/dbfake/databasefake.go

+15
Original file line numberDiff line numberDiff line change
@@ -2922,6 +2922,21 @@ func (q *fakeQuerier) InsertUser(_ context.Context, arg database.InsertUserParam
29222922
return database.User{}, err
29232923
}
29242924

2925+
// There is a common bug when using dbfake that 2 inserted users have the
2926+
// same created_at time. This causes user order to not be deterministic,
2927+
// which breaks some unit tests.
2928+
// To fix this, we make sure that the created_at time is always greater
2929+
// than the last user's created_at time.
2930+
allUsers, _ := q.GetUsers(context.Background(), database.GetUsersParams{})
2931+
if len(allUsers) > 0 {
2932+
lastUser := allUsers[len(allUsers)-1]
2933+
if arg.CreatedAt.Before(lastUser.CreatedAt) ||
2934+
arg.CreatedAt.Equal(lastUser.CreatedAt) {
2935+
// 1 ms is a good enough buffer.
2936+
arg.CreatedAt = lastUser.CreatedAt.Add(time.Millisecond)
2937+
}
2938+
}
2939+
29252940
q.mutex.Lock()
29262941
defer q.mutex.Unlock()
29272942

coderd/database/dbfake/databasefake_test.go

+25-1
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,11 @@ import (
99
"time"
1010

1111
"github.com/stretchr/testify/assert"
12+
"github.com/stretchr/testify/require"
1213

1314
"github.com/coder/coder/coderd/database"
14-
1515
"github.com/coder/coder/coderd/database/dbfake"
16+
"github.com/coder/coder/coderd/database/dbgen"
1617
)
1718

1819
// test that transactions don't deadlock, and that we don't see intermediate state.
@@ -105,6 +106,29 @@ func TestExactMethods(t *testing.T) {
105106
}
106107
}
107108

109+
// TestUserOrder ensures that the fake database returns users in the order they
110+
// were created.
111+
func TestUserOrder(t *testing.T) {
112+
t.Parallel()
113+
114+
db := dbfake.New()
115+
now := database.Now()
116+
count := 10
117+
for i := 0; i < count; i++ {
118+
dbgen.User(t, db, database.User{
119+
Username: fmt.Sprintf("user%d", i),
120+
CreatedAt: now,
121+
})
122+
}
123+
124+
users, err := db.GetUsers(context.Background(), database.GetUsersParams{})
125+
require.NoError(t, err)
126+
require.Lenf(t, users, count, "expected %d users", count)
127+
for i, user := range users {
128+
require.Equal(t, fmt.Sprintf("user%d", i), user.Username)
129+
}
130+
}
131+
108132
func methods(rt reflect.Type) map[string]bool {
109133
methods := make(map[string]bool)
110134
for i := 0; i < rt.NumMethod(); i++ {

0 commit comments

Comments
 (0)