CDbFixtureManager

优质
小牛编辑
131浏览
2023-12-01
所有包 | 属性 | 方法
system.test
继承class CDbFixtureManager » CApplicationComponent » CComponent
实现IApplicationComponent
源自1.1
版本$Id: CDbFixtureManager.php 3426 2011-10-25 00:01:09Z alexander.makarow $
源码framework/test/CDbFixtureManager.php
CDbFixtureManager manages database fixtures during tests.

A fixture represents a list of rows for a specific table. For a test method, using a fixture means that at the begin of the method, the table has and only has the rows that are given in the fixture. Therefore, the table's state is predictable.

A fixture is represented as a PHP script whose name (without suffix) is the same as the table name (if schema name is needed, it should be prefixed to the table name). The PHP script returns an array representing a list of table rows. Each row is an associative array of column values indexed by column names.

A fixture can be associated with an init script which sits under the same fixture directory and is named as "TableName.init.php". The init script is used to initialize the table before populating the fixture data into the table. If the init script does not exist, the table will be emptied.

Fixtures must be stored under the basePath directory. The directory may contain a file named "init.php" which will be executed once to initialize the database. If this file is not found, all available fixtures will be loaded into the database.

公共属性

隐藏继承属性

属性类型描述定义在
basePathstringthe base path containing all fixtures.CDbFixtureManager
behaviorsarray这个应用组件附加的行为。 这此行为将在应用组件调用init时附加在应用组件上。 请参照CModel::behaviors如何指定此属性值。CApplicationComponent
connectionIDstringthe ID of the database connection.CDbFixtureManager
dbConnectionCDbConnectionReturns the database connection used to load fixtures.CDbFixtureManager
fixturesarrayReturns the information of the available fixtures.CDbFixtureManager
initScriptstringthe name of the initialization script that would be executed before the whole test set runs.CDbFixtureManager
initScriptSuffixstringthe suffix for fixture initialization scripts.CDbFixtureManager
isInitializedboolean检查应用组件是否已经初始化。CApplicationComponent
schemasarraylist of database schemas that the test tables may reside in.CDbFixtureManager

公共方法

隐藏继承方法

方法描述定义在
__call()如果类中没有调的方法名,则调用这个方法。CComponent
__get()返回一个属性值、一个事件处理程序列表或一个行为名称。CComponent
__isset()检查一个属性是否为null。CComponent
__set()设置一个组件的属性值。CComponent
__unset()设置一个组件的属性为null。CComponent
asa()返回这个名字的行为对象。CComponent
attachBehavior()附加一个行为到组件。CComponent
attachBehaviors()附加一个行为列表到组件。CComponent
attachEventHandler()为事件附加一个事件处理程序。CComponent
canGetProperty()确定属性是否可读。CComponent
canSetProperty()确定属性是否可写。CComponent
checkIntegrity()Enables or disables database integrity check.CDbFixtureManager
detachBehavior()从组件中分离一个行为。CComponent
detachBehaviors()从组件中分离所有行为。CComponent
detachEventHandler()分离一个存在的事件处理程序。CComponent
disableBehavior()禁用一个附加行为。CComponent
disableBehaviors()禁用组件附加的所有行为。CComponent
enableBehavior()启用一个附加行为。CComponent
enableBehaviors()启用组件附加的所有行为。CComponent
evaluateExpression()计算一个PHP表达式,或根据组件上下文执行回调。CComponent
getDbConnection()Returns the database connection used to load fixtures.CDbFixtureManager
getEventHandlers()返回一个事件的附加处理程序列表。CComponent
getFixtures()Returns the information of the available fixtures.CDbFixtureManager
getIsInitialized()检查应用组件是否已经初始化。CApplicationComponent
getRecord()Returns the specified ActiveRecord instance in the fixture data.CDbFixtureManager
getRows()Returns the fixture data rows.CDbFixtureManager
hasEvent()确定一个事件是否定义。CComponent
hasEventHandler()检查事件是否有附加的处理程序。CComponent
hasProperty()确定属性是否被定义。CComponent
init()Initializes this application component.CDbFixtureManager
load()Loads the specified fixtures.CDbFixtureManager
loadFixture()Loads the fixture for the specified table.CDbFixtureManager
prepare()Prepares the fixtures for the whole test.CDbFixtureManager
raiseEvent()发起一个事件。CComponent
resetTable()Resets the table to the state that it contains no fixture data.CDbFixtureManager
truncateTable()Removes all rows from the specified table and resets its primary key sequence, if any.CDbFixtureManager
truncateTables()Truncates all tables in the specified schema.CDbFixtureManager

属性详细

basePath 属性 public string $basePath;

the base path containing all fixtures. Defaults to null, meaning the path 'protected/tests/fixtures'.

connectionID 属性 public string $connectionID;

the ID of the database connection. Defaults to 'db'. Note, data in this database may be deleted or modified during testing. Make sure you have a backup database.

dbConnection 属性 只读 public CDbConnection getDbConnection()

Returns the database connection used to load fixtures.

fixtures 属性 只读 public array getFixtures()

Returns the information of the available fixtures. This method will search for all PHP files under basePath. If a file's name is the same as a table name, it is considered to be the fixture data for that table.

initScript 属性 public string $initScript;

the name of the initialization script that would be executed before the whole test set runs. Defaults to 'init.php'. If the script does not exist, every table with a fixture file will be reset.

initScriptSuffix 属性 public string $initScriptSuffix;

the suffix for fixture initialization scripts. If a table is associated with such a script whose name is TableName suffixed this property value, then the script will be executed each time before the table is reset.

schemas 属性 public array $schemas;

list of database schemas that the test tables may reside in. Defaults to array(''), meaning using the default schema (an empty string refers to the default schema). This property is mainly used when turning on and off integrity checks so that fixture data can be populated into the database without causing problem.

方法详细

checkIntegrity() 方法
public void checkIntegrity(boolean $check)
$checkbooleanwhether to enable database integrity check
源码: framework/test/CDbFixtureManager.php#232 (显示) publicfunctioncheckIntegrity($check)
{
foreach($this->schemasas$schema)
$this->getDbConnection()->getSchema()->checkIntegrity($check,$schema);
}

Enables or disables database integrity check. This method may be used to temporarily turn off foreign constraints check.

getDbConnection() 方法
public CDbConnection getDbConnection()
{return}CDbConnectionthe database connection
源码: framework/test/CDbFixtureManager.php#95 (显示) publicfunctiongetDbConnection()
{
if($this->_db===null)
{
$this->_db=Yii::app()->getComponent($this->connectionID);
if(!$this->_dbinstanceofCDbConnection)
thrownewCException(Yii::t('yii','CDbTestFixture.connectionID"{id}"isinvalid.PleasemakesureitreferstotheIDofaCDbConnectionapplicationcomponent.',
array('{id}'=>$this->connectionID)));
}
return$this->_db;
}

Returns the database connection used to load fixtures.

getFixtures() 方法
public array getFixtures()
{return}arraythe information of the available fixtures (table name => fixture file)
源码: framework/test/CDbFixtureManager.php#202 (显示) publicfunctiongetFixtures()
{
if($this->_fixtures===null)
{
$this->_fixtures=array();
$schema=$this->getDbConnection()->getSchema();
$folder=opendir($this->basePath);
$suffixLen=strlen($this->initScriptSuffix);
while($file=readdir($folder))
{
if($file==='.'||$file==='..'||$file===$this->initScript)
continue;
$path=$this->basePath.DIRECTORY_SEPARATOR.$file;
if(substr($file,-4)==='.php'&&is_file($path)&&substr($file,-$suffixLen)!==$this->initScriptSuffix)
{
$tableName=substr($file,0,-4);
if($schema->getTable($tableName)!==null)
$this->_fixtures[$tableName]=$path;
}
}
closedir($folder);
}
return$this->_fixtures;
}

Returns the information of the available fixtures. This method will search for all PHP files under basePath. If a file's name is the same as a table name, it is considered to be the fixture data for that table.

getRecord() 方法
public CActiveRecord getRecord(string $name, string $alias)
$namestringthe fixture name
$aliasstringthe alias for the fixture data row
{return}CActiveRecordthe ActiveRecord instance. False is returned if there is no such fixture row.
源码: framework/test/CDbFixtureManager.php#341 (显示) publicfunctiongetRecord($name,$alias)
{
if(isset($this->_records[$name][$alias]))
{
if(is_string($this->_records[$name][$alias]))
{
$row=$this->_rows[$name][$alias];
$model=CActiveRecord::model($this->_records[$name][$alias]);
$key=$model->getTableSchema()->primaryKey;
if(is_string($key))
$pk=$row[$key];
else
{
foreach($keyas$k)
$pk[$k]=$row[$k];
}
$this->_records[$name][$alias]=$model->findByPk($pk);
}
return$this->_records[$name][$alias];
}
else
returnfalse;
}

Returns the specified ActiveRecord instance in the fixture data.

getRows() 方法
public array getRows(string $name)
$namestringthe fixture name
{return}arraythe fixture data rows. False is returned if there is no such fixture data.
源码: framework/test/CDbFixtureManager.php#327 (显示) publicfunctiongetRows($name)
{
if(isset($this->_rows[$name]))
return$this->_rows[$name];
else
returnfalse;
}

Returns the fixture data rows. The rows will have updated primary key values if the primary key is auto-incremental.

init() 方法
public void init()
源码: framework/test/CDbFixtureManager.php#83 (显示) publicfunctioninit()
{
parent::init();
if($this->basePath===null)
$this->basePath=Yii::getPathOfAlias('application.tests.fixtures');
$this->prepare();
}

Initializes this application component.

load() 方法
public void load(array $fixtures)
$fixturesarrayfixtures to be loaded. The array keys are fixture names, and the array values are either AR class names or table names. If table names, they must begin with a colon character (e.g. 'Post' means an AR class, while ':Post' means a table name).
源码: framework/test/CDbFixtureManager.php#284 (显示) publicfunctionload($fixtures)
{
$schema=$this->getDbConnection()->getSchema();
$schema->checkIntegrity(false);

$this->_rows=array();
$this->_records=array();
foreach($fixturesas$fixtureName=>$tableName)
{
if($tableName[0]===':')
{
$tableName=substr($tableName,1);
unset($modelClass);
}
else
{
$modelClass=Yii::import($tableName,true);
$tableName=CActiveRecord::model($modelClass)->tableName();
if(($prefix=$this->getDbConnection()->tablePrefix)!==null)
$tableName=preg_replace('/{{(.*?)}}/',$prefix.'1',$tableName);
}
$this->resetTable($tableName);
$rows=$this->loadFixture($tableName);
if(is_array($rows)&&is_string($fixtureName))
{
$this->_rows[$fixtureName]=$rows;
if(isset($modelClass))
{
foreach(array_keys($rows)as$alias)
$this->_records[$fixtureName][$alias]=$modelClass;
}
}
}

$schema->checkIntegrity(true);
}

Loads the specified fixtures. For each fixture, the corresponding table will be reset first by calling resetTable and then be populated with the fixture data. The loaded fixture data may be later retrieved using getRows and getRecord. Note, if a table does not have fixture data, resetTable will still be called to reset the table.

loadFixture() 方法
public array loadFixture(string $tableName)
$tableNamestringtable name
{return}arraythe loaded fixture rows indexed by row aliases (if any). False is returned if the table does not have a fixture.
源码: framework/test/CDbFixtureManager.php#160 (显示) publicfunctionloadFixture($tableName)
{
$fileName=$this->basePath.DIRECTORY_SEPARATOR.$tableName.'.php';
if(!is_file($fileName))
returnfalse;

$rows=array();
$schema=$this->getDbConnection()->getSchema();
$builder=$schema->getCommandBuilder();
$table=$schema->getTable($tableName);

foreach(require($fileName)as$alias=>$row)
{
$builder->createInsertCommand($table,$row)->execute();
$primaryKey=$table->primaryKey;
if($table->sequenceName!==null)
{
if(is_string($primaryKey)&&!isset($row[$primaryKey]))
$row[$primaryKey]=$builder->getLastInsertID($table);
elseif(is_array($primaryKey))
{
foreach($primaryKeyas$pk)
{
if(!isset($row[$pk]))
{
$row[$pk]=$builder->getLastInsertID($table);
break;
}
}
}
}
$rows[$alias]=$row;
}
return$rows;
}

Loads the fixture for the specified table. This method will insert rows given in the fixture into the corresponding table. The loaded rows will be returned by this method. If the table has auto-incremental primary key, each row will contain updated primary key value. If the fixture does not exist, this method will return false. Note, you may want to call resetTable before calling this method so that the table is emptied first.

prepare() 方法
public void prepare()
源码: framework/test/CDbFixtureManager.php#112 (显示) publicfunctionprepare()
{
$initFile=$this->basePath.DIRECTORY_SEPARATOR.$this->initScript;

$this->checkIntegrity(false);

if(is_file($initFile))
require($initFile);
else
{
foreach($this->getFixtures()as$tableName=>$fixturePath)
{
$this->resetTable($tableName);
$this->loadFixture($tableName);
}
}
$this->checkIntegrity(true);
}

Prepares the fixtures for the whole test. This method is invoked in init. It executes the database init script if it exists. Otherwise, it will load all available fixtures.

resetTable() 方法
public void resetTable(string $tableName)
$tableNamestringthe table name
源码: framework/test/CDbFixtureManager.php#139 (显示) publicfunctionresetTable($tableName)
{
$initFile=$this->basePath.DIRECTORY_SEPARATOR.$tableName.$this->initScriptSuffix;
if(is_file($initFile))
require($initFile);
else
$this->truncateTable($tableName);
}

Resets the table to the state that it contains no fixture data. If there is an init script named "tests/fixtures/TableName.init.php", the script will be executed. Otherwise, truncateTable will be invoked to delete all rows in the table and reset primary key sequence, if any.

truncateTable() 方法
public void truncateTable(string $tableName)
$tableNamestringthe table name
源码: framework/test/CDbFixtureManager.php#244 (显示) publicfunctiontruncateTable($tableName)
{
$db=$this->getDbConnection();
$schema=$db->getSchema();
if(($table=$schema->getTable($tableName))!==null)
{
$db->createCommand('DELETEFROM'.$table->rawName)->execute();
$schema->resetSequence($table,1);
}
else
thrownewCException("Table'$tableName'doesnotexist.");
}

Removes all rows from the specified table and resets its primary key sequence, if any. You may need to call checkIntegrity to turn off integrity check temporarily before you call this method.

truncateTables() 方法
public void truncateTables(string $schema='')
$schemastringthe schema name. Defaults to empty string, meaning the default database schema.
源码: framework/test/CDbFixtureManager.php#264 (显示) publicfunctiontruncateTables($schema='')
{
$tableNames=$this->getDbConnection()->getSchema()->getTableNames($schema);
foreach($tableNamesas$tableName)
$this->truncateTable($tableName);
}

Truncates all tables in the specified schema. You may need to call checkIntegrity to turn off integrity check temporarily before you call this method.

参见

  • truncateTable