Yii Framework v1.1.10 绫诲弬鑰

CDbFixtureManager

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.

鍏叡灞炴

闅愯棌缁ф壙灞炴

灞炴绫诲瀷鎻忚堪瀹氫箟鍦
basePath string the base path containing all fixtures. CDbFixtureManager
behaviors array 杩欎釜搴旂敤缁勪欢闄勫姞鐨勮涓恒 杩欐琛屼负灏嗗湪搴旂敤缁勪欢璋冪敤init鏃堕檮鍔犲湪搴旂敤缁勪欢涓娿 璇峰弬鐓CModel::behaviors濡備綍鎸囧畾姝ゅ睘鎬у笺 CApplicationComponent
connectionID string the ID of the database connection. CDbFixtureManager
dbConnection CDbConnection Returns the database connection used to load fixtures. CDbFixtureManager
fixtures array Returns the information of the available fixtures. CDbFixtureManager
initScript string the name of the initialization script that would be executed before the whole test set runs. CDbFixtureManager
initScriptSuffix string the suffix for fixture initialization scripts. CDbFixtureManager
isInitialized boolean 妫鏌ュ簲鐢ㄧ粍浠舵槸鍚﹀凡缁忓垵濮嬪寲銆 CApplicationComponent
schemas array list 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() 璁$畻涓涓狿HP琛ㄨ揪寮忥紝鎴栨牴鎹粍浠朵笂涓嬫枃鎵ц鍥炶皟銆 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 灞炴 鍙

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)
$check boolean whether to enable database integrity check
婧愮爜锛 framework/test/CDbFixtureManager.php#232 (鏄剧ず)
public function checkIntegrity($check)
{
    foreach(
$this->schemas as $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} CDbConnection the database connection
婧愮爜锛 framework/test/CDbFixtureManager.php#95 (鏄剧ず)
public function getDbConnection()
{
    if(
$this->_db===null)
    {
        
$this->_db=Yii::app()->getComponent($this->connectionID);
        if(!
$this->_db instanceof CDbConnection)
            throw new 
CException(Yii::t('yii','CDbTestFixture.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
                array(
'{id}'=>$this->connectionID)));
    }
    return 
$this->_db;
}

Returns the database connection used to load fixtures.

getFixtures() 鏂规硶
public array getFixtures()
{return} array the information of the available fixtures (table name => fixture file)
婧愮爜锛 framework/test/CDbFixtureManager.php#202 (鏄剧ず)
public function getFixtures()
{
    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)
$name string the fixture name
$alias string the alias for the fixture data row
{return} CActiveRecord the ActiveRecord instance. False is returned if there is no such fixture row.
婧愮爜锛 framework/test/CDbFixtureManager.php#341 (鏄剧ず)
public function getRecord($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(
$key as $k)
                    
$pk[$k]=$row[$k];
            }
            
$this->_records[$name][$alias]=$model->findByPk($pk);
        }
        return 
$this->_records[$name][$alias];
    }
    else
        return 
false;
}

Returns the specified ActiveRecord instance in the fixture data.

getRows() 鏂规硶
public array getRows(string $name)
$name string the fixture name
{return} array the fixture data rows. False is returned if there is no such fixture data.
婧愮爜锛 framework/test/CDbFixtureManager.php#327 (鏄剧ず)
public function getRows($name)
{
    if(isset(
$this->_rows[$name]))
        return 
$this->_rows[$name];
    else
        return 
false;
}

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 (鏄剧ず)
public function init()
{
    
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)
$fixtures array fixtures 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 (鏄剧ず)
public function load($fixtures)
{
    
$schema=$this->getDbConnection()->getSchema();
    
$schema->checkIntegrity(false);

    
$this->_rows=array();
    
$this->_records=array();
    foreach(
$fixtures as $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)
$tableName string table name
{return} array the 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 (鏄剧ず)
public function loadFixture($tableName)
{
    
$fileName=$this->basePath.DIRECTORY_SEPARATOR.$tableName.'.php';
    if(!
is_file($fileName))
        return 
false;

    
$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);
            else if(
is_array($primaryKey))
            {
                foreach(
$primaryKey as $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 (鏄剧ず)
public function prepare()
{
    
$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)
$tableName string the table name
婧愮爜锛 framework/test/CDbFixtureManager.php#139 (鏄剧ず)
public function resetTable($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)
$tableName string the table name
婧愮爜锛 framework/test/CDbFixtureManager.php#244 (鏄剧ず)
public function truncateTable($tableName)
{
    
$db=$this->getDbConnection();
    
$schema=$db->getSchema();
    if((
$table=$schema->getTable($tableName))!==null)
    {
        
$db->createCommand('DELETE FROM '.$table->rawName)->execute();
        
$schema->resetSequence($table,1);
    }
    else
        throw new 
CException("Table '$tableName' does not exist.");
}

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='')
$schema string the schema name. Defaults to empty string, meaning the default database schema.
婧愮爜锛 framework/test/CDbFixtureManager.php#264 (鏄剧ず)
public function truncateTables($schema='')
{
    
$tableNames=$this->getDbConnection()->getSchema()->getTableNames($schema);
    foreach(
$tableNames as $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.

鍙傝

Copyright © 2008-2011 by Yii Software LLC
All Rights Reserved.