Skip to content

Commit bd6347f

Browse files
committed
Discover and re-use running dbs
1 parent 584fa9a commit bd6347f

File tree

1 file changed

+30
-10
lines changed

1 file changed

+30
-10
lines changed

Tests/AppTests/Helpers/DatabasePool.swift

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -40,25 +40,45 @@ actor DatabasePool {
4040
var availableDatabases: Set<Database> = .init()
4141

4242
func setUp() async throws {
43+
// Call DotEnvFile.load once to ensure env variables are set
4344
await DotEnvFile.load(for: .testing, fileio: .init(threadPool: .singleton))
44-
try await withThrowingTaskGroup(of: Database.self) { group in
45-
for _ in (0..<maxCount) {
46-
group.addTask {
47-
let db = try await self.launchDB()
48-
try await db.setup(for: .testing)
49-
return db
45+
46+
// Re-use up to maxCount running dbs
47+
let runningDbs = try await runningDatabases()
48+
for db in runningDbs.prefix(maxCount) {
49+
availableDatabases.insert(db)
50+
}
51+
52+
do { // Delete overprovisioned dbs
53+
let overprovisioned = runningDbs.dropFirst(maxCount)
54+
try await tearDown(databases: overprovisioned)
55+
}
56+
57+
do { // Create missing dbs
58+
let underprovisionedCount = max(maxCount - availableDatabases.count, 0)
59+
try await withThrowingTaskGroup(of: Database.self) { group in
60+
for _ in (0..<underprovisionedCount) {
61+
group.addTask {
62+
let db = try await self.launchDB()
63+
try await db.setup(for: .testing)
64+
return db
65+
}
66+
}
67+
for try await db in group {
68+
availableDatabases.insert(db)
5069
}
51-
}
52-
for try await info in group {
53-
availableDatabases.insert(info)
5470
}
5571
}
5672
}
5773

5874
func tearDown() async throws {
75+
try await tearDown(databases: runningDatabases())
76+
}
77+
78+
func tearDown(databases: any Collection<Database>) async throws {
5979
guard Environment.databasePoolTearDown else { return }
6080
try await withThrowingTaskGroup { group in
61-
for db in try await runningDatabases() {
81+
for db in databases {
6282
group.addTask {
6383
try await self.removeDB(database: db)
6484
}

0 commit comments

Comments
 (0)