Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 363 lines (342 sloc) 12.055 kB
dd334c0 refactored test framework.
qiang.xue authored
1 <?php
ed259c3 Finished all test framework classes.
qiang.xue authored
2 /**
3 * This file contains the CDbFixtureManager class.
4 *
5 * @author Qiang Xue <qiang.xue@gmail.com>
6 * @link http://www.yiiframework.com/
4be0af6 changed copyright year.
qiang.xue authored
7 * @copyright Copyright &copy; 2008-2011 Yii Software LLC
ed259c3 Finished all test framework classes.
qiang.xue authored
8 * @license http://www.yiiframework.com/license/
9 */
dd334c0 refactored test framework.
qiang.xue authored
10
ed259c3 Finished all test framework classes.
qiang.xue authored
11 /**
12 * CDbFixtureManager manages database fixtures during tests.
13 *
14 * A fixture represents a list of rows for a specific table. For a test method,
15 * using a fixture means that at the begin of the method, the table has and only
16 * has the rows that are given in the fixture. Therefore, the table's state is
17 * predictable.
18 *
19 * A fixture is represented as a PHP script whose name (without suffix) is the
20 * same as the table name (if schema name is needed, it should be prefixed to
21 * the table name). The PHP script returns an array representing a list of table
22 * rows. Each row is an associative array of column values indexed by column names.
23 *
24 * A fixture can be associated with an init script which sits under the same fixture
25 * directory and is named as "TableName.init.php". The init script is used to
26 * initialize the table before populating the fixture data into the table.
27 * If the init script does not exist, the table will be emptied.
28 *
29 * Fixtures must be stored under the {@link basePath} directory. The directory
c3bdff4 * Added phpunit-based testing framework.
qiang.xue authored
30 * may contain a file named "init.php" which will be executed once to initialize
31 * the database. If this file is not found, all available fixtures will be loaded
32 * into the database.
ed259c3 Finished all test framework classes.
qiang.xue authored
33 *
646cbb2 Documented component accessors with @property for significantly bette…
alexander.makarow authored
34 * @property CDbConnection $dbConnection The database connection.
35 * @property array $fixtures The information of the available fixtures (table name => fixture file).
36 *
ed259c3 Finished all test framework classes.
qiang.xue authored
37 * @author Qiang Xue <qiang.xue@gmail.com>
38 * @package system.test
39 * @since 1.1
40 */
dd334c0 refactored test framework.
qiang.xue authored
41 class CDbFixtureManager extends CApplicationComponent
42 {
43 /**
18787dd
qiang.xue authored
44 * @var string the name of the initialization script that would be executed before the whole test set runs.
45 * Defaults to 'init.php'. If the script does not exist, every table with a fixture file will be reset.
dd334c0 refactored test framework.
qiang.xue authored
46 */
18787dd
qiang.xue authored
47 public $initScript='init.php';
dd334c0 refactored test framework.
qiang.xue authored
48 /**
18787dd
qiang.xue authored
49 * @var string the suffix for fixture initialization scripts.
50 * If a table is associated with such a script whose name is TableName suffixed this property value,
51 * then the script will be executed each time before the table is reset.
dd334c0 refactored test framework.
qiang.xue authored
52 */
18787dd
qiang.xue authored
53 public $initScriptSuffix='.init.php';
dd334c0 refactored test framework.
qiang.xue authored
54 /**
55 * @var string the base path containing all fixtures. Defaults to null, meaning
56 * the path 'protected/tests/fixtures'.
57 */
58 public $basePath;
59 /**
60 * @var string the ID of the database connection. Defaults to 'db'.
ed259c3 Finished all test framework classes.
qiang.xue authored
61 * Note, data in this database may be deleted or modified during testing.
dd334c0 refactored test framework.
qiang.xue authored
62 * Make sure you have a backup database.
63 */
64 public $connectionID='db';
65 /**
66 * @var array list of database schemas that the test tables may reside in. Defaults to
67 * array(''), meaning using the default schema (an empty string refers to the
ed259c3 Finished all test framework classes.
qiang.xue authored
68 * default schema). This property is mainly used when turning on and off integrity checks
69 * so that fixture data can be populated into the database without causing problem.
dd334c0 refactored test framework.
qiang.xue authored
70 */
71 public $schemas=array('');
72
73 private $_db;
74 private $_fixtures;
75 private $_rows; // fixture name, row alias => row
76 private $_records; // fixture name, row alias => record (or class name)
77
78
79 /**
80 * Initializes this application component.
81 */
82 public function init()
83 {
84 parent::init();
85 if($this->basePath===null)
86 $this->basePath=Yii::getPathOfAlias('application.tests.fixtures');
c3bdff4 * Added phpunit-based testing framework.
qiang.xue authored
87 $this->prepare();
dd334c0 refactored test framework.
qiang.xue authored
88 }
89
90 /**
91 * Returns the database connection used to load fixtures.
92 * @return CDbConnection the database connection
93 */
94 public function getDbConnection()
95 {
96 if($this->_db===null)
97 {
98 $this->_db=Yii::app()->getComponent($this->connectionID);
99 if(!$this->_db instanceof CDbConnection)
100 throw new CException(Yii::t('yii','CDbTestFixture.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
101 array('{id}'=>$this->connectionID)));
102 }
103 return $this->_db;
104 }
105
106 /**
107 * Prepares the fixtures for the whole test.
c3bdff4 * Added phpunit-based testing framework.
qiang.xue authored
108 * This method is invoked in {@link init}. It executes the database init script
109 * if it exists. Otherwise, it will load all available fixtures.
dd334c0 refactored test framework.
qiang.xue authored
110 */
111 public function prepare()
112 {
18787dd
qiang.xue authored
113 $initFile=$this->basePath . DIRECTORY_SEPARATOR . $this->initScript;
dd334c0 refactored test framework.
qiang.xue authored
114
115 $this->checkIntegrity(false);
116
117 if(is_file($initFile))
118 require($initFile);
c3bdff4 * Added phpunit-based testing framework.
qiang.xue authored
119 else
120 {
cf7f06d (Fixes issue 1046)
qiang.xue authored
121 foreach($this->getFixtures() as $tableName=>$fixturePath)
122 {
123 $this->resetTable($tableName);
124 $this->loadFixture($tableName);
125 }
c3bdff4 * Added phpunit-based testing framework.
qiang.xue authored
126 }
dd334c0 refactored test framework.
qiang.xue authored
127 $this->checkIntegrity(true);
128 }
129
130 /**
131 * Resets the table to the state that it contains no fixture data.
132 * If there is an init script named "tests/fixtures/TableName.init.php",
ed259c3 Finished all test framework classes.
qiang.xue authored
133 * the script will be executed.
dd334c0 refactored test framework.
qiang.xue authored
134 * Otherwise, {@link truncateTable} will be invoked to delete all rows in the table
135 * and reset primary key sequence, if any.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
136 * @param string $tableName the table name
dd334c0 refactored test framework.
qiang.xue authored
137 */
138 public function resetTable($tableName)
139 {
18787dd
qiang.xue authored
140 $initFile=$this->basePath . DIRECTORY_SEPARATOR . $tableName . $this->initScriptSuffix;
dd334c0 refactored test framework.
qiang.xue authored
141 if(is_file($initFile))
142 require($initFile);
143 else
144 $this->truncateTable($tableName);
145 }
146
147 /**
148 * Loads the fixture for the specified table.
149 * This method will insert rows given in the fixture into the corresponding table.
150 * The loaded rows will be returned by this method.
151 * If the table has auto-incremental primary key, each row will contain updated primary key value.
ed259c3 Finished all test framework classes.
qiang.xue authored
152 * If the fixture does not exist, this method will return false.
dd334c0 refactored test framework.
qiang.xue authored
153 * Note, you may want to call {@link resetTable} before calling this method
154 * so that the table is emptied first.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
155 * @param string $tableName table name
dd334c0 refactored test framework.
qiang.xue authored
156 * @return array the loaded fixture rows indexed by row aliases (if any).
157 * False is returned if the table does not have a fixture.
158 */
159 public function loadFixture($tableName)
160 {
161 $fileName=$this->basePath.DIRECTORY_SEPARATOR.$tableName.'.php';
162 if(!is_file($fileName))
163 return false;
164
165 $rows=array();
166 $schema=$this->getDbConnection()->getSchema();
167 $builder=$schema->getCommandBuilder();
168 $table=$schema->getTable($tableName);
169
170 foreach(require($fileName) as $alias=>$row)
171 {
172 $builder->createInsertCommand($table,$row)->execute();
173 $primaryKey=$table->primaryKey;
174 if($table->sequenceName!==null)
175 {
176 if(is_string($primaryKey) && !isset($row[$primaryKey]))
177 $row[$primaryKey]=$builder->getLastInsertID($table);
4867238 @creocoder else if => elseif
creocoder authored
178 elseif(is_array($primaryKey))
dd334c0 refactored test framework.
qiang.xue authored
179 {
180 foreach($primaryKey as $pk)
181 {
182 if(!isset($row[$pk]))
183 {
184 $row[$pk]=$builder->getLastInsertID($table);
185 break;
186 }
187 }
188 }
189 }
190 $rows[$alias]=$row;
191 }
192 return $rows;
193 }
194
195 /**
cf7f06d (Fixes issue 1046)
qiang.xue authored
196 * Returns the information of the available fixtures.
197 * This method will search for all PHP files under {@link basePath}.
198 * If a file's name is the same as a table name, it is considered to be the fixture data for that table.
199 * @return array the information of the available fixtures (table name => fixture file)
dd334c0 refactored test framework.
qiang.xue authored
200 */
201 public function getFixtures()
202 {
203 if($this->_fixtures===null)
204 {
205 $this->_fixtures=array();
206 $schema=$this->getDbConnection()->getSchema();
207 $folder=opendir($this->basePath);
18787dd
qiang.xue authored
208 $suffixLen=strlen($this->initScriptSuffix);
dd334c0 refactored test framework.
qiang.xue authored
209 while($file=readdir($folder))
210 {
18787dd
qiang.xue authored
211 if($file==='.' || $file==='..' || $file===$this->initScript)
dd334c0 refactored test framework.
qiang.xue authored
212 continue;
213 $path=$this->basePath.DIRECTORY_SEPARATOR.$file;
18787dd
qiang.xue authored
214 if(substr($file,-4)==='.php' && is_file($path) && substr($file,-$suffixLen)!==$this->initScriptSuffix)
dd334c0 refactored test framework.
qiang.xue authored
215 {
216 $tableName=substr($file,0,-4);
217 if($schema->getTable($tableName)!==null)
218 $this->_fixtures[$tableName]=$path;
219 }
220 }
221 closedir($folder);
222 }
223 return $this->_fixtures;
224 }
225
226 /**
227 * Enables or disables database integrity check.
228 * This method may be used to temporarily turn off foreign constraints check.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
229 * @param boolean $check whether to enable database integrity check
dd334c0 refactored test framework.
qiang.xue authored
230 */
231 public function checkIntegrity($check)
232 {
233 foreach($this->schemas as $schema)
234 $this->getDbConnection()->getSchema()->checkIntegrity($check,$schema);
235 }
236
237 /**
238 * Removes all rows from the specified table and resets its primary key sequence, if any.
239 * You may need to call {@link checkIntegrity} to turn off integrity check temporarily
240 * before you call this method.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
241 * @param string $tableName the table name
dd334c0 refactored test framework.
qiang.xue authored
242 */
243 public function truncateTable($tableName)
244 {
245 $db=$this->getDbConnection();
246 $schema=$db->getSchema();
247 if(($table=$schema->getTable($tableName))!==null)
248 {
249 $db->createCommand('DELETE FROM '.$table->rawName)->execute();
250 $schema->resetSequence($table,1);
251 }
252 else
ed259c3 Finished all test framework classes.
qiang.xue authored
253 throw new CException("Table '$tableName' does not exist.");
dd334c0 refactored test framework.
qiang.xue authored
254 }
255
256 /**
257 * Truncates all tables in the specified schema.
258 * You may need to call {@link checkIntegrity} to turn off integrity check temporarily
259 * before you call this method.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
260 * @param string $schema the schema name. Defaults to empty string, meaning the default database schema.
dd334c0 refactored test framework.
qiang.xue authored
261 * @see truncateTable
262 */
263 public function truncateTables($schema='')
264 {
265 $tableNames=$this->getDbConnection()->getSchema()->getTableNames($schema);
266 foreach($tableNames as $tableName)
267 $this->truncateTable($tableName);
268 }
269
270 /**
271 * Loads the specified fixtures.
272 * For each fixture, the corresponding table will be reset first by calling
273 * {@link resetTable} and then be populated with the fixture data.
274 * The loaded fixture data may be later retrieved using {@link getRows}
275 * and {@link getRecord}.
ed259c3 Finished all test framework classes.
qiang.xue authored
276 * Note, if a table does not have fixture data, {@link resetTable} will still
277 * be called to reset the table.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
278 * @param array $fixtures fixtures to be loaded. The array keys are fixture names,
dd334c0 refactored test framework.
qiang.xue authored
279 * and the array values are either AR class names or table names.
280 * If table names, they must begin with a colon character (e.g. 'Post'
281 * means an AR class, while ':Post' means a table name).
282 */
283 public function load($fixtures)
284 {
285 $schema=$this->getDbConnection()->getSchema();
286 $schema->checkIntegrity(false);
287
288 $this->_rows=array();
289 $this->_records=array();
290 foreach($fixtures as $fixtureName=>$tableName)
291 {
292 if($tableName[0]===':')
293 {
294 $tableName=substr($tableName,1);
295 unset($modelClass);
296 }
297 else
298 {
299 $modelClass=Yii::import($tableName,true);
300 $tableName=CActiveRecord::model($modelClass)->tableName();
301 }
e4c958f @resurtm Table name in fixtures list enclosed into double curly brackets (e.g.…
resurtm authored
302 if(($prefix=$this->getDbConnection()->tablePrefix)!==null)
303 $tableName=preg_replace('/{{(.*?)}}/',$prefix.'\1',$tableName);
dd334c0 refactored test framework.
qiang.xue authored
304 $this->resetTable($tableName);
305 $rows=$this->loadFixture($tableName);
306 if(is_array($rows) && is_string($fixtureName))
307 {
308 $this->_rows[$fixtureName]=$rows;
309 if(isset($modelClass))
310 {
311 foreach(array_keys($rows) as $alias)
312 $this->_records[$fixtureName][$alias]=$modelClass;
313 }
314 }
315 }
316
317 $schema->checkIntegrity(true);
318 }
319
ed259c3 Finished all test framework classes.
qiang.xue authored
320 /**
321 * Returns the fixture data rows.
322 * The rows will have updated primary key values if the primary key is auto-incremental.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
323 * @param string $name the fixture name
ed259c3 Finished all test framework classes.
qiang.xue authored
324 * @return array the fixture data rows. False is returned if there is no such fixture data.
325 */
dd334c0 refactored test framework.
qiang.xue authored
326 public function getRows($name)
327 {
328 if(isset($this->_rows[$name]))
329 return $this->_rows[$name];
330 else
331 return false;
332 }
333
ed259c3 Finished all test framework classes.
qiang.xue authored
334 /**
335 * Returns the specified ActiveRecord instance in the fixture data.
72b9745 Updated PHPDoc @param parameter names
mdomba authored
336 * @param string $name the fixture name
337 * @param string $alias the alias for the fixture data row
ed259c3 Finished all test framework classes.
qiang.xue authored
338 * @return CActiveRecord the ActiveRecord instance. False is returned if there is no such fixture row.
339 */
dd334c0 refactored test framework.
qiang.xue authored
340 public function getRecord($name,$alias)
341 {
342 if(isset($this->_records[$name][$alias]))
343 {
344 if(is_string($this->_records[$name][$alias]))
345 {
346 $row=$this->_rows[$name][$alias];
347 $model=CActiveRecord::model($this->_records[$name][$alias]);
348 $key=$model->getTableSchema()->primaryKey;
349 if(is_string($key))
350 $pk=$row[$key];
351 else
352 {
353 foreach($key as $k)
354 $pk[$k]=$row[$k];
355 }
356 $this->_records[$name][$alias]=$model->findByPk($pk);
357 }
358 return $this->_records[$name][$alias];
359 }
360 else
361 return false;
362 }
363 }
Something went wrong with that request. Please try again.