CDbFixtureManager.php 12 KB

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