Skip to content

Commit 584fa9a

Browse files
committed
Add DATABASEPOOL_TEARDOWN, optionally tear down all running dbs
1 parent 4ad7cf6 commit 584fa9a

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

Tests/AppTests/Helpers/DatabasePool.swift

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15-
import App
15+
@testable import App
16+
1617
import PostgresNIO
1718
import ShellOut
1819
import Vapor
@@ -28,7 +29,7 @@ actor DatabasePool {
2829
}
2930
}
3031

31-
static let shared = DatabasePool(maxCount: Environment.get("DATABASEPOOL_SIZE").flatMap(Int.init) ?? 4)
32+
static let shared = DatabasePool(maxCount: Environment.databasePoolSize)
3233

3334
var maxCount: Int
3435

@@ -55,8 +56,9 @@ actor DatabasePool {
5556
}
5657

5758
func tearDown() async throws {
59+
guard Environment.databasePoolTearDown else { return }
5860
try await withThrowingTaskGroup { group in
59-
for db in availableDatabases {
61+
for db in try await runningDatabases() {
6062
group.addTask {
6163
try await self.removeDB(database: db)
6264
}
@@ -68,7 +70,6 @@ actor DatabasePool {
6870
func withDatabase(_ operation: @Sendable (Database) async throws -> Void) async throws {
6971
let db = try await retainDatabase()
7072
do {
71-
// print("⚠️ available", availableDatabases.map(\.port).sorted())
7273
try await operation(db)
7374
try await releaseDatabase(database: db)
7475
} catch {
@@ -77,6 +78,16 @@ actor DatabasePool {
7778
}
7879
}
7980

81+
private func runningDatabases() async throws -> [Database] {
82+
let stdout = try await ShellOut.shellOut(to: .getContainerNames).stdout
83+
return stdout
84+
.components(separatedBy: "\n")
85+
.filter { $0.starts(with: "spi_test_") }
86+
.map { String($0.dropFirst("spi_test_".count)) }
87+
.compactMap(Int.init)
88+
.map(Database.init(port:))
89+
}
90+
8091
private func retainDatabase() async throws -> Database {
8192
var database = availableDatabases.randomElement()
8293
while database == nil {
@@ -220,3 +231,13 @@ private func _withDatabase(_ databaseName: String,
220231
}
221232
}
222233

234+
235+
extension Environment {
236+
static var databasePoolSize: Int {
237+
Environment.get("DATABASEPOOL_SIZE").flatMap(Int.init) ?? 4
238+
}
239+
240+
static var databasePoolTearDown: Bool {
241+
Environment.get("DATABASEPOOL_TEARDOWN").flatMap(\.asBool) ?? true
242+
}
243+
}

Tests/AppTests/Helpers/ShellOutCommand+ext.swift

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,10 @@ extension ShellOutCommand {
3535
"rm", "-f", "spi_test_\(port)"
3636
])
3737
}
38+
39+
static var getContainerNames: ShellOutCommand {
40+
.init(command: "docker", arguments: [
41+
"ps", "--format", "{{.Names}}"
42+
])
43+
}
3844
}

0 commit comments

Comments
 (0)