Skip to content

Commit 7d6a91c

Browse files
easyCZroboquat
authored andcommitted
[usage] Automatically cleanup records between test DB connections
1 parent 4a5f8ec commit 7d6a91c

File tree

4 files changed

+16
-16
lines changed

4 files changed

+16
-16
lines changed

components/usage/pkg/db/conn.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,26 @@ func ConnectForTests(t *testing.T) *gorm.DB {
7272
})
7373
require.NoError(t, err, "Failed to establish connection to DB. In a workspace, run `leeway build components/usage:init-testdb` once to bootstrap the DB.")
7474

75+
conn = conn.Debug()
76+
7577
t.Cleanup(func() {
78+
// Delete records for known models from the DB
79+
log.Info("Cleaning up DB between connections.")
80+
for _, model := range []interface{}{
81+
&WorkspaceInstance{},
82+
&Workspace{},
83+
&Project{},
84+
&Team{},
85+
} {
86+
// See https://gorm.io/docs/delete.html#Block-Global-Delete
87+
tx := conn.Session(&gorm.Session{AllowGlobalUpdate: true}).Delete(model)
88+
require.NoError(t, tx.Error)
89+
}
90+
7691
rawConn, err := conn.DB()
7792
require.NoError(t, err)
78-
7993
require.NoError(t, rawConn.Close(), "must close database connection")
8094
})
8195

82-
return conn.Debug()
96+
return conn
8397
}

components/usage/pkg/db/project_test.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,10 +64,5 @@ func insertRawProject(t *testing.T, conn *gorm.DB, obj map[string]interface{}) u
6464
tx := conn.Exec(statement, values)
6565
require.NoError(t, tx.Error)
6666

67-
t.Cleanup(func() {
68-
tx = conn.Delete(&db.Project{ID: id})
69-
require.NoError(t, tx.Error)
70-
})
71-
7267
return id
7368
}

components/usage/pkg/db/workspace_instance_test.go

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,6 @@ func insertRawWorkspaceInstance(t *testing.T, conn *gorm.DB, object map[string]i
7070
statement := fmt.Sprintf(`INSERT INTO d_b_workspace_instance (%s) VALUES ?;`, strings.Join(columns, ", "))
7171
id := uuid.MustParse(insertRawObject(t, conn, columns, statement, object))
7272

73-
t.Cleanup(func() {
74-
tx := conn.Delete(&db.WorkspaceInstance{ID: id})
75-
require.NoError(t, tx.Error)
76-
})
77-
7873
return id
7974
}
8075

components/usage/pkg/db/workspace_test.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,10 +73,6 @@ func insertRawWorkspace(t *testing.T, conn *gorm.DB, rawWorkspace map[string]int
7373
) VALUES ?;`, strings.Join(columns, ", "))
7474
id := insertRawObject(t, conn, columns, statement, rawWorkspace)
7575

76-
t.Cleanup(func() {
77-
tx := conn.Delete(&db.Workspace{ID: id})
78-
require.NoError(t, tx.Error)
79-
})
8076
return id
8177
}
8278

0 commit comments

Comments
 (0)