forked from coollabsio/coolify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HandlesTestDatabase.php
78 lines (67 loc) · 2.46 KB
/
HandlesTestDatabase.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
namespace Tests\Traits;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
trait HandlesTestDatabase
{
protected function setUpTestDatabase(): void
{
try {
// Create test database if it doesn't exist
$database = config('database.connections.testing.database');
$this->createTestDatabase($database);
// Run migrations
Artisan::call('migrate:fresh', [
'--database' => 'testing',
'--seed' => false,
]);
} catch (\Exception $e) {
$this->tearDownTestDatabase();
throw $e;
}
}
protected function tearDownTestDatabase(): void
{
try {
// Drop test database
$database = config('database.connections.testing.database');
$this->dropTestDatabase($database);
} catch (\Exception $e) {
// Log error but don't throw
error_log('Failed to tear down test database: '.$e->getMessage());
}
}
protected function createTestDatabase($database)
{
try {
// Connect to postgres database to create/drop test database
config(['database.connections.pgsql.database' => 'postgres']);
DB::purge('pgsql');
DB::reconnect('pgsql');
// Drop if exists and create new database
DB::connection('pgsql')->statement("DROP DATABASE IF EXISTS $database WITH (FORCE);");
DB::connection('pgsql')->statement("CREATE DATABASE $database;");
// Switch back to testing connection
DB::disconnect('pgsql');
DB::reconnect('testing');
} catch (\Exception $e) {
$this->tearDownTestDatabase();
throw new \Exception('Could not create test database: '.$e->getMessage());
}
}
protected function dropTestDatabase($database)
{
try {
// Connect to postgres database to drop test database
config(['database.connections.pgsql.database' => 'postgres']);
DB::purge('pgsql');
DB::reconnect('pgsql');
// Drop the test database
DB::connection('pgsql')->statement("DROP DATABASE IF EXISTS $database WITH (FORCE);");
DB::disconnect('pgsql');
} catch (\Exception $e) {
// Log error but don't throw
error_log('Failed to drop test database: '.$e->getMessage());
}
}
}