-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
TestUtil.php
221 lines (185 loc) · 6.8 KB
/
TestUtil.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
<?php
declare(strict_types=1);
namespace Doctrine\Tests;
use Doctrine\DBAL\Connection;
use Doctrine\DBAL\DriverManager;
use UnexpectedValueException;
use function explode;
use function fwrite;
use function get_class;
use function getenv;
use function sprintf;
use function strlen;
use function strpos;
use function substr;
use const STDERR;
/**
* TestUtil is a class with static utility methods used during tests.
*/
class TestUtil
{
/** @var bool Whether the database schema is initialized. */
private static $initialized = false;
/**
* Gets a <b>real</b> database connection using the following parameters
* of the $GLOBALS array:
*
* 'db_type' : The name of the Doctrine DBAL database driver to use.
* 'db_username' : The username to use for connecting.
* 'db_password' : The password to use for connecting.
* 'db_host' : The hostname of the database to connect to.
* 'db_server' : The server name of the database to connect to
* (optional, some vendors allow multiple server instances with different names on the same host).
* 'db_name' : The name of the database to connect to.
* 'db_port' : The port of the database to connect to.
*
* Usually these variables of the $GLOBALS array are filled by PHPUnit based
* on an XML configuration file. If no such parameters exist, an SQLite
* in-memory database is used.
*
* IMPORTANT:
* 1) Each invocation of this method returns a NEW database connection.
* 2) The database is dropped and recreated to ensure it's clean.
*
* @return Connection The database connection instance.
*/
public static function getConnection(): Connection
{
$params = self::getConnectionParams();
$conn = DriverManager::getConnection($params);
// Note, writes direct to STDERR to prevent phpunit detecting output - otherwise this would cause either an
// "unexpected output" warning or a failure on the first test case to call this method.
fwrite(
STDERR,
sprintf(
"\nUsing DB driver %s\n",
get_class($conn->getDriver())
)
);
$expectDriver = getenv('EXPECT_DB_DRIVER');
if (getenv('CI') && empty($expectDriver)) {
throw new UnexpectedValueException(
'CI builds must provide an EXPECT_DB_DRIVER environment variable'
);
}
if ($expectDriver && ($expectDriver !== $params['driver'])) {
// Compare the resolved driver type manually rather than using a phpunit assert method, so that we don't
// affect phpunit's count of assertions run during the calling test.
throw new UnexpectedValueException(
sprintf(
"Invalid test environment config\n - EXPECT_DB_DRIVER = `%s`\n - Actual driver = `%s`",
$expectDriver,
$params['driver']
)
);
}
self::addDbEventSubscribers($conn);
return $conn;
}
public static function getTempConnection(): Connection
{
return DriverManager::getConnection(self::getParamsForTemporaryConnection());
}
/**
* @psalm-return array<string, mixed>
*/
private static function getConnectionParams()
{
$realDbParams = self::getParamsForMainConnection();
if (! self::$initialized) {
$tmpDbParams = self::getParamsForTemporaryConnection();
$realConn = DriverManager::getConnection($realDbParams);
// Connect to tmpdb in order to drop and create the real test db.
$tmpConn = DriverManager::getConnection($tmpDbParams);
$platform = $tmpConn->getDatabasePlatform();
if ($platform->supportsCreateDropDatabase()) {
$dbname = $realConn->getDatabase();
$realConn->close();
$tmpConn->getSchemaManager()->dropAndCreateDatabase($dbname);
$tmpConn->close();
} else {
$sm = $realConn->getSchemaManager();
$schema = $sm->createSchema();
$stmts = $schema->toDropSql($realConn->getDatabasePlatform());
foreach ($stmts as $stmt) {
$realConn->exec($stmt);
}
}
self::$initialized = true;
}
return $realDbParams;
}
private static function addDbEventSubscribers(Connection $conn): void
{
if (isset($GLOBALS['db_event_subscribers'])) {
$evm = $conn->getEventManager();
foreach (explode(',', $GLOBALS['db_event_subscribers']) as $subscriberClass) {
$subscriberInstance = new $subscriberClass();
$evm->addEventSubscriber($subscriberInstance);
}
}
}
/**
* @psalm-return array<string, mixed>
*/
private static function getParamsForTemporaryConnection()
{
if (isset($GLOBALS['tmpdb_driver'])) {
return self::mapConnectionParameters($GLOBALS, 'tmpdb_');
}
$parameters = self::mapConnectionParameters($GLOBALS, 'db_');
unset($parameters['dbname']);
return $parameters;
}
/**
* @psalm-return array<string, mixed>
*/
private static function getParamsForMainConnection()
{
if (! isset($GLOBALS['db_driver'])) {
throw new UnexpectedValueException(
'You must provide database connection params including a db_driver value. See phpunit.xml.dist for details'
);
}
return self::mapConnectionParameters($GLOBALS, 'db_');
}
/**
* @param array<string,mixed> $configuration
*
* @return array<string,mixed>
*/
private static function mapConnectionParameters(array $configuration, string $prefix): array
{
$parameters = [];
foreach (
[
'driver',
'user',
'password',
'host',
'dbname',
'port',
'server',
'memory',
'ssl_key',
'ssl_cert',
'ssl_ca',
'ssl_capath',
'ssl_cipher',
'unix_socket',
] as $parameter
) {
if (! isset($configuration[$prefix . $parameter])) {
continue;
}
$parameters[$parameter] = $configuration[$prefix . $parameter];
}
foreach ($configuration as $param => $value) {
if (strpos($param, $prefix . 'driver_option_') !== 0) {
continue;
}
$parameters['driverOptions'][substr($param, strlen($prefix . 'driver_option_'))] = $value;
}
return $parameters;
}
}