/
CakeTestFixture.php
328 lines (299 loc) · 9.2 KB
/
CakeTestFixture.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
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
<?php
/**
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.TestSuite.Fixture
* @since CakePHP(tm) v 1.2.0.4667
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeSchema', 'Model');
/**
* CakeTestFixture is responsible for building and destroying tables to be used
* during testing.
*
* @package Cake.TestSuite.Fixture
*/
class CakeTestFixture {
/**
* Name of the object
*
* @var string
*/
public $name = null;
/**
* CakePHP's DBO driver (e.g: DboMysql).
*
* @var object
*/
public $db = null;
/**
* Fixture Datasource
*
* @var string
*/
public $useDbConfig = 'test';
/**
* Full Table Name
*
* @var string
*/
public $table = null;
/**
* List of datasources where this fixture has been created
*
* @var array
*/
public $created = array();
/**
* Fields / Schema for the fixture.
* This array should match the output of Model::schema()
*
* @var array
*/
public $fields = array();
/**
* Fixture records to be inserted.
*
* @var array
*/
public $records = array();
/**
* The primary key for the table this fixture represents.
*
* @var string
*/
public $primaryKey = null;
/**
* Fixture data can be stored in memory by default.
* When table is created for a fixture the MEMORY engine is used
* where possible. Set $canUseMemory to false if you don't want this.
*
* @var bool
*/
public $canUseMemory = true;
/**
* Instantiate the fixture.
*
* @throws CakeException on invalid datasource usage.
*/
public function __construct() {
if ($this->name === null) {
if (preg_match('/^(.*)Fixture$/', get_class($this), $matches)) {
$this->name = $matches[1];
} else {
$this->name = get_class($this);
}
}
$connection = 'test';
if (!empty($this->useDbConfig)) {
$connection = $this->useDbConfig;
if (strpos($connection, 'test') !== 0) {
$message = __d(
'cake_dev',
'Invalid datasource name "%s" for "%s" fixture. Fixture datasource names must begin with "test".',
$connection,
$this->name
);
throw new CakeException($message);
}
}
$this->Schema = new CakeSchema(array('name' => 'TestSuite', 'connection' => $connection));
$this->init();
}
/**
* Initialize the fixture.
*
* @return void
* @throws MissingModelException Whe importing from a model that does not exist.
*/
public function init() {
if (isset($this->import) && (is_string($this->import) || is_array($this->import))) {
$import = array_merge(
array('connection' => 'default', 'records' => false),
is_array($this->import) ? $this->import : array('model' => $this->import)
);
$this->Schema->connection = $import['connection'];
if (isset($import['model'])) {
list($plugin, $modelClass) = pluginSplit($import['model'], true);
App::uses($modelClass, $plugin . 'Model');
if (!class_exists($modelClass)) {
throw new MissingModelException(array('class' => $modelClass));
}
$model = new $modelClass(null, null, $import['connection']);
$db = $model->getDataSource();
if (empty($model->tablePrefix)) {
$model->tablePrefix = $db->config['prefix'];
}
$this->fields = $model->schema(true);
$this->fields[$model->primaryKey]['key'] = 'primary';
$this->table = $db->fullTableName($model, false, false);
$this->primaryKey = $model->primaryKey;
ClassRegistry::config(array('ds' => 'test'));
ClassRegistry::flush();
} elseif (isset($import['table'])) {
$model = new Model(null, $import['table'], $import['connection']);
$db = ConnectionManager::getDataSource($import['connection']);
$db->cacheSources = false;
$model->useDbConfig = $import['connection'];
$model->name = Inflector::camelize(Inflector::singularize($import['table']));
$model->table = $import['table'];
$model->tablePrefix = $db->config['prefix'];
$this->fields = $model->schema(true);
$this->primaryKey = $model->primaryKey;
ClassRegistry::flush();
}
if (!empty($db->config['prefix']) && strpos($this->table, $db->config['prefix']) === 0) {
$this->table = str_replace($db->config['prefix'], '', $this->table);
}
if (isset($import['records']) && $import['records'] !== false && isset($model) && isset($db)) {
$this->records = array();
$query = array(
'fields' => $db->fields($model, null, array_keys($this->fields)),
'table' => $db->fullTableName($model),
'alias' => $model->alias,
'conditions' => array(),
'order' => null,
'limit' => null,
'group' => null
);
$records = $db->fetchAll($db->buildStatement($query, $model), false, $model->alias);
if ($records !== false && !empty($records)) {
$this->records = Hash::extract($records, '{n}.' . $model->alias);
}
}
}
if (!isset($this->table)) {
$this->table = Inflector::underscore(Inflector::pluralize($this->name));
}
if (!isset($this->primaryKey) && isset($this->fields['id'])) {
$this->primaryKey = 'id';
}
}
/**
* Run before all tests execute, should return SQL statement to create table for this fixture could be executed successfully.
*
* @param DboSource $db An instance of the database object used to create the fixture table
* @return bool True on success, false on failure
*/
public function create($db) {
if (!isset($this->fields) || empty($this->fields)) {
return false;
}
if (empty($this->fields['tableParameters']['engine'])) {
$canUseMemory = $this->canUseMemory;
foreach ($this->fields as $args) {
if (is_string($args)) {
$type = $args;
} elseif (!empty($args['type'])) {
$type = $args['type'];
} else {
continue;
}
if (in_array($type, array('blob', 'text', 'binary'))) {
$canUseMemory = false;
break;
}
}
if ($canUseMemory) {
$this->fields['tableParameters']['engine'] = 'MEMORY';
}
}
$this->Schema->build(array($this->table => $this->fields));
try {
$db->execute($db->createSchema($this->Schema), array('log' => false));
$this->created[] = $db->configKeyName;
} catch (Exception $e) {
$msg = __d(
'cake_dev',
'Fixture creation for "%s" failed "%s"',
$this->table,
$e->getMessage()
);
CakeLog::error($msg);
trigger_error($msg, E_USER_WARNING);
return false;
}
return true;
}
/**
* Run after all tests executed, should return SQL statement to drop table for this fixture.
*
* @param DboSource $db An instance of the database object used to create the fixture table
* @return bool True on success, false on failure
*/
public function drop($db) {
if (empty($this->fields)) {
return false;
}
$this->Schema->build(array($this->table => $this->fields));
try {
$db->execute($db->dropSchema($this->Schema), array('log' => false));
$this->created = array_diff($this->created, array($db->configKeyName));
} catch (Exception $e) {
return false;
}
return true;
}
/**
* Run before each tests is executed, should return a set of SQL statements to insert records for the table
* of this fixture could be executed successfully.
*
* @param DboSource $db An instance of the database into which the records will be inserted
* @return bool on success or if there are no records to insert, or false on failure
* @throws CakeException if counts of values and fields do not match.
*/
public function insert($db) {
if (!isset($this->_insert)) {
$values = array();
if (isset($this->records) && !empty($this->records)) {
$fields = array();
foreach ($this->records as $record) {
$fields = array_merge($fields, array_keys(array_intersect_key($record, $this->fields)));
}
$fields = array_unique($fields);
$default = array_fill_keys($fields, null);
foreach ($this->records as $record) {
$merge = array_values(array_merge($default, $record));
if (count($fields) !== count($merge)) {
throw new CakeException('Fixture invalid: Count of fields does not match count of values in ' . get_class($this));
}
$values[] = $merge;
}
$nested = $db->useNestedTransactions;
$db->useNestedTransactions = false;
$result = $db->insertMulti($this->table, $fields, $values);
if (
$this->primaryKey &&
isset($this->fields[$this->primaryKey]['type']) &&
in_array($this->fields[$this->primaryKey]['type'], array('integer', 'biginteger'))
) {
$db->resetSequence($this->table, $this->primaryKey);
}
$db->useNestedTransactions = $nested;
return $result;
}
return true;
}
}
/**
* Truncates the current fixture. Can be overwritten by classes extending
* CakeFixture to trigger other events before / after truncate.
*
* @param DboSource $db A reference to a db instance
* @return bool
*/
public function truncate($db) {
$fullDebug = $db->fullDebug;
$db->fullDebug = false;
$return = $db->truncate($this->table);
$db->fullDebug = $fullDebug;
return $return;
}
}