Initial commit

This commit is contained in:
mareksebera 2014-09-10 20:20:58 +02:00
commit 3b93da31de
1004 changed files with 265840 additions and 0 deletions

View file

@ -0,0 +1,306 @@
<?php
/**
* A factory class to manage the life cycle of test fixtures
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* 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://cakephp.org CakePHP(tm) Project
* @package Cake.TestSuite.Fixture
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConnectionManager', 'Model');
App::uses('ClassRegistry', 'Utility');
/**
* A factory class to manage the life cycle of test fixtures
*
* @package Cake.TestSuite.Fixture
*/
class CakeFixtureManager {
/**
* Was this class already initialized?
*
* @var bool
*/
protected $_initialized = false;
/**
* Default datasource to use
*
* @var DataSource
*/
protected $_db = null;
/**
* Holds the fixture classes that where instantiated
*
* @var array
*/
protected $_loaded = array();
/**
* Holds the fixture classes that where instantiated indexed by class name
*
* @var array
*/
protected $_fixtureMap = array();
/**
* Inspects the test to look for unloaded fixtures and loads them
*
* @param CakeTestCase $test the test case to inspect
* @return void
*/
public function fixturize($test) {
if (!$this->_initialized) {
ClassRegistry::config(array('ds' => 'test', 'testing' => true));
}
if (empty($test->fixtures) || !empty($this->_processed[get_class($test)])) {
$test->db = $this->_db;
return;
}
$this->_initDb();
$test->db = $this->_db;
if (!is_array($test->fixtures)) {
$test->fixtures = array_map('trim', explode(',', $test->fixtures));
}
if (isset($test->fixtures)) {
$this->_loadFixtures($test->fixtures);
}
$this->_processed[get_class($test)] = true;
}
/**
* Initializes this class with a DataSource object to use as default for all fixtures
*
* @return void
*/
protected function _initDb() {
if ($this->_initialized) {
return;
}
$db = ConnectionManager::getDataSource('test');
$db->cacheSources = false;
$this->_db = $db;
$this->_initialized = true;
}
/**
* Parse the fixture path included in test cases, to get the fixture class name, and the
* real fixture path including sub-directories
*
* @param string $fixturePath the fixture path to parse
* @return array containing fixture class name and optional additional path
*/
protected function _parseFixturePath($fixturePath) {
$pathTokenArray = explode('/', $fixturePath);
$fixture = array_pop($pathTokenArray);
$additionalPath = '';
foreach ($pathTokenArray as $pathToken) {
$additionalPath .= DS . $pathToken;
}
return array('fixture' => $fixture, 'additionalPath' => $additionalPath);
}
/**
* Looks for fixture files and instantiates the classes accordingly
*
* @param array $fixtures the fixture names to load using the notation {type}.{name}
* @return void
* @throws UnexpectedValueException when a referenced fixture does not exist.
*/
protected function _loadFixtures($fixtures) {
foreach ($fixtures as $fixture) {
$fixtureFile = null;
$fixtureIndex = $fixture;
if (isset($this->_loaded[$fixture])) {
continue;
}
if (strpos($fixture, 'core.') === 0) {
$fixture = substr($fixture, strlen('core.'));
$fixturePaths[] = CAKE . 'Test' . DS . 'Fixture';
} elseif (strpos($fixture, 'app.') === 0) {
$fixturePrefixLess = substr($fixture, strlen('app.'));
$fixtureParsedPath = $this->_parseFixturePath($fixturePrefixLess);
$fixture = $fixtureParsedPath['fixture'];
$fixturePaths = array(
TESTS . 'Fixture' . $fixtureParsedPath['additionalPath']
);
} elseif (strpos($fixture, 'plugin.') === 0) {
$explodedFixture = explode('.', $fixture, 3);
$pluginName = $explodedFixture[1];
$fixtureParsedPath = $this->_parseFixturePath($explodedFixture[2]);
$fixture = $fixtureParsedPath['fixture'];
$fixturePaths = array(
CakePlugin::path(Inflector::camelize($pluginName)) . 'Test' . DS . 'Fixture' . $fixtureParsedPath['additionalPath'],
TESTS . 'Fixture' . $fixtureParsedPath['additionalPath']
);
} else {
$fixturePaths = array(
TESTS . 'Fixture',
CAKE . 'Test' . DS . 'Fixture'
);
}
$loaded = false;
foreach ($fixturePaths as $path) {
$className = Inflector::camelize($fixture);
if (is_readable($path . DS . $className . 'Fixture.php')) {
$fixtureFile = $path . DS . $className . 'Fixture.php';
require_once $fixtureFile;
$fixtureClass = $className . 'Fixture';
$this->_loaded[$fixtureIndex] = new $fixtureClass();
$this->_fixtureMap[$fixtureClass] = $this->_loaded[$fixtureIndex];
$loaded = true;
break;
}
}
if (!$loaded) {
$firstPath = str_replace(array(APP, CAKE_CORE_INCLUDE_PATH, ROOT), '', $fixturePaths[0] . DS . $className . 'Fixture.php');
throw new UnexpectedValueException(__d('cake_dev', 'Referenced fixture class %s (%s) not found', $className, $firstPath));
}
}
}
/**
* Runs the drop and create commands on the fixtures if necessary.
*
* @param CakeTestFixture $fixture the fixture object to create
* @param DataSource $db the datasource instance to use
* @param bool $drop whether drop the fixture if it is already created or not
* @return void
*/
protected function _setupTable($fixture, $db = null, $drop = true) {
if (!$db) {
if (!empty($fixture->useDbConfig)) {
$db = ConnectionManager::getDataSource($fixture->useDbConfig);
} else {
$db = $this->_db;
}
}
if (!empty($fixture->created) && in_array($db->configKeyName, $fixture->created)) {
return;
}
$sources = (array)$db->listSources();
$table = $db->config['prefix'] . $fixture->table;
$exists = in_array($table, $sources);
if ($drop && $exists) {
$fixture->drop($db);
$fixture->create($db);
} elseif (!$exists) {
$fixture->create($db);
} else {
$fixture->created[] = $db->configKeyName;
}
}
/**
* Creates the fixtures tables and inserts data on them.
*
* @param CakeTestCase $test the test to inspect for fixture loading
* @return void
*/
public function load(CakeTestCase $test) {
if (empty($test->fixtures)) {
return;
}
$fixtures = $test->fixtures;
if (empty($fixtures) || !$test->autoFixtures) {
return;
}
foreach ($fixtures as $f) {
if (!empty($this->_loaded[$f])) {
$fixture = $this->_loaded[$f];
$db = ConnectionManager::getDataSource($fixture->useDbConfig);
$db->begin();
$this->_setupTable($fixture, $db, $test->dropTables);
$fixture->truncate($db);
$fixture->insert($db);
$db->commit();
}
}
}
/**
* Truncates the fixtures tables
*
* @param CakeTestCase $test the test to inspect for fixture unloading
* @return void
*/
public function unload(CakeTestCase $test) {
$fixtures = !empty($test->fixtures) ? $test->fixtures : array();
foreach (array_reverse($fixtures) as $f) {
if (isset($this->_loaded[$f])) {
$fixture = $this->_loaded[$f];
if (!empty($fixture->created)) {
foreach ($fixture->created as $ds) {
$db = ConnectionManager::getDataSource($ds);
$fixture->truncate($db);
}
}
}
}
}
/**
* Creates a single fixture table and loads data into it.
*
* @param string $name of the fixture
* @param DataSource $db DataSource instance or leave null to get DataSource from the fixture
* @param bool $dropTables Whether or not tables should be dropped and re-created.
* @return void
* @throws UnexpectedValueException if $name is not a previously loaded class
*/
public function loadSingle($name, $db = null, $dropTables = true) {
$name .= 'Fixture';
if (isset($this->_fixtureMap[$name])) {
$fixture = $this->_fixtureMap[$name];
if (!$db) {
$db = ConnectionManager::getDataSource($fixture->useDbConfig);
}
$this->_setupTable($fixture, $db, $dropTables);
$fixture->truncate($db);
$fixture->insert($db);
} else {
throw new UnexpectedValueException(__d('cake_dev', 'Referenced fixture class %s not found', $name));
}
}
/**
* Drop all fixture tables loaded by this class
*
* This will also close the session, as failing to do so will cause
* fatal errors with database sessions.
*
* @return void
*/
public function shutDown() {
if (session_id()) {
session_write_close();
}
foreach ($this->_loaded as $fixture) {
if (!empty($fixture->created)) {
foreach ($fixture->created as $ds) {
$db = ConnectionManager::getDataSource($ds);
$fixture->drop($db);
}
}
}
}
}

View file

@ -0,0 +1,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;
}
}

View file

@ -0,0 +1,58 @@
<?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('Model', 'Model');
/**
* A model to extend from to help you during testing.
*
* @package Cake.TestSuite.Fixture
*/
class CakeTestModel extends Model {
public $useDbConfig = 'test';
public $cacheSources = false;
/**
* Sets default order for the model to avoid failing tests caused by
* incorrect order when no order has been defined in the finds.
* Postgres can return the results in any order it considers appropriate if none is specified
*
* @param int|string|array $id Set this ID for this model on startup, can also be an array of options, see above.
* @param string $table Name of database table to use.
* @param string $ds DataSource connection name.
*/
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->order = array($this->alias . '.' . $this->primaryKey => 'ASC');
}
/**
* Overriding save() to set CakeTestSuiteDispatcher::date() as formatter for created, modified and updated fields
*
* @param array $data Data to save
* @param bool|array $validate Validate or options.
* @param array $fieldList Whitelist of fields
* @return mixed
*/
public function save($data = null, $validate = true, $fieldList = array()) {
$db = $this->getDataSource();
$db->columns['datetime']['formatter'] = 'CakeTestSuiteDispatcher::date';
return parent::save($data, $validate, $fieldList);
}
}