Repository navigation
Expand file tree
/
Copy pathDb.php
More file actions
308 lines (276 loc) · 8.78 KB
/
Copy pathDb.php
File metadata and controls
308 lines (276 loc) · 8.78 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
<?php
namespace Codeception\Module;
/**
* Works with SQL database.
*
* The most important function of this module is cleaning database before each test.
* That's why this module was added into global configuration file: codeception.yml.
* To have your database properly cleaned you should configure it to access the database.
* Also provides actions to perform checks in database.
*
* In order to have your database populated with data you need a raw SQL dump.
* Just put it in `tests/_data` dir (by default) and specify path to it in config.
* Next time after database is cleared all your data will be restored from dump.
* Don't forget to include CREATE TABLE statements into it.
*
* Supported and tested databases are:
*
* * MySQL
* * SQLite (only file)
* * PostgreSQL
*
* Supported but not tested.
*
* * MSSQL
* * Oracle
*
* Connection is done by database Drivers, which are stored in Codeception\Lib\Driver namespace.
* Check out drivers if you get problems loading dumps and cleaning databases.
*
* ## Status
*
* * Maintainer: **davert**
* * stability:
* - Mysql: **stable**
* - SQLite: **stable**
* - Postgres: **beta**
* - MSSQL: **alpha**
* - Oracle: **alpha**
* * Contact: codecept@davert.mail.ua
*
* *Please review the code of non-stable modules and provide patches if you have issues.*
*
* ## Config
*
* * dsn *required* - PDO DSN
* * user *required* - user to access database
* * password *required* - password
* * dump - path to database dump.
* * populate: true - should the dump be loaded before test suite is started.
* * cleanup: true - should the dump be reloaded after each test
*
* ### Example
*
* modules:
* enabled: [Db]
* config:
* Db:
* dsn: 'mysql:host=localhost;dbname=testdb'
* user: 'root'
* password: ''
* dump: 'tests/_data/dump.sql'
* populate: true
* cleanup: false
*
* ## Public Properties
* * dbh - contains PDO connection.
* * driver - contains Connection Driver. See [list all available drivers](https://github.com/Codeception/Codeception/tree/master/src/Codeception/Util/Driver)
*
*/
use Codeception\TestCase;
use Codeception\Module;
use Codeception\Lib\Driver\Db as Driver;
use Codeception\Lib\Interfaces\Db as DbInterface;
use Codeception\Exception\Module as ModuleException;
use Codeception\Exception\ModuleConfig as ModuleConfigException;
use Codeception\Configuration as Configuration;
class Db extends Module implements DbInterface
{
/**
* @api
* @var
*/
public $dbh;
/**
* @var array
*/
protected $sql = [];
/**
* @var array
*/
protected $config = [
'populate' => true,
'cleanup' => true,
'dump' => null
];
/**
* @var bool
*/
protected $populated = false;
/**
* @var \Codeception\Lib\Driver\Db
*/
public $driver;
/**
* @var array
*/
protected $insertedIds = [];
/**
* @var array
*/
protected $requiredFields = ['dsn', 'user', 'password'];
public function _initialize()
{
if ($this->config['dump'] && ($this->config['cleanup'] or ($this->config['populate']))) {
if (!file_exists(Configuration::projectDir() . $this->config['dump'])) {
throw new ModuleConfigException(
__CLASS__,
"\nFile with dump doesn't exist.
Please, check path for sql file: " . $this->config['dump']
);
}
$sql = file_get_contents(Configuration::projectDir() . $this->config['dump']);
$sql = preg_replace('%/\*(?!!\d+)(?:(?!\*/).)*\*/%s', "", $sql);
if (!empty($sql)) {
$this->sql = explode("\n", $sql);
}
}
try {
$this->driver = Driver::create($this->config['dsn'], $this->config['user'], $this->config['password']);
} catch (\PDOException $e) {
$message = $e->getMessage();
if ($message === 'could not find driver') {
list ($missingDriver,) = explode(':', $this->config['dsn'],2);
$message = "could not find $missingDriver driver";
}
throw new ModuleException(__CLASS__, $message . ' while creating PDO connection');
}
$this->dbh = $this->driver->getDbh();
// starting with loading dump
if ($this->config['populate']) {
if ($this->config['cleanup']) {
$this->cleanup();
}
$this->loadDump();
$this->populated = true;
}
}
public function _before(TestCase $test)
{
if ($this->config['cleanup'] && !$this->populated) {
$this->cleanup();
$this->loadDump();
}
parent::_before($test);
}
public function _after(TestCase $test)
{
$this->populated = false;
$this->removeInserted();
parent::_after($test);
}
protected function removeInserted()
{
foreach (array_reverse($this->insertedIds) as $insertId) {
try {
$this->driver->deleteQuery($insertId['table'], $insertId['id'], $insertId['primary']);
} catch (\Exception $e) {
$this->debug("coudn't delete record {$insertId['id']} from {$insertId['table']}");
}
}
$this->insertedIds = [];
}
protected function cleanup()
{
$dbh = $this->driver->getDbh();
if (!$dbh) {
throw new ModuleConfigException(
__CLASS__,
"No connection to database. Remove this module from config if you don't need database repopulation"
);
}
try {
// don't clear database for empty dump
if (!count($this->sql)) {
return;
}
$this->driver->cleanup();
} catch (\Exception $e) {
throw new ModuleException(__CLASS__, $e->getMessage());
}
}
protected function loadDump()
{
if (!$this->sql) {
return;
}
try {
$this->driver->load($this->sql);
} catch (\PDOException $e) {
throw new ModuleException(
__CLASS__,
$e->getMessage() . "\nSQL query being executed: " . $this->driver->sqlToRun
);
}
}
/**
* Inserts SQL record into database. This record will be erased after the test.
*
* ``` php
* <?php
* $I->haveInDatabase('users', array('name' => 'miles', 'email' => 'miles@davis.com'));
* ?>
* ```
*
* @param $table
* @param array $data
*
* @return integer $id
*/
public function haveInDatabase($table, array $data)
{
$query = $this->driver->insert($table, $data);
$this->debugSection('Query', $query);
$sth = $this->driver->getDbh()->prepare($query);
if (!$sth) {
$this->fail("Query '$query' can't be executed.");
}
$i = 1;
foreach ($data as $val) {
$sth->bindValue($i, $val);
$i++;
}
$res = $sth->execute();
if (!$res) {
$this->fail(sprintf("Record with %s couldn't be inserted into %s", json_encode($data), $table));
}
try {
$lastInsertId = (int) $this->driver->lastInsertId($table);
} catch (\PDOException $e) {
// ignore errors due to uncommon DB structure,
// such as tables without _id_seq in PGSQL
$lastInsertId = 0;
}
$this->insertedIds[] = [
'table' => $table,
'id' => $lastInsertId,
'primary' => $this->driver->getPrimaryColumn($table)
];
return $lastInsertId;
}
public function seeInDatabase($table, $criteria = [])
{
$res = $this->proceedSeeInDatabase($table, 'count(*)', $criteria);
$this->assertGreaterThan(0, (int) $res, 'No matching records found');
}
public function dontSeeInDatabase($table, $criteria = [])
{
$res = $this->proceedSeeInDatabase($table, 'count(*)', $criteria);
$this->assertLessThan(1, (int) $res);
}
protected function proceedSeeInDatabase($table, $column, $criteria)
{
$query = $this->driver->select($column, $table, $criteria);
$this->debugSection('Query', $query, json_encode($criteria));
$sth = $this->driver->getDbh()->prepare($query);
if (!$sth) {
$this->fail("Query '$query' can't be executed.");
}
$sth->execute(array_values($criteria));
return $sth->fetchColumn();
}
public function grabFromDatabase($table, $column, $criteria = [])
{
return $this->proceedSeeInDatabase($table, $column, $criteria);
}
}