Merge branch '2.0' into 2.0-request

Conflicts:
	cake/libs/router.php
	cake/tests/cases/dispatcher.test.php
	cake/tests/cases/libs/controller/components/auth.test.php
	cake/tests/cases/libs/controller/components/request_handler.test.php
	cake/tests/cases/libs/controller/controller.test.php
	cake/tests/cases/libs/router.test.php
	cake/tests/cases/libs/view/helpers/html.test.php
	cake/tests/cases/libs/view/helpers/js.test.php
This commit is contained in:
mark_story 2010-06-28 23:41:48 -04:00
commit 7c0cda7ce5
170 changed files with 7480 additions and 8180 deletions

View file

@ -19,6 +19,7 @@
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'File');
/**
* API shell to show method signatures of CakePHP core classes.
@ -91,7 +92,7 @@ class ApiShell extends Shell {
$this->_stop();
}
$parsed = $this->__parseClass($path . $file .'.php');
$parsed = $this->__parseClass($path . $file .'.php', $class);
if (!empty($parsed)) {
if (isset($this->params['m'])) {
@ -116,7 +117,7 @@ class ApiShell extends Shell {
while ($number = strtolower($this->in(__('Select a number to see the more information about a specific method. q to quit. l to list.'), null, 'q'))) {
if ($number === 'q') {
$this->out(__('Done'));
$this->_stop();
return $this->_stop();
}
if ($number === 'l') {
@ -180,30 +181,35 @@ class ApiShell extends Shell {
* @return array Methods and signatures indexed by method name
* @access private
*/
function __parseClass($path) {
function __parseClass($path, $class) {
$parsed = array();
$File = new File($path);
if (!$File->exists()) {
$this->err(sprintf(__('%s could not be found'), $File->name));
$this->_stop();
if (!include_once($path)) {
$this->err(sprintf(__('%s could not be found'), $path));
}
$reflection = new ReflectionClass($class);
$contents = $File->read();
if (preg_match_all('%(/\\*\\*[\\s\\S]*?\\*/)(\\s+function\\s+\\w+)(\\(.*\\))%', $contents, $result, PREG_PATTERN_ORDER)) {
foreach ($result[2] as $key => $method) {
$method = str_replace('function ', '', trim($method));
if (strpos($method, '__') === false && $method[0] != '_') {
$parsed[$method] = array(
'comment' => str_replace(array('/*', '*/', '*'), '', trim($result[1][$key])),
'method' => $method,
'parameters' => trim($result[3][$key])
foreach ($reflection->getMethods() as $method) {
if (!$method->isPublic() || strpos($method->getName(), '_') === 0) {
continue;
}
if ($method->getDeclaringClass()->getName() != $class) {
continue;
}
$args = array();
foreach ($method->getParameters() as $param) {
$paramString = '$' . $param->getName();
if ($param->isDefaultValueAvailable()) {
$paramString .= ' = ' . str_replace("\n", '', var_export($param->getDefaultValue(), true));
}
$args[] = $paramString;
}
$parsed[$method->getName()] = array(
'comment' => str_replace(array('/*', '*/', '*'), '', $method->getDocComment()),
'method' => $method->getName(),
'parameters' => '(' . implode(', ', $args) . ')'
);
}
}
}
ksort($parsed);
return $parsed;
}

View file

@ -157,7 +157,7 @@ class SchemaShell extends Shell {
$numToUse = $this->params['s'];
}
$count = 1;
$count = 0;
if (!empty($result[1])) {
foreach ($result[1] as $file) {
if (preg_match('/schema(?:[_\d]*)?\.php$/', $file)) {

View file

@ -411,10 +411,9 @@ class ControllerTask extends BakeTask {
while ($enteredController == '') {
$enteredController = $this->in(__("Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit"), null, 'q');
if ($enteredController === 'q') {
$this->out(__('Exit'));
$this->_stop();
return $this->_stop();
}
if ($enteredController == '' || intval($enteredController) > count($controllers)) {

View file

@ -40,7 +40,7 @@ class DbConfigTask extends Shell {
* @var array
* @access private
*/
private $__defaultConfig = array(
protected $_defaultConfig = array(
'name' => 'default', 'driver'=> 'mysql', 'persistent'=> 'false', 'host'=> 'localhost',
'login'=> 'root', 'password'=> 'password', 'database'=> 'project_name',
'schema'=> null, 'prefix'=> null, 'encoding' => null, 'port' => null
@ -174,9 +174,10 @@ class DbConfigTask extends Shell {
$config = compact('name', 'driver', 'persistent', 'host', 'login', 'password', 'database', 'prefix', 'encoding', 'port', 'schema');
while ($this->__verify($config) == false) {
while ($this->_verify($config) == false) {
$this->_interactive();
}
$dbConfigs[] = $config;
$doneYet = $this->in('Do you wish to add another database configuration?', null, 'n');
@ -195,8 +196,8 @@ class DbConfigTask extends Shell {
*
* @return boolean True if user says it looks good, false otherwise
*/
private function __verify($config) {
$config = array_merge($this->__defaultConfig, $config);
protected function _verify($config) {
$config = array_merge($this->_defaultConfig, $config);
extract($config);
$this->out();
$this->hr();
@ -257,7 +258,7 @@ class DbConfigTask extends Shell {
$temp = get_class_vars(get_class($db));
foreach ($temp as $configName => $info) {
$info = array_merge($this->__defaultConfig, $info);
$info = array_merge($this->_defaultConfig, $info);
if (!isset($info['schema'])) {
$info['schema'] = null;

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 1.2.0.5012
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'File');
/**
* Language string extractor
*

View file

@ -22,52 +22,11 @@
class TestSuiteShell extends Shell {
/**
* The test category, "app", "core" or the name of a plugin
* Dispatcher object for the run.
*
* @var string
* @access public
* @var CakeTestDispatcher
*/
public $category = '';
/**
* "group", "case" or "all"
*
* @var string
* @access public
*/
public $type = '';
/**
* Path to the test case/group file
*
* @var string
* @access public
*/
public $file = '';
/**
* Storage for plugins that have tests
*
* @var string
* @access public
*/
public $plugins = array();
/**
* Convenience variable to avoid duplicated code
*
* @var string
* @access public
*/
public $isPluginTest = false;
/**
* Stores if the user wishes to get a code coverage analysis report
*
* @var string
* @access public
*/
public $doCoverage = false;
protected $_dispatcher = null;
/**
* Initialization method installs Simpletest and loads all plugins
@ -75,69 +34,59 @@ class TestSuiteShell extends Shell {
* @return void
*/
public function initialize() {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'cake_test_suite_dispatcher.php';
$corePath = App::core('cake');
if (isset($corePath[0])) {
define('TEST_CAKE_CORE_INCLUDE_PATH', rtrim($corePath[0], DS) . DS);
} else {
define('TEST_CAKE_CORE_INCLUDE_PATH', CAKE_CORE_INCLUDE_PATH);
}
$params = $this->parseArgs();
$this->__installSimpleTest();
require_once CAKE . 'tests' . DS . 'lib' . DS . 'test_manager.php';
require_once CAKE . 'tests' . DS . 'lib' . DS . 'reporter' . DS . 'cake_cli_reporter.php';
$plugins = App::objects('plugin');
foreach ($plugins as $p) {
$this->plugins[] = Inflector::underscore($p);
}
$this->parseArgs();
$this->getManager();
$this->_dispatcher = new CakeTestSuiteDispatcher();
$this->_dispatcher->setParams($params);
}
/**
* Parse the arguments given into the Shell object properties.
* Parse the CLI options into an array CakeTestDispatcher can use.
*
* @return void
* @return array Array of params for CakeTestDispatcher
*/
public function parseArgs() {
if (empty($this->args)) {
return;
}
$this->category = $this->args[0];
$params = array(
'app' => false,
'plugin' => null,
'output' => 'text',
'codeCoverage' => false,
'filter' => false,
'case' => null
);
if (!in_array($this->category, array('app', 'core'))) {
$this->isPluginTest = true;
$category = $this->args[0];
if ($category == 'app') {
$params['app'] = true;
} elseif ($category != 'core') {
$params['plugin'] = $category;
}
if (isset($this->args[1])) {
$this->type = $this->args[1];
$params['case'] = Inflector::underscore($this->args[1]) . '.test.php';
}
if (isset($this->args[2])) {
if ($this->args[2] == 'cov') {
$this->doCoverage = true;
} else {
$this->file = Inflector::underscore($this->args[2]);
if (isset($this->args[2]) && $this->args[2] == 'cov') {
$params['codeCoverage'] = true;
}
if (isset($this->params['filter'])) {
$params['filter'] = $this->params['filter'];
}
if (isset($this->args[3]) && $this->args[3] == 'cov') {
$this->doCoverage = true;
}
}
/**
* Gets a manager instance, and set the app/plugin properties.
*
* @return void
*/
function getManager() {
$this->Manager = new TestManager();
$this->Manager->appTest = ($this->category === 'app');
if ($this->isPluginTest) {
$this->Manager->pluginTest = $this->category;
if (isset($this->params['coverage'])) {
$params['codeCoverage'] = true;
}
return $params;
}
/**
@ -153,18 +102,12 @@ class TestSuiteShell extends Shell {
$this->error(__('Sorry, you did not pass any arguments!'));
}
if ($this->__canRun()) {
$message = sprintf(__('Running %s %s %s'), $this->category, $this->type, $this->file);
$this->out($message);
$exitCode = 0;
if (!$this->__run()) {
$exitCode = 1;
}
$this->_stop($exitCode);
} else {
$this->error(__('Sorry, the tests could not be found.'));
$result = $this->_dispatcher->dispatch();
$exit = 0;
if ($result instanceof PHPUnit_Framework_TestResult) {
$exit = ($result->errorCount() + $result->failureCount()) > 0;
}
$this->_stop($exit);
}
/**
@ -173,194 +116,36 @@ class TestSuiteShell extends Shell {
* @return void
*/
public function help() {
$this->out('Usage: ');
$this->out("\tcake testsuite category test_type file");
$this->out("\t\t- category - \"app\", \"core\" or name of a plugin");
$this->out("\t\t- test_type - \"case\", \"group\" or \"all\"");
$this->out("\t\t- test_file - file name with folder prefix and without the (test|group).php suffix");
$this->out();
$this->out('Examples: ');
$this->out("\t\tcake testsuite app all");
$this->out("\t\tcake testsuite core all");
$this->out();
$this->out("\t\tcake testsuite app case behaviors/debuggable");
$this->out("\t\tcake testsuite app case models/my_model");
$this->out("\t\tcake testsuite app case controllers/my_controller");
$this->out();
$this->out("\t\tcake testsuite core case file");
$this->out("\t\tcake testsuite core case router");
$this->out("\t\tcake testsuite core case set");
$this->out();
$this->out("\t\tcake testsuite app group mygroup");
$this->out("\t\tcake testsuite core group acl");
$this->out("\t\tcake testsuite core group socket");
$this->out();
$this->out("\t\tcake testsuite bugs case models/bug");
$this->out("\t\t // for the plugin 'bugs' and its test case 'models/bug'");
$this->out("\t\tcake testsuite bugs group bug");
$this->out("\t\t // for the plugin bugs and its test group 'bug'");
$this->out();
$this->out('Code Coverage Analysis: ');
$this->out("\n\nAppend 'cov' to any of the above in order to enable code coverage analysis");
}
$help = <<<TEXT
Usage:
-----
cake testsuite <category> <file> [params]
- category - "app", "core" or name of a plugin
- file - file name with folder prefix and without the test.php suffix.
/**
* Checks if the arguments supplied point to a valid test file and thus the shell can be run.
*
* @return bool true if it's a valid test file, false otherwise
* @access private
*/
function __canRun() {
$isNeitherAppNorCore = !in_array($this->category, array('app', 'core'));
$isPlugin = in_array(Inflector::underscore($this->category), $this->plugins);
Params:
-------
-filter
The -filter option allows you supply a pattern that is used to match
test method names. This can be a regular expression.
if ($isNeitherAppNorCore && !$isPlugin) {
$message = sprintf(
__('%s is an invalid test category (either "app", "core" or name of a plugin)'),
$this->category
);
$this->error($message);
return false;
}
-coverage
Enable code coverage for this run.
$folder = $this->__findFolderByCategory($this->category);
if (!file_exists($folder)) {
$this->err(sprintf(__('%s not found'), $folder));
return false;
}
Examples:
---------
cake testsuite app behaviors/debuggable;
cake testsuite app models/my_model;
cake testsuite app controllers/my_controller
if (!in_array($this->type, array('all', 'group', 'case'))) {
$this->err(sprintf(__('%s is invalid. Should be case, group or all'), $this->type));
return false;
}
cake testsuite core libs/file
cake testsuite core libs/router
cake testsuite core libs/set
$fileName = $this->__getFileName($folder, $this->isPluginTest);
if ($fileName === true || file_exists($folder . $fileName)) {
return true;
}
cake testsuite bugs models/bug
// for the plugin 'bugs' and its test case 'models/bug'
$message = sprintf(
__('%s %s %s is an invalid test identifier'),
$this->category, $this->type, $this->file
);
$this->err($message);
return false;
}
/**
* Executes the tests depending on our settings
*
* @return void
* @access private
*/
function __run() {
$Reporter = new CakeCliReporter('utf-8', array(
'app' => $this->Manager->appTest,
'plugin' => $this->Manager->pluginTest,
'group' => ($this->type === 'group'),
'codeCoverage' => $this->doCoverage
));
if ($this->type == 'all') {
return $this->Manager->runAllTests($Reporter);
}
if ($this->doCoverage) {
if (!extension_loaded('xdebug')) {
$this->out(__('You must install Xdebug to use the CakePHP(tm) Code Coverage Analyzation. Download it from http://www.xdebug.org/docs/install'));
$this->_stop(0);
}
}
if ($this->type == 'group') {
$ucFirstGroup = ucfirst($this->file);
if ($this->doCoverage) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php';
CodeCoverageManager::init($ucFirstGroup, $Reporter);
CodeCoverageManager::start();
}
$result = $this->Manager->runGroupTest($ucFirstGroup, $Reporter);
return $result;
}
$folder = $folder = $this->__findFolderByCategory($this->category);
$case = $this->__getFileName($folder, $this->isPluginTest);
if ($this->doCoverage) {
require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php';
CodeCoverageManager::init($case, $Reporter);
CodeCoverageManager::start();
}
$result = $this->Manager->runTestCase($case, $Reporter);
return $result;
}
/**
* Gets the concrete filename for the inputted test name and category/type
*
* @param string $folder Folder name to look for files in.
* @param boolean $isPlugin If the test case is a plugin.
* @return mixed Either string filename or boolean false on failure. Or true if the type is 'all'
* @access private
*/
function __getFileName($folder, $isPlugin) {
$ext = $this->Manager->getExtension($this->type);
switch ($this->type) {
case 'all':
return true;
case 'group':
return $this->file . $ext;
case 'case':
if ($this->category == 'app' || $isPlugin) {
return $this->file . $ext;
}
$coreCase = $this->file . $ext;
$coreLibCase = 'libs' . DS . $this->file . $ext;
if ($this->category == 'core' && file_exists($folder . DS . $coreCase)) {
return $coreCase;
} elseif ($this->category == 'core' && file_exists($folder . DS . $coreLibCase)) {
return $coreLibCase;
}
}
return false;
}
/**
* Finds the correct folder to look for tests for based on the input category and type.
*
* @param string $category The category of the test. Either 'app', 'core' or a plugin name.
* @return string the folder path
* @access private
*/
function __findFolderByCategory($category) {
$folder = '';
$paths = array(
'core' => CAKE,
'app' => APP
);
$typeDir = $this->type === 'group' ? 'groups' : 'cases';
if (array_key_exists($category, $paths)) {
$folder = $paths[$category] . 'tests' . DS . $typeDir . DS;
} else {
$pluginPath = App::pluginPath($category);
if (is_dir($pluginPath . 'tests')) {
$folder = $pluginPath . 'tests' . DS . $typeDir . DS;
}
}
return $folder;
}
/**
* tries to install simpletest and exits gracefully if it is not there
*
* @return void
* @access private
*/
function __installSimpleTest() {
if (!App::import('Vendor', 'simpletest' . DS . 'reporter')) {
$this->err(__('Sorry, Simpletest could not be found. Download it from http://simpletest.org and install it to your vendors directory.'));
exit;
}
TEXT;
$this->out($help);
}
}

View file

@ -408,6 +408,8 @@ class Dispatcher extends Object {
if ($ext === 'css' || $ext === 'js') {
include($assetFile);
} else {
ob_clean();
flush();
readfile($assetFile);
}

View file

@ -49,8 +49,10 @@ class XcacheEngine extends CacheEngine {
*/
public function init($settings) {
parent::init(array_merge(array(
'engine' => 'Xcache', 'prefix' => Inflector::slug(APP_DIR) . '_
PHP_AUTH_USER' => 'user', 'PHP_AUTH_PW' => 'password'
'engine' => 'Xcache',
'prefix' => Inflector::slug(APP_DIR) . '_',
'PHP_AUTH_USER' => 'user',
'PHP_AUTH_PW' => 'password'
), $settings)
);
return function_exists('xcache_info');
@ -128,7 +130,7 @@ class XcacheEngine extends CacheEngine {
*
* @return boolean True if the cache was succesfully cleared, false otherwise
*/
public function clear() {
public function clear($check) {
$this->__auth();
$max = xcache_count(XC_TYPE_VAR);
for ($i = 0; $i < $max; $i++) {

View file

@ -262,8 +262,8 @@ class DbAcl extends Object implements AclInterface {
if (!class_exists('AclNode')) {
require LIBS . 'model' . DS . 'db_acl.php';
}
$this->Aro =& ClassRegistry::init(array('class' => 'Aro', 'alias' => 'Aro'));
$this->Aco =& ClassRegistry::init(array('class' => 'Aco', 'alias' => 'Aco'));
$this->Aro = ClassRegistry::init(array('class' => 'Aro', 'alias' => 'Aro'));
$this->Aco = ClassRegistry::init(array('class' => 'Aco', 'alias' => 'Aco'));
}
/**

View file

@ -925,4 +925,18 @@ class AuthComponent extends Object {
$this->Session->delete('Auth.redirect');
}
}
/**
* Sets or gets whether the user is logged in
*
* @param boolean $logged sets the status of the user, true to logged in, false to logged out
* @return boolean true if the user is logged in, false otherwise
* @access public
*/
public function loggedIn($logged = null) {
if (!is_null($logged)) {
$this->_loggedIn = $logged;
}
return $this->_loggedIn;
}
}

View file

@ -270,33 +270,33 @@ class EmailComponent extends Object{
* Temporary store of message header lines
*
* @var array
* @access private
* @access protected
*/
private $__header = array();
protected $_header = array();
/**
* If set, boundary to use for multipart mime messages
*
* @var string
* @access private
* @access protected
*/
private $__boundary = null;
protected $_boundary = null;
/**
* Temporary store of message lines
*
* @var array
* @access private
* @access protected
*/
private $__message = array();
protected $_message = array();
/**
* Variable that holds SMTP connection
*
* @var resource
* @access private
* @access protected
*/
private $__smtpConnection = null;
protected $_smtpConnection = null;
/**
* Initialize component
@ -304,7 +304,7 @@ class EmailComponent extends Object{
* @param object $controller Instantiating controller
*/
public function initialize(&$controller, $settings = array()) {
$this->Controller =& $controller;
$this->Controller = $controller;
if (Configure::read('App.encoding') !== null) {
$this->charset = Configure::read('App.encoding');
}
@ -366,24 +366,24 @@ class EmailComponent extends Object{
}
$message[] = '';
$this->__message = $message;
$this->_message = $message;
if (!empty($this->attachments)) {
$this->_attachFiles();
}
if (!is_null($this->__boundary)) {
$this->__message[] = '';
$this->__message[] = '--' . $this->__boundary . '--';
$this->__message[] = '';
if (!is_null($this->_boundary)) {
$this->_message[] = '';
$this->_message[] = '--' . $this->_boundary . '--';
$this->_message[] = '';
}
$_method = '_' . $this->delivery;
$sent = $this->$_method();
$this->__header = array();
$this->__message = array();
$this->_header = array();
$this->_message = array();
return $sent;
}
@ -408,9 +408,9 @@ class EmailComponent extends Object{
$this->htmlMessage = null;
$this->textMessage = null;
$this->messageId = true;
$this->__header = array();
$this->__boundary = null;
$this->__message = array();
$this->_header = array();
$this->_boundary = null;
$this->_message = array();
}
/**
@ -438,11 +438,11 @@ class EmailComponent extends Object{
if ($this->sendAs === 'both') {
$htmlContent = $content;
if (!empty($this->attachments)) {
$msg[] = '--' . $this->__boundary;
$msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->_boundary . '"';
$msg[] = '';
}
$msg[] = '--alt-' . $this->__boundary;
$msg[] = '--alt-' . $this->_boundary;
$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
@ -454,7 +454,7 @@ class EmailComponent extends Object{
$msg = array_merge($msg, $content);
$msg[] = '';
$msg[] = '--alt-' . $this->__boundary;
$msg[] = '--alt-' . $this->_boundary;
$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
@ -464,7 +464,7 @@ class EmailComponent extends Object{
$htmlContent = explode("\n", $this->htmlMessage = str_replace(array("\r\n", "\r"), "\n", $View->renderLayout($htmlContent)));
$msg = array_merge($msg, $htmlContent);
$msg[] = '';
$msg[] = '--alt-' . $this->__boundary . '--';
$msg[] = '--alt-' . $this->_boundary . '--';
$msg[] = '';
return $msg;
@ -473,12 +473,12 @@ class EmailComponent extends Object{
if (!empty($this->attachments)) {
if ($this->sendAs === 'html') {
$msg[] = '';
$msg[] = '--' . $this->__boundary;
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: text/html; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
} else {
$msg[] = '--' . $this->__boundary;
$msg[] = '--' . $this->_boundary;
$msg[] = 'Content-Type: text/plain; charset=' . $this->charset;
$msg[] = 'Content-Transfer-Encoding: 7bit';
$msg[] = '';
@ -506,7 +506,7 @@ class EmailComponent extends Object{
* @access private
*/
function _createboundary() {
$this->__boundary = md5(uniqid(time()));
$this->_boundary = md5(uniqid(time()));
}
/**
@ -517,7 +517,7 @@ class EmailComponent extends Object{
*/
function header($headers) {
foreach ($headers as $header => $value) {
$this->__header[] = sprintf('%s: %s', trim($header), trim($value));
$this->_header[] = sprintf('%s: %s', trim($header), trim($value));
}
}
/**
@ -578,7 +578,7 @@ class EmailComponent extends Object{
if (!empty($this->attachments)) {
$this->_createBoundary();
$headers['MIME-Version'] = '1.0';
$headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->__boundary . '"';
$headers['Content-Type'] = 'multipart/mixed; boundary="' . $this->_boundary . '"';
$headers[] = 'This part of the E-mail should never be seen. If';
$headers[] = 'you are reading this, consider upgrading your e-mail';
$headers[] = 'client to a MIME-compatible client.';
@ -587,7 +587,7 @@ class EmailComponent extends Object{
} elseif ($this->sendAs === 'html') {
$headers['Content-Type'] = 'text/html; charset=' . $this->charset;
} elseif ($this->sendAs === 'both') {
$headers['Content-Type'] = 'multipart/alternative; boundary="alt-' . $this->__boundary . '"';
$headers['Content-Type'] = 'multipart/alternative; boundary="alt-' . $this->_boundary . '"';
}
$headers['Content-Transfer-Encoding'] = '7bit';
@ -603,13 +603,13 @@ class EmailComponent extends Object{
*/
function _formatMessage($message) {
if (!empty($this->attachments)) {
$prefix = array('--' . $this->__boundary);
$prefix = array('--' . $this->_boundary);
if ($this->sendAs === 'text') {
$prefix[] = 'Content-Type: text/plain; charset=' . $this->charset;
} elseif ($this->sendAs === 'html') {
$prefix[] = 'Content-Type: text/html; charset=' . $this->charset;
} elseif ($this->sendAs === 'both') {
$prefix[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->__boundary . '"';
$prefix[] = 'Content-Type: multipart/alternative; boundary="alt-' . $this->_boundary . '"';
}
$prefix[] = 'Content-Transfer-Encoding: 7bit';
$prefix[] = '';
@ -642,13 +642,13 @@ class EmailComponent extends Object{
$data = chunk_split(base64_encode($data)) ;
fclose($handle);
$this->__message[] = '--' . $this->__boundary;
$this->__message[] = 'Content-Type: application/octet-stream';
$this->__message[] = 'Content-Transfer-Encoding: base64';
$this->__message[] = 'Content-Disposition: attachment; filename="' . basename($filename) . '"';
$this->__message[] = '';
$this->__message[] = $data;
$this->__message[] = '';
$this->_message[] = '--' . $this->_boundary;
$this->_message[] = 'Content-Type: application/octet-stream';
$this->_message[] = 'Content-Transfer-Encoding: base64';
$this->_message[] = 'Content-Disposition: attachment; filename="' . basename($filename) . '"';
$this->_message[] = '';
$this->_message[] = $data;
$this->_message[] = '';
}
}
@ -770,8 +770,8 @@ class EmailComponent extends Object{
* @access private
*/
function _mail() {
$header = implode("\n", $this->__header);
$message = implode("\n", $this->__message);
$header = implode("\n", $this->_header);
$message = implode("\n", $this->_message);
if (is_array($this->to)) {
$to = implode(', ', array_map(array($this, '_formatAddress'), $this->to));
} else {
@ -799,10 +799,10 @@ class EmailComponent extends Object{
'timeout' => 30
);
$this->smtpOptions = array_merge($defaults, $this->smtpOptions);
$this->__smtpConnection =& new CakeSocket($this->smtpOptions);
$this->_smtpConnection = new CakeSocket($this->smtpOptions);
if (!$this->__smtpConnection->connect()) {
$this->smtpError = $this->__smtpConnection->lastError();
if (!$this->_smtpConnection->connect()) {
$this->smtpError = $this->_smtpConnection->lastError();
return false;
} elseif (!$this->_smtpSend(null, '220')) {
return false;
@ -866,14 +866,14 @@ class EmailComponent extends Object{
return false;
}
$header = implode("\r\n", $this->__header);
$message = implode("\r\n", $this->__message);
$header = implode("\r\n", $this->_header);
$message = implode("\r\n", $this->_message);
if (!$this->_smtpSend($header . "\r\n\r\n" . $message . "\r\n\r\n\r\n.")) {
return false;
}
$this->_smtpSend('QUIT', false);
$this->__smtpConnection->disconnect();
$this->_smtpConnection->disconnect();
return true;
}
@ -887,13 +887,13 @@ class EmailComponent extends Object{
*/
function _smtpSend($data, $checkCode = '250') {
if (!is_null($data)) {
$this->__smtpConnection->write($data . "\r\n");
$this->_smtpConnection->write($data . "\r\n");
}
while ($checkCode !== false) {
$response = '';
$startTime = time();
while (substr($response, -2) !== "\r\n" && ((time() - $startTime) < $this->smtpOptions['timeout'])) {
$response .= $this->__smtpConnection->read();
$response .= $this->_smtpConnection->read();
}
if (substr($response, -2) !== "\r\n") {
$this->smtpError = 'timeout';
@ -921,8 +921,8 @@ class EmailComponent extends Object{
*/
function _debug() {
$nl = "\n";
$header = implode($nl, $this->__header);
$message = implode($nl, $this->__message);
$header = implode($nl, $this->_header);
$message = implode($nl, $this->_message);
$fm = '<pre>';
if (is_array($this->to)) {

View file

@ -458,6 +458,7 @@ class RequestHandlerComponent extends Object {
}
}
}
return false;
}
/**

View file

@ -54,7 +54,7 @@ class SessionComponent extends CakeSession {
*
* @param string $base The base path for the Session
*/
function __construct($base = null) {
public function __construct($base = null) {
if (Configure::read('Session.start') === true) {
parent::__construct($base);
} else {
@ -70,7 +70,7 @@ class SessionComponent extends CakeSession {
*/
public function startup(&$controller) {
if ($this->started() === false && $this->__active === true) {
$this->__start();
$this->_start();
}
}
@ -88,6 +88,28 @@ class SessionComponent extends CakeSession {
$this->__active = true;
}
/**
* Check if the session is active. Returns the private __active flag.
*
* @return boolean
*/
public function active() {
return $this->__active;
}
/**
* Get / Set the userAgent
*
* @param string $userAgent Set the userAgent
* @return void
*/
public function userAgent($userAgent = null) {
if ($userAgent) {
$this->_userAgent = $userAgent;
}
return $this->_userAgent;
}
/**
* Used to write a value to a session key.
*
@ -101,7 +123,7 @@ class SessionComponent extends CakeSession {
*/
public function write($name, $value = null) {
if ($this->__active === true) {
$this->__start();
$this->_start();
if (is_array($name)) {
foreach ($name as $key => $value) {
if (parent::write($key, $value) === false) {
@ -130,7 +152,7 @@ class SessionComponent extends CakeSession {
*/
public function read($name = null) {
if ($this->__active === true) {
$this->__start();
$this->_start();
return parent::read($name);
}
return false;
@ -147,7 +169,7 @@ class SessionComponent extends CakeSession {
*/
public function delete($name) {
if ($this->__active === true) {
$this->__start();
$this->_start();
return parent::delete($name);
}
return false;
@ -164,7 +186,7 @@ class SessionComponent extends CakeSession {
*/
public function check($name) {
if ($this->__active === true) {
$this->__start();
$this->_start();
return parent::check($name);
}
return false;
@ -180,7 +202,7 @@ class SessionComponent extends CakeSession {
*/
public function error() {
if ($this->__active === true) {
$this->__start();
$this->_start();
return parent::error();
}
return false;
@ -201,7 +223,7 @@ class SessionComponent extends CakeSession {
*/
public function setFlash($message, $element = 'default', $params = array(), $key = 'flash') {
if ($this->__active === true) {
$this->__start();
$this->_start();
$this->write('Message.' . $key, compact('message', 'element', 'params'));
}
}
@ -215,7 +237,7 @@ class SessionComponent extends CakeSession {
*/
public function renew() {
if ($this->__active === true) {
$this->__start();
$this->_start();
parent::renew();
}
}
@ -229,7 +251,7 @@ class SessionComponent extends CakeSession {
*/
public function valid() {
if ($this->__active === true) {
$this->__start();
$this->_start();
return parent::valid();
}
return false;
@ -245,7 +267,7 @@ class SessionComponent extends CakeSession {
*/
public function destroy() {
if ($this->__active === true) {
$this->__start();
$this->_start();
parent::destroy();
}
}
@ -268,9 +290,9 @@ class SessionComponent extends CakeSession {
* or is called from
*
* @return boolean
* @access private
* @access protected
*/
function __start() {
protected function _start() {
if ($this->started() === false) {
if (!$this->id() && parent::start()) {
parent::_checkValid();
@ -280,4 +302,14 @@ class SessionComponent extends CakeSession {
}
return $this->started();
}
/**
* Returns whether the session is active or not
*
* @return boolean
* @access public
*/
public function isActive() {
return $this->__active;
}
}

View file

@ -66,7 +66,7 @@ class Folder {
* @var array
* @access private
*/
private $__errors = false;
private $__errors = array();
/**
* Holds array of complete directory paths.
@ -678,11 +678,14 @@ class Folder {
$to = $options;
$options = (array)$options;
}
$options = array_merge(array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()), $options);
$options = array_merge(
array('to' => $to, 'from' => $this->path, 'mode' => $this->mode, 'skip' => array()),
$options
);
if ($this->copy($options)) {
if ($this->delete($options['from'])) {
return $this->cd($options['to']);
return (bool)$this->cd($options['to']);
}
}
return false;

View file

@ -176,7 +176,7 @@ class CakeSchema extends Object {
}
if (class_exists($class)) {
$Schema =& new $class($options);
$Schema = new $class($options);
return $Schema;
}
$false = false;
@ -204,7 +204,7 @@ class CakeSchema extends Object {
),
$options
));
$db =& ConnectionManager::getDataSource($connection);
$db = ConnectionManager::getDataSource($connection);
App::import('Model', 'AppModel');
if (isset($this->plugin)) {
@ -232,11 +232,7 @@ class CakeSchema extends Object {
if (isset($this->plugin)) {
$model = $this->plugin . '.' . $model;
}
if (PHP5) {
$Object = ClassRegistry::init(array('class' => $model, 'ds' => null));
} else {
$Object =& ClassRegistry::init(array('class' => $model, 'ds' => null));
}
if (is_object($Object) && $Object->useTable !== false) {
$Object->setDataSource($connection);
@ -358,11 +354,9 @@ class CakeSchema extends Object {
}
$out .= "}\n";
$File =& new File($path . DS . $file, true);
$header = '$Id';
$content = "<?php \n/* SVN FILE: {$header}$ */\n/* {$name} schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
$content = $File->prepare($content);
if ($File->write($content)) {
$file = new SplFileObject($path . DS . $file, 'w+');
$content = "<?php \n/* {$name} schema generated on: " . date('Y-m-d H:m:s') . " : ". time() . "*/\n{$out}?>";
if ($file->fwrite($content)) {
return $content;
}
return false;
@ -423,7 +417,7 @@ class CakeSchema extends Object {
*/
public function compare($old, $new = null) {
if (empty($new)) {
$new =& $this;
$new = $this;
}
if (is_array($new)) {
if (isset($new['tables'])) {
@ -528,7 +522,7 @@ class CakeSchema extends Object {
* @return array Formatted columns
*/
public function __columns(&$Obj) {
$db =& ConnectionManager::getDataSource($Obj->useDbConfig);
$db = ConnectionManager::getDataSource($Obj->useDbConfig);
$fields = $Obj->schema(true);
$columns = $props = array();
foreach ($fields as $name => $value) {

View file

@ -701,7 +701,7 @@ class DboMssql extends DboSource {
* @param string $fields
* @param array $values
*/
protected function insertMulti($table, $fields, $values) {
public function insertMulti($table, $fields, $values) {
$primaryKey = $this->_getPrimaryKey($table);
$hasPrimaryKey = $primaryKey != null && (
(is_array($fields) && in_array($primaryKey, $fields)

View file

@ -125,7 +125,6 @@ class DboSqlite extends DboSource {
*/
function connect() {
$config = $this->config;
if (!$config['persistent']) {
$this->connection = sqlite_open($config['database']);
} else {

View file

@ -388,10 +388,8 @@ class DboSource extends DataSource {
* @return array Array of resultset rows, or false if no rows matched
*/
public function fetchAll($sql, $cache = true, $modelName = null) {
if ($cache && isset($this->_queryCache[$sql])) {
if (preg_match('/^\s*select/i', $sql)) {
return $this->_queryCache[$sql];
}
if ($cache && ($cached = $this->getQueryCache($sql)) !== false) {
return $cached;
}
if ($this->execute($sql)) {
@ -407,9 +405,7 @@ class DboSource extends DataSource {
}
if ($cache) {
if (strpos(trim(strtolower($sql)), 'select') !== false) {
$this->_queryCache[$sql] = $out;
}
$this->_writeQueryCache($sql, $out);
}
if (empty($out) && is_bool($this->_result)) {
return $this->_result;
@ -2854,4 +2850,31 @@ class DboSource extends DataSource {
}
return 'string';
}
/**
* Writes a new key for the in memory sql query cache
*
* @param string $sql SQL query
* @param mixed $data result of $sql query
* @return void
*/
protected function _writeQueryCache($sql, $data) {
if (strpos(trim(strtolower($sql)), 'select') !== false) {
$this->_queryCache[$sql] = $data;
}
}
/**
* Returns the result for a sql query if it is already cached
*
* @param string $sql SQL query
* @return mixed results for query if it is cached, false otherwise
*/
public function getQueryCache($sql = null) {
if (isset($this->_queryCache[$sql]) && preg_match('/^\s*select/i', $sql)) {
return $this->_queryCache[$sql];
}
return false;
}
}

View file

@ -1725,6 +1725,7 @@ class Model extends Object {
break;
}
}
return $return;
}
/**

View file

@ -60,7 +60,7 @@ class Router {
* @var array
* @access private
*/
protected static $_validExtensions = null;
protected static $_validExtensions = array();
/**
* 'Constant' regular expression definitions for named route elements

View file

@ -191,6 +191,7 @@ class Validation {
return self::luhn($check, $deep);
}
}
return false;
}
/**

View file

@ -578,6 +578,41 @@ class HtmlHelper extends AppHelper {
}
}
/**
* Returns breadcrumbs as a (x)html list
*
* This method uses HtmlHelper::tag() to generate list and its elements. Works
* similiary to HtmlHelper::getCrumbs(), so it uses options which every
* crumb was added with.
*
* @param array $options Array of html attributes to apply to the generated list elements.
* @return string breadcrumbs html list
* @access public
*/
function getCrumbList($options = array()) {
if (!empty($this->_crumbs)) {
$result = '';
$crumbCount = count($this->_crumbs);
foreach ($this->_crumbs as $which => $crumb) {
$options = array();
if (empty($crumb[1])) {
$elementContent = $crumb[0];
} else {
$elementContent = $this->link($crumb[0], $crumb[1], $crumb[2]);
}
if ($which == 0) {
$options['class'] = 'first';
} elseif ($which == $crumbCount - 1) {
$options['class'] = 'last';
}
$result .= $this->tag('li', $elementContent, $options);
}
return $this->tag('ul', $result, $options);
} else {
return null;
}
}
/**
* Creates a formatted IMG element. If `$options['url']` is provided, an image link will be
* generated with the link pointed at `$options['url']`. This method will set an empty

View file

@ -91,8 +91,9 @@ class PaginatorHelper extends AppHelper {
$ajaxProvider = isset($config['ajax']) ? $config['ajax'] : 'Js';
$this->helpers[] = $ajaxProvider;
$this->_ajaxHelperClass = $ajaxProvider;
if (!class_exists($ajaxProvider . 'Helper')) {
App::import('Helper', $ajaxProvider);
}
$classname = $ajaxProvider . 'Helper';
if (!method_exists($classname, 'link')) {
throw new Exception(sprintf(

View file

@ -152,7 +152,7 @@ class BasicsTest extends CakeTestCase {
$_SERVER = $_ENV = array();
$this->assertFalse(env('TEST_ME'));
$this->assertNull(env('TEST_ME'));
$_ENV['TEST_ME'] = 'a';
$this->assertEqual(env('TEST_ME'), 'a');
@ -237,7 +237,7 @@ class BasicsTest extends CakeTestCase {
Configure::write('Cache.disable', false);
$result = cache('basics_test', 'simple cache write');
$this->assertTrue($result);
$this->assertTrue((boolean)$result);
$this->assertTrue(file_exists(CACHE . 'basics_test'));
$result = cache('basics_test');

View file

@ -0,0 +1,48 @@
<?php
/**
* AllShellsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllShellsTest class
*
* This test group will run all top level shell classes.
*
* @package cake
* @subpackage cake.tests.cases.console
*/
class AllShellsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All shell classes');
$path = CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS;
$suite->addTestFile(CORE_TEST_CASES . DS . 'console' . DS . 'cake.test.php');
$tasks = array('acl', 'api', 'bake', 'schema', 'shell');
foreach ($tasks as $task) {
$suite->addTestFile($path . $task . '.test.php');
}
return $suite;
}
}

View file

@ -191,7 +191,7 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testParseParams() {
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
@ -285,14 +285,14 @@ class ShellDispatcherTest extends CakeTestCase {
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'dry' => true,
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'new'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH),
'dry' => 1
'webroot' => 'webroot'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$this->assertEquals($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
@ -311,8 +311,8 @@ class ShellDispatcherTest extends CakeTestCase {
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'app'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH),
'dry' => 1,
'f' => 1,
'dry' => true,
'f' => true,
'name' => 'DbAcl'
);
$Dispatcher->params = $Dispatcher->args = array();
@ -338,7 +338,7 @@ class ShellDispatcherTest extends CakeTestCase {
'webroot' => 'webroot',
'working' => '/cake/1.2.x.x/app',
'root' => '/cake/1.2.x.x',
'dry' => 1,
'dry' => true,
'name' => 'DbAcl'
);
$Dispatcher->params = $Dispatcher->args = array();
@ -449,7 +449,7 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testBuildPaths() {
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->shellPaths;
@ -474,7 +474,7 @@ class ShellDispatcherTest extends CakeTestCase {
$this->skipIf(class_exists('SampleShell'), '%s SampleShell Class already loaded');
$this->skipIf(class_exists('ExampleShell'), '%s ExampleShell Class already loaded');
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$Dispatcher->shell = 'sample';
$Dispatcher->shellName = 'Sample';
@ -483,7 +483,7 @@ class ShellDispatcherTest extends CakeTestCase {
$result = $Dispatcher->getShell();
$this->assertIsA($result, 'SampleShell');
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$Dispatcher->shell = 'example';
$Dispatcher->shellName = 'Example';
@ -499,84 +499,86 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchShellWithMain() {
Mock::generate('Shell', 'MockWithMainShell', array('main', '_secret'));
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Shell');
array_push($methods, 'main', '_secret');
$Mock = $this->getMock('Shell', $methods, array(&$Dispatcher), 'MockWithMainShell');
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('initialize');
$Shell->expectOnce('loadTasks');
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Mock->expects($this->once())->method('main')->will($this->returnValue(true));
$Mock->expects($this->once())->method('initialize');
$Mock->expects($this->once())->method('loadTasks');
$Mock->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Mock;
$Dispatcher->args = array('mock_with_main');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('initdb'));
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('help');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('help');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', 'help');
$result = $Dispatcher->dispatch();
$this->assertNull($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectNever('hr');
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->never())->method('hr');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', 'hr');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('hr'));
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('dispatch'));
$Shell = new MockWithMainShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', 'idontexist');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('idontexist'));
$Shell = new MockWithMainShell();
$Shell->expectNever('startup');
$Shell->expectNever('main');
$Shell->expectNever('_secret');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('main');
$Shell->expects($this->never())->method('startup');
$Shell->expects($this->never())->method('_secret');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main', '_secret');
$result = $Dispatcher->dispatch();
@ -589,65 +591,69 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchShellWithoutMain() {
Mock::generate('Shell', 'MockWithoutMainShell', array('initDb', '_secret'));
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Shell');
array_push($methods, 'initDb', '_secret');
$Shell = $this->getMock('Shell', $methods, array(&$Dispatcher), 'MockWithoutMainShell');
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithoutMainShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectOnce('initialize');
$Shell->expectOnce('loadTasks');
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('loadTasks');
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithoutMainShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('initDb');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('initDb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('loadTasks');
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithoutMainShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('startup');
$Shell->expectNever('hr');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('hr');
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', 'hr');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$this->assertEqual($Dispatcher->args, array('hr'));
$Shell = new MockWithoutMainShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainShell();
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', 'idontexist');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainShell();
$Shell->expectNever('startup');
$Shell->expectNever('_secret');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('startup');
$Shell->expects($this->never())->method('_secret');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main', '_secret');
$result = $Dispatcher->dispatch();
@ -660,73 +666,72 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchNotAShellWithMain() {
Mock::generate('Object', 'MockWithMainNotAShell',
array('main', 'initialize', 'loadTasks', 'startup', '_secret'));
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods, array(&$Dispatcher), 'MockWithMainNotAShell');
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithMainNotAShell();
$Shell->setReturnValue('main', true);
$Shell->expectNever('initialize');
$Shell->expectNever('loadTasks');
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->never())->method('loadTasks');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithMainNotAShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('initdb'));
$Shell = new MockWithMainNotAShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', 'hr');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('hr'));
$Shell = new MockWithMainNotAShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('dispatch'));
$Shell = new MockWithMainNotAShell();
$Shell->setReturnValue('main', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('main');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', 'idontexist');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('idontexist'));
$Shell = new MockWithMainNotAShell();
$Shell->expectNever('startup');
$Shell->expectNever('main');
$Shell->expectNever('_secret');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('_secret');
$Shell->expects($this->never())->method('main');
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main_not_a', '_secret');
$result = $Dispatcher->dispatch();
@ -739,63 +744,72 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchNotAShellWithoutMain() {
Mock::generate('Object', 'MockWithoutMainNotAShell',
array('initDb', 'initialize', 'loadTasks', 'startup', '_secret'));
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods, array(&$Dispatcher), 'MockWithoutMainNotAShell');
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('initialize');
$Shell->expectNever('loadTasks');
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->never())->method('loadTasks');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectOnce('startup');
$Shell->expectOnce('initDb');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'initdb');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'hr');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('hr'));
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('dispatch'));
$Shell = new MockWithoutMainNotAShell();
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'idontexist');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array('idontexist'));
$Shell = new MockWithoutMainNotAShell();
$Shell->expectNever('startup');
$Shell->expectNever('_secret');
$Dispatcher->TestShell =& $Shell;
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell->expects($this->never())->method('_secret');
$Shell->expects($this->never())->method('main');
$Shell->expects($this->never())->method('startup');
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_without_main_not_a', '_secret');
$result = $Dispatcher->dispatch();
@ -809,41 +823,48 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchTask() {
Mock::generate('Shell', 'MockWeekShell', array('main'));
Mock::generate('Shell', 'MockOnSundayTask', array('execute'));
$Dispatcher = new TestShellDispatcher();
$mainMethods = $executeMethods = get_class_methods('Shell');
array_push($mainMethods, 'main');
array_push($executeMethods, 'execute');
$Dispatcher =& new TestShellDispatcher();
$Week = $this->getMock('Shell', $mainMethods, array(&$Dispatcher), 'MockWeekShell');
$Sunday = $this->getMock('Shell', $executeMethods, array(&$Dispatcher), 'MockOnSundayTask');
$Shell = new MockWeekShell();
$Shell->expectOnce('initialize');
$Shell->expectOnce('loadTasks');
$Shell->expectNever('startup');
$Shell->expectNever('main');
$Shell = new MockWeekShell($Dispather);
$this->mockObjects[] = $Shell;
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('loadTasks');
$Shell->expects($this->never())->method('startup');
$Shell->expects($this->never())->method('main');
$Task = new MockOnSundayTask();
$Task->setReturnValue('execute', true);
$Task->expectOnce('initialize');
$Task->expectOnce('loadTasks');
$Task->expectOnce('startup');
$Task->expectOnce('execute');
$Task = new MockOnSundayTask($Dispatcher);
$this->mockObjects[] = $Task;
$Task->expects($this->once())->method('execute')->will($this->returnValue(true));
$Task->expects($this->once())->method('initialize');;
$Task->expects($this->once())->method('loadTasks');
$Task->expects($this->once())->method('startup');
$Task->expects($this->once())->method('execute');
$Shell->MockOnSunday =& $Task;
$Shell->MockOnSunday = $Task;
$Shell->taskNames = array('MockOnSunday');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_week', 'mock_on_sunday');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
$this->assertEqual($Dispatcher->args, array());
$Shell = new MockWeekShell();
$Task = new MockOnSundayTask();
$Task->expectNever('execute');
$Task->expectOnce('help');
$Shell = new MockWeekShell($Dispatcher);
$Task = new MockOnSundayTask($Dispatcher);
array_push($this->mockObjects, $Shell, $Task);
$Shell->MockOnSunday =& $Task;
$Task->expects($this->never())->method('execute');
$Task->expects($this->once())->method('help');
$Shell->MockOnSunday = $Task;
$Shell->taskNames = array('MockOnSunday');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_week', 'mock_on_sunday', 'help');
$result = $Dispatcher->dispatch();
@ -856,7 +877,7 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testShiftArgs() {
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$Dispatcher->args = array('a', 'b', 'c');
$this->assertEqual($Dispatcher->shiftArgs(), 'a');
@ -885,7 +906,7 @@ class ShellDispatcherTest extends CakeTestCase {
* @return void
*/
public function testHelpCommand() {
$Dispatcher =& new TestShellDispatcher();
$Dispatcher = new TestShellDispatcher();
$expected = "/example \[.*TestPlugin, TestPluginTwo.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);

View file

@ -34,17 +34,6 @@ if (!class_exists('AclShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'acl.php';
}
Mock::generatePartial(
'ShellDispatcher', 'TestAclShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment', 'dispatch')
);
Mock::generatePartial(
'AclShell', 'MockAclShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err')
);
Mock::generate('AclComponent', 'MockAclShellAclComponent');
/**
* AclShellTest class
*
@ -61,42 +50,30 @@ class AclShellTest extends CakeTestCase {
*/
public $fixtures = array('core.aco', 'core.aro', 'core.aros_aco');
/**
* configure Configure for testcase
*
* @return void
*/
public function startCase() {
$this->_aclDb = Configure::read('Acl.database');
$this->_aclClass = Configure::read('Acl.classname');
Configure::write('Acl.database', 'test_suite');
Configure::write('Acl.classname', 'DbAcl');
}
/**
* restore Environment settings
*
* @return void
*/
public function endCase() {
Configure::write('Acl.database', $this->_aclDb);
Configure::write('Acl.classname', $this->_aclClass);
}
/**
* startTest method
*
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestAclShellMockShellDispatcher();
$this->Task =& new MockAclShell($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->_aclDb = Configure::read('Acl.database');
$this->_aclClass = Configure::read('Acl.classname');
Configure::write('Acl.database', 'test_suite');
Configure::write('Acl.classname', 'DbAcl');
$this->Dispatcher = $this->getMock(
'ShellDispather',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment', 'dispatch')
);
$this->Task = $this->getMock(
'AclShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err'),
array(&$this->Dispatcher)
);
$this->Task->Acl = new AclComponent();
$this->Task->params['datasource'] = 'test_suite';
$this->Task->Acl =& new AclComponent();
$controller = null;
$this->Task->Acl->startup($controller);
}
/**
@ -106,6 +83,8 @@ class AclShellTest extends CakeTestCase {
*/
public function endTest() {
ClassRegistry::flush();
Configure::write('Acl.database', $this->_aclDb);
Configure::write('Acl.classname', $this->_aclClass);
}
/**
@ -125,10 +104,15 @@ class AclShellTest extends CakeTestCase {
$this->Task->Acl->Aro->save();
$this->Task->args[0] = 'aro';
$this->Task->expectAt(0, 'out', array('Aro tree:'));
$this->Task->expectAt(1, 'out', array(new PatternExpectation('/\[1\] ROOT/')));
$this->Task->expectAt(3, 'out', array(new PatternExpectation('/\[3\] Gandalf/')));
$this->Task->expectAt(5, 'out', array(new PatternExpectation('/\[5\] MyModel.2/')));
$this->Task->expects($this->at(0))->method('out')->with('Aro tree:');
$this->Task->expects($this->at(2))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/\[1\] ROOT/'));
$this->Task->expects($this->at(4))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/\[3\] Gandalf/'));
$this->Task->expects($this->at(6))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/\[5\] MyModel\.2/'));
$this->Task->view();
}
@ -140,10 +124,12 @@ class AclShellTest extends CakeTestCase {
*/
public function testViewWithArgument() {
$this->Task->args = array('aro', 'admins');
$this->Task->expectAt(0, 'out', array('Aro tree:'));
$this->Task->expectAt(1, 'out', array(' [2] admins'));
$this->Task->expectAt(2, 'out', array(' [3] Gandalf'));
$this->Task->expectAt(3, 'out', array(' [4] Elrond'));
$this->Task->expects($this->at(0))->method('out')->with('Aro tree:');
$this->Task->expects($this->at(2))->method('out')->with(' [2] admins');
$this->Task->expects($this->at(3))->method('out')->with(' [3] Gandalf');
$this->Task->expects($this->at(4))->method('out')->with(' [4] Elrond');
$this->Task->view();
}
@ -170,10 +156,13 @@ class AclShellTest extends CakeTestCase {
*/
public function testCreate() {
$this->Task->args = array('aro', 'root', 'User.1');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/created/'), '*'));
$this->Task->expects($this->at(0))->method('out')->with("New Aro 'User.1' created.\n", true);
$this->Task->expects($this->at(1))->method('out')->with("New Aro 'User.3' created.\n", true);
$this->Task->expects($this->at(2))->method('out')->with("New Aro 'somealias' created.\n", true);
$this->Task->create();
$Aro =& ClassRegistry::init('Aro');
$Aro = ClassRegistry::init('Aro');
$Aro->cacheQueries = false;
$result = $Aro->read();
$this->assertEqual($result['Aro']['model'], 'User');
@ -182,20 +171,18 @@ class AclShellTest extends CakeTestCase {
$id = $result['Aro']['id'];
$this->Task->args = array('aro', 'User.1', 'User.3');
$this->Task->expectAt(1, 'out', array(new PatternExpectation('/created/'), '*'));
$this->Task->create();
$Aro =& ClassRegistry::init('Aro');
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read();
$this->assertEqual($result['Aro']['model'], 'User');
$this->assertEqual($result['Aro']['foreign_key'], 3);
$this->assertEqual($result['Aro']['parent_id'], $id);
$this->Task->args = array('aro', 'root', 'somealias');
$this->Task->expectAt(2, 'out', array(new PatternExpectation('/created/'), '*'));
$this->Task->create();
$Aro =& ClassRegistry::init('Aro');
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read();
$this->assertEqual($result['Aro']['alias'], 'somealias');
$this->assertEqual($result['Aro']['model'], null);
@ -210,11 +197,12 @@ class AclShellTest extends CakeTestCase {
*/
public function testDelete() {
$this->Task->args = array('aro', 'AuthUser.1');
$this->Task->expectAt(0, 'out', array(new NoPatternExpectation('/not/'), true));
$this->Task->expects($this->at(0))->method('out')
->with("Aro deleted.\n", true);
$this->Task->delete();
$Aro =& ClassRegistry::init('Aro');
$result = $Aro->read(null, 3);
$Aro = ClassRegistry::init('Aro');
$result = $Aro->findById(3);
$this->assertFalse($result);
}
@ -227,7 +215,7 @@ class AclShellTest extends CakeTestCase {
$this->Task->args = array('aro', 'AuthUser.2', 'root');
$this->Task->setParent();
$Aro =& ClassRegistry::init('Aro');
$Aro = ClassRegistry::init('Aro');
$result = $Aro->read(null, 4);
$this->assertEqual($result['Aro']['parent_id'], null);
}
@ -239,7 +227,8 @@ class AclShellTest extends CakeTestCase {
*/
public function testGrant() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true));
$this->Task->expects($this->at(0))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Permission granted/'), true);
$this->Task->grant();
$node = $this->Task->Acl->Aro->read(null, 4);
@ -254,7 +243,9 @@ class AclShellTest extends CakeTestCase {
*/
public function testDeny() {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission denied/'), true));
$this->Task->expects($this->at(0))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Permission denied/'), true);
$this->Task->deny();
$node = $this->Task->Acl->Aro->read(null, 4);
@ -268,20 +259,25 @@ class AclShellTest extends CakeTestCase {
* @return void
*/
public function testCheck() {
$this->Task->expects($this->at(0))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/not allowed/'), true);
$this->Task->expects($this->at(1))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Permission granted/'), true);
$this->Task->expects($this->at(2))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/is allowed/'), true);
$this->Task->expects($this->at(3))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/not allowed/'), true);
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/not allowed/'), true));
$this->Task->check();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(1, 'out', array(new PatternExpectation('/Permission granted/'), true));
$this->Task->grant();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(2, 'out', array(new PatternExpectation('/is allowed/'), true));
$this->Task->check();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->expectAt(3, 'out', array(new PatternExpectation('/not allowed/'), true));
$this->Task->check();
}
@ -291,12 +287,15 @@ class AclShellTest extends CakeTestCase {
* @return void
*/
public function testInherit() {
$this->Task->expects($this->at(0))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Permission granted/'), true);
$this->Task->expects($this->at(1))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Permission inherited/'), true);
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/Permission granted/'), true));
$this->Task->grant();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'all');
$this->Task->expectAt(1, 'out', array(new PatternExpectation('/permission inherited/i'), true));
$this->Task->inherit();
$node = $this->Task->Acl->Aro->read(null, 4);
@ -311,9 +310,9 @@ class AclShellTest extends CakeTestCase {
*/
public function testGetPath() {
$this->Task->args = array('aro', 'AuthUser.2');
$this->Task->expectAt(1, 'out', array('[1] ROOT'));
$this->Task->expectAt(2, 'out', array(' [2] admins'));
$this->Task->expectAt(3, 'out', array(' [4] Elrond'));
$this->Task->expects($this->at(2))->method('out')->with('[1] ROOT');
$this->Task->expects($this->at(3))->method('out')->with(' [2] admins');
$this->Task->expects($this->at(4))->method('out')->with(' [4] Elrond');
$this->Task->getPath();
}
@ -323,7 +322,7 @@ class AclShellTest extends CakeTestCase {
* @return void
*/
function testInitDb() {
$this->Task->Dispatch->expectOnce('dispatch');
$this->Task->Dispatch->expects($this->once())->method('dispatch');
$this->Task->initdb();
$this->assertEqual($this->Task->Dispatch->args, array('schema', 'create', 'DbAcl'));

View file

@ -0,0 +1,49 @@
<?php
/**
* AllBakeTasksTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllBakeTasksTest class
*
* This test group will run bake and its task's tests.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllBakeTasksTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('Bake and its task tests');
$path = CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'tasks' . DS;
$suite->addTestFile(CORE_TEST_CASES . DS . 'console' . DS . 'libs' . DS . 'bake.test.php');
$tasks = array('controller', 'model', 'view', 'fixture', 'test', 'db_config', 'project', 'plugin');
foreach ($tasks as $task) {
$suite->addTestFile($path . $task . '.test.php');
}
return $suite;
}
}

View file

@ -34,15 +34,6 @@ if (!class_exists('ApiShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'api.php';
}
Mock::generatePartial(
'ShellDispatcher', 'ApiShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ApiShell', 'MockApiShell',
array('in', 'out', 'createFile', 'hr', '_stop')
);
/**
* ApiShellTest class
*
@ -52,14 +43,20 @@ Mock::generatePartial(
class ApiShellTest extends CakeTestCase {
/**
* setUp method
* startTest method
*
* @return void
*/
public function startTest() {
$this->Dispatcher =& new ApiShellMockShellDispatcher();
$this->Shell =& new MockApiShell($this->Dispatcher);
$this->Shell->Dispatch =& $this->Dispatcher;
$this->Dispatcher = $this->getMock(
'ShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment', 'dispatch')
);
$this->Shell = $this->getMock(
'ApiShell',
array('in', 'out', 'createFile', 'hr', '_stop'),
array(&$this->Dispatcher)
);
}
/**
@ -77,10 +74,10 @@ class ApiShellTest extends CakeTestCase {
* @return void
*/
public function testMethodNameDetection () {
$this->Shell->setReturnValueAt(0, 'in', 'q');
$this->Shell->expectAt(0, 'out', array('Controller'));
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('q'));
$this->Shell->expects($this->at(0))->method('out')->with('Controller');
$expected = array(
array(
'1. afterFilter()',
'2. beforeFilter()',
'3. beforeRender()',
@ -88,23 +85,22 @@ class ApiShellTest extends CakeTestCase {
'5. disableCache()',
'6. flash($message, $url, $pause = 1, $layout = \'flash\')',
'7. header($status)',
'8. httpCodes($code = null)',
'8. httpCodes($code = NULL)',
'9. isAuthorized()',
'10. loadModel($modelClass = null, $id = null)',
'11. paginate($object = null, $scope = array(), $whitelist = array())',
'12. postConditions($data = array(), $op = null, $bool = \'AND\', $exclusive = false)',
'13. redirect($url, $status = null, $exit = true)',
'14. referer($default = null, $local = false)',
'15. render($action = null, $layout = null, $file = null)',
'16. set($one, $two = null)',
'10. loadModel($modelClass = NULL, $id = NULL)',
'11. paginate($object = NULL, $scope = array (), $whitelist = array ())',
'12. postConditions($data = array (), $op = NULL, $bool = \'AND\', $exclusive = false)',
'13. redirect($url, $status = NULL, $exit = true)',
'14. referer($default = NULL, $local = false)',
'15. render($action = NULL, $layout = NULL, $file = NULL)',
'16. set($one, $two = NULL)',
'17. setAction($action)',
'18. shutdownProcess()',
'19. startupProcess()',
'20. validate()',
'21. validateErrors()'
)
);
$this->Shell->expectAt(1, 'out', $expected);
$this->Shell->expects($this->at(2))->method('out')->with($expected);
$this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS;

View file

@ -36,26 +36,13 @@ require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'db_config.php';
Mock::generatePartial(
'ShellDispatcher', 'BakeShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'BakeShell', 'MockBakeShell',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generate('DbConfigTask', 'BakeShellMockDbConfigTask');
Mock::generate('ModelTask', 'BakeShellMockModelTask');
Mock::generate('ControllerTask', 'BakeShellMockControllerTask');
if (!class_exists('UsersController')) {
class UsersController extends Controller {
public $name = 'Users';
}
}
class BakeShellTestCase extends CakeTestCase {
class BakeShellTest extends CakeTestCase {
/**
* fixtures
@ -71,9 +58,15 @@ class BakeShellTestCase extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatch =& new BakeShellMockShellDispatcher();
$this->Shell =& new MockBakeShell();
$this->Shell->Dispatch =& $this->Dispatch;
$this->Dispatcher = $this->getMock(
'ShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
$this->Shell = $this->getMock(
'BakeShell',
array('in', 'out', 'hr', 'err', 'createFile', '_stop', '_checkUnitTest'),
array(&$this->Dispatcher)
);
$this->Shell->Dispatch->shellPaths = App::path('shells');
}
@ -97,28 +90,24 @@ class BakeShellTestCase extends CakeTestCase {
if ($this->skipIf($userExists, 'User class exists, cannot test `bake all [param]`. %s')) {
return;
}
$this->Shell->Model =& new BakeShellMockModelTask();
$this->Shell->Controller =& new BakeShellMockControllerTask();
$this->Shell->View =& new BakeShellMockModelTask();
$this->Shell->DbConfig =& new BakeShellMockDbConfigTask();
$this->Shell->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatch));
$this->Shell->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatch));
$this->Shell->View = $this->getMock('ModelTask', array(), array(&$this->Dispatch));
$this->Shell->DbConfig = $this->getMock('DbConfigTask', array(), array(&$this->Dispatch));
$this->Shell->DbConfig->expectOnce('getConfig');
$this->Shell->DbConfig->setReturnValue('getConfig', 'test_suite');
$this->Shell->DbConfig->expects($this->once())->method('getConfig')->will($this->returnValue('test_suite'));
$this->Shell->Model->setReturnValue('bake', true);
$this->Shell->Model->expectNever('getName');
$this->Shell->Model->expectOnce('bake');
$this->Shell->Model->expects($this->never())->method('getName');
$this->Shell->Model->expects($this->once())->method('bake')->will($this->returnValue(true));
$this->Shell->Controller->expectOnce('bake');
$this->Shell->Controller->setReturnValue('bake', true);
$this->Shell->Controller->expects($this->once())->method('bake')->will($this->returnValue(true));
$this->Shell->View->expects($this->once())->method('execute');
$this->Shell->View->expectOnce('execute');
$this->Shell->expectAt(0, 'out', array('Bake All'));
$this->Shell->expectAt(1, 'out', array('User Model was baked.'));
$this->Shell->expectAt(2, 'out', array('User Controller was baked.'));
$this->Shell->expectAt(3, 'out', array('User Views were baked.'));
$this->Shell->expectAt(4, 'out', array('Bake All complete'));
$this->Shell->expects($this->at(1))->method('out')->with('Bake All');
$this->Shell->expects($this->at(3))->method('out')->with('User Model was baked.');
$this->Shell->expects($this->at(5))->method('out')->with('User Controller was baked.');
$this->Shell->expects($this->at(7))->method('out')->with('User Views were baked.');
$this->Shell->expects($this->at(8))->method('out')->with('Bake All complete');
$this->Shell->params = array();
$this->Shell->args = array('User');

View file

@ -35,17 +35,6 @@ if (!class_exists('SchemaShell')) {
require CAKE . 'console' . DS . 'libs' . DS . 'schema.php';
}
Mock::generatePartial(
'ShellDispatcher', 'TestSchemaShellMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'SchemaShell', 'MockSchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop')
);
Mock::generate('CakeSchema', 'MockSchemaCakeSchema');
/**
* Test for Schema database management
*
@ -131,9 +120,15 @@ class SchemaShellTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestSchemaShellMockShellDispatcher();
$this->Shell =& new MockSchemaShell($this->Dispatcher);
$this->Shell->Dispatch =& $this->Dispatcher;
$this->Dispatcher = $this->getMock(
'ShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop'),
array(&$this->Dispatcher)
);
}
/**
@ -189,8 +184,8 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->startup();
$this->Shell->Schema->path = APP . 'config' . DS . 'schema';
$this->Shell->params['file'] = 'i18n.php';
$this->Shell->expectOnce('_stop');
$this->Shell->expectOnce('out');
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->expects($this->once())->method('out');
$this->Shell->view();
}
@ -205,8 +200,8 @@ class SchemaShellTest extends CakeTestCase {
));
$this->Shell->args = array('TestPlugin.schema');
$this->Shell->startup();
$this->Shell->expectCallCount('_stop', 2);
$this->Shell->expectCallCount('out', 2);
$this->Shell->expects($this->exactly(2))->method('_stop');
$this->Shell->expects($this->exactly(2))->method('out');
$this->Shell->view();
$this->Shell->args = array();
@ -227,7 +222,7 @@ class SchemaShellTest extends CakeTestCase {
'name' => 'i18n',
'write' => TMP . 'tests' . DS . 'i18n.sql'
);
$this->Shell->expectOnce('_stop');
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->startup();
$this->Shell->dump();
@ -260,7 +255,7 @@ class SchemaShellTest extends CakeTestCase {
'write' => TMP . 'tests' . DS . 'dump_test.sql'
);
$this->Shell->startup();
$this->Shell->expectOnce('_stop');
$this->Shell->expects($this->once())->method('_stop');
$this->Shell->dump();
$file =& new File(TMP . 'tests' . DS . 'dump_test.sql');
@ -279,16 +274,16 @@ class SchemaShellTest extends CakeTestCase {
*
* @return void
*/
public function testGenerateSnaphot() {
public function testGenerateSnapshot() {
$this->Shell->path = TMP;
$this->Shell->params['file'] = 'schema.php';
$this->Shell->args = array('snapshot');
$this->Shell->Schema =& new MockSchemaCakeSchema();
$this->Shell->Schema->setReturnValue('read', array('schema data'));
$this->Shell->Schema->setReturnValue('write', true);
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->expects($this->at(0))->method('read')->will($this->returnValue(array('schema data')));
$this->Shell->Schema->expects($this->at(0))->method('write')->will($this->returnValue(true));
$this->Shell->Schema->expectOnce('read');
$this->Shell->Schema->expectOnce('write', array(array('schema data', 'file' => 'schema_1.php')));
$this->Shell->Schema->expects($this->at(1))->method('read');
$this->Shell->Schema->expects($this->at(1))->method('write')->with(array('schema data', 'file' => 'schema_1.php'));
$this->Shell->generate();
}
@ -303,10 +298,10 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->params['file'] = 'schema.php';
$this->Shell->args = array();
$this->Shell->setReturnValue('in', 'q');
$this->Shell->Schema =& new MockSchemaCakeSchema();
$this->Shell->expects($this->once())->method('in')->will($this->returnValue('q'));
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expectNever('read');
$this->Shell->Schema->expects($this->never())->method('read');
$result = $this->Shell->generate();
unlink(TMP . 'schema.php');
@ -322,15 +317,19 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->params['file'] = 'schema.php';
$this->Shell->args = array();
$this->Shell->setReturnValue('in', 'o');
$this->Shell->expectAt(1, 'out', array(new PatternExpectation('/Schema file:\s[a-z\.]+\sgenerated/')));
$this->Shell->Schema =& new MockSchemaCakeSchema();
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->setReturnValue('read', array('schema data'));
$this->Shell->Schema->setReturnValue('write', true);
$this->Shell->expects($this->once())->method('in')->will($this->returnValue('o'));
$this->Shell->Schema->expectOnce('read');
$this->Shell->Schema->expectOnce('write', array(array('schema data', 'file' => 'schema.php')));
$this->Shell->expects($this->at(2))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/Schema file:\s[a-z\.]+\sgenerated/'));
$this->Shell->Schema = $this->getMock('CakeSchema');
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expects($this->once())->method('read')->will($this->returnValue(array('schema data')));
$this->Shell->Schema->expects($this->once())->method('write')->will($this->returnValue(true));
$this->Shell->Schema->expects($this->once())->method('read');
$this->Shell->Schema->expects($this->once())->method('write')
->with(array('schema data', 'file' => 'schema.php'));
$this->Shell->generate();
unlink(TMP . 'schema.php');
@ -354,7 +353,7 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$file =& new File(TMP . 'tests' . DS . 'schema.php');
$file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $file->read();
$this->assertPattern('/var \$posts/', $contents);
@ -380,14 +379,14 @@ class SchemaShellTest extends CakeTestCase {
);
$this->Shell->args = array('i18n');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');
$db = ConnectionManager::getDataSource('test_suite');
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources));
$schema =& new i18nSchema();
$schema = new i18nSchema();
$db->execute($db->dropSchema($schema));
}
@ -404,7 +403,7 @@ class SchemaShellTest extends CakeTestCase {
);
$this->Shell->args = array('DbAcl', 'acos');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');
@ -428,15 +427,13 @@ class SchemaShellTest extends CakeTestCase {
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->update();
$article =& new Model(array('name' => 'Article', 'ds' => 'test_suite'));
$fields = $article->schema();
$this->assertTrue(isset($fields['summary']));
$this->_fixtures['core.article']->drop($this->db);
$this->_fixtures['core.article']->create($this->db);
}
/**
@ -473,7 +470,7 @@ class SchemaShellTest extends CakeTestCase {
);
$this->Shell->args = array('TestPlugin.TestPluginApp');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');

View file

@ -34,9 +34,6 @@ if (!class_exists('ShellDispatcher')) {
ob_end_clean();
}
Mock::generatePartial('ShellDispatcher', 'TestShellMockShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
/**
* TestShell class
@ -115,7 +112,12 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function setUp() {
$this->Dispatcher =& new TestShellMockShellDispatcher();
parent::setUp();
$this->Dispatcher = $this->getMock(
'ShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
$this->Shell =& new TestShell($this->Dispatcher);
}
@ -125,6 +127,7 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function tearDown() {
parent::tearDown();
ClassRegistry::flush();
}
@ -134,7 +137,7 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testConstruct() {
$this->assertIsA($this->Shell->Dispatch, 'TestShellMockShellDispatcher');
$this->assertEquals($this->Dispatcher, $this->Shell->Dispatch);
$this->assertEqual($this->Shell->name, 'TestShell');
$this->assertEqual($this->Shell->alias, 'TestShell');
}
@ -177,28 +180,43 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testIn() {
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(0, 'getInput', array('Just a test?', array('y', 'n'), 'n'));
$this->Dispatcher->expects($this->at(0))
->method('getInput')
->with('Just a test?', array('y', 'n'), 'n')
->will($this->returnValue('n'));
$this->Dispatcher->expects($this->at(1))
->method('getInput')
->with('Just a test?', array('y', 'n'), 'n')
->will($this->returnValue('Y'));
$this->Dispatcher->expects($this->at(2))
->method('getInput')
->with('Just a test?', 'y,n', 'n')
->will($this->returnValue('y'));
$this->Dispatcher->expects($this->at(3))
->method('getInput')
->with('Just a test?', 'y/n', 'n')
->will($this->returnValue('y'));
$this->Dispatcher->expects($this->at(4))
->method('getInput')
->with('Just a test?', 'y', 'y')
->will($this->returnValue('y'));
$result = $this->Shell->in('Just a test?', array('y', 'n'), 'n');
$this->assertEqual($result, 'n');
$this->Shell->Dispatch->setReturnValueAt(1, 'getInput', 'Y');
$this->Shell->Dispatch->expectAt(1, 'getInput', array('Just a test?', array('y', 'n'), 'n'));
$result = $this->Shell->in('Just a test?', array('y', 'n'), 'n');
$this->assertEqual($result, 'Y');
$this->Shell->Dispatch->setReturnValueAt(2, 'getInput', 'y');
$this->Shell->Dispatch->expectAt(2, 'getInput', array('Just a test?', 'y,n', 'n'));
$result = $this->Shell->in('Just a test?', 'y,n', 'n');
$this->assertEqual($result, 'y');
$this->Shell->Dispatch->setReturnValueAt(3, 'getInput', 'y');
$this->Shell->Dispatch->expectAt(3, 'getInput', array('Just a test?', 'y/n', 'n'));
$result = $this->Shell->in('Just a test?', 'y/n', 'n');
$this->assertEqual($result, 'y');
$this->Shell->Dispatch->setReturnValueAt(4, 'getInput', 'y');
$this->Shell->Dispatch->expectAt(4, 'getInput', array('Just a test?', 'y', 'y'));
$result = $this->Shell->in('Just a test?', 'y', 'y');
$this->assertEqual($result, 'y');
@ -214,16 +232,28 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testOut() {
$this->Shell->Dispatch->expectAt(0, 'stdout', array("Just a test\n", false));
$this->Shell->Dispatch->expects($this->at(0))
->method('stdout')
->with("Just a test\n", false);
$this->Shell->Dispatch->expects($this->at(1))
->method('stdout')
->with("Just\na\ntest\n", false);
$this->Shell->Dispatch->expects($this->at(2))
->method('stdout')
->with("Just\na\ntest\n\n", false);
$this->Shell->Dispatch->expects($this->at(3))
->method('stdout')
->with("\n", false);
$this->Shell->out('Just a test');
$this->Shell->Dispatch->expectAt(1, 'stdout', array("Just\na\ntest\n", false));
$this->Shell->out(array('Just', 'a', 'test'));
$this->Shell->Dispatch->expectAt(2, 'stdout', array("Just\na\ntest\n\n", false));
$this->Shell->out(array('Just', 'a', 'test'), 2);
$this->Shell->Dispatch->expectAt(3, 'stdout', array("\n", false));
$this->Shell->out();
}
@ -233,16 +263,28 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testErr() {
$this->Shell->Dispatch->expectAt(0, 'stderr', array("Just a test\n"));
$this->Shell->Dispatch->expects($this->at(0))
->method('stderr')
->with("Just a test\n");
$this->Shell->Dispatch->expects($this->at(1))
->method('stderr')
->with("Just\na\ntest\n");
$this->Shell->Dispatch->expects($this->at(2))
->method('stderr')
->with("Just\na\ntest\n\n");
$this->Shell->Dispatch->expects($this->at(3))
->method('stderr')
->with("\n");
$this->Shell->err('Just a test');
$this->Shell->Dispatch->expectAt(1, 'stderr', array("Just\na\ntest\n"));
$this->Shell->err(array('Just', 'a', 'test'));
$this->Shell->Dispatch->expectAt(2, 'stderr', array("Just\na\ntest\n\n"));
$this->Shell->err(array('Just', 'a', 'test'), 2);
$this->Shell->Dispatch->expectAt(3, 'stderr', array("\n"));
$this->Shell->err();
}
@ -267,19 +309,22 @@ class ShellTest extends CakeTestCase {
public function testHr() {
$bar = '---------------------------------------------------------------';
$this->Shell->Dispatch->expectAt(0, 'stdout', array('', false));
$this->Shell->Dispatch->expectAt(1, 'stdout', array($bar . "\n", false));
$this->Shell->Dispatch->expectAt(2, 'stdout', array('', false));
$this->Shell->Dispatch->expects($this->at(0))->method('stdout')->with('', false);
$this->Shell->Dispatch->expects($this->at(1))->method('stdout')->with($bar . "\n", false);
$this->Shell->Dispatch->expects($this->at(2))->method('stdout')->with('', false);
$this->Shell->Dispatch->expects($this->at(3))->method('stdout')->with("\n", false);
$this->Shell->Dispatch->expects($this->at(4))->method('stdout')->with($bar . "\n", false);
$this->Shell->Dispatch->expects($this->at(5))->method('stdout')->with("\n", false);
$this->Shell->Dispatch->expects($this->at(6))->method('stdout')->with("\n\n", false);
$this->Shell->Dispatch->expects($this->at(7))->method('stdout')->with($bar . "\n", false);
$this->Shell->Dispatch->expects($this->at(8))->method('stdout')->with("\n\n", false);
$this->Shell->hr();
$this->Shell->Dispatch->expectAt(3, 'stdout', array("\n", false));
$this->Shell->Dispatch->expectAt(4, 'stdout', array($bar . "\n", false));
$this->Shell->Dispatch->expectAt(5, 'stdout', array("\n", false));
$this->Shell->hr(true);
$this->Shell->Dispatch->expectAt(3, 'stdout', array("\n\n", false));
$this->Shell->Dispatch->expectAt(4, 'stdout', array($bar . "\n", false));
$this->Shell->Dispatch->expectAt(5, 'stdout', array("\n\n", false));
$this->Shell->hr(2);
}
@ -289,14 +334,23 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testError() {
$this->Shell->Dispatch->expectAt(0, 'stderr', array("Error: Foo Not Found\n"));
$this->Shell->Dispatch->expects($this->at(0))
->method('stderr')
->with("Error: Foo Not Found\n");
$this->Shell->Dispatch->expects($this->at(1))
->method('stderr')
->with("Error: Foo Not Found\n");
$this->Shell->Dispatch->expects($this->at(2))
->method('stderr')
->with("Searched all...\n");
$this->Shell->error('Foo Not Found');
$this->assertIdentical($this->Shell->stopped, 1);
$this->Shell->stopped = null;
$this->Shell->Dispatch->expectAt(1, 'stderr', array("Error: Foo Not Found\n"));
$this->Shell->Dispatch->expectAt(2, 'stderr', array("Searched all...\n"));
$this->Shell->error('Foo Not Found', 'Searched all...');
$this->assertIdentical($this->Shell->stopped, 1);
}
@ -389,13 +443,13 @@ class ShellTest extends CakeTestCase {
*
* @return void
*/
public function testCreateFile() {
public function testCreateFileNonInteractive() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Not supported on Windows');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$Folder = new Folder($path, true);
$this->Shell->interactive = false;
@ -411,26 +465,54 @@ class ShellTest extends CakeTestCase {
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$Folder->delete();
}
/**
* test createFile when the shell is interactive.
*
* @return void
*/
function testCreateFileInteractive() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Not supported on Windows');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
$Folder = new Folder($path, true);
$this->Shell->interactive = true;
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(1, 'stdout', array('File exists, overwrite?', '*'));
$this->Shell->Dispatch->expects($this->at(5))
->method('getInput')
->withAnyParameters()
->will($this->returnValue('n'));
$this->Shell->Dispatch->expects($this->at(9))
->method('getInput')
->withAnyParameters()
->will($this->returnValue('y'));
$contents = "<?php\necho 'yet another test';\n\$te = 'st';\n?>";
$result = $this->Shell->createFile($file, $contents);
$this->assertFalse($result);
$this->assertTrue(file_exists($file));
$this->assertNotEqual(file_get_contents($file), $contents);
$this->Shell->Dispatch->setReturnValueAt(1, 'getInput', 'y');
$this->Shell->Dispatch->expectAt(3, 'stdout', array('File exists, overwrite?', '*'));
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$Folder = new Folder($path);
// no overwrite
$contents = 'new contents';
$result = $this->Shell->createFile($file, $contents);
$this->assertFalse($result);
$this->assertTrue(file_exists($file));
$this->assertNotEqual($contents, file_get_contents($file));
// overwrite
$contents = 'more new contents';
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEquals($contents, file_get_contents($file));
$Folder->delete();
}
@ -439,13 +521,13 @@ class ShellTest extends CakeTestCase {
*
* @return void
*/
public function testCreateFileWindows() {
$this->skipUnless(DIRECTORY_SEPARATOR === '\\', 'testCreateFileWindows supported on Windows only');
public function testCreateFileWindowsNonInteractive() {
$this->skipIf(DIRECTORY_SEPARATOR === '/', 'testCreateFileWindows supported on Windows only');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$Folder = new Folder($path, true);
$this->Shell->interactive = false;
@ -461,10 +543,32 @@ class ShellTest extends CakeTestCase {
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$Folder = new Folder($path);
$Folder->delete();
}
/**
* test createFile on windows with interactive on.
*
* @return void
*/
function testCreateFileWindowsInteractive() {
$this->skipIf(DIRECTORY_SEPARATOR === '/', 'testCreateFileWindowsInteractive supported on Windows only');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
$Folder = new Folder($path, true);
$this->Shell->interactive = true;
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(1, 'stdout', array('File exists, overwrite?'));
$this->Shell->Dispatch->expects($this->at(5))
->method('getInput')
->will($this->returnValue('y'));
$this->Shell->Dispatch->expects($this->at(9))
->method('getInput')
->will($this->returnValue('n'));
$contents = "<?php\necho 'yet another test';\r\n\$te = 'st';\r\n?>";
$result = $this->Shell->createFile($file, $contents);
@ -472,15 +576,11 @@ class ShellTest extends CakeTestCase {
$this->assertTrue(file_exists($file));
$this->assertNotEqual(file_get_contents($file), $contents);
$this->Shell->Dispatch->setReturnValueAt(1, 'getInput', 'y');
$this->Shell->Dispatch->expectAt(3, 'stdout', array('File exists, overwrite?'));
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$Folder = new Folder($path);
$Folder->delete();
}
}

View file

@ -38,27 +38,6 @@ require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'test.php';
Mock::generatePartial(
'ShellDispatcher', 'TestControllerTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ControllerTask', 'MockControllerTask',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generatePartial(
'ModelTask', 'ControllerMockModelTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generatePartial(
'ProjectTask', 'ControllerMockProjectTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest', 'getPrefix')
);
Mock::generate('TestTask', 'ControllerMockTestTask');
$imported = App::import('Model', 'Article');
$imported = $imported || App::import('Model', 'Comment');
@ -98,16 +77,27 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestControllerTaskMockShellDispatcher();
$this->Task =& new MockControllerTask($this->Dispatcher);
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('ControllerTask',
array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest'),
array(&$this->Dispatcher)
);
$this->Task->name = 'ControllerTask';
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->Template->params['theme'] = 'default';
$this->Task->Model =& new ControllerMockModelTask($this->Task->Dispatch);
$this->Task->Project =& new ControllerMockProjectTask($this->Task->Dispatch);
$this->Task->Test =& new ControllerMockTestTask();
$this->Task->Model = $this->getMock('ModelTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest'),
array(&$this->Dispatcher)
);
$this->Task->Project = $this->getMock('ProjectTask',
array('in', 'out', 'err', 'createFile', '_stop', '_checkUnitTest', 'getPrefix'),
array(&$this->Dispatcher)
);
$this->Task->Test = $this->getMock('TestTask', array(), array(&$this->Dispatcher));
}
/**
@ -128,20 +118,15 @@ class ControllerTaskTest extends CakeTestCase {
public function testListAll() {
$this->Task->connection = 'test_suite';
$this->Task->interactive = true;
$this->Task->expectAt(1, 'out', array('1. Articles'));
$this->Task->expectAt(2, 'out', array('2. ArticlesTags'));
$this->Task->expectAt(3, 'out', array('3. Comments'));
$this->Task->expectAt(4, 'out', array('4. Tags'));
$this->Task->expects($this->at(1))->method('out')->with('1. Articles');
$this->Task->expects($this->at(2))->method('out')->with('2. ArticlesTags');
$this->Task->expects($this->at(3))->method('out')->with('3. Comments');
$this->Task->expects($this->at(4))->method('out')->with('4. Tags');
$expected = array('Articles', 'ArticlesTags', 'Comments', 'Tags');
$result = $this->Task->listAll('test_suite');
$this->assertEqual($result, $expected);
$this->Task->expectAt(6, 'out', array('1. Articles'));
$this->Task->expectAt(7, 'out', array('2. ArticlesTags'));
$this->Task->expectAt(8, 'out', array('4. Comments'));
$this->Task->expectAt(9, 'out', array('5. Tags'));
$this->Task->interactive = false;
$result = $this->Task->listAll();
@ -154,27 +139,32 @@ class ControllerTaskTest extends CakeTestCase {
*
* @return void
*/
public function testGetName() {
public function testGetNameValidIndex() {
$this->Task->interactive = true;
$this->Task->setReturnValue('in', 1);
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->expectOnce('_stop');
$this->Task->getName('test_suite');
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getName('test_suite');
$expected = 'Articles';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 3);
$this->Task->expects($this->at(5))->method('in')->will($this->returnValue(3));
$result = $this->Task->getName('test_suite');
$expected = 'Comments';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 10);
$this->Task->expects($this->at(7))->method('in')->will($this->returnValue(1));
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
$expected = 'Articles';
$this->assertEqual($result, $expected);
}
/**
* test getting invalid indexes.
*
* @return void
*/
function testGetNameInvalidIndex() {
$this->Task->interactive = true;
$this->Task->expects($this->at(5))->method('in')->will($this->returnValue(10));
$this->Task->expects($this->at(7))->method('in')->will($this->returnValue('q'));
$this->Task->expects($this->once())->method('err');
$this->Task->expects($this->once())->method('_stop');
$this->Task->getName('test_suite');
}
/**
@ -182,19 +172,33 @@ class ControllerTaskTest extends CakeTestCase {
*
* @return void
*/
public function testDoHelpers() {
$this->Task->setReturnValue('in', 'n');
public function testDoHelpersNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doHelpers();
$this->assertEqual($result, array());
}
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', ' Javascript, Ajax, CustomOne ');
/**
* test getting helper values
*
* @return void
*/
function testDoHelpersTrailingSpace() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne '));
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$this->assertEqual($result, $expected);
}
$this->Task->setReturnValueAt(3, 'in', 'y');
$this->Task->setReturnValueAt(4, 'in', ' Javascript, Ajax, CustomOne, , ');
/**
* test doHelpers with extra commas
*
* @return void
*/
function testDoHelpersTrailingCommas() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne, , '));
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$this->assertEqual($result, $expected);
@ -205,19 +209,35 @@ class ControllerTaskTest extends CakeTestCase {
*
* @return void
*/
public function testDoComponents() {
$this->Task->setReturnValue('in', 'n');
public function testDoComponentsNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doComponents();
$this->assertEqual($result, array());
}
/**
* test components with spaces
*
* @return void
*/
function testDoComponentsTrailingSpaces() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security '));
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', ' RequestHandler, Security ');
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$this->assertEqual($result, $expected);
}
/**
* test components with commas
*
* @return void
*/
function testDoComponentsTrailingCommas() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security, , '));
$this->Task->setReturnValueAt(3, 'in', 'y');
$this->Task->setReturnValueAt(4, 'in', ' RequestHandler, Security, , ');
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$this->assertEqual($result, $expected);
@ -235,9 +255,9 @@ class ControllerTaskTest extends CakeTestCase {
$components = array('Acl', 'Auth');
$uses = array('Comment', 'User');
$this->Task->expectAt(2, 'out', array("Controller Name:\n\t$controller"));
$this->Task->expectAt(3, 'out', array("Helpers:\n\tAjax, Time"));
$this->Task->expectAt(4, 'out', array("Components:\n\tAcl, Auth"));
$this->Task->expects($this->at(4))->method('out')->with("Controller Name:\n\t$controller");
$this->Task->expects($this->at(5))->method('out')->with("Helpers:\n\tAjax, Time");
$this->Task->expects($this->at(6))->method('out')->with("Components:\n\tAcl, Auth");
$this->Task->confirmController($controller, $scaffold, $helpers, $components);
}
@ -249,7 +269,7 @@ class ControllerTaskTest extends CakeTestCase {
public function testBake() {
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$this->Task->setReturnValue('createFile', true);
$this->Task->expects($this->any())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Articles', '--actions--', $helpers, $components);
$this->assertPattern('/class ArticlesController extends AppController/', $result);
@ -282,13 +302,20 @@ class ControllerTaskTest extends CakeTestCase {
$uses = array('Comment', 'User');
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'controllers' . DS . 'articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->expects($this->at(0))->method('createFile')->with(
$path,
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(1))->method('createFile')->with(
$path,
new PHPUnit_Framework_Constraint_PCREMatch('/ArticlesController extends ControllerTestAppController/')
);
$this->Task->bake('Articles', '--actions--', array(), array(), array());
$this->Task->plugin = 'controllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'controllers' . DS . 'articles_controller.php';
$this->Task->expectAt(1, 'createFile', array(
$path, new PatternExpectation('/ArticlesController extends ControllerTestAppController/')));
$this->Task->bake('Articles', '--actions--', array(), array(), array());
}
@ -358,6 +385,7 @@ class ControllerTaskTest extends CakeTestCase {
$this->assertTrue(strpos($result, 'function add()') !== false);
$this->assertTrue(strpos($result, 'if (!empty($this->data))') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->save($this->data))') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('The article has been saved.'), array('action' => 'index'))") !== false);
$this->assertTrue(strpos($result, 'function edit($id = null)') !== false);
@ -379,7 +407,7 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->connection = 'test_suite';
$this->Task->interactive = false;
$this->Task->Test->expectOnce('bake', array('Controller', 'Articles'));
$this->Task->Test->expects($this->once())->method('bake')->with('Controller', 'Articles');
$this->Task->bakeTest('Articles');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
@ -394,21 +422,27 @@ class ControllerTaskTest extends CakeTestCase {
*/
public function testInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path';
$this->Task->setReturnValue('in', '1');
$this->Task->setReturnValueAt(1, 'in', 'y'); // build interactive
$this->Task->setReturnValueAt(2, 'in', 'n'); // build no scaffolds
$this->Task->setReturnValueAt(3, 'in', 'y'); // build normal methods
$this->Task->setReturnValueAt(4, 'in', 'n'); // build admin methods
$this->Task->setReturnValueAt(5, 'in', 'n'); // helpers?
$this->Task->setReturnValueAt(6, 'in', 'n'); // components?
$this->Task->setReturnValueAt(7, 'in', 'y'); // use sessions
$this->Task->setReturnValueAt(8, 'in', 'y'); // looks good
$this->Task->path = '/my/path/';
$this->Task->execute();
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(
'1',
'y', // build interactive
'n', // build no scaffolds
'y', // build normal methods
'n', // build admin methods
'n', // helpers?
'n', // components?
'y', // sessions ?
'y' // looks good?
));
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesController/')
);
$this->Task->execute();
}
/**
@ -417,27 +451,36 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
* @access public
*/
public function testInteractiveAdminMethodsNotInteractive() {
function testInteractiveAdminMethodsNotInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->interactive = true;
$this->Task->path = '/my/path';
$this->Task->setReturnValue('in', '1');
$this->Task->setReturnValueAt(1, 'in', 'y'); // build interactive
$this->Task->setReturnValueAt(2, 'in', 'n'); // build no scaffolds
$this->Task->setReturnValueAt(3, 'in', 'y'); // build normal methods
$this->Task->setReturnValueAt(4, 'in', 'y'); // build admin methods
$this->Task->setReturnValueAt(5, 'in', 'n'); // helpers?
$this->Task->setReturnValueAt(6, 'in', 'n'); // components?
$this->Task->setReturnValueAt(7, 'in', 'y'); // use sessions
$this->Task->setReturnValueAt(8, 'in', 'y'); // looks good
$this->Task->setReturnValue('createFile', true);
$this->Task->Project->setReturnValue('getPrefix', 'admin_');
$this->Task->path = '/my/path/';
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(
'1',
'y', // build interactive
'n', // build no scaffolds
'y', // build normal methods
'y', // build admin methods
'n', // helpers?
'n', // components?
'y', // sessions ?
'y' // looks good?
));
$this->Task->Project->expects($this->any())
->method('getPrefix')
->will($this->returnValue('admin_'));
$filename = '/my/path/articles_controller.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesController/')
)->will($this->returnValue(true));
$result = $this->Task->execute();
$this->assertPattern('/admin_index/', $result);
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
}
/**
@ -455,12 +498,14 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->Test->expectCallCount('bake', 1);
$this->Task->expects($this->any())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->Test->expects($this->once())->method('bake');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesController/')
)->will($this->returnValue(true));
$this->Task->execute();
}
@ -481,19 +526,32 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->args = array('Articles');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new PatternExpectation('/\$scaffold/')
));
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
new PHPUnit_Framework_Constraint_PCREMatch('/\$scaffold/')
);
$this->Task->execute();
}
/**
* test that both plural and singular forms work for controller baking.
* data provider for testExecuteWithControllerNameVariations
*
* @return void
*/
public function testExecuteWithControllerNameVariations() {
static function nameVariations() {
return array(
array('Articles'), array('Article'), array('article'), array('articles')
);
}
/**
* test that both plural and singular forms work for controller baking.
*
* @dataProvider nameVariations
* @return void
*/
public function testExecuteWithControllerNameVariations($name) {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
@ -501,41 +559,12 @@ class ControllerTaskTest extends CakeTestCase {
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles');
$this->Task->args = array($name);
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new PatternExpectation('/\$scaffold/')
));
$this->Task->execute();
$this->Task->args = array('Article');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(1, 'createFile', array(
$filename, new PatternExpectation('/class ArticlesController/')
));
$this->Task->execute();
$this->Task->args = array('article');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(2, 'createFile', array(
$filename, new PatternExpectation('/class ArticlesController/')
));
$this->Task->args = array('articles');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(3, 'createFile', array(
$filename, new PatternExpectation('/class ArticlesController/')
));
$this->Task->execute();
$this->Task->args = array('Articles');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(4, 'createFile', array(
$filename, new PatternExpectation('/class ArticlesController/')
));
$this->Task->execute();
$this->Task->expects($this->once())->method('createFile')->with(
$filename, new PHPUnit_Framework_Constraint_PCREMatch('/\$scaffold/')
);
$this->Task->execute();
}
@ -555,10 +584,10 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->args = array('Articles', 'public');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new NoPatternExpectation('/var \$scaffold/')
));
$expected = new PHPUnit_Framework_Constraint_Not(new PHPUnit_Framework_Constraint_PCREMatch('/\$scaffold/'));
$this->Task->expects($this->once())->method('createFile')->with(
$filename, $expected
);
$this->Task->execute();
}
@ -573,16 +602,15 @@ class ControllerTaskTest extends CakeTestCase {
if ($skip) {
return;
}
$this->Task->Project->setReturnValue('getPrefix', 'admin_');
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles', 'public', 'admin');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new PatternExpectation('/admin_index/')
));
$this->Task->expects($this->once())->method('createFile')->with(
$filename, new PHPUnit_Framework_Constraint_PCREMatch('/admin_index/')
);
$this->Task->execute();
}
@ -597,16 +625,15 @@ class ControllerTaskTest extends CakeTestCase {
if ($skip) {
return;
}
$this->Task->Project->setReturnValue('getPrefix', 'admin_');
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles', 'admin');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new PatternExpectation('/admin_index/')
));
$this->Task->expects($this->once())->method('createFile')->with(
$filename, new PHPUnit_Framework_Constraint_PCREMatch('/admin_index/')
);
$this->Task->execute();
}
}

View file

@ -31,17 +31,7 @@ if (!class_exists('ShellDispatcher')) {
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'db_config.php';
//require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestDbConfigTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'DbConfigTask', 'MockDbConfigTask',
array('in', 'hr', 'out', 'err', 'createFile', '_stop', '_checkUnitTest')
);
class TEST_DATABASE_CONFIG {
public $default = array(
@ -79,9 +69,13 @@ class DbConfigTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestDbConfigTaskMockShellDispatcher();
$this->Task =& new MockDbConfigTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('DbConfigTask',
array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest', '_verify'),
array(&$this->Dispatcher)
);
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->params['working'] = rtrim(APP, DS);
@ -104,7 +98,7 @@ class DbConfigTaskTest extends CakeTestCase {
* @return void
*/
public function testGetConfig() {
$this->Task->setReturnValueAt(0, 'in', 'otherOne');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('otherOne'));
$result = $this->Task->getConfig();
$this->assertEqual($result, 'otherOne');
}
@ -129,21 +123,21 @@ class DbConfigTaskTest extends CakeTestCase {
*/
public function testExecuteIntoInteractive() {
$this->Task->initialize();
$this->Task = $this->getMock('DbConfigTask', array('in', '_stop', 'createFile'), array(&$this->Dispatcher));
$this->Task->expectOnce('_stop');
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', 'default');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'localhost');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->setReturnValueAt(4, 'in', 'root');
$this->Task->setReturnValueAt(5, 'in', 'password');
$this->Task->setReturnValueAt(6, 'in', 'cake_test');
$this->Task->setReturnValueAt(7, 'in', 'n');
$this->Task->setReturnValueAt(8, 'in', 'y');
$this->Task->setReturnValueAt(9, 'in', 'y');
$this->Task->setReturnValueAt(10, 'in', 'y');
$this->Task->setReturnValueAt(11, 'in', 'n');
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('default')); //name
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('mysql')); //db type
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); //persistant
$this->Task->expects($this->at(3))->method('in')->will($this->returnValue('localhost')); //server
$this->Task->expects($this->at(4))->method('in')->will($this->returnValue('n')); //port
$this->Task->expects($this->at(5))->method('in')->will($this->returnValue('root')); //user
$this->Task->expects($this->at(6))->method('in')->will($this->returnValue('password')); //password
$this->Task->expects($this->at(10))->method('in')->will($this->returnValue('cake_test')); //db
$this->Task->expects($this->at(11))->method('in')->will($this->returnValue('n')); //prefix
$this->Task->expects($this->at(12))->method('in')->will($this->returnValue('n')); //encoding
$this->Task->expects($this->at(13))->method('in')->will($this->returnValue('y')); //looks good
$this->Task->expects($this->at(14))->method('in')->will($this->returnValue('n')); //another
$result = $this->Task->execute();
}

View file

@ -35,12 +35,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'extract.php';
Mock::generatePartial(
'ShellDispatcher', 'TestExtractTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
/**
* ExtractTaskTest class
*
@ -55,7 +49,9 @@ class ExtractTaskTest extends CakeTestCase {
* @return void
*/
public function setUp() {
$this->Dispatcher =& new TestExtractTaskMockShellDispatcher();
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task =& new ExtractTask($this->Dispatcher);
}
@ -81,8 +77,9 @@ class ExtractTaskTest extends CakeTestCase {
$this->Task->params['paths'] = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'pages';
$this->Task->params['output'] = $path . DS;
$this->Task->Dispatch->expectNever('stderr');
$this->Task->Dispatch->expectNever('_stop');
$this->Dispatcher->expects($this->never())->method('stderr');
$this->Dispatcher->expects($this->never())->method('_stop');
$this->Task->execute();
$this->assertTrue(file_exists($path . DS . 'default.pot'));
$result = file_get_contents($path . DS . 'default.pot');
@ -132,7 +129,7 @@ class ExtractTaskTest extends CakeTestCase {
$this->assertPattern($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:14\n';
$pattern .= '\#: (\\\\|\/)home\.ctp:74\n';
$pattern .= '\#: (\\\\|\/)home\.ctp:66\n';
$pattern .= 'msgid "Editing this Page"\nmsgstr ""/';
$this->assertPattern($pattern, $result);

View file

@ -33,21 +33,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'fixture.php';
Mock::generatePartial(
'ShellDispatcher', 'TestFixtureTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'FixtureTask', 'MockFixtureTask',
array('in', 'out', 'err', 'createFile', '_stop')
);
Mock::generatePartial(
'Shell', 'MockFixtureModelTask',
array('in', 'out', 'err', 'createFile', '_stop', 'getName', 'getTable', 'listAll')
);
/**
* FixtureTaskTest class
*
@ -70,11 +55,18 @@ class FixtureTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestFixtureTaskMockShellDispatcher();
$this->Task =& new MockFixtureTask();
$this->Task->Model =& new MockFixtureModelTask();
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('FixtureTask',
array('in', 'err', 'createFile', '_stop'),
array(&$this->Dispatcher)
);
$this->Task->Model = $this->getMock('Shell',
array('in', 'out', 'erro', 'createFile', 'getName', 'getTable', 'listAll'),
array(&$this->Dispatcher)
);
$this->Task->Template =& new TemplateTask($this->Dispatcher);
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template->initialize();
}
@ -96,7 +88,7 @@ class FixtureTaskTest extends CakeTestCase {
*/
public function testConstruct() {
$this->Dispatch->params['working'] = DS . 'my' . DS . 'path';
$Task =& new FixtureTask($this->Dispatch);
$Task = new FixtureTask($this->Dispatch);
$expected = DS . 'my' . DS . 'path' . DS . 'tests' . DS . 'fixtures' . DS;
$this->assertEqual($Task->path, $expected);
@ -107,25 +99,39 @@ class FixtureTaskTest extends CakeTestCase {
*
* @return void
*/
public function testImportOptions() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'y');
public function testImportOptionsSchemaRecords() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article', 'records' => true);
$this->assertEqual($result, $expected);
}
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->setReturnValueAt(4, 'in', 'n');
/**
* test importOptions choosing nothing.
*
* @return void
*/
public function testImportOptionsNothing() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array();
$this->assertEqual($result, $expected);
}
$this->Task->setReturnValueAt(5, 'in', 'n');
$this->Task->setReturnValueAt(6, 'in', 'n');
$this->Task->setReturnValueAt(7, 'in', 'y');
/**
* test importOptions choosing from Table.
*
* @return void
*/
public function testImportOptionsTable() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y'));
$result = $this->Task->importOptions('Article');
$expected = array('fromTable' => true);
$this->assertEqual($result, $expected);
@ -138,10 +144,15 @@ class FixtureTaskTest extends CakeTestCase {
*/
public function testImportRecordsFromDatabaseWithConditions() {
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', 'WHERE 1=1 LIMIT 10');
$this->Task->expects($this->at(0))->method('in')
->will($this->returnValue('WHERE 1=1 LIMIT 10'));
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', false, array('fromTable' => true, 'schema' => 'Article', 'records' => false));
$result = $this->Task->bake('Article', false, array(
'fromTable' => true, 'schema' => 'Article', 'records' => false
));
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/public \$records/', $result);
@ -161,37 +172,39 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
$this->Task->execute();
}
/**
* data provider for model name variations.
*
* @return array
*/
public static function modelNameProvider() {
return array(
array('article'), array('articles'), array('Articles'), array('Article')
);
}
/**
* test that execute passes runs bake depending with named model.
*
* @dataProvider modelNameProvider
* @return void
*/
public function testExecuteWithNamedModelVariations() {
public function testExecuteWithNamedModelVariations($modelName) {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$this->Task->args = array($modelName);
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
$this->Task->args = array('articles');
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$this->Task->args = array('Articles');
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$this->Task->args = array('Article');
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
}
@ -204,14 +217,17 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->Model->setReturnValue('listAll', array('articles', 'comments'));
$this->Task->Model->expects($this->any())->method('listAll')
->will($this->returnValue(array('articles', 'comments')));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
$filename = '/my/path/comment_fixture.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class CommentFixture/')));
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CommentFixture/'));
$this->Task->execute();
}
@ -225,14 +241,19 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params = array('count' => 10, 'records' => true);
$this->Task->Model->setReturnValue('listAll', array('articles', 'comments'));
$this->Task->Model->expects($this->any())->method('listAll')
->will($this->returnValue(array('articles', 'comments')));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/title\' => \'Third Article\'/')));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/title\' => \'Third Article\'/'));
$filename = '/my/path/comment_fixture.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/comment\' => \'First Comment for First Article/')));
$this->Task->expectCallCount('createFile', 2);
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/comment\' => \'First Comment for First Article/'));
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->all();
}
@ -245,12 +266,16 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->setReturnValue('in', 'y');
$this->Task->Model->setReturnValue('getName', 'Article');
$this->Task->Model->setReturnValue('getTable', 'articles', array('Article'));
$this->Task->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Task->Model->expects($this->any())->method('getName')->will($this->returnValue('Article'));
$this->Task->Model->expects($this->any())->method('getTable')
->with('Article')
->will($this->returnValue('articles'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticleFixture/'));
$this->Task->execute();
}
@ -315,10 +340,14 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->path = '/my/path/';
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/Article/')));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/Article/'));
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/\<\?php(.*)\?\>/ms'));
$result = $this->Task->generateFixtureFile('Article', array());
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/\<\?php(.*)\?\>/ms')));
$result = $this->Task->generateFixtureFile('Article', array());
}
@ -333,7 +362,9 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->plugin = 'TestFixture';
$filename = APP . 'plugins' . DS . 'test_fixture' . DS . 'tests' . DS . 'fixtures' . DS . 'article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/Article/')));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/Article/'));
$result = $this->Task->generateFixtureFile('Article', array());
}
}

View file

@ -36,23 +36,6 @@ require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'fixture.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestModelTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ModelTask', 'MockModelTask',
array('in', 'out', 'hr', 'err', 'createFile', '_stop', '_checkUnitTest')
);
Mock::generate(
'Model', 'MockModelTaskModel'
);
Mock::generate(
'FixtureTask', 'MockModelTaskFixtureTask'
);
/**
* ModelTaskTest class
*
@ -75,15 +58,42 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestModelTaskMockShellDispatcher();
$this->Task =& new MockModelTask($this->Dispatcher);
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('ModelTask',
array('in', 'err', 'createFile', '_stop', '_checkUnitTest'),
array(&$this->Dispatcher)
);
$this->_setupOtherMocks();
}
/**
* Setup a mock that has out mocked. Normally this is not used as it makes $this->at() really tricky.
*
* @return void
*/
protected function _useMockedOut() {
$this->Task = $this->getMock('ModelTask',
array('in', 'out', 'err', 'hr', 'createFile', '_stop', '_checkUnitTest'),
array(&$this->Dispatcher)
);
$this->_setupOtherMocks();
}
/**
* sets up the rest of the dependencies for Model Task
*
* @return void
*/
protected function _setupOtherMocks() {
$this->Task->Fixture = $this->getMock('FixtureTask', array(), array(&$this->Dispatcher));
$this->Task->Test = $this->getMock('FixtureTask', array(), array(&$this->Dispatcher));
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->name = 'ModelTask';
$this->Task->interactive = true;
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template =& new TemplateTask($this->Task->Dispatch);
$this->Task->Fixture =& new MockModelTaskFixtureTask();
$this->Task->Test =& new MockModelTaskFixtureTask();
}
/**
@ -102,21 +112,24 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testListAll() {
$this->Task->expectAt(1, 'out', array('1. Article'));
$this->Task->expectAt(2, 'out', array('2. ArticlesTag'));
$this->Task->expectAt(3, 'out', array('3. CategoryThread'));
$this->Task->expectAt(4, 'out', array('4. Comment'));
$this->Task->expectAt(5, 'out', array('5. Tag'));
$this->_useMockedOut();
$this->Task->expects($this->at(1))->method('out')->with('1. Article');
$this->Task->expects($this->at(2))->method('out')->with('2. ArticlesTag');
$this->Task->expects($this->at(3))->method('out')->with('3. CategoryThread');
$this->Task->expects($this->at(4))->method('out')->with('4. Comment');
$this->Task->expects($this->at(5))->method('out')->with('5. Tag');
$this->Task->expects($this->at(7))->method('out')->with('1. Article');
$this->Task->expects($this->at(8))->method('out')->with('2. ArticlesTag');
$this->Task->expects($this->at(9))->method('out')->with('3. CategoryThread');
$this->Task->expects($this->at(10))->method('out')->with('4. Comment');
$this->Task->expects($this->at(11))->method('out')->with('5. Tag');
$result = $this->Task->listAll('test_suite');
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
$this->assertEqual($result, $expected);
$this->Task->expectAt(7, 'out', array('1. Article'));
$this->Task->expectAt(8, 'out', array('2. ArticlesTag'));
$this->Task->expectAt(9, 'out', array('3. CategoryThread'));
$this->Task->expectAt(10, 'out', array('4. Comment'));
$this->Task->expectAt(11, 'out', array('5. Tag'));
$this->Task->connection = 'test_suite';
$result = $this->Task->listAll();
$expected = array('articles', 'articles_tags', 'category_threads', 'comments', 'tags');
@ -128,26 +141,41 @@ class ModelTaskTest extends CakeTestCase {
*
* @return void
*/
public function testGetName() {
$this->Task->setReturnValue('in', 1);
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->expectOnce('_stop');
public function testGetNameQuit() {
$this->Task->expects($this->once())->method('in')->will($this->returnValue('q'));
$this->Task->expects($this->once())->method('_stop');
$this->Task->getName('test_suite');
}
/**
* test getName with a valid option.
*
* @return void
*/
function testGetNameValidOption() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue(1));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(4));
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getName('test_suite');
$expected = 'Article';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 4);
$result = $this->Task->getName('test_suite');
$expected = 'Comment';
$this->assertEqual($result, $expected);
}
/**
* test that an out of bounds option causes an error.
*
* @return void
*/
function testGetNameWithOutOfBoundsOption() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue(10));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue(1));
$this->Task->expects($this->once())->method('err');
$this->Task->setReturnValueAt(3, 'in', 10);
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
}
/**
@ -156,13 +184,20 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testGetTableName() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$result = $this->Task->getTable('Article', 'test_suite');
$expected = 'articles';
$this->assertEqual($result, $expected);
}
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'my_table');
/**
* test gettting a custom table name.
*
* @return void
*/
function testGetTableNameCustom() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('my_table'));
$result = $this->Task->getTable('Article', 'test_suite');
$expected = 'my_table';
$this->assertEqual($result, $expected);
@ -215,10 +250,8 @@ class ModelTaskTest extends CakeTestCase {
public function testInteractiveFieldValidation() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '20');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', '16');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('20', 'y', '16', 'n'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty', 'maxlength' => 'maxlength');
@ -231,12 +264,15 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
function testInteractiveFieldValidationWithBogusResponse() {
$this->_useMockedOut();
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '999999');
$this->Task->setReturnValueAt(1, 'in', '20');
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->expectAt(4, 'out', array(new PatternExpectation('/make a valid/')));
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('999999', '20', 'n'));
$this->Task->expects($this->at(7))->method('out')
->with(new PHPUnit_Framework_Constraint_PCREMatch('/make a valid/'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
@ -251,8 +287,8 @@ class ModelTaskTest extends CakeTestCase {
function testInteractiveFieldValidationWithRegexp() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '/^[a-z]{0,9}$/');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('/^[a-z]{0,9}$/'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('a_z_0_9' => '/^[a-z]{0,9}$/');
@ -265,9 +301,9 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testNonInteractiveDoValidation() {
$Model =& new MockModelTaskModel();
$Model = $this->getMock('Model');
$Model->primaryKey = 'id';
$Model->setReturnValue('schema', array(
$Model->expects($this->any())->method('schema')->will($this->returnValue(array(
'id' => array(
'type' => 'integer',
'length' => 11,
@ -299,7 +335,7 @@ class ModelTaskTest extends CakeTestCase {
'length' => '',
'null' => false,
)
));
)));
$this->Task->interactive = false;
$result = $this->Task->doValidation($Model);
@ -331,8 +367,11 @@ class ModelTaskTest extends CakeTestCase {
'two' => array(),
'key' => array('key' => 'primary')
);
$this->Task->expectAt(0, 'in', array('*', null, 'key'));
$this->Task->setReturnValue('in', 'my_field');
$anything = new PHPUnit_Framework_Constraint_IsAnything();
$this->Task->expects($this->once())->method('in')
->with($anything, null, 'key')
->will($this->returnValue('my_field'));
$result = $this->Task->findPrimaryKey($fields);
$expected = 'my_field';
$this->assertEqual($result, $expected);
@ -343,17 +382,28 @@ class ModelTaskTest extends CakeTestCase {
*
* @return void
*/
public function testFindDisplayField() {
$fields = array('id' => array(), 'tagname' => array(), 'body' => array(),
'created' => array(), 'modified' => array());
$this->Task->setReturnValue('in', 'n');
$this->Task->setReturnValueAt(0, 'in', 'n');
public function testFindDisplayFieldNone() {
$fields = array(
'id' => array(), 'tagname' => array(), 'body' => array(),
'created' => array(), 'modified' => array()
);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$result = $this->Task->findDisplayField($fields);
$this->assertFalse($result);
}
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', 2);
/**
* Test finding a displayname from user input
*
* @return void
*/
public function testFindDisplayName() {
$fields = array(
'id' => array(), 'tagname' => array(), 'body' => array(),
'created' => array(), 'modified' => array()
);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(2));
$result = $this->Task->findDisplayField($fields);
$this->assertEqual($result, 'tagname');
}
@ -507,7 +557,7 @@ class ModelTaskTest extends CakeTestCase {
public function testBakeFixture() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Fixture->expectAt(0, 'bake', array('Article', 'articles'));
$this->Task->Fixture->expects($this->at(0))->method('bake')->with('Article', 'articles');
$this->Task->bakeFixture('Article', 'articles');
$this->assertEqual($this->Task->plugin, $this->Task->Fixture->plugin);
@ -523,7 +573,7 @@ class ModelTaskTest extends CakeTestCase {
public function testBakeTest() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Test->expectAt(0, 'bake', array('Model', 'Article'));
$this->Task->Test->expects($this->at(0))->method('bake')->with('Model', 'Article');
$this->Task->bakeTest('Article');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
@ -562,11 +612,13 @@ class ModelTaskTest extends CakeTestCase {
)
);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('n', 'y', 'n', 'n', 'n'));
$result = $this->Task->confirmAssociations($model, $associations);
$this->assertTrue(empty($result['hasOne']));
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->confirmAssociations($model, $associations);
$this->assertTrue(empty($result['hasMany']));
$this->assertTrue(empty($result['hasOne']));
@ -578,16 +630,18 @@ class ModelTaskTest extends CakeTestCase {
* @return void
*/
public function testInOptions() {
$options = array('one', 'two', 'three');
$this->Task->expectAt(0, 'out', array('1. one'));
$this->Task->expectAt(1, 'out', array('2. two'));
$this->Task->expectAt(2, 'out', array('3. three'));
$this->Task->setReturnValueAt(0, 'in', 10);
$this->_useMockedOut();
$this->Task->expectAt(3, 'out', array('1. one'));
$this->Task->expectAt(4, 'out', array('2. two'));
$this->Task->expectAt(5, 'out', array('3. three'));
$this->Task->setReturnValueAt(1, 'in', 2);
$options = array('one', 'two', 'three');
$this->Task->expects($this->at(0))->method('out')->with('1. one');
$this->Task->expects($this->at(1))->method('out')->with('2. two');
$this->Task->expects($this->at(2))->method('out')->with('3. three');
$this->Task->expects($this->at(3))->method('in')->will($this->returnValue(10));
$this->Task->expects($this->at(4))->method('out')->with('1. one');
$this->Task->expects($this->at(5))->method('out')->with('2. two');
$this->Task->expects($this->at(6))->method('out')->with('3. three');
$this->Task->expects($this->at(7))->method('in')->will($this->returnValue(2));
$result = $this->Task->inOptions($options, 'Pick a number');
$this->assertEqual($result, 1);
}
@ -690,17 +744,12 @@ STRINGEND;
* @return void
*/
public function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'article.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('Article', array(), array());
$this->Task->plugin = 'controllerTest';
$path = APP . 'plugins' . DS . 'controller_test' . DS . 'models' . DS . 'article.php';
$this->Task->expectAt(1, 'createFile', array(
$path, new PatternExpectation('/Article extends ControllerTestAppModel/')));
$this->Task->expects($this->once())->method('createFile')
->with($path, new PHPUnit_Framework_Constraint_PCREMatch('/Article extends ControllerTestAppModel/'));
$this->Task->bake('Article', array(), array());
$this->assertEqual(count(ClassRegistry::keys()), 0);
@ -717,8 +766,11 @@ STRINGEND;
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article.php';
$this->Task->setReturnValue('_checkUnitTest', 1);
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article extends AppModel/')));
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article extends AppModel/'));
$this->Task->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
@ -726,27 +778,32 @@ STRINGEND;
}
/**
* test that execute passes with different inflections of the same name.
* data provider for testExecuteWithNamedModelVariations
*
* @return void
*/
public function testExecuteWithNamedModelVariations() {
static function nameVariations() {
return array(
array('Articles'), array('Article'), array('article'), array('articles')
);
}
/**
* test that execute passes with different inflections of the same name.
*
* @dataProvider nameVariations
* @return void
*/
public function testExecuteWithNamedModelVariations($name) {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->setReturnValue('_checkUnitTest', 1);
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->args = array('article');
$this->Task->args = array($name);
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article extends AppModel/')));
$this->Task->execute();
$this->Task->args = array('Articles');
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class Article extends AppModel/')));
$this->Task->execute();
$this->Task->args = array('articles');
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class Article extends AppModel/')));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article extends AppModel/'));
$this->Task->execute();
}
@ -760,8 +817,11 @@ STRINGEND;
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$filename = '/my/path/article.php';
$this->Task->setReturnValue('_checkUnitTest', 1);
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation("/'Comment' \=\> array\(/")));
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(1));
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch("/'Comment' \=\> array\(/"));
$this->Task->execute();
}
@ -774,25 +834,30 @@ STRINGEND;
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->Fixture->expectCallCount('bake', 5);
$this->Task->Test->expectCallCount('bake', 5);
$this->Task->Fixture->expects($this->exactly(5))->method('bake');
$this->Task->Test->expects($this->exactly(5))->method('bake');
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
$filename = '/my/path/articles_tag.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticlesTag/')));
$this->Task->expects($this->at(2))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesTag/'));
$filename = '/my/path/category_thread.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class CategoryThread/')));
$this->Task->expects($this->at(3))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CategoryThread/'));
$filename = '/my/path/comment.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class Comment/')));
$this->Task->expects($this->at(4))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Comment/'));
$filename = '/my/path/tag.php';
$this->Task->expectAt(4, 'createFile', array($filename, new PatternExpectation('/class Tag/')));
$this->Task->expects($this->at(5))
->method('createFile')->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Tag/'));
$this->Task->execute();
@ -809,23 +874,27 @@ STRINGEND;
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->skipTables = array('tags');
$this->Task->Fixture->expectCallCount('bake', 4);
$this->Task->Test->expectCallCount('bake', 4);
$this->Task->Fixture->expects($this->exactly(4))->method('bake');
$this->Task->Test->expects($this->exactly(4))->method('bake');
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
$filename = '/my/path/articles_tag.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticlesTag/')));
$this->Task->expects($this->at(2))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class ArticlesTag/'));
$filename = '/my/path/category_thread.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class CategoryThread/')));
$this->Task->expects($this->at(3))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class CategoryThread/'));
$filename = '/my/path/comment.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class Comment/')));
$this->Task->expects($this->at(4))->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Comment/'));
$this->Task->execute();
}
@ -840,22 +909,27 @@ STRINGEND;
$this->Task->path = '/my/path/';
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '1'); //choose article
$this->Task->setReturnValueAt(1, 'in', 'n'); //no validation
$this->Task->setReturnValueAt(2, 'in', 'y'); //yes to associations
$this->Task->setReturnValueAt(3, 'in', 'y'); //yes to comment relation
$this->Task->setReturnValueAt(4, 'in', 'y'); //yes to user relation
$this->Task->setReturnValueAt(5, 'in', 'y'); //yes to tag relation
$this->Task->setReturnValueAt(6, 'in', 'n'); //no to additional assocs
$this->Task->setReturnValueAt(7, 'in', 'y'); //yes to looksGood?
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls(
'1', // article
'n', // no validation
'y', // associations
'y', // comment relation
'y', // user relation
'y', // tag relation
'n', // additional assocs
'y' // looks good?
));
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->Test->expectOnce('bake');
$this->Task->Fixture->expectOnce('bake');
$this->Task->Test->expects($this->once())->method('bake');
$this->Task->Fixture->expects($this->once())->method('bake');
$filename = '/my/path/article.php';
$this->Task->expectOnce('createFile');
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$this->Task->expects($this->once())->method('createFile')
->with($filename, new PHPUnit_Framework_Constraint_PCREMatch('/class Article/'));
$this->Task->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
@ -871,11 +945,11 @@ STRINGEND;
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->expectOnce('_stop');
$this->Task->expectOnce('err');
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->once())->method('err');
$this->Task->setReturnValueAt(0, 'in', 'Foobar');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('Foobar'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$this->Task->execute();
}
}

View file

@ -20,6 +20,7 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
App::import('Core', array('File'));
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
@ -35,17 +36,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'plugin.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'model.php';
Mock::generatePartial(
'ShellDispatcher', 'TestPluginTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'PluginTask', 'MockPluginTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
Mock::generate('ModelTask', 'PluginTestMockModelTask');
/**
* PluginTaskPlugin class
*
@ -54,16 +44,23 @@ Mock::generate('ModelTask', 'PluginTestMockModelTask');
*/
class PluginTaskTest extends CakeTestCase {
public static $_paths = array();
public static $_testPath = array();
/**
* startTest method
*
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestPluginTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockPluginTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('PluginTask',
array('in', 'err', 'createFile', '_stop'),
array(&$this->Dispatcher)
);
$this->Task->path = TMP . 'tests' . DS;
}
@ -72,9 +69,9 @@ class PluginTaskTest extends CakeTestCase {
*
* @return void
*/
public function startCase() {
$this->_paths = $paths = App::path('plugins');
$this->_testPath = array_push($paths, TMP . 'tests' . DS);
public static function setUpBeforeClass() {
self::$_paths = $paths = App::path('plugins');
self::$_testPath = array_push($paths, TMP . 'tests' . DS);
App::build(array('plugins' => $paths));
}
@ -83,8 +80,8 @@ class PluginTaskTest extends CakeTestCase {
*
* @return void
*/
public function endCase() {
App::build(array('plugins' => $this->_paths));
public static function tearDownAfterClass() {
App::build(array('plugins' => self::$_paths));
}
/**
@ -102,8 +99,19 @@ class PluginTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeFoldersAndFiles() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue(self::$_testPath));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$path = $this->Task->path . 'bake_test_plugin';
$file = $path . DS . 'bake_test_plugin_app_controller.php';
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expects($this->at(4))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('BakeTestPlugin');
$path = $this->Task->path . 'bake_test_plugin';
@ -173,13 +181,7 @@ class PluginTaskTest extends CakeTestCase {
$this->assertTrue(is_dir($path . DS . 'libs'), 'No libs dir %s');
$this->assertTrue(is_dir($path . DS . 'webroot'), 'No webroot dir %s');
$file = $path . DS . 'bake_test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$Folder =& new Folder($this->Task->path . 'bake_test_plugin');
$Folder = new Folder($this->Task->path . 'bake_test_plugin');
$Folder->delete();
}
@ -189,22 +191,24 @@ class PluginTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithNoArgs() {
$this->Task->setReturnValueAt(0, 'in', 'TestPlugin');
$this->Task->setReturnValueAt(1, 'in', '3');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->setReturnValueAt(3, 'in', 'n');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestPlugin'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('3'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(3))->method('in')->will($this->returnValue('n'));
$path = $this->Task->path . 'test_plugin';
$file = $path . DS . 'test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$this->Task->expects($this->at(4))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = $path . DS . 'test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->expects($this->at(5))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->args = array();
$this->Task->execute();
$Folder =& new Folder($path);
$Folder = new Folder($path);
$Folder->delete();
}
@ -214,21 +218,27 @@ class PluginTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithOneArg() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->Dispatch->args = array('BakeTestPlugin');
$this->Task->args =& $this->Task->Dispatch->args;
$this->Task->expects($this->at(0))->method('in')
->will($this->returnValue(self::$_testPath));
$this->Task->expects($this->at(1))->method('in')
->will($this->returnValue('y'));
$path = $this->Task->path . 'bake_test_plugin';
$file = $path . DS . 'bake_test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$path = $this->Task->path . 'bake_test_plugin';
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->expects($this->at(4))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->Dispatch->args = array('BakeTestPlugin');
$this->Task->args =& $this->Task->Dispatch->args;
$this->Task->execute();
$Folder =& new Folder($this->Task->path . 'bake_test_plugin');
$Folder = new Folder($this->Task->path . 'bake_test_plugin');
$Folder->delete();
}
@ -238,17 +248,18 @@ class PluginTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithTwoArgs() {
$this->Task->Model =& new PluginTestMockModelTask();
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->Model = $this->getMock('ModelTask', array(), array(&$this->Dispatcher));
$Folder =& new Folder($this->Task->path . 'bake_test_plugin', true);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue(self::$_testPath));
$this->Task->Model->expects($this->once())->method('loadTasks');
$this->Task->Model->expects($this->once())->method('execute');
$Folder = new Folder($this->Task->path . 'bake_test_plugin', true);
$this->Task->Dispatch->args = array('BakeTestPlugin', 'model');
$this->Task->args =& $this->Task->Dispatch->args;
$this->Task->args = $this->Task->Dispatch->args;
$this->Task->Model->expectOnce('loadTasks');
$this->Task->Model->expectOnce('execute');
$this->Task->execute();
$Folder->delete();
}

View file

@ -20,6 +20,8 @@
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
App::import('Core', 'File');
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
@ -34,15 +36,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
Mock::generatePartial(
'ShellDispatcher', 'TestProjectTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ProjectTask', 'MockProjectTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
/**
* ProjectTask Test class
*
@ -57,10 +50,14 @@ class ProjectTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestProjectTaskMockShellDispatcher();
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('ProjectTask',
array('in', 'err', 'createFile', '_stop'),
array(&$this->Dispatcher)
);
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockProjectTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->path = TMP . 'tests' . DS;
}
@ -72,8 +69,9 @@ class ProjectTaskTest extends CakeTestCase {
public function endTest() {
ClassRegistry::flush();
$Folder =& new Folder($this->Task->path . 'bake_test_app');
$Folder = new Folder($this->Task->path . 'bake_test_app');
$Folder->delete();
unset($this->Dispatcher, $this->Task);
}
/**
@ -83,8 +81,8 @@ class ProjectTaskTest extends CakeTestCase {
*/
protected function _setupTestProject() {
$skel = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS . 'templates' . DS . 'skel';
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->bake($this->Task->path . 'bake_test_app', $skel);
}
@ -162,12 +160,12 @@ class ProjectTaskTest extends CakeTestCase {
$result = $this->Task->securitySalt($path);
$this->assertTrue($result);
$file =& new File($path . 'config' . DS . 'core.php');
$file = new File($path . 'config' . DS . 'core.php');
$contents = $file->read();
$this->assertNoPattern('/DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi/', $contents, 'Default Salt left behind. %s');
}
/**
/**
* test generation of Security.cipherSeed
*
* @return void
@ -179,7 +177,7 @@ class ProjectTaskTest extends CakeTestCase {
$result = $this->Task->securityCipherSeed($path);
$this->assertTrue($result);
$file =& new File($path . 'config' . DS . 'core.php');
$file = new File($path . 'config' . DS . 'core.php');
$contents = $file->read();
$this->assertNoPattern('/76859309657453542496749683645/', $contents, 'Default CipherSeed left behind. %s');
}
@ -195,11 +193,11 @@ class ProjectTaskTest extends CakeTestCase {
$path = $this->Task->path . 'bake_test_app' . DS;
$this->Task->corePath($path);
$file =& new File($path . 'webroot' . DS . 'index.php');
$file = new File($path . 'webroot' . DS . 'index.php');
$contents = $file->read();
$this->assertNoPattern('/define\(\'CAKE_CORE_INCLUDE_PATH\', \'ROOT/', $contents);
$file =& new File($path . 'webroot' . DS . 'test.php');
$file = new File($path . 'webroot' . DS . 'test.php');
$contents = $file->read();
$this->assertNoPattern('/define\(\'CAKE_CORE_INCLUDE_PATH\', \'ROOT/', $contents);
}
@ -217,12 +215,12 @@ class ProjectTaskTest extends CakeTestCase {
Configure::write('Routing.prefixes', null);
$this->_setupTestProject();
$this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'config' . DS;
$this->Task->setReturnValue('in', 'super_duper_admin');
$this->Task->expects($this->once())->method('in')->will($this->returnValue('super_duper_admin'));
$result = $this->Task->getPrefix();
$this->assertEqual($result, 'super_duper_admin_');
$file =& new File($this->Task->configPath . 'core.php');
$file = new File($this->Task->configPath . 'core.php');
$file->delete();
}
@ -232,9 +230,9 @@ class ProjectTaskTest extends CakeTestCase {
* @return void
*/
public function testCakeAdmin() {
$file =& new File(CONFIGS . 'core.php');
$file = new File(CONFIGS . 'core.php');
$contents = $file->read();;
$file =& new File(TMP . 'tests' . DS . 'core.php');
$file = new File(TMP . 'tests' . DS . 'core.php');
$file->write($contents);
Configure::write('Routing.prefixes', null);
@ -255,7 +253,7 @@ class ProjectTaskTest extends CakeTestCase {
Configure::write('Routing.prefixes', array('admin', 'ninja', 'shinobi'));
$this->_setupTestProject();
$this->Task->configPath = $this->Task->path . 'bake_test_app' . DS . 'config' . DS;
$this->Task->setReturnValue('in', 2);
$this->Task->expects($this->once())->method('in')->will($this->returnValue(2));
$result = $this->Task->getPrefix();
$this->assertEqual($result, 'ninja_');
@ -271,8 +269,8 @@ class ProjectTaskTest extends CakeTestCase {
$this->Task->params['working'] = TMP . 'tests' . DS;
$path = $this->Task->path . 'bake_test_app';
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', $path);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue($path));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$this->Task->execute();
$this->assertTrue(is_dir($path), 'No project dir %s');

View file

@ -35,16 +35,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestTemplateTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'TemplateTask', 'MockTemplateTask',
array('in', 'out', 'err', 'createFile', '_stop')
);
/**
* TemplateTaskTest class
*
@ -59,9 +49,13 @@ class TemplateTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestTemplateTaskMockShellDispatcher();
$this->Task =& new MockTemplateTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('TemplateTask',
array('in', 'err', 'createFile', '_stop'),
array(&$this->Dispatcher)
);
$this->Task->Dispatch->shellPaths = App::path('shells');
}
@ -113,7 +107,8 @@ class TemplateTaskTest extends CakeTestCase {
public function testGetThemePath() {
$defaultTheme = CAKE_CORE_INCLUDE_PATH . DS . dirname(CONSOLE_LIBS) . 'templates' . DS . 'default' .DS;
$this->Task->templatePaths = array('default' => $defaultTheme);
$this->Task->expectCallCount('in', 1);
$this->Task->expects($this->exactly(1))->method('in')->will($this->returnValue('1'));
$result = $this->Task->getThemePath();
$this->assertEqual($result, $defaultTheme);
@ -124,7 +119,6 @@ class TemplateTaskTest extends CakeTestCase {
$this->assertEqual($result, '/some/path');
$this->Task->params = array();
$this->Task->setReturnValueAt(0, 'in', '1');
$result = $this->Task->getThemePath();
$this->assertEqual($result, $defaultTheme);
$this->assertEqual($this->Dispatcher->params['theme'], 'default');
@ -142,7 +136,8 @@ class TemplateTaskTest extends CakeTestCase {
)
));
$this->Task->initialize();
$this->Task->setReturnValue('in', 1);
$this->Task->expects($this->any())->method('in')->will($this->returnValue(1));
$result = $this->Task->generate('classes', 'test_object', array('test' => 'foo'));
$expected = "I got rendered\nfoo";
$this->assertEqual($result, $expected);

View file

@ -37,16 +37,6 @@ if (!class_exists('ShellDispatcher')) {
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'test.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
Mock::generatePartial(
'ShellDispatcher', 'TestTestTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'TestTask', 'MockTestTask',
array('in', '_stop', 'err', 'out', 'createFile', 'isLoadableClass')
);
/**
* Test Article model
*
@ -258,11 +248,15 @@ class TestTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestTestTaskMockShellDispatcher();
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('TestTask',
array('in', 'err', 'createFile', '_stop', 'isLoadableClass'),
array(&$this->Dispatcher)
);
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockTestTask($this->Dispatcher);
$this->Task->name = 'TestTask';
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Dispatcher);
}
@ -280,21 +274,24 @@ class TestTaskTest extends CakeTestCase {
*
* @return void
*/
public function testFilePathGeneration() {
public function testFilePathGenerationModelRepeated() {
$this->Task->Dispatch->expects($this->never())->method('stderr');
$this->Task->Dispatch->expects($this->never())->method('_stop');
$file = TESTS . 'cases' . DS . 'models' . DS . 'my_class.test.php';
$this->Task->Dispatch->expectNever('stderr');
$this->Task->Dispatch->expectNever('_stop');
$this->Task->expects($this->at(1))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->setReturnValue('in', 'y');
$this->Task->expectAt(0, 'createFile', array($file, '*'));
$this->Task->bake('Model', 'MyClass');
$this->Task->expectAt(1, 'createFile', array($file, '*'));
$this->Task->bake('Model', 'MyClass');
$this->Task->expects($this->at(3))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = TESTS . 'cases' . DS . 'controllers' . DS . 'comments_controller.test.php';
$this->Task->expectAt(2, 'createFile', array($file, '*'));
$this->Task->expects($this->at(5))->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('Model', 'MyClass');
$this->Task->bake('Model', 'MyClass');
$this->Task->bake('Controller', 'Comments');
}
@ -344,11 +341,12 @@ class TestTaskTest extends CakeTestCase {
* @return void
*/
public function testGetObjectType() {
$this->Task->expectOnce('_stop');
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('q'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue(2));
$this->Task->getObjectType();
$this->Task->setReturnValueAt(1, 'in', 2);
$result = $this->Task->getObjectType();
$this->assertEqual($result, $this->Task->classTypes[1]);
}
@ -388,11 +386,12 @@ class TestTaskTest extends CakeTestCase {
if ($skip) {
return;
}
$this->Task->setReturnValueAt(0, 'in', 'MyCustomClass');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('MyCustomClass'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(1));
$result = $this->Task->getClassName('Model');
$this->assertEqual($result, 'MyCustomClass');
$this->Task->setReturnValueAt(1, 'in', 1);
$result = $this->Task->getClassName('Model');
$options = App::objects('model');
$this->assertEqual($result, $options[0]);
@ -404,8 +403,10 @@ class TestTaskTest extends CakeTestCase {
* @return void
*/
public function testGetUserFixtures() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')
->will($this->returnValue('app.pizza, app.topping, app.side_dish'));
$result = $this->Task->getUserFixtures();
$expected = array('app.pizza', 'app.topping', 'app.side_dish');
$this->assertEqual($result, $expected);
@ -440,8 +441,8 @@ class TestTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeModelTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$result = $this->Task->bake('Model', 'TestTaskArticle');
@ -458,9 +459,7 @@ class TestTaskTest extends CakeTestCase {
$this->assertPattern('/function testDoSomethingElse\(\)/i', $result);
$this->assertPattern("/'app\.test_task_article'/", $result);
if (PHP5) {
$this->assertPattern("/'plugin\.test_task\.test_task_comment'/", $result);
}
$this->assertPattern("/'app\.test_task_tag'/", $result);
$this->assertPattern("/'app\.articles_tag'/", $result);
}
@ -473,8 +472,8 @@ class TestTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeControllerTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expects($this->once())->method('createFile')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$result = $this->Task->bake('Controller', 'TestTaskComments');
@ -493,9 +492,7 @@ class TestTaskTest extends CakeTestCase {
$this->assertPattern('/unset\(\$this->TestTaskComments\)/', $result);
$this->assertPattern("/'app\.test_task_article'/", $result);
if (PHP5) {
$this->assertPattern("/'plugin\.test_task\.test_task_comment'/", $result);
}
$this->assertPattern("/'app\.test_task_tag'/", $result);
$this->assertPattern("/'app\.articles_tag'/", $result);
}
@ -538,7 +535,9 @@ class TestTaskTest extends CakeTestCase {
$this->Task->plugin = 'TestTest';
$path = APP . 'plugins' . DS . 'test_test' . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'form.test.php';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->expects($this->once())->method('createFile')
->with($path, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('Helper', 'Form');
}
@ -583,9 +582,13 @@ class TestTaskTest extends CakeTestCase {
*/
public function testExecuteWithOneArg() {
$this->Task->args[0] = 'Model';
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expectAt(0, 'createFile', array('*', new PatternExpectation('/class TestTaskTagTestCase extends CakeTestCase/')));
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag'));
$this->Task->expects($this->once())->method('isLoadableClass')->will($this->returnValue(true));
$this->Task->expects($this->once())->method('createFile')
->with(
new PHPUnit_Framework_Constraint_IsAnything(),
new PHPUnit_Framework_Constraint_PCREMatch('/class TestTaskTagTestCase extends CakeTestCase/')
);
$this->Task->execute();
}
@ -596,9 +599,13 @@ class TestTaskTest extends CakeTestCase {
*/
public function testExecuteWithTwoArgs() {
$this->Task->args = array('Model', 'TestTaskTag');
$this->Task->setReturnValueAt(0, 'in', 'TestTaskTag');
$this->Task->setReturnValue('isLoadableClass', true);
$this->Task->expectAt(0, 'createFile', array('*', new PatternExpectation('/class TestTaskTagTestCase extends CakeTestCase/')));
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('TestTaskTag'));
$this->Task->expects($this->once())->method('createFile')
->with(
new PHPUnit_Framework_Constraint_IsAnything(),
new PHPUnit_Framework_Constraint_PCREMatch('/class TestTaskTagTestCase extends CakeTestCase/')
);
$this->Task->expects($this->any())->method('isLoadableClass')->will($this->returnValue(true));
$this->Task->execute();
}
}

View file

@ -37,17 +37,6 @@ require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.p
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'template.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
Mock::generatePartial(
'ShellDispatcher', 'TestViewTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
Mock::generatePartial(
'ViewTask', 'MockViewTask',
array('in', '_stop', 'err', 'out', 'createFile')
);
Mock::generate('ControllerTask', 'ViewTaskMockControllerTask');
Mock::generate('ProjectTask', 'ViewTaskMockProjectTask');
/**
* Test View Task Comment Model
@ -242,14 +231,18 @@ class ViewTaskTest extends CakeTestCase {
* @return void
*/
public function startTest() {
$this->Dispatcher =& new TestViewTaskMockShellDispatcher();
$this->Dispatcher = $this->getMock('ShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
$this->Task = $this->getMock('ViewTask',
array('in', 'err', 'createFile', '_stop'),
array(&$this->Dispatcher)
);
$this->Task->Template = new TemplateTask($this->Dispatcher);
$this->Task->Controller = $this->getMock('ControllerTask', array(), array(&$this->Dispatcher));
$this->Task->Project = $this->getMock('ProjectTask', array(), array(&$this->Dispatcher));
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockViewTask($this->Dispatcher);
$this->Task->name = 'ViewTask';
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Template =& new TemplateTask($this->Dispatcher);
$this->Task->Controller =& new ViewTaskMockControllerTask();
$this->Task->Project =& new ViewTaskMockProjectTask();
$this->Task->path = TMP;
$this->Task->Template->params['theme'] = 'default';
@ -340,23 +333,50 @@ class ViewTaskTest extends CakeTestCase {
*
* @return void
*/
public function testBake() {
public function testBakeView() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/View Task Articles/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/View Task Articles/')
);
$this->Task->bake('view', true);
}
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'edit.ctp', '*'));
/**
* test baking an edit file
*
* @return void
*/
function testBakeEdit() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->bake('edit', true);
}
$this->Task->expectAt(2, 'createFile', array(
/**
* test baking an index
*
* @return void
*/
function testBakeIndex() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/\$viewTaskComment\[\'Article\'\]\[\'title\'\]/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/\$viewTaskComment\[\'Article\'\]\[\'title\'\]/')
);
$this->Task->bake('index', true);
}
@ -369,9 +389,12 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->plugin = 'TestTest';
$this->Task->name = 'ViewTask';
$path = APP . 'plugins' . DS . 'test_test' . DS . 'views' . DS . 'view_task_comments' . DS . 'view.ctp';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->expects($this->once())->method('createFile')
->with($path, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('view', true);
}
@ -384,18 +407,21 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/View Task Comments/')
));
$this->Task->expectAt(1, 'createFile', array(
new PHPUnit_Framework_Constraint_PCREMatch('/View Task Comments/')
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PatternExpectation('/Edit View Task Comment/')
));
$this->Task->expectAt(2, 'createFile', array(
new PHPUnit_Framework_Constraint_PCREMatch('/Edit View Task Comment/')
);
$this->Task->expects($this->at(2))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->bakeActions(array('view', 'edit', 'index'), array());
}
@ -410,10 +436,14 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->controllerPath = 'view_task_comments';
$this->Task->params['app'] = APP;
$this->Task->setReturnValueAt(0, 'in', '');
$this->Task->setReturnValueAt(1, 'in', 'my_action');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'my_action.ctp', '*'));
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('', 'my_action', 'y'));
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'my_action.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->customAction();
}
@ -426,12 +456,20 @@ class ViewTaskTest extends CakeTestCase {
public function testExecuteIntoAll() {
$this->Task->args[0] = 'all';
$this->Task->Controller->setReturnValue('listAll', array('view_task_comments'));
$this->Task->Controller->expectOnce('listAll');
$this->Task->Controller->expects($this->once())->method('listAll')
->will($this->returnValue(array('view_task_comments')));
$this->Task->expectCallCount('createFile', 2);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->execute();
}
@ -444,11 +482,14 @@ class ViewTaskTest extends CakeTestCase {
public function testExecuteIntoAllWithActionName() {
$this->Task->args = array('all', 'index');
$this->Task->Controller->setReturnValue('listAll', array('view_task_comments'));
$this->Task->Controller->expectOnce('listAll');
$this->Task->Controller->expects($this->once())->method('listAll')
->will($this->returnValue(array('view_task_comments')));
$this->Task->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->execute();
}
@ -462,8 +503,11 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->args[1] = 'view';
$this->Task->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'view.ctp', '*'));
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->execute();
}
@ -476,29 +520,49 @@ class ViewTaskTest extends CakeTestCase {
public function testExecuteWithController() {
$this->Task->args[0] = 'ViewTaskComments';
$this->Task->expectCallCount('createFile', 2);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->execute();
}
/**
* test that both plural and singular forms can be used for baking views.
* static dataprovider for test cases
*
* @return void
*/
public function testExecuteWithControllerVariations() {
$this->Task->args = array('ViewTaskComments');
public static function nameVariations() {
return array(array('ViewTaskComments'), array('ViewTaskComment'), array('view_task_comment'));
}
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->execute();
/**
* test that both plural and singular forms can be used for baking views.
*
* @dataProvider nameVariations
* @return void
*/
public function testExecuteWithControllerVariations($name) {
$this->Task->args = array($name);
$this->Task->args = array('ViewTaskComment');
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'add.ctp', '*'));
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->expects($this->at(1))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PHPUnit_Framework_Constraint_IsAnything()
);
$this->Task->execute();
}
@ -513,14 +577,19 @@ class ViewTaskTest extends CakeTestCase {
Configure::write('Routing.prefixes', array('admin'));
$this->Task->args[0] = 'ViewTaskArticles';
$this->Task->params['admin'] = 1;
$this->Task->Project->setReturnValue('getPrefix', 'admin_');
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_index.ctp', '*'));
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_add.ctp', '*'));
$this->Task->expectAt(2, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_view.ctp', '*'));
$this->Task->expectAt(3, 'createFile', array(TMP . 'view_task_articles' . DS . 'admin_edit.ctp', '*'));
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->expects($this->exactly(4))->method('createFile');
$views = array('admin_index.ctp', 'admin_add.ctp', 'admin_view.ctp', 'admin_edit.ctp');
foreach ($views as $i => $view) {
$this->Task->expects($this->at($i))->method('createFile')
->with(
TMP . 'view_task_articles' . DS . $view,
new PHPUnit_Framework_Constraint_IsAnything()
);
}
$this->Task->execute();
Configure::write('Routing', $_back);
}
@ -535,30 +604,38 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->args = array();
$this->Task->params = array();
$this->Task->Controller->setReturnValue('getName', 'ViewTaskComments');
$this->Task->setReturnValue('in', 'y');
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->Controller->expects($this->once())->method('getName')
->will($this->returnValue('ViewTaskComments'));
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('y', 'y', 'n'));
$this->Task->expects($this->at(3))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PatternExpectation('/Add View Task Comment/')
));
$this->Task->expectAt(3, 'createFile', array(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PatternExpectation('/Edit View Task Comment/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->expects($this->at(4))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->expects($this->at(5))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'add.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/Add View Task Comment/')
);
$this->Task->expects($this->at(6))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/Edit View Task Comment/')
);
$this->Task->expects($this->exactly(4))->method('createFile');
$this->Task->execute();
}
@ -572,11 +649,11 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->args = array('ViewTaskComments', 'index', 'list');
$this->Task->params = array();
$this->Task->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(
$this->Task->expects($this->once())->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'list.ctp',
new PatternExpectation('/ViewTaskComment/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->execute();
}
@ -590,30 +667,40 @@ class ViewTaskTest extends CakeTestCase {
$this->Task->connection = 'test_suite';
$this->Task->args = array();
$this->Task->Controller->setReturnValue('getName', 'ViewTaskComments');
$this->Task->Project->setReturnValue('getPrefix', 'admin_');
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'n');
$this->Task->setReturnValueAt(2, 'in', 'y');
$this->Task->Controller->expects($this->once())->method('getName')
->will($this->returnValue('ViewTaskComments'));
$this->Task->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
$this->Task->Project->expects($this->once())->method('getPrefix')
->will($this->returnValue('admin_'));
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('y', 'n', 'y'));
$this->Task->expects($this->at(3))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'admin_index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_view.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_add.ctp',
new PatternExpectation('/Add View Task Comment/')
));
$this->Task->expectAt(3, 'createFile', array(
TMP . 'view_task_comments' . DS . 'admin_edit.ctp',
new PatternExpectation('/Edit View Task Comment/')
));
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->expects($this->at(4))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'admin_view.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/ViewTaskComment/')
);
$this->Task->expects($this->at(5))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'admin_add.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/Add View Task Comment/')
);
$this->Task->expects($this->at(6))->method('createFile')
->with(
TMP . 'view_task_comments' . DS . 'admin_edit.ctp',
new PHPUnit_Framework_Constraint_PCREMatch('/Edit View Task Comment/')
);
$this->Task->expects($this->exactly(4))->method('createFile');
$this->Task->execute();
}

View file

@ -42,14 +42,11 @@ class TestDispatcher extends Dispatcher {
* @return void
*/
protected function _invoke(&$controller, $params) {
restore_error_handler();
if ($result = parent::_invoke($controller, $params)) {
if ($result[0] === 'missingAction') {
return $result;
}
}
set_error_handler('simpleTestErrorHandler');
return $controller;
}
@ -537,7 +534,7 @@ class DispatcherTest extends CakeTestCase {
*
* @return void
*/
public function startTest() {
public function setUp() {
$this->_get = $_GET;
$_GET = array();
$this->_post = $_POST;
@ -563,7 +560,7 @@ class DispatcherTest extends CakeTestCase {
*
* @return void
*/
public function endTest() {
public function tearDown() {
$_GET = $this->_get;
$_POST = $this->_post;
$_FILES = $this->_files;
@ -581,6 +578,7 @@ class DispatcherTest extends CakeTestCase {
*/
public function testParseParamsWithoutZerosAndEmptyPost() {
$Dispatcher = new Dispatcher();
$test = $Dispatcher->parseParams(new CakeRequest("/testcontroller/testaction/params1/params2/params3"));
$this->assertIdentical($test['controller'], 'testcontroller');
$this->assertIdentical($test['action'], 'testaction');
@ -600,8 +598,8 @@ class DispatcherTest extends CakeTestCase {
$Dispatcher = new Dispatcher();
$test = $Dispatcher->parseParams(new CakeRequest("/"));
$this->assertTrue(isset($test['form']), "Parsed URL not returning post data");
$this->assertIdentical($test['form']['testdata'], "My Posted Content");
$this->assertFalse(empty($test['form']), "Parsed URL not returning post data");
$this->assertEquals($test['form']['testdata'], "My Posted Content");
}
/**
@ -659,6 +657,7 @@ class DispatcherTest extends CakeTestCase {
*/
public function testParseParamsWithMixedOneToManyZerosInEachSectionOfUrl() {
$Dispatcher = new Dispatcher();
$request = new CakeRequest("/testcontroller/testaction/01/0403/04010/000002/000030/0000400");
$test = $Dispatcher->parseParams($request);
$this->assertPattern('/\\A(?:01)\\z/', $test['pass'][0]);
@ -690,6 +689,7 @@ class DispatcherTest extends CakeTestCase {
$Dispatcher = new Dispatcher();
$uri = new CakeRequest('/?coffee=life&sleep=sissy');
$result = $Dispatcher->parseParams($uri);
$this->assertPattern('/pages/', $result['controller']);
$this->assertPattern('/display/', $result['action']);
@ -704,7 +704,7 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
public function testPrivate() {
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Configure::write('App.baseUrl','/index.php');
$url = 'some_pages/_protected/param:value/param2:value2';
@ -726,7 +726,7 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
public function testMissingAction() {
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Configure::write('App.baseUrl', '/index.php');
$url = 'some_pages/home/param:value/param2:value2';
@ -741,7 +741,7 @@ class DispatcherTest extends CakeTestCase {
)));
$this->assertEqual($expected, $controller);
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Configure::write('App.baseUrl','/index.php');
$url = 'some_pages/redirect/param:value/param2:value2';
@ -763,6 +763,9 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatch() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$Dispatcher = new TestDispatcher();
Configure::write('App.baseUrl','/index.php');
$url = 'pages/home/param:value/param2:value2';
@ -823,6 +826,9 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
public function testDispatchWithArray() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
Router::reload();
Configure::write('App.baseUrl', '/index.php');
$Dispatcher = new TestDispatcher();
@ -890,7 +896,7 @@ class DispatcherTest extends CakeTestCase {
$expected = array(
'pass' => array('home'),
'named' => array('param'=> 'value', 'param2'=> 'value2'), 'plugin'=> 'my_plugin',
'controller'=> 'some_pages', 'action'=> 'display', 'form'=> null,
'controller'=> 'some_pages', 'action'=> 'display', 'form'=> array(),
'url'=> array('url'=> 'my_plugin/some_pages/home/param:value/param2:value2'),
);
foreach ($expected as $key => $value) {
@ -919,7 +925,7 @@ class DispatcherTest extends CakeTestCase {
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
Router::reload();
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Router::connect(
'/my_plugin/:controller/:action/*',
array('plugin' => 'my_plugin', 'controller' => 'pages', 'action' => 'display')
@ -1053,7 +1059,7 @@ class DispatcherTest extends CakeTestCase {
App::setObjects('plugin', $plugins);
Router::reload();
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
$Dispatcher->base = false;
$url = 'my_plugin/';
@ -1081,7 +1087,7 @@ class DispatcherTest extends CakeTestCase {
), true);
App::objects('plugin', null, false);
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
$Dispatcher->base = false;
$url = 'test_plugin/';
@ -1118,7 +1124,7 @@ class DispatcherTest extends CakeTestCase {
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
Router::reload();
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
$Dispatcher->base = false;
$url = 'my_plugin/not_here/param:value/param2:value2';
@ -1134,7 +1140,7 @@ class DispatcherTest extends CakeTestCase {
$this->assertIdentical($expected, $controller);
Router::reload();
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
$Dispatcher->base = false;
$url = 'my_plugin/param:value/param2:value2';
@ -1212,7 +1218,7 @@ class DispatcherTest extends CakeTestCase {
*/
public function testChangingParamsFromBeforeFilter() {
$_SERVER['PHP_SELF'] = '/cake/repo/branches/1.2.x.x/index.php';
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
$url = 'some_posts/index/param:value/param2:value2';
$controller = $Dispatcher->dispatch($url, array('return' => 1));
@ -1261,12 +1267,12 @@ class DispatcherTest extends CakeTestCase {
ob_start();
$Dispatcher->dispatch('theme/test_theme/../webroot/css/test_asset.css');
$result = ob_get_clean();
$this->assertFalse($result);
$this->assertEquals($result, '');
ob_start();
$Dispatcher->dispatch('theme/test_theme/pdfs');
$result = ob_get_clean();
$this->assertFalse($result);
$this->assertEquals($result, '');
ob_start();
$Dispatcher->dispatch('theme/test_theme/flash/theme_test.swf');
@ -1379,7 +1385,7 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
function testMissingAssetProcessor404() {
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Configure::write('Asset.filter', array(
'js' => '',
'css' => null
@ -1400,7 +1406,7 @@ class DispatcherTest extends CakeTestCase {
* @return void
*/
function testAssetFilterForThemeAndPlugins() {
$Dispatcher =& new TestDispatcher();
$Dispatcher = new TestDispatcher();
Configure::write('Asset.filter', array(
'js' => '',
'css' => ''
@ -1449,7 +1455,6 @@ class DispatcherTest extends CakeTestCase {
), true);
$dispatcher = new TestDispatcher();
$url = '/';
ob_start();
@ -1584,7 +1589,7 @@ class DispatcherTest extends CakeTestCase {
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$dispatcher =& new TestDispatcher();
$dispatcher = new TestDispatcher();
$dispatcher->base = false;
$url = 'test_cached_pages/cache_form';

View file

@ -0,0 +1,47 @@
<?php
/**
* AllBehaviorsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllBehaviorsTest class
*
* This test group will run all test in the cases/libs/models/behaviors directory
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllBehaviorsTest extends PHPUnit_Framework_TestSuite {
/**
* Suite define the tests for this suite
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('Model Behavior and all behaviors');
$path = CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'behaviors' . DS;
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_behavior.test.php');
$suite->addTestFile($path . 'acl.test.php');
// $suite->addTestFile($path . 'containable.test.php');
$suite->addTestFile($path . 'translate.test.php');
$suite->addTestFile($path . 'tree.test.php');
return $suite;
}
}

View file

@ -0,0 +1,49 @@
<?php
/**
* AllCacheEnginesTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllCacheEnginesTest class
*
* This test group will run cache engine tests.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllCacheEnginesTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Cache related class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cache.test.php');
$cacheIterator = new DirectoryIterator(CORE_TEST_CASES . DS . 'libs' . DS . 'cache');
foreach ($cacheIterator as $i => $file) {
if (!$file->isDot()) {
$suite->addTestfile($file->getPathname());
}
}
return $suite;
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* AllConfigureTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllConfigureTest class
*
* This test group will run cache engine tests.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllConfigureTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Configure, App and ClassRegistry related tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'configure.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'class_registry.test.php');
return $suite;
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* AllControllersTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllControllersTest class
*
* This test group will run cache engine tests.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllControllersTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Controller related class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'controller.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'scaffold.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'pages_controller.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'component.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'controller_merge_vars.test.php');
return $suite;
}
}

View file

@ -0,0 +1,47 @@
<?php
/**
* AllDatabaseTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllDatabaseTest class
*
* This test group will run database tests not in model or behavior group.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllDatabaseTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('Datasources, Schema and DbAcl tests');
$path = CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS;
$tasks = array('db_acl', 'cake_schema', 'connection_manager', 'datasources' . DS . 'dbo_source');
foreach ($tasks as $task) {
$suite->addTestFile($path . $task . '.test.php');
}
return $suite;
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* HelpersGroupTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* HelpersGroupTest class
*
* This test group will run all test in the cases/libs/view/helpers directory.
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllHelpersTest extends PHPUnit_Framework_TestSuite {
/**
* suite declares tests to run
*
* @access public
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Helper tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helper.test.php');
$helperIterator = new DirectoryIterator(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS);
// The following test cases cause segfaults for me.
$segfaulty = array('form.test.php', 'cache.test.php', 'session.test.php');
foreach ($helperIterator as $i => $file) {
if (!$file->isDot() && !in_array($file->getFilename(), $segfaulty)) {
$suite->addTestfile($file->getPathname());
}
}
return $suite;
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* AllJavascriptHelpersTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllJavascriptHelpersTest class
*
* This test group will run all test in the cases/libs/view/helpers directory related
* to Js helper and its engines
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllJavascriptHelpersTest extends PHPUnit_Framework_TestSuite {
/**
* Suite define the tests for this suite
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('Js Helper and all Engine Helpers');
$helperTestPath = CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS;
$suite->addTestFile($helperTestPath . 'js.test.php');
$suite->addTestFile($helperTestPath . 'jquery_engine.test.php');
$suite->addTestFile($helperTestPath . 'mootools_engine.test.php');
$suite->addTestFile($helperTestPath . 'prototype_engine.test.php');
return $suite;
}
}

View file

@ -0,0 +1,54 @@
<?php
/**
* AllLibsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllLibsTest class
*
* This test group will run all non mvc related lib class tests
*
* @package cake
* @subpackage cake.tests.cases
*/
class AllLibsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All non-MVC lib class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'basics.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_session.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'debugger.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'error.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'file.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'folder.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'log' . DS . 'file_log.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_log.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'class_registry.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'sanitize.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'set.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'string.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'validation.test.php');
return $suite;
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* AllLocalizationTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllLocalizationTest class
*
* This test group will run i18n/l10n tests
*
* @package cake
* @subpackage cake.tests.cases
*/
class AllLocalizationTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All localization class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'i18n.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'l10n.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'multibyte.test.php');
return $suite;
}
}

View file

@ -0,0 +1,46 @@
<?php
/**
* AllModelTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllModelTest class
*
* This test group will run model class tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllModelTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Model related class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_behavior.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_read.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_write.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_validation.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'model' . DS . 'model_integration.test.php');
return $suite;
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* AllRoutingTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllRoutingTest class
*
* This test group will run view class tests (view, theme)
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllRoutingTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Router and Dispatcher class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'router.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'dispatcher.test.php');
return $suite;
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* AllSocketTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllSocketTest class
*
* This test group will run socket class tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllSocketTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Socket related class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_socket.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'http_socket.test.php');
return $suite;
}
}

View file

@ -0,0 +1,45 @@
<?php
/**
* AllTestSuiteTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllTestSuiteTest class
*
* This test group will run socket class tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllTestSuiteTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Test Suite classes tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'test_manager.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_test_case.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'cake_test_fixture.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'html_coverage_report.test.php');
return $suite;
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* AllViewsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllViewsTest class
*
* This test group will run view class tests (view, theme)
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllViewsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All View class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'view.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'theme.test.php');
return $suite;
}
}

View file

@ -0,0 +1,44 @@
<?php
/**
* AllXmlTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllXmlTest class
*
* This test group will run xml class tests
*
* @package cake
* @subpackage cake.tests.groups
*/
class AllXmlTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Xml related class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'xml.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS . 'rss.test.php');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'view' . DS . 'helpers' . DS . 'xml.test.php');
return $suite;
}
}

View file

@ -21,8 +21,6 @@ if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
Mock::generate('StdClass', 'RubbishEngine');
/**
* CacheTest class
*
@ -139,6 +137,7 @@ class CacheTest extends CakeTestCase {
* @return void
*/
function testAttemptingToConfigureANonCacheEngineClass() {
$this->getMock('StdClass', array(), array(), 'RubbishEngine');
$this->expectException();
Cache::config('Garbage', array(
'engine' => 'Rubbish'

View file

@ -205,7 +205,7 @@ class MemcacheEngineTest extends CakeTestCase {
$this->assertEqual($result, $expecting);
$result = Cache::read('long_expiry_test');
$this->assertTrue($result);
$this->assertEquals($expecting, $result);
Cache::config('memcache', array('duration' => 3600));
}

View file

@ -27,21 +27,7 @@ if (!class_exists('Cache')) {
* @package cake
* @subpackage cake.tests.cases.libs.cache
*/
class XcacheEngineTest extends UnitTestCase {
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$skip = true;
if (function_exists('xcache_set')) {
$skip = false;
}
$this->skipIf($skip, '%s Xcache is not installed or configured properly');
}
class XcacheEngineTest extends CakeTestCase {
/**
* setUp method
@ -50,6 +36,7 @@ class XcacheEngineTest extends UnitTestCase {
* @return void
*/
function setUp() {
$this->skipUnless(function_exists('xcache_set'), 'Xcache is not installed or configured properly');
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_'));

View file

@ -69,20 +69,20 @@ class CakeLogTest extends CakeTestCase {
/**
* test all the errors from failed logger imports
*
* @expectedException Exception
* @return void
*/
function testImportingLoggerFailure() {
$this->expectException();
CakeLog::config('fail', array());
}
/**
* test that loggers have to implement the correct interface.
*
* @expectedException Exception
* @return void
*/
function testNotImplementingInterface() {
$this->expectException();
CakeLog::config('fail', array('engine' => 'stdClass'));
}

View file

@ -226,7 +226,7 @@ class CakeSessionTest extends CakeTestCase {
$this->Session->write('Watching', "I'm watching you");
$this->Session->watch('Watching');
$this->expectError('Writing session key {Watching}: "They found us!"');
$this->expectError();
$this->Session->write('Watching', 'They found us!');
$this->expectError('Deleting session key {Watching}');
@ -390,7 +390,7 @@ class CakeSessionTest extends CakeTestCase {
$this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->assertNull($this->Session->read('SessionTestCase'));
}
/**
@ -427,7 +427,7 @@ class CakeSessionTest extends CakeTestCase {
$this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->assertNull($this->Session->read('SessionTestCase'));
}
/**
@ -465,7 +465,7 @@ class CakeSessionTest extends CakeTestCase {
$this->assertEqual($this->Session->read('SessionTestCase'), 'Some additional data');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->assertNull($this->Session->read('SessionTestCase'));
session_write_close();
unset($_SESSION);

View file

@ -131,7 +131,7 @@ class CakeSocketTest extends CakeTestCase {
*/
function testSocketWriting() {
$request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
$this->assertTrue($this->Socket->write($request));
$this->assertTrue((bool)$this->Socket->write($request));
}
/**

View file

@ -4,7 +4,7 @@
*
* Test Case for CakeTestCase class
*
* PHP versions 4 and 5
* PHP version 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
@ -19,7 +19,6 @@
* @since CakePHP v 1.2.0.4487
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'CakeTestCase');
if (!class_exists('AppController')) {
require_once LIBS . 'controller' . DS . 'app_controller.php';
@ -27,41 +26,6 @@ if (!class_exists('AppController')) {
define('APP_CONTROLLER_EXISTS', true);
}
Mock::generate('CakeHtmlReporter');
Mock::generate('CakeTestCase', 'CakeDispatcherMockTestCase');
SimpleTest::ignore('SubjectCakeTestCase');
SimpleTest::ignore('CakeDispatcherMockTestCase');
/**
* SubjectCakeTestCase
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SubjectCakeTestCase extends CakeTestCase {
/**
* Feed a Mocked Reporter to the subject case
* prevents its pass/fails from affecting the real test
*
* @param string $reporter
* @access public
* @return void
*/
function setReporter(&$reporter) {
$this->_reporter = &$reporter;
}
/**
* testDummy method
*
* @return void
*/
public function testDummy() {
}
}
/**
* CakeTestCaseTest
*
@ -70,6 +34,11 @@ class SubjectCakeTestCase extends CakeTestCase {
*/
class CakeTestCaseTest extends CakeTestCase {
public static function setUpBeforeClass() {
require_once TEST_CAKE_CORE_INCLUDE_PATH . DS . 'tests' . DS . 'fixtures' . DS . 'assert_tags_test_case.php';
require_once TEST_CAKE_CORE_INCLUDE_PATH . DS . 'tests' . DS . 'fixtures' . DS . 'fixturized_test_case.php';
}
/**
* setUp
*
@ -78,10 +47,7 @@ class CakeTestCaseTest extends CakeTestCase {
*/
function setUp() {
$this->_debug = Configure::read('debug');
$this->Case =& new SubjectCakeTestCase();
$reporter =& new MockCakeHtmlReporter();
$this->Case->setReporter($reporter);
$this->Reporter = $reporter;
$this->Reporter = $this->getMock('CakeHtmlReporter');
}
/**
@ -93,104 +59,22 @@ class CakeTestCaseTest extends CakeTestCase {
function tearDown() {
Configure::write('debug', $this->_debug);
unset($this->Case);
unset($this->Result);
unset($this->Reporter);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testAssertGoodTags
*
* @access public
* @return void
*/
function testAssertGoodTags() {
$this->Reporter->expectAtLeastOnce('paintPass');
$this->Reporter->expectNever('paintFail');
$input = '<p>Text</p>';
$pattern = array(
'<p',
'Text',
'/p',
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
$input = '<a href="/test.html" class="active">My link</a>';
$pattern = array(
'a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
$pattern = array(
'a' => array('class' => 'active', 'href' => '/test.html'),
'My link',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern), 'Attributes in wrong order. %s');
$input = "<a href=\"/test.html\"\t\n\tclass=\"active\"\tid=\"primary\">\t<span>My link</span></a>";
$pattern = array(
'a' => array('id' => 'primary', 'href' => '/test.html', 'class' => 'active'),
'<span',
'My link',
'/span',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern), 'Whitespace consumption %s');
$input = '<p class="info"><a href="/test.html" class="active"><strong onClick="alert(\'hey\');">My link</strong></a></p>';
$pattern = array(
'p' => array('class' => 'info'),
'a' => array('class' => 'active', 'href' => '/test.html' ),
'strong' => array('onClick' => 'alert(\'hey\');'),
'My link',
'/strong',
'/a',
'/p'
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
}
/**
* test that assertTags knows how to handle correct quoting.
*
* @return void
*/
function testAssertTagsQuotes() {
$input = '<a href="/test.html" class="active">My link</a>';
$pattern = array(
'a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern), 'Double quoted attributes %s');
$input = "<a href='/test.html' class='active'>My link</a>";
$pattern = array(
'a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern), 'Single quoted attributes %s');
$input = "<a href='/test.html' class='active'>My link</a>";
$pattern = array(
'a' => array('href' => 'preg:/.*\.html/', 'class' => 'active'),
'My link',
'/a'
);
$this->assertTrue($this->Case->assertTags($input, $pattern), 'Single quoted attributes %s');
$test = new AssertTagsTestCase('testAssertTagsQuotes');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertTrue($result->wasSuccessful());
$this->assertEquals(0, $result->failureCount());
}
/**
@ -200,109 +84,31 @@ class CakeTestCaseTest extends CakeTestCase {
* @return void
*/
function testNumericValuesInExpectationForAssertTags() {
$value = 220985;
$input = '<p><strong>' . $value . '</strong></p>';
$pattern = array(
'<p',
'<strong',
$value,
'/strong',
'/p'
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
$input = '<p><strong>' . $value . '</strong></p><p><strong>' . $value . '</strong></p>';
$pattern = array(
'<p',
'<strong',
$value,
'/strong',
'/p',
'<p',
'<strong',
$value,
'/strong',
'/p',
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
$input = '<p><strong>' . $value . '</strong></p><p id="' . $value . '"><strong>' . $value . '</strong></p>';
$pattern = array(
'<p',
'<strong',
$value,
'/strong',
'/p',
'p' => array('id' => $value),
'<strong',
$value,
'/strong',
'/p',
);
$this->assertTrue($this->Case->assertTags($input, $pattern));
$test = new AssertTagsTestCase('testNumericValuesInExpectationForAssertTags');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertTrue($result->wasSuccessful());
$this->assertEquals(0, $result->failureCount());
}
/**
/**
* testBadAssertTags
*
* @access public
* @return void
*/
function testBadAssertTags() {
$this->Reporter->expectAtLeastOnce('paintFail');
$this->Reporter->expectNever('paintPass');
$test = new AssertTagsTestCase('testBadAssertTags');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertFalse($result->wasSuccessful());
$this->assertEquals(1, $result->failureCount());
$input = '<a href="/test.html" class="active">My link</a>';
$pattern = array(
'a' => array('hRef' => '/test.html', 'clAss' => 'active'),
'My link',
'/a'
);
$this->assertFalse($this->Case->assertTags($input, $pattern));
$input = '<a href="/test.html" class="active">My link</a>';
$pattern = array(
'<a' => array('href' => '/test.html', 'class' => 'active'),
'My link',
'/a'
);
$this->assertFalse($this->Case->assertTags($input, $pattern));
}
/**
* testBefore
*
* @access public
* @return void
*/
function testBefore() {
$this->Case->before('testDummy');
$this->assertFalse(isset($this->Case->db));
$this->Case->fixtures = array('core.post');
$this->Case->before('start');
$this->assertTrue(isset($this->Case->db));
$this->assertTrue(isset($this->Case->_fixtures['core.post']));
$this->assertTrue(is_a($this->Case->_fixtures['core.post'], 'CakeTestFixture'));
$this->assertEqual($this->Case->_fixtureClassMap['Post'], 'core.post');
}
/**
* testAfter
*
* @access public
* @return void
*/
function testAfter() {
$this->Case->after('testDummy');
$this->assertFalse($this->Case->getTruncated());
$this->Case->fixtures = array('core.post');
$this->Case->before('start');
$this->Case->start();
$this->Case->after('testDummy');
$this->assertTrue($this->Case->getTruncated());
$test = new AssertTagsTestCase('testBadAssertTags2');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertFalse($result->wasSuccessful());
$this->assertEquals(1, $result->failureCount());
}
/**
@ -312,189 +118,80 @@ class CakeTestCaseTest extends CakeTestCase {
* @return void
*/
function testLoadFixtures() {
$this->Case->fixtures = array('core.post');
$this->Case->autoFixtures = false;
$this->Case->before('start');
$this->expectError();
$this->Case->loadFixtures('Wrong!');
$this->Case->end();
$test = new FixturizedTestCase('testFixturePresent');
$manager = $this->getMock('CakeFixtureManager');
$manager->fixturize($test);
$test->sharedFixture = $manager;
$manager->expects($this->once())->method('load');
$manager->expects($this->once())->method('unload');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
$this->assertTrue($result->wasSuccessful());
$this->assertEquals(0, $result->failureCount());
}
/**
* testGetTests Method
*
* @return void
*/
public function testGetTests() {
$result = $this->Case->getTests();
$this->assertEqual(array_slice($result, 0, 2), array('start', 'startCase'));
$this->assertEqual(array_slice($result, -2), array('endCase', 'end'));
}
/**
* TestTestAction
* testLoadFixturesOnDemand
*
* @access public
* @return void
*/
function testTestAction() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS)
), true);
$result = $this->Case->testAction('/tests_apps/index', array('return' => 'view'));
$this->assertPattern('/This is the TestsAppsController index view/', $result);
$result = $this->Case->testAction('/tests_apps/index', array('return' => 'contents'));
$this->assertPattern('/This is the TestsAppsController index view/', $result);
$this->assertPattern('/<html/', $result);
$this->assertPattern('/<\/html>/', $result);
$result = $this->Case->testAction('/tests_apps/some_method', array('return' => 'result'));
$this->assertEqual($result, 5);
$result = $this->Case->testAction('/tests_apps/set_action', array('return' => 'vars'));
$this->assertEqual($result, array('var' => 'string'));
$db =& ConnectionManager::getDataSource('test_suite');
$fixture =& new PostFixture();
$fixture->create($db);
$result = $this->Case->testAction('/tests_apps_posts/add', array('return' => 'vars'));
$this->assertTrue(array_key_exists('posts', $result));
$this->assertEqual(count($result['posts']), 1);
$result = $this->Case->testAction('/tests_apps_posts/url_var/var1:value1/var2:val2', array(
'return' => 'vars',
'method' => 'get',
));
$this->assertTrue(isset($result['params']['url']['url']));
$this->assertEqual(array_keys($result['params']['named']), array('var1', 'var2'));
$result = $this->Case->testAction('/tests_apps_posts/url_var/gogo/val2', array(
'return' => 'vars',
'method' => 'get',
));
$this->assertEqual($result['params']['pass'], array('gogo', 'val2'));
$result = $this->Case->testAction('/tests_apps_posts/url_var', array(
'return' => 'vars',
'method' => 'get',
'data' => array(
'red' => 'health',
'blue' => 'mana'
)
));
$this->assertTrue(isset($result['params']['url']['red']));
$this->assertTrue(isset($result['params']['url']['blue']));
$this->assertTrue(isset($result['params']['url']['url']));
$result = $this->Case->testAction('/tests_apps_posts/post_var', array(
'return' => 'vars',
'method' => 'post',
'data' => array(
'name' => 'is jonas',
'pork' => 'and beans',
)
));
$this->assertEqual(array_keys($result['data']), array('name', 'pork'));
$fixture->drop($db);
$db =& ConnectionManager::getDataSource('test_suite');
$_backPrefix = $db->config['prefix'];
$db->config['prefix'] = 'cake_testaction_test_suite_';
$config = $db->config;
$config['prefix'] = 'cake_testcase_test_';
ConnectionManager::create('cake_test_case', $config);
$db2 =& ConnectionManager::getDataSource('cake_test_case');
$fixture =& new PostFixture($db2);
$fixture->create($db2);
$fixture->insert($db2);
$result = $this->Case->testAction('/tests_apps_posts/fixtured', array(
'return' => 'vars',
'fixturize' => true,
'connection' => 'cake_test_case',
));
$this->assertTrue(isset($result['posts']));
$this->assertEqual(count($result['posts']), 3);
$tables = $db2->listSources();
$this->assertFalse(in_array('cake_testaction_test_suite_posts', $tables));
$fixture->drop($db2);
$db =& ConnectionManager::getDataSource('test_suite');
//test that drop tables behaves as exepected with testAction
$db =& ConnectionManager::getDataSource('test_suite');
$_backPrefix = $db->config['prefix'];
$db->config['prefix'] = 'cake_testaction_test_suite_';
$config = $db->config;
$config['prefix'] = 'cake_testcase_test_';
ConnectionManager::create('cake_test_case', $config);
$db =& ConnectionManager::getDataSource('cake_test_case');
$fixture =& new PostFixture($db);
$fixture->create($db);
$fixture->insert($db);
$this->Case->dropTables = false;
$result = $this->Case->testAction('/tests_apps_posts/fixtured', array(
'return' => 'vars',
'fixturize' => true,
'connection' => 'cake_test_case',
));
$tables = $db->listSources();
$this->assertTrue(in_array('cake_testaction_test_suite_posts', $tables));
$fixture->drop($db);
$db =& ConnectionManager::getDataSource('test_suite');
$db->config['prefix'] = $_backPrefix;
$fixture->drop($db);
function testLoadFixturesOnDemand() {
$test = new FixturizedTestCase('testFixtureLoadOnDemand');
$test->autoFixtures = false;
$manager = $this->getMock('CakeFixtureManager');
$manager->fixturize($test);
$test->sharedFixture = $manager;
$manager->expects($this->once())->method('loadSingle');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
}
/**
* testLoadFixturesOnDemand
*
* @access public
* @return void
*/
function testUnoadFixturesAfterFailure() {
$test = new FixturizedTestCase('testFixtureLoadOnDemand');
$test->autoFixtures = false;
$manager = $this->getMock('CakeFixtureManager');
$manager->fixturize($test);
$test->sharedFixture = $manager;
$manager->expects($this->once())->method('loadSingle');
$result = $test->run();
$this->assertEquals(0, $result->errorCount());
}
/**
* testThrowException
*
* @access public
* @return void
*/
function testThrowException() {
$test = new FixturizedTestCase('testThrowException');
$test->autoFixtures = false;
$manager = $this->getMock('CakeFixtureManager');
$manager->fixturize($test);
$test->sharedFixture = $manager;
$manager->expects($this->once())->method('unload');
$result = $test->run();
$this->assertEquals(1, $result->errorCount());
}
/**
* testSkipIf
*
* @return void
*/
function testSkipIf() {
$this->assertTrue($this->Case->skipIf(true));
$this->assertFalse($this->Case->skipIf(false));
}
$test = new FixturizedTestCase('testSkipIfTrue');
$result = $test->run();
$this->assertEquals(1, $result->skippedCount());
/**
* testTestDispatcher
*
* @access public
* @return void
*/
function testTestDispatcher() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'controllers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'controllers' . DS)
), true);
$Dispatcher =& new CakeTestDispatcher();
$Case =& new CakeDispatcherMockTestCase();
$Case->expectOnce('startController');
$Case->expectOnce('endController');
$Dispatcher->testCase($Case);
$this->assertTrue(isset($Dispatcher->testCase));
$return = $Dispatcher->dispatch('/tests_apps/index', array('autoRender' => 0, 'return' => 1, 'requested' => 1));
$test = new FixturizedTestCase('testSkipIfFalse');
$result = $test->run();
$this->assertEquals(0, $result->skippedCount());
}
}

View file

@ -84,7 +84,7 @@ class CakeTestFixtureImportFixture extends CakeTestFixture {
*
* @var mixed
*/
public $import = array('table' => 'fixture_tests', 'connection' => 'test_suite');
public $import = array('table' => 'fixture_tests', 'connection' => 'fixture_test_suite');
}
/**
@ -122,8 +122,6 @@ class FixturePrefixTest extends Model {
public $useDbConfig = 'test_suite';
}
Mock::generate('DboSource', 'FixtureMockDboSource');
/**
* Test case for CakeTestFixture
*
@ -139,8 +137,14 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function setUp() {
$this->criticDb =& new FixtureMockDboSource();
$this->criticDb = $this->getMock('DboSource');
$this->criticDb->fullDebug = true;
$dbs = ConnectionManager::enumConnectionObjects();
if (!isset($dbs['test_suite'])) {
$db = ConnectionManager::getDatasource('test');
ConnectionManager::create('test_suite', $db->config);
}
}
/**
@ -160,34 +164,35 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testInit() {
$Fixture =& new CakeTestFixtureTestFixture();
$Fixture = new CakeTestFixtureTestFixture();
unset($Fixture->table);
$Fixture->init();
$this->assertEqual($Fixture->table, 'fixture_tests');
$this->assertEqual($Fixture->primaryKey, 'id');
$Fixture =& new CakeTestFixtureTestFixture();
$Fixture = new CakeTestFixtureTestFixture();
$Fixture->primaryKey = 'my_random_key';
$Fixture->init();
$this->assertEqual($Fixture->primaryKey, 'my_random_key');
}
/**
* test that init() correctly sets the fixture table when the connection or model have prefixes defined.
*
* @return void
*/
function testInitDbPrefix() {
$this->_initDb();
$Source =& new CakeTestFixtureTestFixture();
$Source->create($this->db);
$Source->insert($this->db);
$db = ConnectionManager::getDataSource('test_suite');
$Source = new CakeTestFixtureTestFixture();
$Source->drop($db);
$Source->create($db);
$Source->insert($db);
$Fixture =& new CakeTestFixtureImportFixture();
$Fixture = new CakeTestFixtureTestFixture();
$expected = array('id', 'name', 'created');
$this->assertEqual(array_keys($Fixture->fields), $expected);
$db =& ConnectionManager::getDataSource('test_suite');
$config = $db->config;
$config['prefix'] = 'fixture_test_suite_';
ConnectionManager::create('fixture_test_suite', $config);
@ -196,17 +201,19 @@ class CakeTestFixtureTest extends CakeTestCase {
$Fixture->import = array('table' => 'fixture_tests', 'connection' => 'test_suite', 'records' => true);
$Fixture->init();
$this->assertEqual(count($Fixture->records), count($Source->records));
$Fixture->create(ConnectionManager::getDataSource('fixture_test_suite'));
$Fixture =& new CakeTestFixtureImportFixture();
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test_suite');
$Fixture->init();
$this->assertEqual(array_keys($Fixture->fields), array('id', 'name', 'created'));
$Fixture2 = new CakeTestFixtureImportFixture();
$Fixture2->fields = $Fixture->records = null;
$Fixture2->import = array('model' => 'FixtureImportTestModel', 'connection' => 'fixture_test_suite');
$Fixture2->init();
$this->assertEqual(array_keys($Fixture2->fields), array('id', 'name', 'created'));
$keys = array_flip(ClassRegistry::keys());
$this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
$Source->drop($this->db);
$Fixture->drop(ConnectionManager::getDataSource('fixture_test_suite'));
$Source->drop($db);
}
/**
@ -215,12 +222,13 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testInitModelTablePrefix() {
$this->_initDb();
$Source =& new CakeTestFixtureTestFixture();
$Source->create($this->db);
$Source->insert($this->db);
$db = ConnectionManager::getDataSource('test_suite');
$Fixture =& new CakeTestFixtureImportFixture();
$Source =& new CakeTestFixtureTestFixture();
$Source->create($db);
$Source->insert($db);
$Fixture =& new CakeTestFixtureTestFixture();
unset($Fixture->table);
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('model' => 'FixturePrefixTest', 'connection' => 'test_suite', 'records' => false);
@ -230,7 +238,7 @@ class CakeTestFixtureTest extends CakeTestCase {
$keys = array_flip(ClassRegistry::keys());
$this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
$Source->drop($this->db);
$Source->drop($db);
}
/**
@ -240,22 +248,20 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testImport() {
$this->_initDb();
$defaultDb =& ConnectionManager::getDataSource('default');
$testSuiteDb =& ConnectionManager::getDataSource('test_suite');
$defaultDb = ConnectionManager::getDataSource('default');
$testSuiteDb = ConnectionManager::getDataSource('test_suite');
$defaultConfig = $defaultDb->config;
$testSuiteConfig = $testSuiteDb->config;
ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix'])));
$newTestSuiteDb =& ConnectionManager::getDataSource('new_test_suite');
$newTestSuiteDb = ConnectionManager::getDataSource('new_test_suite');
$Source =& new CakeTestFixtureTestFixture();
$Source = new CakeTestFixtureTestFixture();
$Source->create($newTestSuiteDb);
$Source->insert($newTestSuiteDb);
$defaultDb->config = $newTestSuiteDb->config;
$Fixture =& new CakeTestFixtureDefaultImportFixture();
$Fixture = new CakeTestFixtureDefaultImportFixture();
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite');
$Fixture->init();
@ -276,22 +282,21 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testImportWithRecords() {
$this->_initDb();
$defaultDb =& ConnectionManager::getDataSource('default');
$testSuiteDb =& ConnectionManager::getDataSource('test_suite');
$defaultDb = ConnectionManager::getDataSource('default');
$testSuiteDb = ConnectionManager::getDataSource('test_suite');
$defaultConfig = $defaultDb->config;
$testSuiteConfig = $testSuiteDb->config;
ConnectionManager::create('new_test_suite', array_merge($testSuiteConfig, array('prefix' => 'new_' . $testSuiteConfig['prefix'])));
$newTestSuiteDb =& ConnectionManager::getDataSource('new_test_suite');
$newTestSuiteDb = ConnectionManager::getDataSource('new_test_suite');
$Source =& new CakeTestFixtureTestFixture();
$Source = new CakeTestFixtureTestFixture();
$Source->create($newTestSuiteDb);
$Source->insert($newTestSuiteDb);
$defaultDb->config = $newTestSuiteDb->config;
$Fixture =& new CakeTestFixtureDefaultImportFixture();
$Fixture = new CakeTestFixtureDefaultImportFixture();
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array(
'model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite', 'records' => true
@ -313,9 +318,9 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testCreate() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->expectAtLeastOnce('execute');
$this->criticDb->expectAtLeastOnce('createSchema');
$Fixture = new CakeTestFixtureTestFixture();
$this->criticDb->expects($this->atLeastOnce())->method('execute');
$this->criticDb->expects($this->atLeastOnce())->method('createSchema');
$return = $Fixture->create($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
$this->assertTrue($return);
@ -332,9 +337,8 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testInsert() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->setReturnValue('insertMulti', true);
$this->criticDb->expectAtLeastOnce('insertMulti');
$Fixture = new CakeTestFixtureTestFixture();
$this->criticDb->expects($this->atLeastOnce())->method('insertMulti')->will($this->returnValue(true));
$return = $Fixture->insert($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
@ -348,16 +352,15 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testDrop() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->setReturnValueAt(0, 'execute', true);
$this->criticDb->expectAtLeastOnce('execute');
$this->criticDb->expectAtLeastOnce('dropSchema');
$Fixture = new CakeTestFixtureTestFixture();
$this->criticDb->expects($this->at(1))->method('execute')->will($this->returnValue(true));
$this->criticDb->expects($this->at(3))->method('execute')->will($this->returnValue(false));
$this->criticDb->expects($this->exactly(2))->method('dropSchema');
$return = $Fixture->drop($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
$this->assertTrue($return);
$this->criticDb->setReturnValueAt(1, 'execute', false);
$return = $Fixture->drop($this->criticDb);
$this->assertFalse($return);
}
@ -369,8 +372,8 @@ class CakeTestFixtureTest extends CakeTestCase {
* @return void
*/
function testTruncate() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->expectAtLeastOnce('truncate');
$Fixture = new CakeTestFixtureTestFixture();
$this->criticDb->expects($this->atLeastOnce())->method('truncate');
$Fixture->truncate($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
}

View file

@ -165,69 +165,42 @@ class ClassRegistryTest extends CakeTestCase {
$Tag->name = 'SomeNewName';
if (PHP5) {
$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
} else {
$TagCopy =& ClassRegistry::getObject('RegisterArticleTag');
}
$this->assertTrue(is_a($TagCopy, 'RegisterArticleTag'));
$this->assertIdentical($Tag, $TagCopy);
$this->assertSame($Tag, $TagCopy);
if (PHP5) {
$NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
} else {
$NewTag =& ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
}
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
if (PHP5) {
$NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
} else {
$NewTagCopy =& ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
}
$this->assertNotIdentical($Tag, $NewTag);
$this->assertIdentical($NewTag, $NewTagCopy);
$NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertNotSame($Tag, $NewTag);
$this->assertSame($NewTag, $NewTagCopy);
$NewTag->name = 'SomeOtherName';
$this->assertNotIdentical($Tag, $NewTag);
$this->assertIdentical($NewTag, $NewTagCopy);
$this->assertNotSame($Tag, $NewTag);
$this->assertSame($NewTag, $NewTagCopy);
$Tag->name = 'SomeOtherName';
$this->assertNotIdentical($Tag, $NewTag);
$this->assertNotSame($Tag, $NewTag);
$this->assertTrue($TagCopy->name === 'SomeOtherName');
if (PHP5) {
$User = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
} else {
$User =& ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
}
$this->assertTrue(is_a($User, 'AppModel'));
if (PHP5) {
$UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
} else {
$UserCopy =& ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
}
$this->assertTrue(is_a($UserCopy, 'AppModel'));
$this->assertIdentical($User, $UserCopy);
$this->assertEquals($User, $UserCopy);
if (PHP5) {
$Category = ClassRegistry::init(array('class' => 'RegisterCategory'));
} else {
$Category =& ClassRegistry::init(array('class' => 'RegisterCategory'));
}
$this->assertTrue(is_a($Category, 'RegisterCategory'));
if (PHP5) {
$ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
} else {
$ParentCategory =& ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
}
$this->assertTrue(is_a($ParentCategory, 'RegisterCategory'));
$this->assertNotIdentical($Category, $ParentCategory);
$this->assertNotSame($Category, $ParentCategory);
$this->assertNotEqual($Category->alias, $ParentCategory->alias);
$this->assertEqual('RegisterCategory', $Category->alias);
@ -307,19 +280,11 @@ class ClassRegistryTest extends CakeTestCase {
$this->assertEqual($TestRegistryPluginModel->tablePrefix, 'something_');
if (PHP5) {
$PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
} else {
$PluginUser =& ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
}
$this->assertTrue(is_a($PluginUser, 'RegistryPluginAppModel'));
if (PHP5) {
$PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser');
} else {
$PluginUserCopy =& ClassRegistry::getObject('RegistryPluginUser');
}
$this->assertTrue(is_a($PluginUserCopy, 'RegistryPluginAppModel'));
$this->assertIdentical($PluginUser, $PluginUserCopy);
$this->assertSame($PluginUser, $PluginUserCopy);
}
}

View file

@ -1,512 +0,0 @@
<?php
/**
* CodeCoverageManagerTest file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once CAKE . 'tests' . DS . 'lib' . DS . 'code_coverage_manager.php';
require_once CAKE . 'tests' . DS . 'lib' . DS . 'reporter' . DS . 'cake_cli_reporter.php';
/**
* CodeCoverageManagerTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CodeCoverageManagerTest extends CakeTestCase {
/**
* Skip if XDebug not installed
*
*/
public function skip() {
$this->skipIf(!extension_loaded('xdebug'), '%s XDebug not installed');
}
/**
* startTest Method
* Store reference of $_GET to restore later.
*
* @return void
*/
function startCase() {
$this->_get = $_GET;
}
/**
* End Case - restore GET vars.
*
* @return void
*/
function endCase() {
$_GET = $this->_get;
}
/**
* testNoTestCaseSupplied method
*
* @access public
* @return void
*/
function testNoTestCaseSupplied() {
if ($this->skipIf(PHP_SAPI == 'cli', 'Is cli, cannot run this test %s')) {
return;
}
$reporter =& new CakeHtmlReporter(null, array('group' => false, 'app' => false, 'plugin' => false));
CodeCoverageManager::init(substr(md5(microtime()), 0, 5), $reporter);
CodeCoverageManager::report(false);
$this->assertError();
CodeCoverageManager::init('tests' . DS . 'lib' . DS . basename(__FILE__), $reporter);
CodeCoverageManager::report(false);
$this->assertError();
}
/**
* Test that test cases don't cause errors
*
* @return void
*/
function testNoTestCaseSuppliedNoErrors() {
if ($this->skipIf(PHP_SAPI == 'cli', 'Is cli, cannot run this test %s')) {
return;
}
$reporter =& new CakeHtmlReporter(null, array('group' => false, 'app' => false, 'plugin' => false));
$path = LIBS;
if (strpos(LIBS, ROOT) === false) {
$path = ROOT.DS.LIBS;
}
App::import('Core', 'Folder');
$folder = new Folder();
$folder->cd($path);
$contents = $folder->read();
$contents[1] = array_filter($contents[1], array(&$this, '_basenameFilter'));
foreach ($contents[1] as $file) {
CodeCoverageManager::init('libs' . DS . $file, $reporter);
CodeCoverageManager::report(false);
$this->assertNoErrors('libs' . DS . $file);
}
}
/**
* Remove file names that don't share a basename with the current file.
*
* @return void
*/
function _basenameFilter($var) {
return ($var != basename(__FILE__));
}
/**
* testGetTestObjectFileNameFromTestCaseFile method
*
* @access public
* @return void
*/
function testGetTestObjectFileNameFromTestCaseFile() {
$manager =& CodeCoverageManager::getInstance();
$manager->reporter = new CakeHtmlReporter();
$expected = $manager->__testObjectFileFromCaseFile('models/some_file.test.php', true);
$this->assertIdentical(APP.'models'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('models/datasources/some_file.test.php', true);
$this->assertIdentical(APP.'models'.DS.'datasources'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('controllers/some_file.test.php', true);
$this->assertIdentical(APP.'controllers'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('views/some_file.test.php', true);
$this->assertIdentical(APP.'views'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('behaviors/some_file.test.php', true);
$this->assertIdentical(APP.'models'.DS.'behaviors'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('components/some_file.test.php', true);
$this->assertIdentical(APP.'controllers'.DS.'components'.DS.'some_file.php', $expected);
$expected = $manager->__testObjectFileFromCaseFile('helpers/some_file.test.php', true);
$this->assertIdentical(APP.'views'.DS.'helpers'.DS.'some_file.php', $expected);
$manager->pluginTest = 'bugs';
$expected = $manager->__testObjectFileFromCaseFile('models/some_file.test.php', false);
$this->assertIdentical(APP.'plugins'.DS.'bugs'.DS.'models'.DS.'some_file.php', $expected);
$manager->pluginTest = false;
$manager->reporter = new CakeCliReporter;
$expected = $manager->__testObjectFileFromCaseFile('libs/set.test.php', false);
$this->assertIdentical(ROOT.DS.'cake'.DS.'libs'.DS.'set.php', $expected);
}
/**
* testOfHtmlDiffReport method
*
* @access public
* @return void
*/
function testOfHtmlDiffReport() {
$manager =& CodeCoverageManager::getInstance();
$code = <<<PHP
/**
* Set class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class Set extends Object {
/**
* Value of the Set object.
*
* @var array
* @access public
*/
var \$value = array();
/**
* Constructor. Defaults to an empty array.
*
*/
public function __construct() {
if (func_num_args() == 1 && is_array(func_get_arg(0))) {
\$this->value = func_get_arg(0);
} else {
\$this->value = func_get_args();
}
}
/**
* Returns the contents of the Set object
*
* @return array
*/
public function &get() {
return \$this->value;
}
/**
* This function can be thought of as a hybrid between PHP's array_merge and array_merge_recursive. The difference
* to the two is that if an array key contains another array then the function behaves recursive (unlike array_merge)
* but does not do if for keys containing strings (unlike array_merge_recursive). See the unit test for more information.
*
* Note: This function will work with an unlimited amount of arguments and typecasts non-array parameters into arrays.
*
* @param array \$arr1 Array to be merged
* @param array \$arr2 Array to merge with
* @return array Merged array
*/
public function merge(\$arr1, \$arr2 = null) {
\$args = func_get_args();
if (isset(\$this) && is_a(\$this, 'set')) {
\$backtrace = debug_backtrace();
\$previousCall = strtolower(\$backtrace[1]['class'].'::'.\$backtrace[1]['function']);
if (\$previousCall != 'set::merge') {
\$r =& \$this->value;
array_unshift(\$args, null);
}
}
if (!isset(\$r)) {
\$r = (array)current(\$args);
}
while ((\$arg = next(\$args)) !== false) {
if (is_a(\$arg, 'set')) {
\$arg = \$arg->get();
}
foreach ((array)\$arg as \$key => \$val) {
if (is_array(\$val) && isset(\$r[\$key]) && is_array(\$r[\$key])) {
\$r[\$key] = Set::merge(\$r[\$key], \$val);
} elseif (is_int(\$key)) {
} else {
\$r[\$key] = \$val;
}
}
}
return \$r;
}
PHP;
$testObjectFile = explode("\n", $code);
$coverageData = array(
0 => 1,
1 => 1,
2 => -2,
3 => -2,
4 => -2,
5 => -2,
6 => -2,
7 => -2,
8 => -1,
9 => -2,
10 => -2,
11 => -2,
12 => -2,
13 => -2,
14 => 1,
15 => 1,
16 => -1,
17 => 1,
18 => 1,
19 => -1,
20 => 1,
21 => -2,
22 => -2,
23 => -2,
24 => -2,
25 => -2,
26 => -2,
27 => 1,
28 => -1,
29 => 1,
30 => 1,
31 => -2,
32 => -2,
33 => -2,
34 => -2,
35 => -2,
36 => -2,
37 => -2,
38 => -2,
39 => -2,
40 => -2,
41 => -2,
42 => -2,
43 => -1,
44 => -2,
45 => -2,
46 => -2,
47 => -2,
48 => 1,
49 => 1,
50 => -1,
51 => 1,
52 => 1,
53 => -2,
54 => -2,
55 => 1,
56 => 1,
57 => 1,
58 => 1,
59 => -1,
60 => 1,
61 => 1,
62 => -2,
63 => -2,
64 => 1,
65 => -2,
66 => 1,
67 => -1,
68 => -2,
69 => -1,
70 => -1,
71 => 1,
72 => -2,
);
$expected = array(
0 => 'ignored',
1 => 'ignored',
2 => 'ignored',
3 => 'ignored',
4 => 'ignored',
5 => 'ignored show start realstart',
6 => 'ignored show',
7 => 'ignored show',
8 => 'uncovered show',
9 => 'ignored show',
10 => 'ignored show',
11 => 'ignored show end',
12 => 'ignored',
13 => 'ignored show start',
14 => 'covered show',
15 => 'covered show',
16 => 'uncovered show',
17 => 'covered show show',
18 => 'covered show show',
19 => 'uncovered show',
20 => 'covered show',
21 => 'ignored show',
22 => 'ignored show end',
23 => 'ignored',
24 => 'ignored',
25 => 'ignored show start',
26 => 'ignored show',
27 => 'covered show',
28 => 'uncovered show',
29 => 'covered show',
30 => 'covered show',
31 => 'ignored show end',
32 => 'ignored',
33 => 'ignored',
34 => 'ignored',
35 => 'ignored',
36 => 'ignored',
37 => 'ignored',
38 => 'ignored',
39 => 'ignored',
40 => 'ignored show start',
41 => 'ignored show',
42 => 'ignored show',
43 => 'uncovered show',
41 => 'ignored show',
42 => 'ignored show',
43 => 'uncovered show',
44 => 'ignored show',
45 => 'ignored show',
46 => 'ignored show',
47 => 'ignored show',
48 => 'covered show',
49 => 'covered show',
50 => 'uncovered show',
51 => 'covered show',
52 => 'covered show',
53 => 'ignored show end',
54 => 'ignored',
55 => 'covered',
56 => 'covered show start',
57 => 'covered show',
58 => 'covered show',
59 => 'uncovered show',
60 => 'covered show',
61 => 'covered show',
62 => 'ignored show end',
63 => 'ignored',
64 => 'covered show start',
65 => 'ignored show',
66 => 'covered show show',
67 => 'uncovered show',
68 => 'ignored show',
69 => 'uncovered show',
70 => 'uncovered show',
71 => 'covered show',
72 => 'ignored show',
73 => 'ignored show end end',
);
$execCodeLines = range(0, 72);
$result = explode("</div>", $report = $manager->reportCaseHtmlDiff($testObjectFile, $coverageData, $execCodeLines, 3));
foreach ($result as $line) {
preg_match('/<span class="line-num">(.*?)<\/span>/', $line, $matches);
if (!isset($matches[1])) {
continue;
}
$num = $matches[1];
$class = $expected[$num];
$pattern = '/<div class="code-line '.$class.'">/';
$this->assertPattern($pattern, $line, $num.': '.$line." fails");
}
}
/**
* testArrayStrrpos method
*
* @access public
* @return void
*/
function testArrayStrrpos() {
$manager =& CodeCoverageManager::getInstance();
$a = array(
'apples',
'bananas',
'oranges'
);
$this->assertEqual(1, $manager->__array_strpos($a, 'ba', true));
$this->assertEqual(2, $manager->__array_strpos($a, 'range', true));
$this->assertEqual(0, $manager->__array_strpos($a, 'pp', true));
$this->assertFalse($manager->__array_strpos('', 'ba', true));
$this->assertFalse($manager->__array_strpos(false, 'ba', true));
$this->assertFalse($manager->__array_strpos(array(), 'ba', true));
$a = array(
'rang',
'orange',
'oranges'
);
$this->assertEqual(0, $manager->__array_strpos($a, 'rang'));
$this->assertEqual(2, $manager->__array_strpos($a, 'rang', true));
$this->assertEqual(1, $manager->__array_strpos($a, 'orange', false));
$this->assertEqual(1, $manager->__array_strpos($a, 'orange'));
$this->assertEqual(2, $manager->__array_strpos($a, 'orange', true));
}
/**
* testGetExecutableLines method
*
* @access public
* @return void
*/
function testGetExecutableLines() {
$manager =& CodeCoverageManager::getInstance();
$code = <<<HTML
\$manager =& CodeCoverageManager::getInstance();
HTML;
$result = $manager->__getExecutableLines($code);
foreach ($result as $line) {
$this->assertNotIdentical($line, '');
}
$code = <<<HTML
{
}
<?php?>
?>
<?
}
{{}}
(())
@codeCoverageIgnoreStart
some
more
code
here
@codeCoverageIgnoreEnd
HTML;
$result = $manager->__getExecutableLines($code);
foreach ($result as $line) {
$this->assertIdentical(trim($line), '');
}
}
/**
* testCalculateCodeCoverage method
*
* @access public
* @return void
*/
function testCalculateCodeCoverage() {
$manager =& CodeCoverageManager::getInstance();
$data = array(
'25' => array(100, 25),
'50' => array(100, 50),
'0' => array(0, 0),
'0' => array(100, 0),
'100' => array(100, 100),
);
foreach ($data as $coverage => $lines) {
$this->assertEqual($coverage, $manager->__calcCoverage($lines[0], $lines[1]));
}
$manager->__calcCoverage(100, 1000);
$this->assertError();
}
}

View file

@ -648,14 +648,14 @@ class AppImportTest extends CakeTestCase {
*/
function testFileLoadingReturnValue () {
$file = App::import('File', 'Name', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', true);
$this->assertTrue($file);
$this->assertTrue(!empty($file));
$this->assertTrue(isset($file['Cake.version']));
$type = array('type' => 'File', 'name' => 'OtherName', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', 'return' => true);
$file = App::import($type);
$this->assertTrue($file);
$this->assertTrue(!empty($file));
$this->assertTrue(isset($file['Cake.version']));
}

View file

@ -288,7 +288,6 @@ class SomethingWithEmailComponent extends Object {
public $components = array('Email');
}
Mock::generate('Object', 'ComponentMockComponent', array('startup', 'beforeFilter', 'beforeRender', 'other'));
/**
* ComponentTest class
@ -422,15 +421,22 @@ class ComponentTest extends CakeTestCase {
* @return void
*/
function testTriggerCallback() {
$mock = $this->getMock(
'Object',
array('startup', 'beforeFilter', 'beforeRender', 'other'),
array(),
'ComponentMockComponent'
);
$Controller =& new ComponentTestController();
$Controller->components = array('ComponentMock');
$Controller->uses = null;
$Controller->constructClasses();
$Controller->ComponentMock->expectOnce('beforeRender');
$Controller->ComponentMock->expects($this->once())->method('beforeRender');
$Controller->ComponentMock->expects($this->never())->method('beforeFilter');
$Controller->Component->triggerCallback('beforeRender', $Controller);
$Controller->ComponentMock->expectNever('beforeFilter');
$Controller->ComponentMock->enabled = false;
$Controller->Component->triggerCallback('beforeFilter', $Controller);
}
@ -563,6 +569,54 @@ class ComponentTest extends CakeTestCase {
));
}
/**
* test that components can modify values from beforeRedirect
*
* @return void
*/
function testBeforeRedirectModification() {
$this->markTestIncomplete('This test needs to be implemented');
/*
*$MockController = new MockController();
$MockController->components = array('MockTest');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org');
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://book.cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', 301, false);
$MockController = new MockController();
$MockController->components = array('MockTest');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', false);
$MockController->expectNever('header');
$MockController->redirect('http://cakephp.org', 301, false);
$MockController = new MockController();
$MockController->components = array('MockTest', 'MockTestB');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org');
$MockController->MockTestB->setReturnValue('beforeRedirect', 'http://bakery.cakephp.org');
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://bakery.cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', 301, false);
*/
}
/**
* test that components can pass modifying values from beforeRedirect
*
* @return void
*/
function testBeforeRedirectPass() {
$this->markTestIncomplete('This test needs to be implemented');
}
/**
* Test that SessionComponent doesn't get added if its already in the components array.
*

View file

@ -181,8 +181,6 @@ class DbAclTwoTest extends DbAcl {
}
}
Mock::generate('AclInterface', 'MockAclImplementation');
/**
* Short description for class.
*
@ -196,7 +194,10 @@ class AclComponentTest extends CakeTestCase {
* @access public
* @return void
*/
function startTest() {
function setUp() {
if (!class_exists('MockAclImplementation', false)) {
$this->getMock('AclInterface', array(), array(), 'MockAclImplementation');
}
Configure::write('Acl.classname', 'MockAclImplementation');
$this->Acl = new AclComponent();
}
@ -230,7 +231,7 @@ class AclComponentTest extends CakeTestCase {
*/
function testAdapter() {
$implementation = new MockAclImplementation();
$implementation->expectOnce('initialize', array($this->Acl));
$implementation->expects($this->once())->method('initialize')->with($this->Acl);
$this->assertNull($this->Acl->adapter($implementation));
$this->assertEqual($this->Acl->adapter(), $implementation, 'Returned object is different %s');
@ -264,7 +265,7 @@ class AclComponentTest extends CakeTestCase {
*
* @package cake.tests.cases.libs.controller.components
*/
class IniAclTestCase extends CakeTestCase {
class IniAclTest extends CakeTestCase {
/**
* testIniReadConfigFile
@ -344,7 +345,7 @@ class IniAclTestCase extends CakeTestCase {
*
* @package cake.tests.cases.libs.controller.components
*/
class DbAclTestCase extends CakeTestCase {
class DbAclTest extends CakeTestCase {
/**
* fixtures property
*
@ -386,24 +387,24 @@ class DbAclTestCase extends CakeTestCase {
*/
function testCreate() {
$this->Acl->Aro->create(array('alias' => 'Chotchkey'));
$this->assertTrue($this->Acl->Aro->save());
$this->assertTrue((bool)$this->Acl->Aro->save());
$parent = $this->Acl->Aro->id;
$this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Joanna'));
$this->assertTrue($this->Acl->Aro->save());
$this->assertTrue((bool)$this->Acl->Aro->save());
$this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Stapler'));
$this->assertTrue($this->Acl->Aro->save());
$this->assertTrue((bool)$this->Acl->Aro->save());
$root = $this->Acl->Aco->node('ROOT');
$parent = $root[0]['AcoTwoTest']['id'];
$this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'Drinks'));
$this->assertTrue($this->Acl->Aco->save());
$this->assertTrue((bool)$this->Acl->Aco->save());
$this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'PiecesOfFlair'));
$this->assertTrue($this->Acl->Aco->save());
$this->assertTrue((bool)$this->Acl->Aco->save());
}
/**
@ -460,11 +461,19 @@ class DbAclTestCase extends CakeTestCase {
// Samir should still have his tpsReports/view permissions, but does not
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->expectError();
$this->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
$this->expectError('DbAcl::allow() - Invalid node');
$this->assertFalse($this->Acl->allow('Homer', 'tpsReports', 'create'));
/**
* testAllowInvalidNode method
*
* @access public
* @return void
*/
public function testAllowInvalidNode() {
$this->expectError();
$this->Acl->allow('Homer', 'tpsReports', 'create');
}
/**
@ -479,15 +488,6 @@ class DbAclTestCase extends CakeTestCase {
$this->assertFalse($this->Acl->check('Milton', 'smash', 'read'));
$this->assertFalse($this->Acl->check('Milton', 'current', 'update'));
$this->expectError("DbAcl::check() - Failed ARO/ACO node lookup in permissions check. Node references:\nAro: WRONG\nAco: tpsReports");
$this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read'));
$this->expectError("ACO permissions key foobar does not exist in DbAcl::check()");
$this->assertFalse($this->Acl->check('Lumbergh', 'smash', 'foobar'));
$this->expectError("DbAcl::check() - Failed ARO/ACO node lookup in permissions check. Node references:\nAro: users\nAco: NonExistant");
$this->assertFalse($this->Acl->check('users', 'NonExistant', 'read'));
$this->assertFalse($this->Acl->check(null, 'printers', 'create'));
$this->assertFalse($this->Acl->check('managers', null, 'read'));
@ -497,6 +497,39 @@ class DbAclTestCase extends CakeTestCase {
$this->assertFalse($this->Acl->check('root/users/Milton', 'smash', 'delete'));
}
/**
* testCheckInvalidNode method
*
* @access public
* @return void
*/
public function testCheckInvalidNode() {
$this->expectError();
$this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read'));
}
/**
* testCheckInvalidPermission method
*
* @access public
* @return void
*/
public function testCheckInvalidPermission() {
$this->expectError();
$this->assertFalse($this->Acl->check('Lumbergh', 'smash', 'foobar'));
}
/**
* testCheckMissingPermission method
*
* @access public
* @return void
*/
public function testCheckMissingPermission() {
$this->expectError();
$this->assertFalse($this->Acl->check('users', 'NonExistant', 'read'));
}
/**
* testDbAclCascadingDeny function
*
@ -541,7 +574,7 @@ class DbAclTestCase extends CakeTestCase {
$expected = '-1';
$this->assertEqual($result[0]['PermissionTwoTest']['_delete'], $expected);
$this->expectError('DbAcl::allow() - Invalid node');
$this->expectError();
$this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
@ -606,7 +639,7 @@ class DbAclTestCase extends CakeTestCase {
$this->assertTrue($this->Acl->check('Micheal', 'view', 'update'));
$this->assertFalse($this->Acl->check('Micheal', 'view', 'delete'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->expectError();
$this->assertFalse($this->Acl->allow('Peter', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
@ -627,7 +660,7 @@ class DbAclTestCase extends CakeTestCase {
$this->assertFalse($this->Acl->check('Samir', 'printers', 'read'));
$this->assertFalse($this->Acl->check('Peter', 'printers', 'read'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->expectError();
$this->assertFalse($this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create'));
}
/**

View file

@ -0,0 +1,49 @@
<?php
/**
* AllComponentsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.tests.cases
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
/**
* AllComponentsTest class
*
* This test group will run component class tests
*
* @package cake
* @subpackage cake.tests.cases
*/
class AllComponentsTest extends PHPUnit_Framework_TestSuite {
/**
* suite method, defines tests for this suite.
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All component class tests');
$suite->addTestFile(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'component.test.php');
$iterator = new DirectoryIterator(CORE_TEST_CASES . DS . 'libs' . DS . 'controller' . DS . 'components');
foreach ($iterator as $i => $file) {
if (!$file->isDot()) {
$suite->addTestfile($file->getPathname());
}
}
return $suite;
}
}

View file

@ -21,8 +21,6 @@ App::import('Component', array('Auth', 'Acl'));
App::import('Model', 'DbAcl');
App::import('Core', 'Xml');
Mock::generate('AclComponent', 'AuthTestMockAclComponent');
/**
* TestAuthComponent class
*
@ -479,12 +477,14 @@ class AuthTest extends CakeTestCase {
* @access public
* @return void
*/
function startTest() {
function setUp() {
$this->_server = $_SERVER;
$this->_env = $_ENV;
$this->_securitySalt = Configure::read('Security.salt');
Configure::write('Security.salt', 'JfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
$this->_securityCipher = Configure::read('Security.cipherSeed');
Configure::write('Security.salt', 'YJfIxfs2guVoUubWDYhG93b0qyJfIxfs2guwvniR2G0FgaC9mi');
Configure::write('Security.cipherSeed', 770011223369876);
$this->_acl = Configure::read('Acl');
Configure::write('Acl.database', 'test_suite');
@ -513,11 +513,12 @@ class AuthTest extends CakeTestCase {
* @access public
* @return void
*/
function endTest() {
function tearDown() {
$_SERVER = $this->_server;
$_ENV = $this->_env;
Configure::write('Acl', $this->_acl);
Configure::write('Security.salt', $this->_securitySalt);
Configure::write('Security.cipherSeed', $this->_securityCipher);
$this->Controller->Session->delete('Auth');
$this->Controller->Session->delete('Message.auth');
@ -598,7 +599,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->startup($this->Controller);
$user = $this->Controller->Auth->user();
$this->assertFalse($user);
$this->assertNull($user);
$this->Controller->Session->delete('Auth');
$this->Controller->request->data['AuthUser'] = array(
@ -608,7 +609,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->startup($this->Controller);
$user = $this->Controller->Auth->user();
$this->assertFalse($user);
$this->assertNull($user);
$this->Controller->Session->delete('Auth');
$this->Controller->request->data['AuthUser'] = array(
@ -618,7 +619,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->startup($this->Controller);
$user = $this->Controller->Auth->user();
$this->assertFalse($user);
$this->assertNull($user);
$this->Controller->Session->delete('Auth');
$this->Controller->Auth->userModel = 'UuidUser';
@ -664,7 +665,7 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testAuthorizeFalse() {
$this->AuthUser =& new AuthUser();
$this->AuthUser = new AuthUser();
$user = $this->AuthUser->find();
$this->Controller->Session->write('Auth', $user);
$this->Controller->Auth->userModel = 'AuthUser';
@ -752,13 +753,13 @@ class AuthTest extends CakeTestCase {
$this->Controller->Acl->Aro->id = null;
$this->Controller->Acl->Aro->create(array('alias' => 'Roles'));
$result = $this->Controller->Acl->Aro->save();
$this->assertTrue($result);
$this->assertFalse(empty($result));
$parent = $this->Controller->Acl->Aro->id;
$this->Controller->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Admin'));
$result = $this->Controller->Acl->Aro->save();
$this->assertTrue($result);
$this->assertFalse(empty($result));
$parent = $this->Controller->Acl->Aro->id;
@ -766,17 +767,17 @@ class AuthTest extends CakeTestCase {
'model' => 'AuthUser', 'parent_id' => $parent, 'foreign_key' => 1, 'alias'=> 'mariano'
));
$result = $this->Controller->Acl->Aro->save();
$this->assertTrue($result);
$this->assertFalse(empty($result));
$this->Controller->Acl->Aco->create(array('alias' => 'Root'));
$result = $this->Controller->Acl->Aco->save();
$this->assertTrue($result);
$this->assertFalse(empty($result));
$parent = $this->Controller->Acl->Aco->id;
$this->Controller->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'AuthTest'));
$result = $this->Controller->Acl->Aco->save();
$this->assertTrue($result);
$this->assertFalse(empty($result));
$this->Controller->Acl->allow('Roles/Admin', 'Root');
$this->Controller->Acl->allow('Roles/Admin', 'Root/AuthTest');
@ -807,8 +808,8 @@ class AuthTest extends CakeTestCase {
$this->Controller->request['controller'] = 'auth_test';
$this->Controller->request['action'] = 'add';
$this->Controller->Acl = new AuthTestMockAclComponent();
$this->Controller->Acl->setReturnValue('check', true);
$this->Controller->Acl = $this->getMock('AclComponent');
$this->Controller->Acl->expects($this->atLeastOnce())->method('check')->will($this->returnValue(true));
$this->Controller->Auth->initialize($this->Controller);
@ -816,9 +817,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Auth->authorize = 'actions';
$this->Controller->Auth->actionPath = 'Root/';
$this->Controller->Acl->expectAt(0, 'check', array(
$user, 'Root/AuthTest/add'
));
$this->Controller->Acl->expects($this->at(0))->method('check')->with($user, 'Root/AuthTest/add');
$this->Controller->Auth->startup($this->Controller);
$this->assertTrue($this->Controller->Auth->isAuthorized());
@ -1398,7 +1397,7 @@ class AuthTest extends CakeTestCase {
), true);
App::objects('plugin', null, false);
$PluginModel =& ClassRegistry::init('TestPlugin.TestPluginAuthUser');
$PluginModel = ClassRegistry::init('TestPlugin.TestPluginAuthUser');
$user['id'] = 1;
$user['username'] = 'gwoo';
$user['password'] = Security::hash(Configure::read('Security.salt') . 'cake');
@ -1458,7 +1457,7 @@ class AuthTest extends CakeTestCase {
}
ob_start();
$Dispatcher =& new Dispatcher();
$Dispatcher = new Dispatcher();
$Dispatcher->dispatch('/ajax_auth/add', array('return' => 1));
$result = ob_get_clean();
$this->assertEqual("Ajax!\nthis is the test element", str_replace("\r\n", "\n", $result));
@ -1511,8 +1510,10 @@ class AuthTest extends CakeTestCase {
function testShutDown() {
$this->Controller->Auth->initialize($this->Controller, array('_loggedIn' => true));
$this->Controller->Session->write('Auth.redirect', 'foo');
$this->Controller->Auth->loggedIn(true);
$this->Controller->Auth->shutdown($this->Controller);
$this->assertFalse($this->Controller->Session->read('Auth.redirect'));
$this->assertNull($this->Controller->Session->read('Auth.redirect'));
}
/**
@ -1542,8 +1543,10 @@ class AuthTest extends CakeTestCase {
* @return void
*/
function testComponentSettings() {
$request = new CakeRequest(null, false);
$this->Controller = new AuthTestController($request);
$this->Controller->components = array(
'Auth' => array(
'fields' => array('username' => 'email', 'password' => 'password'),
@ -1557,7 +1560,7 @@ class AuthTest extends CakeTestCase {
$this->Controller->Component->initialize($this->Controller);
Router::reload();
$this->AuthUserCustomField =& new AuthUserCustomField();
$this->AuthUserCustomField = new AuthUserCustomField();
$user = array(
'id' => 1, 'email' => 'harking@example.com',
'password' => Security::hash(Configure::read('Security.salt') . 'cake'

View file

@ -74,13 +74,12 @@ class CookieComponentTest extends CakeTestCase {
* @access public
* @return void
*/
function start() {
function setUp() {
$this->Controller = new CookieComponentTestController();
$this->Controller->constructClasses();
$this->Controller->Component->initialize($this->Controller);
$this->Controller->beforeFilter();
$this->Controller->Component->startup($this->Controller);
$this->Controller->Cookie->destroy();
}
/**
@ -89,10 +88,22 @@ class CookieComponentTest extends CakeTestCase {
* @access public
* @return void
*/
function end() {
function tearDown() {
$this->Controller->Cookie->destroy();
}
protected function _setCookieData() {
$this->Controller->Cookie->write(array('Encrytped_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.name' => 'CakePHP'));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.version' => '1.2.0.x'));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.tag' => 'CakePHP Rocks!'));
$this->Controller->Cookie->write(array('Plain_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.name' => 'CakePHP'), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.version' => '1.2.0.x'), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.tag' => 'CakePHP Rocks!'), null, false);
}
/**
* test that initialize sets settings from components array
*
@ -118,19 +129,6 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEqual($this->Controller->Cookie->name, 'CakeTestCookie');
}
/**
* testSettingEncryptedCookieData
*
* @access public
* @return void
*/
function testSettingEncryptedCookieData() {
$this->Controller->Cookie->write('Encrytped_array', array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!'));
$this->Controller->Cookie->write('Encrytped_multi_cookies.name', 'CakePHP');
$this->Controller->Cookie->write('Encrytped_multi_cookies.version', '1.2.0.x');
$this->Controller->Cookie->write('Encrytped_multi_cookies.tag', 'CakePHP Rocks!');
}
/**
* testReadEncryptedCookieData
*
@ -138,6 +136,7 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testReadEncryptedCookieData() {
$this->_setCookieData();
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
@ -147,19 +146,6 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEqual($data, $expected);
}
/**
* testSettingPlainCookieData
*
* @access public
* @return void
*/
function testSettingPlainCookieData() {
$this->Controller->Cookie->write('Plain_array', array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!'), false);
$this->Controller->Cookie->write('Plain_multi_cookies.name', 'CakePHP', false);
$this->Controller->Cookie->write('Plain_multi_cookies.version', '1.2.0.x', false);
$this->Controller->Cookie->write('Plain_multi_cookies.tag', 'CakePHP Rocks!', false);
}
/**
* testReadPlainCookieData
*
@ -167,6 +153,8 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testReadPlainCookieData() {
$this->_setCookieData();
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
@ -201,6 +189,7 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testReadingCookieValue() {
$this->_setCookieData();
$data = $this->Controller->Cookie->read();
$expected = array(
'Encrytped_array' => array(
@ -229,6 +218,7 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testDeleteCookieValue() {
$this->_setCookieData();
$this->Controller->Cookie->delete('Encrytped_multi_cookies.name');
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array('version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
@ -236,8 +226,7 @@ class CookieComponentTest extends CakeTestCase {
$this->Controller->Cookie->delete('Encrytped_array');
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$this->assertEqual($data, $expected);
$this->assertNull($data);
$this->Controller->Cookie->delete('Plain_multi_cookies.name');
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
@ -246,28 +235,7 @@ class CookieComponentTest extends CakeTestCase {
$this->Controller->Cookie->delete('Plain_array');
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array();
$this->assertEqual($data, $expected);
}
/**
* testSettingCookiesWithArray
*
* @access public
* @return void
*/
function testSettingCookiesWithArray() {
$this->Controller->Cookie->destroy();
$this->Controller->Cookie->write(array('Encrytped_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.name' => 'CakePHP'));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.version' => '1.2.0.x'));
$this->Controller->Cookie->write(array('Encrytped_multi_cookies.tag' => 'CakePHP Rocks!'));
$this->Controller->Cookie->write(array('Plain_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.name' => 'CakePHP'), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.version' => '1.2.0.x'), null, false);
$this->Controller->Cookie->write(array('Plain_multi_cookies.tag' => 'CakePHP Rocks!'), null, false);
$this->assertNull($data);
}
/**
@ -277,6 +245,8 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testReadingCookieArray() {
$this->_setCookieData();
$data = $this->Controller->Cookie->read('Encrytped_array.name');
$expected = 'CakePHP';
$this->assertEqual($data, $expected);
@ -333,23 +303,18 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
function testReadingCookieDataOnStartup() {
$this->Controller->Cookie->destroy();
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$this->assertEqual($data, $expected);
$this->assertNull($data);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$this->assertNull($data);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array();
$this->assertEqual($data, $expected);
$this->assertNull($data);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$this->assertNull($data);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')),
@ -391,19 +356,19 @@ class CookieComponentTest extends CakeTestCase {
*/
function testReadingCookieDataWithoutStartup() {
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$expected = null;
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array();
$expected = null;
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array();
$expected = null;
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array();
$expected = null;
$this->assertEqual($data, $expected);
$_COOKIE['CakeTestCookie'] = array(

View file

@ -20,6 +20,7 @@
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Component', 'Email');
App::import('Core', 'CakeSocket');
/**
* EmailTestComponent class
@ -45,8 +46,8 @@ class EmailTestComponent extends EmailComponent {
* @access public
* @return void
*/
function setConnectionSocket(&$socket) {
$this->__smtpConnection = $socket;
function setConnectionSocket($socket) {
$this->_smtpConnection = $socket;
}
/**
@ -56,7 +57,7 @@ class EmailTestComponent extends EmailComponent {
* @return mixed
*/
function getConnectionSocket() {
return $this->__smtpConnection;
return $this->_smtpConnection;
}
/**
@ -66,7 +67,7 @@ class EmailTestComponent extends EmailComponent {
* @return void
*/
function setHeaders($headers) {
$this->__header += $headers;
$this->_header += $headers;
}
/**
@ -76,7 +77,10 @@ class EmailTestComponent extends EmailComponent {
* @return array
*/
function getHeaders() {
return $this->__header;
if (empty($this->_header)) {
return array();
}
return $this->_header;
}
/**
@ -86,7 +90,7 @@ class EmailTestComponent extends EmailComponent {
* @return void
*/
function setBoundary() {
$this->__createBoundary();
$this->_createBoundary();
}
/**
@ -96,7 +100,10 @@ class EmailTestComponent extends EmailComponent {
* @return string
*/
function getBoundary() {
return $this->__boundary;
if (empty($this->_boundary)) {
return null;
}
return $this->_boundary;
}
/**
@ -106,7 +113,10 @@ class EmailTestComponent extends EmailComponent {
* @return string
*/
function getMessage() {
return $this->__message;
if (empty($this->_message)) {
return array();
}
return $this->_message;
}
/**
@ -116,7 +126,7 @@ class EmailTestComponent extends EmailComponent {
* @return string
*/
function _getMessage() {
return $this->__message;
return $this->_message;
}
/**
@ -205,11 +215,9 @@ class EmailComponentTest extends CakeTestCase {
$this->_appEncoding = Configure::read('App.encoding');
Configure::write('App.encoding', 'UTF-8');
$this->Controller =& new EmailTestController();
$this->Controller = new EmailTestController();
restore_error_handler();
@$this->Controller->Component->init($this->Controller);
set_error_handler('simpleTestErrorHandler');
$this->Controller->Component->init($this->Controller);
$this->Controller->EmailTest->initialize($this->Controller, array());
ClassRegistry::addObject('view', new View($this->Controller));
@ -229,7 +237,6 @@ class EmailComponentTest extends CakeTestCase {
Configure::write('App.encoding', $this->_appEncoding);
App::build();
$this->Controller->Session->delete('Message');
restore_error_handler();
ClassRegistry::flush();
}
@ -635,18 +642,18 @@ TEXTBLOC;
function testSmtpSendSocket() {
$this->skipIf(!@fsockopen('localhost', 25), '%s No SMTP server running on localhost');
$this->Controller->EmailTest->smtpOptions['timeout'] = 10;
$socket =& new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions));
$socket = new CakeSocket(array_merge(array('protocol'=>'smtp'), $this->Controller->EmailTest->smtpOptions));
$this->Controller->EmailTest->setConnectionSocket($socket);
$this->assertTrue($this->Controller->EmailTest->getConnectionSocket());
$this->assertSame($this->Controller->EmailTest->getConnectionSocket(), $socket);
$response = $this->Controller->EmailTest->smtpSend('HELO', '250');
$this->assertPattern('/501 Syntax: HELO hostname/', $this->Controller->EmailTest->smtpError);
$this->Controller->EmailTest->reset();
$response = $this->Controller->EmailTest->smtpSend('HELO somehostname', '250');
$this->assertNoPattern('/501 Syntax: HELO hostname/', $this->Controller->EmailTest->smtpError);
$this->assertNoPattern('/501 Syntax: HELO hostname/', (string)$this->Controller->EmailTest->smtpError);
}
/**
@ -682,7 +689,7 @@ TEXTBLOC;
* @return void
*/
function testSendDebugWithNoSessions() {
$session =& $this->Controller->Session;
$session = $this->Controller->Session;
unset($this->Controller->Session);
$this->Controller->EmailTest->to = 'postmaster@localhost';
$this->Controller->EmailTest->from = 'noreply@example.com';

View file

@ -20,10 +20,6 @@
App::import('Controller', 'Controller', false);
App::import('Component', array('RequestHandler'));
Mock::generatePartial('RequestHandlerComponent', 'NoStopRequestHandler', array('_stop'));
Mock::generate('CakeRequest', 'RequestHandlerMockCakeRequest');
Mock::generatePartial('Controller', 'RequestHandlerMockController', array('header'));
/**
* RequestHandlerTestController class
*
@ -535,9 +531,9 @@ class RequestHandlerComponentTest extends CakeTestCase {
), true);
$this->Controller->request = new CakeRequest('posts/index');
$this->Controller->RequestHandler = new NoStopRequestHandler($this);
$this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'));
$this->Controller->RequestHandler->request = $this->Controller->request;
$this->Controller->RequestHandler->expectOnce('_stop');
$this->Controller->RequestHandler->expects($this->once())->method('_stop');
ob_start();
$this->Controller->RequestHandler->beforeRedirect(
@ -595,7 +591,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/')
));
$RequestHandler =& new NoStopRequestHandler();
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'));
$RequestHandler->request = new CakeRequest('posts/index');
ob_start();
@ -613,12 +609,16 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
function testBeforeRedirectCallingHeader() {
$controller =& new RequestHandlerMockController();
$RequestHandler =& new NoStopRequestHandler();
$RequestHandler->request = new RequestHandlerMockCakeRequest();
$RequestHandler->request->setReturnValue('is', true, array('ajax'));
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$controller->expectOnce('header', array('HTTP/1.1 403 Forbidden'));
$controller = $this->getMock('Controller', array('header'));
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'));
$RequestHandler->request = $this->getMock('CakeRequest');
$RequestHandler->request->expects($this->once())->method('is')
->with('ajax')
->will($this->returnValue(true));
$controller->expects($this->once())->method('header')->with('HTTP/1.1 403 Forbidden');
ob_start();
$RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403);

View file

@ -108,20 +108,20 @@ class SessionComponentTest extends CakeTestCase {
*/
function testSessionAutoStart() {
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$Session = new SessionComponent();
$this->assertFalse($Session->active());
$this->assertFalse($Session->started());
$Session->startup(new SessionTestController());
Configure::write('Session.start', true);
$Session =& new SessionComponent();
$this->assertTrue($Session->__active);
$Session = new SessionComponent();
$this->assertTrue($Session->active());
$this->assertFalse($Session->started());
$Session->startup(new SessionTestController());
$this->assertTrue(isset($_SESSION));
$Object = new Object();
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->start();
$expected = $Session->id();
@ -139,17 +139,17 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionActivate() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertTrue($Session->__active);
$this->assertTrue($Session->active());
$this->assertNull($Session->activate());
$this->assertTrue($Session->__active);
$this->assertTrue($Session->active());
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$Session = new SessionComponent();
$this->assertFalse($Session->active());
$this->assertNull($Session->activate());
$this->assertTrue($Session->__active);
$this->assertTrue($Session->active());
Configure::write('Session.start', true);
$Session->destroy();
}
@ -161,25 +161,25 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionValid() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertTrue($Session->valid());
$Session->_userAgent = 'rweerw';
$Session->userAgent('rweerw');
$this->assertFalse($Session->valid());
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$Session = new SessionComponent();
$this->assertFalse($Session->active());
$this->assertFalse($Session->valid());
Configure::write('Session.start', true);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->time = $Session->read('Config.time') + 1;
$this->assertFalse($Session->valid());
Configure::write('Session.checkAgent', false);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->time = $Session->read('Config.time') + 1;
$this->assertFalse($Session->valid());
Configure::write('Session.checkAgent', true);
@ -192,13 +192,13 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionError() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertFalse($Session->error());
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$Session = new SessionComponent();
$this->assertFalse($Session->active());
$this->assertFalse($Session->error());
Configure::write('Session.start', true);
}
@ -210,9 +210,9 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionReadWrite() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertFalse($Session->read('Test'));
$this->assertNull($Session->read('Test'));
$this->assertTrue($Session->write('Test', 'some value'));
$this->assertEqual($Session->read('Test'), 'some value');
@ -237,7 +237,7 @@ class SessionComponentTest extends CakeTestCase {
$Session->delete('Test');
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertFalse($Session->write('Test', 'some value'));
$Session->write('Test', 'some value');
$this->assertFalse($Session->read('Test'));
@ -251,7 +251,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionDelete() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertFalse($Session->delete('Test'));
@ -259,7 +259,7 @@ class SessionComponentTest extends CakeTestCase {
$this->assertTrue($Session->delete('Test'));
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertFalse($Session->delete('Test'));
Configure::write('Session.start', true);
@ -272,7 +272,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionCheck() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertFalse($Session->check('Test'));
@ -281,7 +281,7 @@ class SessionComponentTest extends CakeTestCase {
$Session->delete('Test');
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertFalse($Session->check('Test'));
Configure::write('Session.start', true);
@ -294,7 +294,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionFlash() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertNull($Session->read('Message.flash'));
@ -321,7 +321,7 @@ class SessionComponentTest extends CakeTestCase {
*/
function testSessionId() {
unset($_SESSION);
$Session =& new SessionComponent();
$Session = new SessionComponent();
$this->assertNull($Session->id());
}
@ -332,7 +332,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
function testSessionDestroy() {
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertEqual($Session->read('Test'), 'some value');
@ -350,7 +350,7 @@ class SessionComponentTest extends CakeTestCase {
session_destroy();
Configure::write('Security.level', 'low');
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertEqual($_SESSION['Config']['timeout'], Security::inactiveMins());
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);
@ -359,7 +359,7 @@ class SessionComponentTest extends CakeTestCase {
session_destroy();
Configure::write('Security.level', 'medium');
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertEqual($_SESSION['Config']['timeout'], Security::inactiveMins());
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);
@ -368,7 +368,7 @@ class SessionComponentTest extends CakeTestCase {
session_destroy();
Configure::write('Security.level', 'high');
$Session =& new SessionComponent();
$Session = new SessionComponent();
$Session->write('Test', 'some value');
$this->assertEqual($_SESSION['Config']['timeout'], Security::inactiveMins());
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);

View file

@ -22,8 +22,6 @@ App::import('Core', 'CakeRequest');
App::import('Component', 'Security');
App::import('Component', 'Cookie');
Mock::generate('CakeRequest', 'ControllerMockCakeRequest');
/**
* AppController class
*
@ -474,6 +472,7 @@ class ControllerTest extends CakeTestCase {
function testConstructClasses() {
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->modelClass = 'ControllerPost';
$Controller->passedArgs[] = '1';
$Controller->constructClasses();
@ -530,9 +529,8 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testPersistent() {
if ($this->skipIf(true, 'Skipping, private access related issues in Controller cause this to puke.')) {
return false;
}
$this->markTestIncomplete('persistModel is totally broken right now.');
Configure::write('Cache.disable', false);
$Controller = new Controller();
$Controller->modelClass = 'ControllerPost';
@ -647,6 +645,7 @@ class ControllerTest extends CakeTestCase {
$request->params['pass'] = $request->params['named'] = array();
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->params['url'] = array();
@ -817,6 +816,7 @@ class ControllerTest extends CakeTestCase {
*/
function testFlash() {
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->flash('this should work', '/flash');
$result = $Controller->output;
@ -857,6 +857,7 @@ class ControllerTest extends CakeTestCase {
function testControllerSet() {
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->set('variable_with_underscores', null);
$this->assertTrue(array_key_exists('variable_with_underscores', $Controller->viewVars));
@ -896,6 +897,7 @@ class ControllerTest extends CakeTestCase {
), true);
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->viewPath = 'posts';
@ -919,6 +921,7 @@ class ControllerTest extends CakeTestCase {
$Controller->ControllerComment->validationErrors = array();
ClassRegistry::flush();
App::build();
}
@ -938,135 +941,142 @@ class ControllerTest extends CakeTestCase {
$this->assertFalse($Controller->_scaffoldError(''));
}
/**
* Generates status codes for redirect test.
*
* @return void
*/
public static function statusCodeProvider() {
return array(
array(100, "Continue"),
array(101, "Switching Protocols"),
array(200, "OK"),
array(201, "Created"),
array(202, "Accepted"),
array(203, "Non-Authoritative Information"),
array(204, "No Content"),
array(205, "Reset Content"),
array(206, "Partial Content"),
array(300, "Multiple Choices"),
array(301, "Moved Permanently"),
array(302, "Found"),
array(303, "See Other"),
array(304, "Not Modified"),
array(305, "Use Proxy"),
array(307, "Temporary Redirect"),
array(400, "Bad Request"),
array(401, "Unauthorized"),
array(402, "Payment Required"),
array(403, "Forbidden"),
array(404, "Not Found"),
array(405, "Method Not Allowed"),
array(406, "Not Acceptable"),
array(407, "Proxy Authentication Required"),
array(408, "Request Time-out"),
array(409, "Conflict"),
array(410, "Gone"),
array(411, "Length Required"),
array(412, "Precondition Failed"),
array(413, "Request Entity Too Large"),
array(414, "Request-URI Too Large"),
array(415, "Unsupported Media Type"),
array(416, "Requested range not satisfiable"),
array(417, "Expectation Failed"),
array(500, "Internal Server Error"),
array(501, "Not Implemented"),
array(502, "Bad Gateway"),
array(503, "Service Unavailable"),
array(504, "Gateway Time-out"),
);
}
/**
* testRedirect method
*
* @dataProvider statusCodeProvider
* @access public
* @return void
*/
function testRedirect() {
$codes = array(
100 => "Continue",
101 => "Switching Protocols",
200 => "OK",
201 => "Created",
202 => "Accepted",
203 => "Non-Authoritative Information",
204 => "No Content",
205 => "Reset Content",
206 => "Partial Content",
300 => "Multiple Choices",
301 => "Moved Permanently",
302 => "Found",
303 => "See Other",
304 => "Not Modified",
305 => "Use Proxy",
307 => "Temporary Redirect",
400 => "Bad Request",
401 => "Unauthorized",
402 => "Payment Required",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
406 => "Not Acceptable",
407 => "Proxy Authentication Required",
408 => "Request Time-out",
409 => "Conflict",
410 => "Gone",
411 => "Length Required",
412 => "Precondition Failed",
413 => "Request Entity Too Large",
414 => "Request-URI Too Large",
415 => "Unsupported Media Type",
416 => "Requested range not satisfiable",
417 => "Expectation Failed",
500 => "Internal Server Error",
501 => "Not Implemented",
502 => "Bad Gateway",
503 => "Service Unavailable",
504 => "Gateway Time-out"
);
function testRedirectByCode($code, $msg) {
$Controller = $this->getMock('Controller', array('header'));
Mock::generatePartial('Controller', 'MockController', array('header'));
Mock::generate('TestComponent', 'MockTestComponent');
Mock::generate('TestComponent', 'MockTestBComponent');
App::import('Helper', 'Cache');
$Controller->Component = new Component();
$Controller->Component->init($Controller);
$Controller->expects($this->at(0))->method('header')
->with("HTTP/1.1 {$code} {$msg}");
foreach ($codes as $code => $msg) {
$MockController = new MockController();
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}"));
$MockController->expectAt(1, 'header', array('Location: http://cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', (int)$code, false);
$this->assertFalse($MockController->autoRender);
}
foreach ($codes as $code => $msg) {
$MockController = new MockController();
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->expectAt(0, 'header', array("HTTP/1.1 {$code} {$msg}"));
$MockController->expectAt(1, 'header', array('Location: http://cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', $msg, false);
$this->assertFalse($MockController->autoRender);
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$Controller->expects($this->exactly(2))->method('header');
$Controller->redirect('http://cakephp.org', (int)$code, false);
$this->assertFalse($Controller->autoRender);
}
$MockController = new MockController();
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->expectAt(0, 'header', array('Location: http://www.example.org/users/login'));
$MockController->expectCallCount('header', 1);
$MockController->redirect('http://www.example.org/users/login', null, false);
/**
* test redirecting by message
*
* @dataProvider statusCodeProvider
* @return void
*/
function testRedirectByMessage($code, $msg) {
$Controller = $this->getMock('Controller', array('header'));
$MockController = new MockController();
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://www.example.org/users/login'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://www.example.org/users/login', 301, false);
$Controller->Component = new Component();
$Controller->Component->init($Controller);
$MockController = new MockController();
$MockController->components = array('MockTest');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', null);
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', 301, false);
$Controller->expects($this->at(0))->method('header')
->with("HTTP/1.1 {$code} {$msg}");
$MockController = new MockController();
$MockController->components = array('MockTest');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org');
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://book.cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', 301, false);
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$MockController = new MockController();
$MockController->components = array('MockTest');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', false);
$MockController->expectNever('header');
$MockController->redirect('http://cakephp.org', 301, false);
$Controller->expects($this->exactly(2))->method('header');
$Controller->redirect('http://cakephp.org', $msg, false);
$this->assertFalse($Controller->autoRender);
}
$MockController = new MockController();
$MockController->components = array('MockTest', 'MockTestB');
$MockController->Component = new Component();
$MockController->Component->init($MockController);
$MockController->MockTest->setReturnValue('beforeRedirect', 'http://book.cakephp.org');
$MockController->MockTestB->setReturnValue('beforeRedirect', 'http://bakery.cakephp.org');
$MockController->expectAt(0, 'header', array('HTTP/1.1 301 Moved Permanently'));
$MockController->expectAt(1, 'header', array('Location: http://bakery.cakephp.org'));
$MockController->expectCallCount('header', 2);
$MockController->redirect('http://cakephp.org', 301, false);
/**
* test that redirect triggers methods on the components.
*
* @return void
*/
function testRedirectTriggeringComponentsReturnNull() {
$Controller = $this->getMock('Controller', array('header'));
$Controller->Component = $this->getMock('Component');
$Controller->Component->expects($this->once())->method('beforeRedirect')->will($this->returnValue(null));
$Controller->expects($this->at(0))->method('header')
->with('HTTP/1.1 301 Moved Permanently');
$Controller->expects($this->at(1))->method('header')
->with('Location: http://cakephp.org');
$Controller->redirect('http://cakephp.org', 301, false);
}
/**
* test that beforeRedirect callback returnning null doesn't affect things.
*
* @return void
*/
function testRedirectBeforeRedirectModifyingParams() {
$Controller = $this->getMock('Controller', array('header'));
$Controller->Component = $this->getMock('Component');
$Controller->Component->expects($this->once())->method('beforeRedirect')
->will($this->returnValue(array('http://book.cakephp.org')));
$Controller->expects($this->at(0))->method('header')
->with('HTTP/1.1 301 Moved Permanently');
$Controller->expects($this->at(1))->method('header')
->with('Location: http://book.cakephp.org');
$Controller->redirect('http://cakephp.org', 301, false);
}
/**
@ -1081,6 +1091,7 @@ class ControllerTest extends CakeTestCase {
}
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$TestController->constructClasses();
@ -1104,6 +1115,7 @@ class ControllerTest extends CakeTestCase {
$this->assertEqual(count(array_diff($TestController->uses, $uses)), 0);
$this->assertEqual(count(array_diff_assoc(Set::normalize($TestController->components), Set::normalize($components))), 0);
$TestController = new AnotherTestController($request);
$TestController->constructClasses();
@ -1144,6 +1156,7 @@ class ControllerTest extends CakeTestCase {
$request = new CakeRequest('controller_posts/index');
$TestController = new TestController($request);
$expected = array('foo');
$TestController->components = array('Cookie' => $expected);
$TestController->constructClasses();
@ -1174,22 +1187,31 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testReferer() {
$request = new ControllerMockCakeRequest();
$request->setReturnValue('referer', 'http://localhost/posts/index', array(false));
$request->setReturnValue('referer', '/posts/index', array(true));
$request = $this->getMock('CakeRequest');
$request->expects($this->any())->method('referer')
->with(true)
->will($this->returnValue('/posts/index'));
$Controller = new Controller($request);
$result = $Controller->referer(null, true);
$this->assertEqual($result, '/posts/index');
$result = $Controller->referer();
$this->assertEqual($result, 'http://localhost/posts/index');
$Controller = new Controller($request);
$request->setReturnValue('referer', '/', array(true));
$result = $Controller->referer(array('controller' => 'posts', 'action' => 'index'), true);
$this->assertEqual($result, '/posts/index');
$request = $this->getMock('CakeRequest');
$request->expects($this->any())->method('referer')
->with(false)
->will($this->returnValue('http://localhost/posts/index'));
$Controller = new Controller($request);
$result = $Controller->referer();
$this->assertEqual($result, 'http://localhost/posts/index');
$Controller = new Controller(null);
$result = $Controller->referer();
$this->assertEqual($result, '/');
@ -1213,6 +1235,7 @@ class ControllerTest extends CakeTestCase {
/**
* testUnimplementedIsAuthorized method
*
* @expectedException PHPUnit_Framework_Error
* @access public
* @return void
*/
@ -1221,7 +1244,6 @@ class ControllerTest extends CakeTestCase {
$TestController = new TestController($request);
$TestController->isAuthorized();
$this->assertError();
}
/**
@ -1340,9 +1362,11 @@ class ControllerTest extends CakeTestCase {
*/
function testRequestHandlerPrefers(){
Configure::write('debug', 2);
$request = new CakeRequest('controller_posts/index');
$Controller = new Controller($request);
$Controller->components = array("RequestHandler");
$Controller->modelClass='ControllerPost';
$Controller->params['url'] = array('ext' => 'rss');
@ -1402,16 +1426,18 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testStartupProcess() {
Mock::generatePartial('AnotherTestController','MockedController', array('beforeFilter', 'afterFilter'));
Mock::generate('TestComponent', 'MockTestComponent', array('startup', 'initialize'));
$MockedController = new MockedController();
$MockedController->components = array('MockTest');
$MockedController->Component = new Component();
$MockedController->Component->init($MockedController);
$MockedController->expectCallCount('beforeFilter', 1);
$MockedController->MockTest->expectCallCount('initialize', 1);
$MockedController->MockTest->expectCallCount('startup', 1);
$MockedController->startupProcess();
$this->getMock('TestComponent', array('startup', 'initialize'), array(), 'MockStartupComponent');
$Controller = $this->getMock('Controller', array('beforeFilter', 'afterFilter'));
$Controller->components = array('MockStartup');
$Controller->Component = new Component();
$Controller->Component->init($Controller);
$Controller->expects($this->once())->method('beforeFilter');
$Controller->MockStartup->expects($this->at(0))->method('initialize');
$Controller->MockStartup->expects($this->at(1))->method('startup');
$Controller->startupProcess();
}
/**
* Tests that the shutdown process calls the correct functions
@ -1420,13 +1446,16 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
function testShutdownProcess() {
Mock::generate('TestComponent', 'MockTestComponent', array('shutdown'));
$MockedController = new MockedController();
$MockedController->components = array('MockTest');
$MockedController->Component = new Component();
$MockedController->Component->init($MockedController);
$MockedController->expectCallCount('afterFilter', 1);
$MockedController->MockTest->expectCallCount('shutdown', 1);
$MockedController->shutdownProcess();
$this->getMock('TestComponent', array('shutdown'), array(), 'MockShutdownComponent');
$Controller = $this->getMock('Controller', array('beforeFilter', 'afterFilter'));
$Controller->components = array('MockShutdown');
$Controller->Component = new Component();
$Controller->Component->init($Controller);
$Controller->expects($this->once())->method('afterFilter');
$Controller->MockShutdown->expects($this->once())->method('shutdown');
$Controller->shutdownProcess();
}
}

View file

@ -127,15 +127,7 @@ class MergePostsController extends MergeVarPluginAppController {
*
* @package cake.tests.cases.libs.controller
*/
class ControllerMergeVarsTestCase extends CakeTestCase {
/**
* Skips the case if APP_CONTROLLER_EXISTS is defined
*
* @return void
*/
function skip() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), 'APP_CONTROLLER_EXISTS cannot run. %s');
}
class ControllerMergeVarsTest extends CakeTestCase {
/**
* end test
*
@ -151,6 +143,8 @@ class ControllerMergeVarsTestCase extends CakeTestCase {
* @return void
*/
function testComponentParamMergingNoDuplication() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), "APP_CONTROLLER_EXISTS cannot run {$this->name}");
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
@ -164,6 +158,8 @@ class ControllerMergeVarsTestCase extends CakeTestCase {
* @return void
*/
function testComponentMergingWithRedeclarations() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), "APP_CONTROLLER_EXISTS cannot run {$this->name}");
$Controller =& new MergeVariablesController();
$Controller->components['MergeVar'] = array('remote', 'redirect' => true);
$Controller->constructClasses();
@ -178,6 +174,8 @@ class ControllerMergeVarsTestCase extends CakeTestCase {
* @return void
*/
function testHelperSettingMergingNoDuplication() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), "APP_CONTROLLER_EXISTS cannot run {$this->name}");
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
@ -191,6 +189,8 @@ class ControllerMergeVarsTestCase extends CakeTestCase {
* @return void
*/
function testMergeVarsWithPlugin() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), "APP_CONTROLLER_EXISTS cannot run {$this->name}");
$Controller =& new MergePostsController();
$Controller->components = array('Email' => array('ports' => 'open'));
$Controller->plugin = 'MergeVarPlugin';
@ -228,6 +228,8 @@ class ControllerMergeVarsTestCase extends CakeTestCase {
* @return void
*/
function testMergeVarsNotGreedy() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), "APP_CONTROLLER_EXISTS cannot run {$this->name}");
$Controller =& new Controller();
$Controller->components = array();
$Controller->uses = array();

View file

@ -46,14 +46,8 @@ class DebuggerTest extends CakeTestCase {
* @return void
*/
function setUp() {
parent::setup();
Configure::write('log', false);
if (!defined('SIMPLETESTVENDORPATH')) {
if (file_exists(APP . DS . 'vendors' . DS . 'simpletest' . DS . 'reporter.php')) {
define('SIMPLETESTVENDORPATH', 'APP' . DS . 'vendors');
} else {
define('SIMPLETESTVENDORPATH', 'CORE' . DS . 'vendors');
}
}
}
/**
@ -63,6 +57,7 @@ class DebuggerTest extends CakeTestCase {
* @return void
*/
function tearDown() {
parent::teardown();
Configure::write('log', true);
}
@ -119,7 +114,6 @@ class DebuggerTest extends CakeTestCase {
$this->assertEqual($result[0]['error'], 'Notice');
$this->assertPattern('/Undefined variable\:\s+out/', $result[0]['description']);
$this->assertPattern('/DebuggerTest::testOutput/i', $result[0]['trace']);
$this->assertPattern('/SimpleInvoker::invoke/i', $result[0]['trace']);
ob_start();
Debugger::output('txt');
@ -129,7 +123,6 @@ class DebuggerTest extends CakeTestCase {
$this->assertPattern('/Undefined variable:\s+other/', $result);
$this->assertPattern('/Context:/', $result);
$this->assertPattern('/DebuggerTest::testOutput/i', $result);
$this->assertPattern('/SimpleInvoker::invoke/i', $result);
ob_start();
Debugger::output('html');
@ -157,7 +150,8 @@ class DebuggerTest extends CakeTestCase {
$this->assertPattern('/Undefined variable:\s+buzz/', $result[1]);
$this->assertPattern('/<a[^>]+>Code/', $result[1]);
$this->assertPattern('/<a[^>]+>Context/', $result[2]);
set_error_handler('simpleTestErrorHandler');
restore_error_handler();
}
/**
@ -185,17 +179,18 @@ class DebuggerTest extends CakeTestCase {
ob_start();
$foo .= '';
$result = ob_get_clean();
set_error_handler('SimpleTestErrorHandler');
$data = array(
'error' => array(),
'code' => array(), '8', '/code',
'file' => array(), 'preg:/[^<]+/', '/file',
'line' => array(), '' . (intval(__LINE__) + -8), '/line',
'line' => array(), '' . (intval(__LINE__) - 7), '/line',
'preg:/Undefined variable:\s+foo/',
'/error'
);
$this->assertTags($result, $data, true);
restore_error_handler();
}
/**
@ -318,16 +313,16 @@ class DebuggerTest extends CakeTestCase {
* @return void
*/
function testGetInstance() {
$result =& Debugger::getInstance();
$result = Debugger::getInstance();
$this->assertIsA($result, 'Debugger');
$result =& Debugger::getInstance('DebuggerTestCaseDebugger');
$result = Debugger::getInstance('DebuggerTestCaseDebugger');
$this->assertIsA($result, 'DebuggerTestCaseDebugger');
$result =& Debugger::getInstance();
$result = Debugger::getInstance();
$this->assertIsA($result, 'DebuggerTestCaseDebugger');
$result =& Debugger::getInstance('Debugger');
$result = Debugger::getInstance('Debugger');
$this->assertIsA($result, 'Debugger');
}
}

View file

@ -193,15 +193,7 @@ class BlueberryController extends AppController {
* @access public
* @return void
*/
public $uses = array('AuthBlueberryUser');
/**
* components property
*
* @access public
* @return void
*/
public $components = array('Auth');
public $uses = array();
}
/**
@ -350,7 +342,7 @@ class ErrorHandlerTest extends CakeTestCase {
$this->assertPattern("/<strong>'\/test_error'<\/strong>/", $result);
ob_start();
$TestErrorHandler =& new TestErrorHandler('error404', array('message' => 'Page not found'));
$TestErrorHandler = new TestErrorHandler('error404', array('message' => 'Page not found'));
ob_get_clean();
ob_start();
$TestErrorHandler->error404(array(
@ -477,11 +469,9 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
function testMissingView() {
restore_error_handler();
ob_start();
$TestErrorHandler = new TestErrorHandler('missingView', array('className' => 'Pages', 'action' => 'display', 'file' => 'pages/about.ctp', 'base' => ''));
$expected = ob_get_clean();
set_error_handler('simpleTestErrorHandler');
$this->assertPattern("/PagesController::/", $expected);
$this->assertPattern("/pages\/about.ctp/", $expected);
}
@ -493,11 +483,9 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
function testMissingLayout() {
restore_error_handler();
ob_start();
$TestErrorHandler = new TestErrorHandler('missingLayout', array( 'layout' => 'my_layout', 'file' => 'layouts/my_layout.ctp', 'base' => ''));
$expected = ob_get_clean();
set_error_handler('simpleTestErrorHandler');
$this->assertPattern("/Missing Layout/", $expected);
$this->assertPattern("/layouts\/my_layout.ctp/", $expected);
}
@ -571,7 +559,6 @@ class ErrorHandlerTest extends CakeTestCase {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingBehaviorClass', array('behavior' => 'MyCustom', 'file' => 'my_custom.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Behavior Class<\/h2>/', $result);
$this->assertPattern('/The behavior class <em>MyCustomBehavior<\/em> can not be found or does not exist./', $result);
$this->assertPattern('/(\/|\\\)my_custom.php/', $result);
}

View file

@ -35,6 +35,28 @@ class FileTest extends CakeTestCase {
*/
public $File = null;
/**
* setup the test case
*
* @return void
*/
function setUp() {
parent::setUp();
$file = __FILE__;
$this->File = new File($file);
}
/**
* tear down for test.
*
* @return void
*/
function teardown() {
parent::teardown();
$this->File->close();
unset($this->File);
}
/**
* testBasic method
*
@ -43,7 +65,6 @@ class FileTest extends CakeTestCase {
*/
function testBasic() {
$file = __FILE__;
$this->File =& new File($file);
$result = $this->File->pwd();
$expecting = $file;
@ -213,7 +234,7 @@ class FileTest extends CakeTestCase {
*/
function testCreate() {
$tmpFile = TMP.'tests'.DS.'cakephp.file.test.tmp';
$File =& new File($tmpFile, true, 0777);
$File = new File($tmpFile, true, 0777);
$this->assertTrue($File->exists());
}
@ -224,7 +245,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testOpeningNonExistantFileCreatesIt() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertEqual($someFile->read(), '');
$someFile->close();
@ -259,7 +280,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testReadable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->readable());
$someFile->close();
@ -273,7 +294,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testWritable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->writable());
$someFile->close();
@ -287,7 +308,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testExecutable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertFalse($someFile->executable());
$someFile->close();
@ -301,7 +322,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testLastAccess() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastAccess());
$this->assertTrue($someFile->open());
$this->assertEqual($someFile->lastAccess(), time());
@ -316,7 +337,7 @@ class FileTest extends CakeTestCase {
* @return void
*/
function testLastChange() {
$someFile =& new File(TMP . 'some_file.txt', false);
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastChange());
$this->assertTrue($someFile->open('r+'));
$this->assertEqual($someFile->lastChange(), time());
@ -340,7 +361,7 @@ class FileTest extends CakeTestCase {
unlink($tmpFile);
}
$TmpFile =& new File($tmpFile);
$TmpFile = new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$this->assertFalse(is_resource($TmpFile->handle));
@ -371,7 +392,7 @@ class FileTest extends CakeTestCase {
unlink($tmpFile);
}
$TmpFile =& new File($tmpFile);
$TmpFile = new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$fragments = array('CakePHP\'s', ' test suite', ' was here ...', '');
@ -400,13 +421,13 @@ class FileTest extends CakeTestCase {
if (!file_exists($tmpFile)) {
touch($tmpFile);
}
$TmpFile =& new File($tmpFile);
$TmpFile = new File($tmpFile);
$this->assertTrue(file_exists($tmpFile));
$result = $TmpFile->delete();
$this->assertTrue($result);
$this->assertFalse(file_exists($tmpFile));
$TmpFile =& new File('/this/does/not/exist');
$TmpFile = new File('/this/does/not/exist');
$result = $TmpFile->delete();
$this->assertFalse($result);
}
@ -420,7 +441,7 @@ class FileTest extends CakeTestCase {
function testCopy() {
$dest = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
$file = __FILE__;
$this->File =& new File($file);
$this->File = new File($file);
$result = $this->File->copy($dest);
$this->assertTrue($result);
@ -433,7 +454,7 @@ class FileTest extends CakeTestCase {
$this->File->close();
unlink($dest);
$TmpFile =& new File('/this/does/not/exist');
$TmpFile = new File('/this/does/not/exist');
$result = $TmpFile->copy($dest);
$this->assertFalse($result);

View file

@ -35,7 +35,7 @@ class FolderTest extends CakeTestCase {
*/
function testBasic() {
$path = dirname(__FILE__);
$Folder =& new Folder($path);
$Folder = new Folder($path);
$result = $Folder->pwd();
$this->assertEqual($result, $path);
@ -62,7 +62,7 @@ class FolderTest extends CakeTestCase {
$path = dirname(dirname(__FILE__));
$inside = dirname($path) . DS;
$Folder =& new Folder($path);
$Folder = new Folder($path);
$result = $Folder->pwd();
$this->assertEqual($result, $path);
@ -86,7 +86,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testCreation() {
$folder =& new Folder(TMP . 'tests');
$folder = new Folder(TMP . 'tests');
$result = $folder->create(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third');
$this->assertTrue($result);
@ -94,7 +94,7 @@ class FolderTest extends CakeTestCase {
rmdir(TMP . 'tests' . DS . 'first' . DS . 'second');
rmdir(TMP . 'tests' . DS . 'first');
$folder =& new Folder(TMP . 'tests');
$folder = new Folder(TMP . 'tests');
$result = $folder->create(TMP . 'tests' . DS . 'first');
$this->assertTrue($result);
rmdir(TMP . 'tests' . DS . 'first');
@ -106,13 +106,13 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testCreateWithTrailingDs() {
$folder =& new Folder(TMP);
$folder = new Folder(TMP);
$path = TMP . 'tests' . DS . 'trailing' . DS . 'dir' . DS;
$folder->create($path);
$this->assertTrue(is_dir($path), 'Folder was not made');
$folder =& new Folder(TMP . 'tests' . DS . 'trailing');
$folder = new Folder(TMP . 'tests' . DS . 'trailing');
$this->assertTrue($folder->delete());
}
@ -129,11 +129,13 @@ class FolderTest extends CakeTestCase {
mkdir($path);
chmod($path, '0444');
$this->expectError();
$folder =& new Folder($path);
try {
$folder = new Folder($path);
$result = $folder->create($path . DS . 'two' . DS . 'three');
$this->assertFalse($result);
} catch (PHPUnit_Framework_Error $e) {
$this->assertTrue(true);
}
chmod($path, '0777');
rmdir($path);
@ -146,7 +148,7 @@ class FolderTest extends CakeTestCase {
*/
function testOperations() {
$path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'templates' . DS . 'skel';
$Folder =& new Folder($path);
$Folder = new Folder($path);
$result = is_dir($Folder->pwd());
$this->assertTrue($result);
@ -168,7 +170,7 @@ class FolderTest extends CakeTestCase {
$this->assertTrue($result);
$result = $Folder->cd($copy);
$this->assertTrue($result);
$this->assertTrue((bool)$result);
$mv = TMP . 'test_folder_mv';
$result = $Folder->move($mv);
@ -200,12 +202,12 @@ class FolderTest extends CakeTestCase {
$this->assertTrue($result);
$result = $Folder->cd($new);
$this->assertTrue($result);
$this->assertTrue((bool)$result);
$result = $Folder->delete();
$this->assertTrue($result);
$Folder =& new Folder('non-existent');
$Folder = new Folder('non-existent');
$result = $Folder->pwd();
$this->assertNull($result);
}
@ -219,7 +221,7 @@ class FolderTest extends CakeTestCase {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Folder permissions tests not supported on Windows');
$path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'templates' . DS . 'skel';
$Folder =& new Folder($path);
$Folder = new Folder($path);
$subdir = 'test_folder_new';
$new = TMP . $subdir;
@ -229,7 +231,7 @@ class FolderTest extends CakeTestCase {
$this->assertTrue($Folder->create($new . DS . 'test2'));
$filePath = $new . DS . 'test1.php';
$File =& new File($filePath);
$File = new File($filePath);
$this->assertTrue($File->create());
$copy = TMP . 'test_folder_copy';
@ -257,7 +259,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testZeroAsDirectory() {
$Folder =& new Folder(TMP);
$Folder = new Folder(TMP);
$new = TMP . '0';
$this->assertTrue($Folder->create($new));
@ -292,7 +294,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testFolderRead() {
$Folder =& new Folder(TMP);
$Folder = new Folder(TMP);
$expected = array('cache', 'logs', 'sessions', 'tests');
$result = $Folder->read(true, true);
@ -311,7 +313,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testFolderTree() {
$Folder =& new Folder();
$Folder = new Folder();
$expected = array(
array(
TEST_CAKE_CORE_INCLUDE_PATH . 'config',
@ -458,7 +460,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testInCakePath() {
$Folder =& new Folder();
$Folder = new Folder();
$Folder->cd(ROOT);
$path = 'C:\\path\\to\\file';
$result = $Folder->inCakePath($path);
@ -483,7 +485,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testFind() {
$Folder =& new Folder();
$Folder = new Folder();
$Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH . 'config');
$result = $Folder->find();
$expected = array('config.php', 'paths.php');
@ -536,7 +538,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testFindRecursive() {
$Folder =& new Folder();
$Folder = new Folder();
$Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH);
$result = $Folder->findRecursive('(config|paths)\.php');
$expected = array(
@ -556,7 +558,7 @@ class FolderTest extends CakeTestCase {
$Folder->cd(TMP);
$Folder->create($Folder->pwd() . DS . 'testme');
$Folder->cd('testme');
$File =& new File($Folder->pwd() . DS . 'paths.php');
$File = new File($Folder->pwd() . DS . 'paths.php');
$File->create();
$Folder->cd(TMP . 'sessions');
$result = $Folder->findRecursive('paths\.php');
@ -564,7 +566,7 @@ class FolderTest extends CakeTestCase {
$this->assertIdentical($result, $expected);
$Folder->cd(TMP . 'testme');
$File =& new File($Folder->pwd() . DS . 'my.php');
$File = new File($Folder->pwd() . DS . 'my.php');
$File->create();
$Folder->cd($Folder->pwd() . '/../..');
@ -596,7 +598,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testConstructWithNonExistantPath() {
$Folder =& new Folder(TMP . 'config_non_existant', true);
$Folder = new Folder(TMP . 'config_non_existant', true);
$this->assertTrue(is_dir(TMP . 'config_non_existant'));
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . 'config_non_existant');
@ -609,10 +611,10 @@ class FolderTest extends CakeTestCase {
* @return void
*/
function testDirSize() {
$Folder =& new Folder(TMP . 'config_non_existant', true);
$Folder = new Folder(TMP . 'config_non_existant', true);
$this->assertEqual($Folder->dirSize(), 0);
$File =& new File($Folder->pwd() . DS . 'my.php', true, 0777);
$File = new File($Folder->pwd() . DS . 'my.php', true, 0777);
$File->create();
$File->write('something here');
$File->close();
@ -630,7 +632,7 @@ class FolderTest extends CakeTestCase {
*/
function testDelete() {
$path = TMP . 'folder_delete_test';
$Folder =& new Folder($path, true);
$Folder = new Folder($path, true);
touch(TMP . 'folder_delete_test' . DS . 'file1');
touch(TMP . 'folder_delete_test' . DS . 'file2');
@ -639,7 +641,7 @@ class FolderTest extends CakeTestCase {
$messages = $Folder->messages();
$errors = $Folder->errors();
$this->assertEqual($errors, array());
$this->assertEquals($errors, array());
$expected = array(
$path . ' created',
@ -677,35 +679,35 @@ class FolderTest extends CakeTestCase {
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$Folder =& new Folder($folder3);
$Folder = new Folder($folder3);
$Folder->delete();
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$Folder =& new Folder($folder3);
$Folder = new Folder($folder3);
$Folder->delete();
new Folder($folder3, true);
new Folder($folder3 . DS . 'folder2', true);
file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->copy($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched');
$Folder =& new Folder($path);
$Folder = new Folder($path);
$Folder->delete();
}
@ -736,7 +738,7 @@ class FolderTest extends CakeTestCase {
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
@ -746,7 +748,7 @@ class FolderTest extends CakeTestCase {
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder = new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
@ -754,7 +756,7 @@ class FolderTest extends CakeTestCase {
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
@ -764,7 +766,7 @@ class FolderTest extends CakeTestCase {
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder = new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
@ -775,7 +777,7 @@ class FolderTest extends CakeTestCase {
touch($file2);
file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder =& new Folder($folder1);
$Folder = new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
@ -784,7 +786,7 @@ class FolderTest extends CakeTestCase {
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($path);
$Folder = new Folder($path);
$Folder->delete();
}
}

View file

@ -0,0 +1,268 @@
<?php
/**
* Test case for HtmlCoverageReport
*
* PHP5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.cake
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
require_once CAKE . 'tests' . DS . 'lib' . DS . 'coverage' . DS . 'html_coverage_report.php';
class HtmlCoverageReportTest extends CakeTestCase {
/**
* setup
*
* @return void
*/
public function setUp() {
$reporter = new CakeBaseReporter();
$reporter->params = array('app' => false, 'plugin' => false, 'group' => false);
$coverage = array();
$this->Coverage = new HtmlCoverageReport($coverage, $reporter);
}
/**
* test getting the path filters.
*
* @return void
*/
function testGetPathFilter() {
$this->Coverage->appTest = false;
$result = $this->Coverage->getPathFilter();
$this->assertEquals(TEST_CAKE_CORE_INCLUDE_PATH, $result);
$this->Coverage->appTest = true;
$result = $this->Coverage->getPathFilter();
$this->assertEquals(ROOT . DS . APP_DIR . DS, $result);
$this->Coverage->appTest = false;
$this->Coverage->pluginTest = 'test_plugin';
$result = $this->Coverage->getPathFilter();
$this->assertEquals(ROOT . DS . APP_DIR . DS . 'plugins' . DS .'test_plugin' . DS, $result);
}
/**
* test filtering coverage data.
*
* @return void
*/
function testFilterCoverageDataByPathRemovingElements() {
$data = array(
array(
'files' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php' => array(
10 => -1,
12 => 1
),
APP . 'app_model.php' => array(
50 => 1,
52 => -1
)
)
)
);
$this->Coverage->setCoverage($data);
$result = $this->Coverage->filterCoverageDataByPath(TEST_CAKE_CORE_INCLUDE_PATH);
$this->assertTrue(isset($result[TEST_CAKE_CORE_INCLUDE_PATH . 'dispatcher.php']));
$this->assertFalse(isset($result[APP . 'app_model.php']));
}
/**
* test that filterCoverageDataByPath correctly merges data sets in each test run.
*
* @return void
*/
function testFilterCoverageDataCorrectlyMergingValues() {
$data = array(
array(
'files' => array(
'/something/dispatcher.php' => array(
10 => 1,
12 => 1
),
),
'executable' => array(
'/something/dispatcher.php' => array(
9 => -1
)
),
'dead' => array(
'/something/dispatcher.php' => array(
22 => -2,
23 => -2
)
)
),
array(
'files' => array(
'/something/dispatcher.php' => array(
10 => 1,
50 => 1,
),
),
'executable' => array(
'/something/dispatcher.php' => array(
12 => -1,
51 => -1
)
),
'dead' => array(
'/something/dispatcher.php' => array(
13 => -2,
42 => -2
)
)
),
);
$this->Coverage->setCoverage($data);
$result = $this->Coverage->filterCoverageDataByPath('/something/');
$path = '/something/dispatcher.php';
$this->assertTrue(isset($result[$path]));
$this->assertEquals(array(10, 12, 50), array_keys($result[$path]['covered']));
$this->assertEquals(array(9, 12, 51), array_keys($result[$path]['executable']));
$this->assertEquals(array(22, 23, 13, 42), array_keys($result[$path]['dead']));
}
/**
* test generating HTML reports from file arrays.
*
* @return void
*/
function testGenerateDiff() {
$file = array(
'line 1',
'line 2',
'line 3',
'line 4',
'line 5',
'line 6',
'line 7',
'line 8',
'line 9',
'line 10',
);
$coverage = array(
'covered' => array(
1 => 1,
3 => 1,
4 => 1,
6 => 1,
7 => 1,
8 => 1,
10 => 1
),
'executable' => array(
5 => -1,
9 => -1
),
'dead' => array(
2 => -2
)
);
$result = $this->Coverage->generateDiff('myfile.php', $file, $coverage);
$this->assertRegExp('/myfile\.php Code coverage\: \d+\.?\d*\%/', $result);
$this->assertRegExp('/<div class="code-coverage-results" id\="coverage\-myfile\.php"/', $result);
$this->assertRegExp('/<pre>/', $result);
foreach ($file as $i => $line) {
$this->assertTrue(strpos($line, $result) !== 0, 'Content is missing ' . $i);
$class = 'covered';
if (in_array($i + 1, array(5, 9, 2))) {
$class = 'uncovered';
}
if ($i + 1 == 2) {
$class .= ' dead';
}
$this->assertTrue(strpos($class, $result) !== 0, 'Class name is wrong ' . $i);
}
}
/**
* test that covering methods show up as title attributes for lines.
*
* @return void
*/
function testCoveredLinesTitleAttributes() {
$file = array(
'line 1',
'line 2',
'line 3',
'line 4',
'line 5',
);
$mock = $this->getMock('PHPUnit_Framework_TestCase');
$mock->expects($this->any())->method('getName')->will($this->returnValue('testAwesomeness'));
$rawdata = array(
array(
'test' => $mock,
'files' => array(
'myfile.php' => array(
1 => 1,
3 => 1,
4 => 1,
)
),
'executable' => array(
'myfile.php' => array(
5 => -1
)
)
)
);
$coverage = array(
'covered' => array(
1 => 1,
3 => 1,
4 => 1,
),
'executable' => array(
5 => -1,
),
'dead' => array(
2 => -2
)
);
$this->Coverage->setCoverage($rawdata);
$result = $this->Coverage->generateDiff('myfile.php', $file, $coverage);
$this->assertTrue(
strpos($result, "title=\"Covered by:\ntestAwesomeness\n\"><span class=\"line-num\">1") !== false,
'Missing method coverage for line 1'
);
$this->assertTrue(
strpos($result, "title=\"Covered by:\ntestAwesomeness\n\"><span class=\"line-num\">3") !== false,
'Missing method coverage for line 3'
);
$this->assertTrue(
strpos($result, "title=\"Covered by:\ntestAwesomeness\n\"><span class=\"line-num\">4") !== false,
'Missing method coverage for line 4'
);
$this->assertTrue(
strpos($result, "title=\"\"><span class=\"line-num\">5") !== false,
'Coverage report is wrong for line 5'
);
}
/**
* teardown
*
* @return void
*/
function tearDown() {
unset($this->Coverage);
}
}

File diff suppressed because it is too large Load diff

View file

@ -17,7 +17,7 @@
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once LIBS . 'log' . DS . 'file_log.php';
App::import('Core', 'log/FileLog');
/**
* CakeLogTest class

View file

@ -189,7 +189,7 @@ class AclPost extends CakeTestModel {
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AclBehaviorTestCase extends CakeTestCase {
class AclBehaviorTest extends CakeTestCase {
/**
* Aco property
@ -220,11 +220,11 @@ class AclBehaviorTestCase extends CakeTestCase {
*
* @return void
*/
public function startTest() {
public function setUp() {
Configure::write('Acl.database', 'test_suite');
$this->Aco =& new Aco();
$this->Aro =& new Aro();
$this->Aco = new Aco();
$this->Aro = new Aro();
}
/**
@ -243,12 +243,12 @@ class AclBehaviorTestCase extends CakeTestCase {
* @return void
*/
public function testSetup() {
$User =& new AclUser();
$User = new AclUser();
$this->assertTrue(isset($User->Behaviors->Acl->settings['User']));
$this->assertEqual($User->Behaviors->Acl->settings['User']['type'], 'requester');
$this->assertTrue(is_object($User->Aro));
$Post =& new AclPost();
$Post = new AclPost();
$this->assertTrue(isset($Post->Behaviors->Acl->settings['Post']));
$this->assertEqual($Post->Behaviors->Acl->settings['Post']['type'], 'controlled');
$this->assertTrue(is_object($Post->Aco));
@ -260,7 +260,7 @@ class AclBehaviorTestCase extends CakeTestCase {
* @return void
*/
public function testAfterSave() {
$Post =& new AclPost();
$Post = new AclPost();
$data = array(
'Post' => array(
'author_id' => 1,
@ -284,7 +284,7 @@ class AclBehaviorTestCase extends CakeTestCase {
);
$this->Aro->save($aroData);
$Person =& new AclPerson();
$Person = new AclPerson();
$data = array(
'AclPerson' => array(
'name' => 'Trent',
@ -339,7 +339,7 @@ class AclBehaviorTestCase extends CakeTestCase {
)
);
$this->Aro->save($aroData);
$Person =& new AclPerson();
$Person = new AclPerson();
$data = array(
'AclPerson' => array(
'name' => 'Trent',
@ -384,7 +384,7 @@ class AclBehaviorTestCase extends CakeTestCase {
* @return void
*/
public function testNode() {
$Person =& new AclPerson();
$Person = new AclPerson();
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',

View file

@ -53,12 +53,12 @@ class TranslateBehaviorTest extends CakeTestCase {
);
/**
* endTest method
* tearDown method
*
* @access public
* @return void
*/
function endTest() {
function tearDown() {
ClassRegistry::flush();
}
@ -69,26 +69,27 @@ class TranslateBehaviorTest extends CakeTestCase {
* @return void
*/
function testTranslateModel() {
$TestModel =& new Tag();
$this->loadFixtures('TranslateTable', 'Tag', 'TranslatedItem', 'Translate', 'User', 'TranslatedArticle', 'TranslateArticle');
$TestModel = new Tag();
$TestModel->translateTable = 'another_i18n';
$TestModel->Behaviors->attach('Translate', array('title'));
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'I18nModel');
$this->assertEqual($translateModel->useTable, 'another_i18n');
$TestModel =& new User();
$TestModel = new User();
$TestModel->Behaviors->attach('Translate', array('title'));
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'I18nModel');
$this->assertEqual($translateModel->useTable, 'i18n');
$TestModel =& new TranslatedArticle();
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$TestModel = new TranslatedArticle();
$translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'TranslateArticleModel');
$this->assertEqual($translateModel->useTable, 'article_i18n');
$TestModel =& new TranslatedItem();
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$TestModel = new TranslatedItem();
$translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'TranslateTestModel');
$this->assertEqual($translateModel->useTable, 'i18n');
}
@ -100,9 +101,9 @@ class TranslateBehaviorTest extends CakeTestCase {
* @return void
*/
function testLocaleFalsePlain() {
$this->loadFixtures('Translate', 'TranslatedItem');
$this->loadFixtures('Translate', 'TranslatedItem', 'User');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = false;
$result = $TestModel->read(null, 1);
@ -127,7 +128,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testLocaleFalseAssociations() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = false;
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
@ -182,7 +183,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testLocaleSingle() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array(
@ -238,7 +239,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testLocaleSingleWithConditions() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated')));
$expected = array(
@ -278,7 +279,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testLocaleSingleAssociations() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
@ -339,7 +340,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testLocaleMultiple() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = array('deu', 'eng', 'cze');
$delete = array(
array('locale' => 'deu'),
@ -349,7 +350,7 @@ class TranslateBehaviorTest extends CakeTestCase {
array('foreign_key' => 2, 'field' => 'content', 'locale' => 'eng'),
array('foreign_key' => 3, 'field' => 'title')
);
$I18nModel =& ClassRegistry::getObject('TranslateTestModel');
$I18nModel = ClassRegistry::getObject('TranslateTestModel');
$I18nModel->deleteAll(array('or' => $delete));
$result = $TestModel->read(null, 1);
@ -403,7 +404,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testMissingTranslation() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'rus';
$result = $TestModel->read(null, 1);
$this->assertFalse($result);
@ -431,7 +432,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testTranslatedFindList() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'deu';
$TestModel->displayField = 'title';
$result = $TestModel->find('list', array('recursive' => 1));
@ -465,7 +466,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testReadSelectedFields() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content')));
$expected = array(
@ -480,7 +481,7 @@ class TranslateBehaviorTest extends CakeTestCase {
$TestModel->locale = array('eng', 'deu', 'cze');
$delete = array(array('locale' => 'deu'), array('field' => 'content', 'locale' => 'eng'));
$I18nModel =& ClassRegistry::getObject('TranslateTestModel');
$I18nModel = ClassRegistry::getObject('TranslateTestModel');
$I18nModel->deleteAll(array('or' => $delete));
$result = $TestModel->find('all', array('fields' => array('title', 'content')));
@ -501,7 +502,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testSaveCreate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'spa';
$data = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'content' => 'Contenido #4');
$TestModel->create($data);
@ -520,7 +521,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testSaveUpdate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'spa';
$oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4');
$TestModel->create($oldData);
@ -543,7 +544,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testMultipleCreate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'deu';
$data = array(
'slug' => 'new_translated',
@ -582,7 +583,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testMultipleUpdate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->validate['title'] = 'notEmpty';
$data = array('TranslatedItem' => array(
@ -625,7 +626,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testMixedCreateUpdateWithArrayLocale() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = array('cze', 'deu');
$data = array('TranslatedItem' => array(
'id' => 1,
@ -665,7 +666,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testValidation() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->validate['title'] = '/Only this title/';
$data = array('TranslatedItem' => array(
@ -685,7 +686,8 @@ class TranslateBehaviorTest extends CakeTestCase {
'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1')
));
$TestModel->create();
$this->assertTrue($TestModel->save($data));
$result = $TestModel->save($data);
$this->assertFalse(empty($result));
}
/**
@ -697,8 +699,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testAttachDetach() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$Behavior =& $this->Model->Behaviors->Translate;
$TestModel = new TranslatedItem();
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
@ -748,7 +749,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testAnotherTranslateTable() {
$this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable');
$TestModel =& new TranslatedItemWithTable();
$TestModel = new TranslatedItemWithTable();
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array(
@ -772,7 +773,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testTranslateWithAssociations() {
$this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'User', 'Comment', 'ArticlesTag', 'Tag');
$TestModel =& new TranslatedArticle();
$TestModel = new TranslatedArticle();
$TestModel->locale = 'eng';
$recursive = $TestModel->recursive;
@ -865,7 +866,7 @@ class TranslateBehaviorTest extends CakeTestCase {
*/
function testTranslateTableWithPrefix() {
$this->loadFixtures('TranslateWithPrefix', 'TranslatedItem');
$TestModel =& new TranslatedItem2;
$TestModel = new TranslatedItem2;
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array('TranslatedItem' => array(
@ -886,7 +887,7 @@ class TranslateBehaviorTest extends CakeTestCase {
function testUnbindTranslationInfinteLoop() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel = new TranslatedItem();
$TestModel->Behaviors->detach('Translate');
$TestModel->actsAs = array();
$TestModel->Behaviors->attach('Translate');

View file

@ -30,13 +30,21 @@ require_once(dirname(dirname(__FILE__)) . DS . 'models.php');
*/
class NumberTreeTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @access public
*/
public $backupGlobals = false;
/**
* settings property
*
* @var array
* @access public
* @access protected
*/
public $settings = array(
protected $settings = array(
'modelClass' => 'NumberTree',
'leftField' => 'lft',
'rightField' => 'rght',
@ -59,7 +67,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testInitialize() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->find('count');
@ -77,7 +85,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectInvalidLeft() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->findByName('1.1');
@ -104,7 +112,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectInvalidRight() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->findByName('1.1');
@ -131,7 +139,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectInvalidParent() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->findByName('1.1');
@ -157,7 +165,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectNoneExistantParent() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->findByName('1.1');
@ -181,7 +189,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testRecoverFromMissingParent() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$result = $this->Tree->findByName('1.1');
@ -205,7 +213,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectInvalidParents() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->updateAll(array($parentField => null));
@ -228,7 +236,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectInvalidLftsRghts() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->updateAll(array($leftField => 0, $rightField => 0));
@ -250,7 +258,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDetectEqualLftsRghts() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 3);
$result = $this->Tree->findByName('1.1');
@ -278,7 +286,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testAddOrphan() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->save(array($modelClass => array('name' => 'testAddOrphan', $parentField => null)));
@ -298,7 +306,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testAddMiddle() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data= $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id'));
@ -332,7 +340,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testAddInvalid() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -357,7 +365,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testAddNotIndexedByModel() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->save(array('name' => 'testAddNotIndexed', $parentField => null));
@ -377,7 +385,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMovePromote() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -404,7 +412,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveWithWhitelist() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -432,7 +440,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testInsertWithWhitelist() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->whitelist = array('name', $parentField);
@ -451,7 +459,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveBefore() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -480,7 +488,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveAfter() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -509,7 +517,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveDemoteInvalid() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -543,7 +551,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveInvalid() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -570,7 +578,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveSelfInvalid() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -597,7 +605,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveUpSuccess() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.2'), array('id'));
@ -619,7 +627,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveUpFail() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.1'));
@ -642,7 +650,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveUp2() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 10);
$data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id'));
@ -673,7 +681,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveUpFirst() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 10);
$data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id'));
@ -704,7 +712,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveDownSuccess() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id'));
@ -726,7 +734,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveDownFail() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.2'));
@ -748,7 +756,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveDownLast() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 10);
$data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id'));
@ -779,7 +787,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveDown2() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 10);
$data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id'));
@ -810,7 +818,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testSaveNoMove() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 10);
$data = $this->Tree->find(array($modelClass . '.name' => '1.5'), array('id'));
@ -841,7 +849,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testMoveToRootAndMoveUp() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(1, 1);
$data = $this->Tree->find(array($modelClass . '.name' => '1.1'), array('id'));
$this->Tree->id = $data[$modelClass]['id'];
@ -866,7 +874,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testDelete() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -902,7 +910,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testRemove() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
$result = $this->Tree->findByName('1.1');
@ -935,7 +943,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testRemoveLastTopParent() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -968,7 +976,7 @@ class NumberTreeTest extends CakeTestCase {
*/
public function testRemoveNoChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -1003,7 +1011,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testRemoveAndDelete() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -1035,7 +1043,7 @@ class NumberTreeTest extends CakeTestCase {
*/
public function testRemoveAndDeleteNoChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -1068,7 +1076,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1. Root'));
@ -1097,7 +1105,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testCountChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1. Root'));
@ -1118,7 +1126,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testGetParentNode() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.2.2'));
@ -1137,7 +1145,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testGetPath() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1.2.2'));
@ -1158,7 +1166,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testNoAmbiguousColumn() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false);
$this->Tree->initialize(2, 2);
@ -1191,7 +1199,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testReorderTree() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(3, 3);
$nodes = $this->Tree->find('list', array('order' => $leftField));
@ -1205,7 +1213,8 @@ class NumberTreeTest extends CakeTestCase {
$this->Tree->moveDown($data[$modelClass]['id']);
$unsortedNodes = $this->Tree->find('list', array('order' => $leftField));
$this->assertNotIdentical($nodes, $unsortedNodes);
$this->assertEquals($nodes, $unsortedNodes);
$this->assertNotEquals(array_keys($nodes), array_keys($unsortedNodes));
$this->Tree->reorder();
$sortedNodes = $this->Tree->find('list', array('order' => $leftField));
@ -1222,7 +1231,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testReorderBigTreeWithQueryCaching() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 10);
$original = $this->Tree->cacheQueries;
@ -1239,7 +1248,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testGenerateTreeListWithSelfJoin() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false);
$this->Tree->initialize(2, 2);
@ -1257,7 +1266,7 @@ class NumberTreeTest extends CakeTestCase {
*/
function testArraySyntax() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(3, 3);
$this->assertIdentical($this->Tree->childCount(2), $this->Tree->childCount(array('id' => 2)));
$this->assertIdentical($this->Tree->getParentNode(2), $this->Tree->getParentNode(array('id' => 2)));
@ -1271,7 +1280,15 @@ class NumberTreeTest extends CakeTestCase {
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class ScopedTreeTest extends NumberTreeTest {
class ScopedTreeTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @access public
*/
public $backupGlobals = false;
/**
* settings property
@ -1301,7 +1318,7 @@ class ScopedTreeTest extends NumberTreeTest {
* @return void
*/
function testStringScope() {
$this->Tree =& new FlagTree();
$this->Tree = new FlagTree();
$this->Tree->initialize(2, 3);
$this->Tree->id = 1;
@ -1338,7 +1355,7 @@ class ScopedTreeTest extends NumberTreeTest {
* @return void
*/
function testArrayScope() {
$this->Tree =& new FlagTree();
$this->Tree = new FlagTree();
$this->Tree->initialize(2, 3);
$this->Tree->id = 1;
@ -1375,7 +1392,7 @@ class ScopedTreeTest extends NumberTreeTest {
* @return void
*/
function testMoveUpWithScope() {
$this->Ad =& new Ad();
$this->Ad = new Ad();
$this->Ad->Behaviors->attach('Tree', array('scope'=>'Campaign'));
$this->Ad->moveUp(6);
@ -1392,7 +1409,7 @@ class ScopedTreeTest extends NumberTreeTest {
* @return void
*/
function testMoveDownWithScope() {
$this->Ad =& new Ad();
$this->Ad = new Ad();
$this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign'));
$this->Ad->moveDown(6);
@ -1410,7 +1427,7 @@ class ScopedTreeTest extends NumberTreeTest {
* @return void
*/
function testTranslatingTree() {
$this->Tree =& new FlagTree();
$this->Tree = new FlagTree();
$this->Tree->cacheQueries = false;
$this->Tree->translateModel = 'TranslateTreeTestModel';
$this->Tree->Behaviors->attach('Translate', array('name'));
@ -1509,10 +1526,10 @@ class ScopedTreeTest extends NumberTreeTest {
*/
public function testAliasesWithScopeInTwoTreeAssociations() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->TreeTwo =& new NumberTreeTwo();
$this->TreeTwo = new NumberTreeTwo();
$record = $this->Tree->find('first');
@ -1543,7 +1560,8 @@ class ScopedTreeTest extends NumberTreeTest {
)
);
$this->TreeTwo->create();
$this->assertTrue($this->TreeTwo->save($data));
$result = $this->TreeTwo->save($data);
$this->assertFalse(empty($result));
$result = $this->TreeTwo->find('first');
$expected = array('NumberTreeTwo' => array(
@ -1564,7 +1582,15 @@ class ScopedTreeTest extends NumberTreeTest {
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class AfterTreeTest extends NumberTreeTest {
class AfterTreeTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @access public
*/
public $backupGlobals = false;
/**
* settings property
@ -1594,7 +1620,7 @@ class AfterTreeTest extends NumberTreeTest {
* @return void
*/
function testAftersaveCallback() {
$this->Tree =& new AfterTree();
$this->Tree = new AfterTree();
$expected = array('AfterTree' => array('name' => 'Six and One Half Changed in AfterTree::afterSave() but not in database', 'parent_id' => 6, 'lft' => 11, 'rght' => 12));
$result = $this->Tree->save(array('AfterTree' => array('name' => 'Six and One Half', 'parent_id' => 6)));
@ -1606,43 +1632,21 @@ class AfterTreeTest extends NumberTreeTest {
}
}
/**
* UnconventionalTreeTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class UnconventionalTreeTest extends NumberTreeTest {
/**
* settings property
*
* @var array
* @access public
*/
public $settings = array(
'modelClass' => 'UnconventionalTree',
'leftField' => 'left',
'rightField' => 'right',
'parentField' => 'join'
);
/**
* fixtures property
*
* @var array
* @access public
*/
public $fixtures = array('core.unconventional_tree');
}
/**
* UuidTreeTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class UuidTreeTest extends NumberTreeTest {
class UuidTreeTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @access public
*/
public $backupGlobals = false;
/**
* settings property
@ -1672,7 +1676,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testMovePromote() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -1698,7 +1702,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testMoveWithWhitelist() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->id = null;
@ -1725,7 +1729,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testRemoveNoChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -1759,7 +1763,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testRemoveAndDeleteNoChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$initialCount = $this->Tree->find('count');
@ -1791,7 +1795,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testChildren() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$data = $this->Tree->find(array($modelClass . '.name' => '1. Root'));
@ -1819,7 +1823,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testNoAmbiguousColumn() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->initialize(2, 2);
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
@ -1852,7 +1856,7 @@ class UuidTreeTest extends NumberTreeTest {
*/
public function testGenerateTreeListWithSelfJoin() {
extract($this->settings);
$this->Tree =& new $modelClass();
$this->Tree = new $modelClass();
$this->Tree->bindModel(array('belongsTo' => array('Dummy' =>
array('className' => $modelClass, 'foreignKey' => $parentField, 'conditions' => array('Dummy.id' => null)))), false);
$this->Tree->initialize(2, 2);

View file

@ -737,7 +737,7 @@ class CakeSchemaTest extends CakeTestCase {
),
'posts' => array(
'add' => array(
'summary' => array('type' => 'text', 'null' => 1),
'summary' => array('type' => 'text', 'null' => true),
),
'drop' => array(
'tableParameters' => array(),
@ -745,7 +745,7 @@ class CakeSchemaTest extends CakeTestCase {
'change' => array(
'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''),
'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => '1')
'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1)
)
),
);

View file

@ -34,7 +34,7 @@ class ConnectionManagerTest extends CakeTestCase {
* @return void
*/
function setUp() {
$this->ConnectionManager =& ConnectionManager::getInstance();
$this->ConnectionManager = ConnectionManager::getInstance();
}
/**
@ -79,12 +79,12 @@ class ConnectionManagerTest extends CakeTestCase {
*/
function testGetDataSource() {
$connections = ConnectionManager::enumConnectionObjects();
$this->assertTrue(count(array_keys($connections) >= 1));
$this->assertTrue((bool)(count(array_keys($connections) >= 1)));
$source = ConnectionManager::getDataSource(key($connections));
$this->assertTrue(is_object($source));
$this->expectError(new PatternExpectation('/Non-existent data source/i'));
$this->expectError();
$source = ConnectionManager::getDataSource('non_existent_source');
$this->assertEqual($source, null);
@ -212,7 +212,7 @@ class ConnectionManagerTest extends CakeTestCase {
$this->assertEqual($result, $name);
$source =& new StdClass();
$source = new StdClass();
$result = ConnectionManager::getSourceName($source);
$this->assertEqual($result, null);
}
@ -238,7 +238,7 @@ class ConnectionManagerTest extends CakeTestCase {
}
$connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent');
$this->expectError(new PatternExpectation('/Unable to import DataSource class/i'));
$this->expectError();
$loaded = ConnectionManager::loadDataSource($connection);
$this->assertEqual($loaded, null);
@ -254,7 +254,7 @@ class ConnectionManagerTest extends CakeTestCase {
$name = 'test_created_connection';
$connections = ConnectionManager::enumConnectionObjects();
$this->assertTrue(count(array_keys($connections) >= 1));
$this->assertTrue((bool)(count(array_keys($connections) >= 1)));
$source = ConnectionManager::getDataSource(key($connections));
$this->assertTrue(is_object($source));

View file

@ -19,8 +19,6 @@
*/
App::import('Core', array('Model', 'DataSource', 'DboSource', 'DboMysql'));
Mock::generatePartial('DboMysql', 'QueryMockDboMysql', array('query'));
/**
* DboMysqlTestDb class
*
@ -167,23 +165,19 @@ class DboMysqlTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $Db = null;
/**
* Skip if cannot connect to mysql
*
*/
public function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mysql', '%s MySQL connection not available');
}
public $Dbo = null;
/**
* Sets up a Dbo class instance for testing
*
*/
public function startTest() {
$db = ConnectionManager::getDataSource('test_suite');
public function setUp() {
$this->Dbo = ConnectionManager::getDataSource('test_suite');
if ($this->Dbo->config['driver'] !== 'mysql') {
$this->markTestSkipped('The MySQL extension is not available.');
}
$this->_debug = Configure::read('debug');
Configure::write('debug', 1);
$this->model = new MysqlTestModel();
}
@ -194,24 +188,6 @@ class DboMysqlTest extends CakeTestCase {
public function tearDown() {
unset($this->model);
ClassRegistry::flush();
}
/**
* startCase
*
* @return void
*/
function startCase() {
$this->_debug = Configure::read('debug');
Configure::write('debug', 1);
}
/**
* endCase
*
* @return void
*/
function endCase() {
Configure::write('debug', $this->_debug);
}
@ -220,7 +196,7 @@ class DboMysqlTest extends CakeTestCase {
*
*/
public function testQuoting() {
$result = $this->db->fields($this->model);
$result = $this->Dbo->fields($this->model);
$expected = array(
'`MysqlTestModel`.`id`',
'`MysqlTestModel`.`client_id`',
@ -244,32 +220,32 @@ class DboMysqlTest extends CakeTestCase {
$this->assertEqual($result, $expected);
$expected = 1.2;
$result = $this->db->value(1.2, 'float');
$result = $this->Dbo->value(1.2, 'float');
$this->assertEqual($expected, $result);
$expected = "'1,2'";
$result = $this->db->value('1,2', 'float');
$result = $this->Dbo->value('1,2', 'float');
$this->assertEqual($expected, $result);
$expected = "'4713e29446'";
$result = $this->db->value('4713e29446');
$result = $this->Dbo->value('4713e29446');
$this->assertEqual($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'integer');
$result = $this->Dbo->value('', 'integer');
$this->assertEqual($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'boolean');
$expected = 0;
$result = $this->Dbo->value('', 'boolean');
$this->assertEqual($expected, $result);
$expected = 10010001;
$result = $this->db->value(10010001);
$result = $this->Dbo->value(10010001);
$this->assertEqual($expected, $result);
$expected = "'00010010001'";
$result = $this->db->value('00010010001');
$result = $this->Dbo->value('00010010001');
$this->assertEqual($expected, $result);
}
@ -280,36 +256,37 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testTinyintCasting() {
$this->db->cacheSources = false;
$this->db->query('CREATE TABLE ' . $this->db->fullTableName('tinyint') . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$this->Dbo->cacheSources = false;
$tableName = 'tinyint_' . uniqid();
$this->Dbo->query('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$this->model = new CakeTestModel(array(
'name' => 'Tinyint', 'table' => 'tinyint', 'ds' => 'test_suite'
'name' => 'Tinyint', 'table' => $tableName, 'ds' => 'test_suite'
));
$result = $this->model->schema();
$this->assertEqual($result['bool']['type'], 'boolean');
$this->assertEqual($result['small_int']['type'], 'integer');
$this->assertTrue($this->model->save(array('bool' => 5, 'small_int' => 5)));
$this->assertTrue((bool)$this->model->save(array('bool' => 5, 'small_int' => 5)));
$result = $this->model->find('first');
$this->assertIdentical($result['Tinyint']['bool'], '1');
$this->assertIdentical($result['Tinyint']['small_int'], '5');
$this->model->deleteAll(true);
$this->assertTrue($this->model->save(array('bool' => 0, 'small_int' => 100)));
$this->assertTrue((bool)$this->model->save(array('bool' => 0, 'small_int' => 100)));
$result = $this->model->find('first');
$this->assertIdentical($result['Tinyint']['bool'], '0');
$this->assertIdentical($result['Tinyint']['small_int'], '100');
$this->model->deleteAll(true);
$this->assertTrue($this->model->save(array('bool' => true, 'small_int' => 0)));
$this->assertTrue((bool)$this->model->save(array('bool' => true, 'small_int' => 0)));
$result = $this->model->find('first');
$this->assertIdentical($result['Tinyint']['bool'], '1');
$this->assertIdentical($result['Tinyint']['small_int'], '0');
$this->model->deleteAll(true);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
$this->Dbo->query('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
}
/**
@ -318,50 +295,50 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
public function testIndexDetection() {
$this->db->cacheSources = false;
$this->Dbo->cacheSources = false;
$name = $this->db->fullTableName('simple');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$name = $this->Dbo->fullTableName('simple');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
$result = $this->db->index('simple', false);
$result = $this->Dbo->index('simple', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_a_key');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
$name = $this->Dbo->fullTableName('with_a_key');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
);
$result = $this->db->index('with_a_key', false);
$result = $this->Dbo->index('with_a_key', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_two_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
$name = $this->Dbo->fullTableName('with_two_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
);
$result = $this->db->index('with_two_keys', false);
$result = $this->Dbo->index('with_two_keys', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_compound_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
$name = $this->Dbo->fullTableName('with_compound_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
);
$result = $this->db->index('with_compound_keys', false);
$result = $this->Dbo->index('with_compound_keys', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_multiple_compound_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
$name = $this->Dbo->fullTableName('with_multiple_compound_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
@ -369,9 +346,9 @@ class DboMysqlTest extends CakeTestCase {
'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
);
$result = $this->db->index('with_multiple_compound_keys', false);
$result = $this->Dbo->index('with_multiple_compound_keys', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
}
/**
@ -381,8 +358,8 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testBuildColumn() {
$restore = $this->db->columns;
$this->db->columns = array('varchar(255)' => 1);
$restore = $this->Dbo->columns;
$this->Dbo->columns = array('varchar(255)' => 1);
$data = array(
'name' => 'testName',
'type' => 'varchar(255)',
@ -391,7 +368,7 @@ class DboMysqlTest extends CakeTestCase {
'key',
'comment' => 'test'
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '`testName` DEFAULT NULL COMMENT \'test\'';
$this->assertEqual($result, $expected);
@ -404,10 +381,10 @@ class DboMysqlTest extends CakeTestCase {
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci'
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '`testName` CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL';
$this->assertEqual($result, $expected);
$this->db->columns = $restore;
$this->Dbo->columns = $restore;
}
/**
@ -417,9 +394,9 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testIndexOnMySQL4Output() {
$name = $this->db->fullTableName('simple');
$name = $this->Dbo->fullTableName('simple');
$mockDbo =& new QueryMockDboMysql($this);
$mockDbo = $this->getMock('DboMysql', array('query'));
$columnData = array(
array('0' => array(
'Table' => 'with_compound_keys',
@ -492,7 +469,10 @@ class DboMysqlTest extends CakeTestCase {
'Comment' => ''
))
);
$mockDbo->setReturnValue('query', $columnData, array('SHOW INDEX FROM ' . $name));
$mockDbo->expects($this->once())
->method('query')
->with('SHOW INDEX FROM ' . $name)
->will($this->returnValue($columnData));
$result = $mockDbo->index($name, false);
$expected = array(
@ -510,43 +490,43 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
public function testColumn() {
$result = $this->db->column('varchar(50)');
$result = $this->Dbo->column('varchar(50)');
$expected = 'string';
$this->assertEqual($result, $expected);
$result = $this->db->column('text');
$result = $this->Dbo->column('text');
$expected = 'text';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11)');
$result = $this->Dbo->column('int(11)');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11) unsigned');
$result = $this->Dbo->column('int(11) unsigned');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('tinyint(1)');
$result = $this->Dbo->column('tinyint(1)');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('boolean');
$result = $this->Dbo->column('boolean');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('float');
$result = $this->Dbo->column('float');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('float unsigned');
$result = $this->Dbo->column('float unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('double unsigned');
$result = $this->Dbo->column('double unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('decimal(14,7) unsigned');
$result = $this->Dbo->column('decimal(14,7) unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
}
@ -559,9 +539,9 @@ class DboMysqlTest extends CakeTestCase {
*/
function testAlterSchemaIndexes() {
App::import('Model', 'CakeSchema');
$this->db->cacheSources = $this->db->testing = false;
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$schema1 =& new CakeSchema(array(
$schema1 = new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
@ -570,9 +550,9 @@ class DboMysqlTest extends CakeTestCase {
'group1' => array('type' => 'integer', 'null' => true),
'group2' => array('type' => 'integer', 'null' => true)
)));
$this->db->query($this->db->createSchema($schema1));
$this->Dbo->query($this->Dbo->createSchema($schema1));
$schema2 =& new CakeSchema(array(
$schema2 = new CakeSchema(array(
'name' => 'AlterTest2',
'connection' => 'test_suite',
'altertest' => array(
@ -586,13 +566,13 @@ class DboMysqlTest extends CakeTestCase {
'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0),
'PRIMARY' => array('column' => 'id', 'unique' => 1))
)));
$this->db->query($this->db->alterSchema($schema2->compare($schema1)));
$this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
// Change three indexes, delete one and add another one
$schema3 =& new CakeSchema(array(
$schema3 = new CakeSchema(array(
'name' => 'AlterTest3',
'connection' => 'test_suite',
'altertest' => array(
@ -607,21 +587,21 @@ class DboMysqlTest extends CakeTestCase {
'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0))
)));
$this->db->query($this->db->alterSchema($schema3->compare($schema2)));
$this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual($schema3->tables['altertest']['indexes'], $indexes);
// Compare us to ourself.
$this->assertEqual($schema3->compare($schema3), array());
// Drop the indexes
$this->db->query($this->db->alterSchema($schema1->compare($schema3)));
$this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual(array(), $indexes);
$this->db->query($this->db->dropSchema($schema1));
$this->Dbo->query($this->Dbo->dropSchema($schema1));
}
/**
* test saving and retrieval of blobs
@ -629,13 +609,13 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testBlobSaving() {
$this->db->cacheSources = false;
$this->Dbo->cacheSources = false;
$data = "GIF87ab
Ò4A¿¿¿ˇˇˇ,b
¢îè©ÀÌ#¥⁄ã≥fi:¯Üá¶jV∂ÓúÎL≥çÀóËıÎ…>ï vFE%ÒâLFI<†µw˝±≈£7˘ç^H“≤« >Éâ*∑ÇnÖA•Ù|flêèj£:=ÿ6óUàµ5'∂®àA¬ñ∆ˆGE(gt≈àÚyÁó«7 VìöÇ√˙Ç™
k”:;kÀAõ{*¡€Î˚˚[;;";
$model =& new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite'));
$model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite'));
$model->save(compact('data'));
$result = $model->find('first');
@ -649,9 +629,9 @@ class DboMysqlTest extends CakeTestCase {
*/
function testAlteringTableParameters() {
App::import('Model', 'CakeSchema');
$this->db->cacheSources = $this->db->testing = false;
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$schema1 =& new CakeSchema(array(
$schema1 = new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
@ -664,8 +644,8 @@ class DboMysqlTest extends CakeTestCase {
)
)
));
$this->db->query($this->db->createSchema($schema1));
$schema2 =& new CakeSchema(array(
$this->Dbo->query($this->Dbo->createSchema($schema1));
$schema2 = new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
@ -678,18 +658,18 @@ class DboMysqlTest extends CakeTestCase {
)
)
));
$result = $this->db->alterSchema($schema2->compare($schema1));
$result = $this->Dbo->alterSchema($schema2->compare($schema1));
$this->assertPattern('/DEFAULT CHARSET=utf8/', $result);
$this->assertPattern('/ENGINE=InnoDB/', $result);
$this->assertPattern('/COLLATE=utf8_general_ci/', $result);
$this->db->query($result);
$result = $this->db->listDetailedSources('altertest');
$this->Dbo->query($result);
$result = $this->Dbo->listDetailedSources('altertest');
$this->assertEqual($result['Collation'], 'utf8_general_ci');
$this->assertEqual($result['Engine'], 'InnoDB');
$this->assertEqual($result['charset'], 'utf8');
$this->db->query($this->db->dropSchema($schema1));
$this->Dbo->query($this->Dbo->dropSchema($schema1));
}
/**
@ -699,24 +679,25 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testReadTableParameters() {
$this->db->cacheSources = $this->db->testing = false;
$this->db->query('CREATE TABLE ' . $this->db->fullTableName('tinyint') . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
$result = $this->db->readTableParameters('tinyint');
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$tableName = 'tinyint_' . uniqid();
$this->Dbo->query('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
$result = $this->Dbo->readTableParameters($tableName);
$expected = array(
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci',
'engine' => 'InnoDB');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
$this->db->query('CREATE TABLE ' . $this->db->fullTableName('tinyint') . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
$result = $this->db->readTableParameters('tinyint');
$this->Dbo->query('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
$this->Dbo->query('CREATE TABLE ' . $this->Dbo->fullTableName($tableName) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
$result = $this->Dbo->readTableParameters($tableName);
$expected = array(
'charset' => 'cp1250',
'collate' => 'cp1250_general_ci',
'engine' => 'MyISAM');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
$this->Dbo->query('DROP TABLE ' . $this->Dbo->fullTableName($tableName));
}
/**
@ -726,12 +707,12 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testBuildTableParameters() {
$this->db->cacheSources = $this->db->testing = false;
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$data = array(
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci',
'engine' => 'InnoDB');
$result = $this->db->buildTableParameters($data);
$result = $this->Dbo->buildTableParameters($data);
$expected = array(
'DEFAULT CHARSET=utf8',
'COLLATE=utf8_unicode_ci',
@ -746,10 +727,10 @@ class DboMysqlTest extends CakeTestCase {
* @return void
*/
function testGetCharsetName() {
$this->db->cacheSources = $this->db->testing = false;
$result = $this->db->getCharsetName('utf8_unicode_ci');
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$result = $this->Dbo->getCharsetName('utf8_unicode_ci');
$this->assertEqual($result, 'utf8');
$result = $this->db->getCharsetName('cp1250_general_ci');
$result = $this->Dbo->getCharsetName('cp1250_general_ci');
$this->assertEqual($result, 'cp1250');
}

View file

@ -140,22 +140,17 @@ class DboMysqliTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $Db = null;
/**
* Skip if cannot connect to mysqli
*
*/
public function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mysqli', '%s MySQLi connection not available');
}
public $Dbo = null;
/**
* Sets up a Dbo class instance for testing
*
*/
public function setUp() {
$this->Dbo = ConnectionManager::getDataSource('test_suite');
if ($this->Dbo->config['driver'] !== 'mysqli') {
$this->markTestSkipped('The MySQLi extension is not available.');
}
$this->model = new MysqliTestModel();
}
@ -174,50 +169,50 @@ class DboMysqliTest extends CakeTestCase {
* @return void
*/
public function testIndexDetection() {
$this->db->cacheSources = false;
$this->Dbo->cacheSources = false;
$name = $this->db->fullTableName('simple');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$name = $this->Dbo->fullTableName('simple');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id));');
$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
$result = $this->db->index($name, false);
$result = $this->Dbo->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_a_key');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
$name = $this->Dbo->fullTableName('with_a_key');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
);
$result = $this->db->index($name, false);
$result = $this->Dbo->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_two_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
$name = $this->Dbo->fullTableName('with_two_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
);
$result = $this->db->index($name, false);
$result = $this->Dbo->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_compound_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
$name = $this->Dbo->fullTableName('with_compound_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'pointless_small_int' => array('column' => 'small_int', 'unique' => 0),
'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
);
$result = $this->db->index($name, false);
$result = $this->Dbo->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('with_multiple_compound_keys');
$this->db->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
$name = $this->Dbo->fullTableName('with_multiple_compound_keys');
$this->Dbo->query('CREATE TABLE ' . $name . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id), KEY `pointless_bool` ( `bool` ), KEY `pointless_small_int` ( `small_int` ), KEY `one_way` ( `bool`, `small_int` ), KEY `other_way` ( `small_int`, `bool` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
@ -225,9 +220,9 @@ class DboMysqliTest extends CakeTestCase {
'one_way' => array('column' => array('bool', 'small_int'), 'unique' => 0),
'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
);
$result = $this->db->index($name, false);
$result = $this->Dbo->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
}
/**
@ -236,43 +231,43 @@ class DboMysqliTest extends CakeTestCase {
* @return void
*/
public function testColumn() {
$result = $this->db->column('varchar(50)');
$result = $this->Dbo->column('varchar(50)');
$expected = 'string';
$this->assertEqual($result, $expected);
$result = $this->db->column('text');
$result = $this->Dbo->column('text');
$expected = 'text';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11)');
$result = $this->Dbo->column('int(11)');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11) unsigned');
$result = $this->Dbo->column('int(11) unsigned');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('tinyint(1)');
$result = $this->Dbo->column('tinyint(1)');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('boolean');
$result = $this->Dbo->column('boolean');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('float');
$result = $this->Dbo->column('float');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('float unsigned');
$result = $this->Dbo->column('float unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('double unsigned');
$result = $this->Dbo->column('double unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('decimal(14,7) unsigned');
$result = $this->Dbo->column('decimal(14,7) unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
}
@ -283,14 +278,15 @@ class DboMysqliTest extends CakeTestCase {
* @return void
*/
public function testTransactions() {
$this->db->testing = false;
$result = $this->db->begin($this->model);
$this->Dbo->testing = false;
$result = $this->Dbo->begin($this->model);
$this->assertTrue($result);
$beginSqlCalls = Set::extract('/.[query=START TRANSACTION]', $this->db->_queriesLog);
$log = $this->Dbo->getLog();
$beginSqlCalls = Set::extract('/.[query=START TRANSACTION]', $log['log']);
$this->assertEqual(1, count($beginSqlCalls));
$result = $this->db->commit($this->model);
$result = $this->Dbo->commit($this->model);
$this->assertTrue($result);
}
/**
@ -300,7 +296,7 @@ class DboMysqliTest extends CakeTestCase {
*/
function testFloatParsing() {
$model =& new Model(array('ds' => 'test_suite', 'table' => 'datatypes', 'name' => 'Datatype'));
$result = $this->db->describe($model);
$result = $this->Dbo->describe($model);
$this->assertEqual((string)$result['float_field']['length'], '5,2');
}
@ -311,23 +307,24 @@ class DboMysqliTest extends CakeTestCase {
* @return void
*/
function testReadTableParameters() {
$this->db->cacheSources = $this->db->testing = false;
$this->db->query('CREATE TABLE ' . $this->db->fullTableName('tinyint') . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
$result = $this->db->readTableParameters('tinyint');
$table = 'tinyint' . uniqid();
$this->Dbo->cacheSources = $this->Dbo->testing = false;
$this->Dbo->query('CREATE TABLE ' . $this->Dbo->fullTableName($table) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
$result = $this->Dbo->readTableParameters($table);
$expected = array(
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci',
'engine' => 'InnoDB');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
$this->db->query('CREATE TABLE ' . $this->db->fullTableName('tinyint') . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
$result = $this->db->readTableParameters('tinyint');
$this->Dbo->query('DROP TABLE ' . $this->Dbo->fullTableName($table));
$this->Dbo->query('CREATE TABLE ' . $this->Dbo->fullTableName($table) . ' (id int(11) AUTO_INCREMENT, bool tinyint(1), small_int tinyint(2), primary key(id)) ENGINE=MyISAM DEFAULT CHARSET=cp1250 COLLATE=cp1250_general_ci;');
$result = $this->Dbo->readTableParameters($table);
$expected = array(
'charset' => 'cp1250',
'collate' => 'cp1250_general_ci',
'engine' => 'MyISAM');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
$this->Dbo->query('DROP TABLE ' . $this->Dbo->fullTableName($table));
}
}

View file

@ -227,7 +227,7 @@ class DboPostgresTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $db = null;
public $Dbo = null;
/**
* Simulated DB connection used in testing
@ -235,24 +235,7 @@ class DboPostgresTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $db2 = null;
/**
* Skip if cannot connect to postgres
*
*/
public function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'postgres', '%s PostgreSQL connection not available');
}
/**
* Set up test suite database connection
*
*/
public function startTest() {
$this->_initDb();
}
public $Dbo2 = null;
/**
* Sets up a Dbo class instance for testing
@ -260,9 +243,9 @@ class DboPostgresTest extends CakeTestCase {
*/
public function setUp() {
Configure::write('Cache.disable', true);
$this->startTest();
$this->db =& ConnectionManager::getDataSource('test_suite');
$this->db2 = new DboPostgresTestDb($this->db->config, false);
$this->Dbo = ConnectionManager::getDataSource('test_suite');
$this->Dbo2 = new DboPostgresTestDb($this->Dbo->config, false);
$this->skipUnless($this->Dbo->config['driver'] == 'postgres', 'PostgreSQL connection not available');
$this->model = new PostgresTestModel();
}
@ -272,7 +255,7 @@ class DboPostgresTest extends CakeTestCase {
*/
public function tearDown() {
Configure::write('Cache.disable', false);
unset($this->db2);
unset($this->Dbo2);
}
/**
@ -301,21 +284,21 @@ class DboPostgresTest extends CakeTestCase {
'"PostgresTestModel"."updated" AS "PostgresTestModel__updated"'
);
$result = $this->db->fields($this->model);
$result = $this->Dbo->fields($this->model);
$expected = $fields;
$this->assertEqual($result, $expected);
$result = $this->db->fields($this->model, null, 'PostgresTestModel.*');
$result = $this->Dbo->fields($this->model, null, 'PostgresTestModel.*');
$expected = $fields;
$this->assertEqual($result, $expected);
$result = $this->db->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
$result = $this->Dbo->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
$expected = array_merge($fields, array(
'"AnotherModel"."id" AS "AnotherModel__id"',
'"AnotherModel"."name" AS "AnotherModel__name"'));
$this->assertEqual($result, $expected);
$result = $this->db->fields($this->model, null, array('*', 'PostgresClientTestModel.*'));
$result = $this->Dbo->fields($this->model, null, array('*', 'PostgresClientTestModel.*'));
$expected = array_merge($fields, array(
'"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"',
'"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"',
@ -332,12 +315,12 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testColumnParsing() {
$this->assertEqual($this->db2->column('text'), 'text');
$this->assertEqual($this->db2->column('date'), 'date');
$this->assertEqual($this->db2->column('boolean'), 'boolean');
$this->assertEqual($this->db2->column('character varying'), 'string');
$this->assertEqual($this->db2->column('time without time zone'), 'time');
$this->assertEqual($this->db2->column('timestamp without time zone'), 'datetime');
$this->assertEqual($this->Dbo2->column('text'), 'text');
$this->assertEqual($this->Dbo2->column('date'), 'date');
$this->assertEqual($this->Dbo2->column('boolean'), 'boolean');
$this->assertEqual($this->Dbo2->column('character varying'), 'string');
$this->assertEqual($this->Dbo2->column('time without time zone'), 'time');
$this->assertEqual($this->Dbo2->column('timestamp without time zone'), 'datetime');
}
/**
@ -347,30 +330,30 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testValueQuoting() {
$this->assertIdentical($this->db2->value(1.2, 'float'), "'1.2'");
$this->assertEqual($this->db2->value('1,2', 'float'), "'1,2'");
$this->assertIdentical($this->Dbo2->value(1.2, 'float'), "'1.2'");
$this->assertEqual($this->Dbo2->value('1,2', 'float'), "'1,2'");
$this->assertEqual($this->db2->value('0', 'integer'), "'0'");
$this->assertEqual($this->db2->value('', 'integer'), 'NULL');
$this->assertEqual($this->db2->value('', 'float'), 'NULL');
$this->assertEqual($this->db2->value('', 'integer', false), "DEFAULT");
$this->assertEqual($this->db2->value('', 'float', false), "DEFAULT");
$this->assertEqual($this->db2->value('0.0', 'float'), "'0.0'");
$this->assertEqual($this->Dbo2->value('0', 'integer'), "'0'");
$this->assertEqual($this->Dbo2->value('', 'integer'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'float'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'integer', false), "DEFAULT");
$this->assertEqual($this->Dbo2->value('', 'float', false), "DEFAULT");
$this->assertEqual($this->Dbo2->value('0.0', 'float'), "'0.0'");
$this->assertEqual($this->db2->value('t', 'boolean'), "TRUE");
$this->assertEqual($this->db2->value('f', 'boolean'), "FALSE");
$this->assertEqual($this->db2->value(true), "TRUE");
$this->assertEqual($this->db2->value(false), "FALSE");
$this->assertEqual($this->db2->value('t'), "'t'");
$this->assertEqual($this->db2->value('f'), "'f'");
$this->assertEqual($this->db2->value('true', 'boolean'), 'TRUE');
$this->assertEqual($this->db2->value('false', 'boolean'), 'FALSE');
$this->assertEqual($this->db2->value('', 'boolean'), 'FALSE');
$this->assertEqual($this->db2->value(0, 'boolean'), 'FALSE');
$this->assertEqual($this->db2->value(1, 'boolean'), 'TRUE');
$this->assertEqual($this->db2->value('1', 'boolean'), 'TRUE');
$this->assertEqual($this->db2->value(null, 'boolean'), "NULL");
$this->assertEqual($this->db2->value(array()), "NULL");
$this->assertEqual($this->Dbo2->value('t', 'boolean'), "TRUE");
$this->assertEqual($this->Dbo2->value('f', 'boolean'), "FALSE");
$this->assertEqual($this->Dbo2->value(true), "TRUE");
$this->assertEqual($this->Dbo2->value(false), "FALSE");
$this->assertEqual($this->Dbo2->value('t'), "'t'");
$this->assertEqual($this->Dbo2->value('f'), "'f'");
$this->assertEqual($this->Dbo2->value('true', 'boolean'), 'TRUE');
$this->assertEqual($this->Dbo2->value('false', 'boolean'), 'FALSE');
$this->assertEqual($this->Dbo2->value('', 'boolean'), 'FALSE');
$this->assertEqual($this->Dbo2->value(0, 'boolean'), 'FALSE');
$this->assertEqual($this->Dbo2->value(1, 'boolean'), 'TRUE');
$this->assertEqual($this->Dbo2->value('1', 'boolean'), 'TRUE');
$this->assertEqual($this->Dbo2->value(null, 'boolean'), "NULL");
$this->assertEqual($this->Dbo2->value(array()), "NULL");
}
/**
@ -379,17 +362,17 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testDateAndTimeAsNull() {
$this->assertEqual($this->db2->value(null, 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'date'), 'NULL');
$this->assertEqual($this->Dbo2->value(null, 'date'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'datetime'), 'NULL');
$this->assertEqual($this->db2->value(null, 'datetime'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'datetime'), 'NULL');
$this->assertEqual($this->Dbo2->value(null, 'datetime'), 'NULL');
$this->assertEqual($this->db2->value('', 'timestamp'), 'NULL');
$this->assertEqual($this->db2->value(null, 'timestamp'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'timestamp'), 'NULL');
$this->assertEqual($this->Dbo2->value(null, 'timestamp'), 'NULL');
$this->assertEqual($this->db2->value('', 'time'), 'NULL');
$this->assertEqual($this->db2->value(null, 'time'), 'NULL');
$this->assertEqual($this->Dbo2->value('', 'time'), 'NULL');
$this->assertEqual($this->Dbo2->value(null, 'time'), 'NULL');
}
/**
@ -399,19 +382,19 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testBooleanNormalization() {
$this->assertTrue($this->db2->boolean('t'));
$this->assertTrue($this->db2->boolean('true'));
$this->assertTrue($this->db2->boolean('TRUE'));
$this->assertTrue($this->db2->boolean(true));
$this->assertTrue($this->db2->boolean(1));
$this->assertTrue($this->db2->boolean(" "));
$this->assertTrue($this->Dbo2->boolean('t'));
$this->assertTrue($this->Dbo2->boolean('true'));
$this->assertTrue($this->Dbo2->boolean('TRUE'));
$this->assertTrue($this->Dbo2->boolean(true));
$this->assertTrue($this->Dbo2->boolean(1));
$this->assertTrue($this->Dbo2->boolean(" "));
$this->assertFalse($this->db2->boolean('f'));
$this->assertFalse($this->db2->boolean('false'));
$this->assertFalse($this->db2->boolean('FALSE'));
$this->assertFalse($this->db2->boolean(false));
$this->assertFalse($this->db2->boolean(0));
$this->assertFalse($this->db2->boolean(''));
$this->assertFalse($this->Dbo2->boolean('f'));
$this->assertFalse($this->Dbo2->boolean('false'));
$this->assertFalse($this->Dbo2->boolean('FALSE'));
$this->assertFalse($this->Dbo2->boolean(false));
$this->assertFalse($this->Dbo2->boolean(0));
$this->assertFalse($this->Dbo2->boolean(''));
}
/**
@ -421,14 +404,10 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testLastInsertIdMultipleInsert() {
$this->loadFixtures('User');
$db1 = ConnectionManager::getDataSource('test_suite');
if (PHP5) {
$db2 = clone $db1;
} else {
$db2 = $db1;
}
$db2->connect();
$this->assertNotEqual($db1->connection, $db2->connection);
@ -438,8 +417,8 @@ class DboPostgresTest extends CakeTestCase {
"INSERT INTO {$table} (\"user\", password) VALUES ('mariano', '{$password}')"
);
$db2->execute("INSERT INTO {$table} (\"user\", password) VALUES ('hoge', '{$password}')");
$this->assertEqual($db1->lastInsertId($table), 1);
$this->assertEqual($db2->lastInsertId($table), 2);
$this->assertEqual($db1->lastInsertId($table), 5);
$this->assertEqual($db2->lastInsertId($table), 6);
}
/**
@ -449,12 +428,12 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testSchemaScoping() {
$db1 =& ConnectionManager::getDataSource('test_suite');
$db1 = ConnectionManager::getDataSource('test_suite');
$db1->cacheSources = false;
$db1->reconnect(array('persistent' => false));
$db1->query('CREATE SCHEMA _scope_test');
$db2 =& ConnectionManager::create(
$db2 = ConnectionManager::create(
'test_suite_2',
array_merge($db1->config, array('driver' => 'postgres', 'schema' => '_scope_test'))
);
@ -473,11 +452,11 @@ class DboPostgresTest extends CakeTestCase {
function testColumnUseLength() {
$result = array('name' => 'foo', 'type' => 'string', 'length' => 100, 'default' => 'FOO');
$expected = '"foo" varchar(100) DEFAULT \'FOO\'';
$this->assertEqual($this->db->buildColumn($result), $expected);
$this->assertEqual($this->Dbo->buildColumn($result), $expected);
$result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO');
$expected = '"foo" text DEFAULT \'FOO\'';
$this->assertEqual($this->db->buildColumn($result), $expected);
$this->assertEqual($this->Dbo->buildColumn($result), $expected);
}
/**
@ -487,6 +466,7 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testBinaryDataIntegrity() {
$this->loadFixtures('BinaryTest');
$data = '%PDF-1.3
%ƒÂÚÂÎßÛ†–ƒ∆
4 0 obj
@ -506,7 +486,7 @@ class DboPostgresTest extends CakeTestCase {
ªºnh˚ºO^∏…®[Ó“ÅfıÌ≥∫F!(π∑T6`¬tΩÆ0ì»rTÎ`»Ñ«
]≈åp˝)=¿Ô0∆öVÂmˇˆ„ø~¯ÁÔ∏b*fc»‡Îı„Ú}∆tœs∂Y∫ÜaÆ˙X∏~<ÿ·Ù vé1p¿TD∆ÔîÄ“úhˆ*Ú€îe)K p¨ÚJ3Ÿ∞ã>ÊuNê°“√Ü Ê9iÙ0˙AAEÍ ˙`∂£\'ûce•åƒXŸÁ´1SK{qdá"tÏ[wQ#SµBe∞∑µó…ÌV`B"Ñ≥„!è_Óφ-ºú¿Ë0ˆeê∂´ë+HFj…‡zvHÓN|ÔL÷ûñ3õÜ$z%sá…pÎóV38âs Çoµ•ß3†<9B·¨û~¢3)ÂxóÿÁCÕòÆ ∫Í=»ÿSπS;∆~±êÆTEp∑óÈ÷ÀuìDHÈ $ÉõæÜjû§"≤ÃONM®RËíRr{õS ∏Ê™op±W;ÂUÔ P∫kÔˇflTæ∑óflË” ÆC©Ô[≥◊HÁ˚¨hê"ÆbF?ú%h˙ˇ4xèÕ(ó2ÙáíM])Ñd|=fë-cI0ñL¢kÖêk‰Rƒ«ıÄWñ8mO3∏&√æËX¯Hó—ì]yF2»˜ádàà‡‹Çο„≥7mªHAS∑¶.;Œx(1} _kd©.fidç48M\áªCp^Krí<ɉXÓıïl!Ì$N<ı∞B»G]…∂Ó¯>˛ÔbõÒπÀ•:ôO<j∂™œ%âÏ—>@È$pÖuÊ´-QqV ?V≥JÆÍqÛX8(lπï@zgÖ}Fe<ˇ‡Sñ“ÿ˜ê?6‡L∫Oß~µ ?ËeäÚ®YîÕ =¢DÁu*GvBk;)L¬N«î:flö∂≠ÇΩq„Ñm하Ë"û≥§:±≤i^ΩÑ!)Wıyŧô á„RÄ÷Òôc≠—s™rıPdêãh˘ßHVç5fifiÈF€çÌÛuçÖ/M=µ±ÿGû1coÔuñæ. õ∑7ÉÏÜÆ,°H†ÍÉÌ∂7e º® íˆ◊øNWK”ÂYµñé;µ¶gV->µtË¥áßN2 ¯¶BaP-)eW.àôt^∏1C∑Ö?L„&”54jvãªZ ÷+4% ´0l…»ú^°´© ûiπ∑é®óܱÒÿ‰ïˆÌdˆ◊Æ19rQ=Í|ı•rMæ¬;ò‰Y‰é9. ˝V«ã¯∏,+ë®j*¡·/';
$model =& new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite'));
$model = new AppModel(array('name' => 'BinaryTest', 'ds' => 'test_suite'));
$model->save(compact('data'));
$result = $model->find('first');
@ -542,7 +522,7 @@ class DboPostgresTest extends CakeTestCase {
)
));
$result = $this->db->createSchema($schema);
$result = $this->Dbo->createSchema($schema);
$this->assertNoPattern('/^CREATE INDEX(.+);,$/', $result);
}
@ -555,7 +535,7 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
public function testCakeSchema() {
$db1 =& ConnectionManager::getDataSource('test_suite');
$db1 = ConnectionManager::getDataSource('test_suite');
$db1->cacheSources = false;
$db1->reconnect(array('persistent' => false));
$db1->query('CREATE TABLE ' . $db1->fullTableName('datatypes') . ' (
@ -566,7 +546,7 @@ class DboPostgresTest extends CakeTestCase {
date date,
CONSTRAINT test_suite_data_types_pkey PRIMARY KEY (id)
)');
$model =& ClassRegistry::init('datatypes');
$model = ClassRegistry::init('datatypes');
$schema = new CakeSchema(array('connection' => 'test_suite'));
$result = $schema->read(array(
'connection' => 'test_suite',
@ -599,30 +579,30 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testIndexGeneration() {
$name = $this->db->fullTableName('index_test', false);
$this->db->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
$this->db->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
$this->db->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
$name = $this->Dbo->fullTableName('index_test', false);
$this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
$this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
$this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'char_index' => array('column' => 'small_char', 'unique' => 1),
'PRIMARY' => array('column' => 'id', 'unique' => true),
'pointless_bool' => array('column' => 'bool', 'unique' => false),
'char_index' => array('column' => 'small_char', 'unique' => true),
);
$result = $this->db->index($name);
$result = $this->Dbo->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$name = $this->db->fullTableName('index_test_2', false);
$this->db->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
$this->db->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
$this->Dbo->query('DROP TABLE ' . $name);
$name = $this->Dbo->fullTableName('index_test_2', false);
$this->Dbo->query('CREATE TABLE ' . $name . ' ("id" serial NOT NULL PRIMARY KEY, "bool" integer, "small_char" varchar(50), "description" varchar(40) )');
$this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => 1),
'PRIMARY' => array('column' => 'id', 'unique' => true),
'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => true),
);
$result = $this->db->index($name);
$result = $this->Dbo->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
}
/**
@ -632,7 +612,7 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testAlterSchema() {
$Old =& new CakeSchema(array(
$Old = new CakeSchema(array(
'connection' => 'test_suite',
'name' => 'AlterPosts',
'alter_posts' => array(
@ -645,9 +625,9 @@ class DboPostgresTest extends CakeTestCase {
'updated' => array('type' => 'datetime'),
)
));
$this->db->query($this->db->createSchema($Old));
$this->Dbo->query($this->Dbo->createSchema($Old));
$New =& new CakeSchema(array(
$New = new CakeSchema(array(
'connection' => 'test_suite',
'name' => 'AlterPosts',
'alter_posts' => array(
@ -660,7 +640,7 @@ class DboPostgresTest extends CakeTestCase {
'updated' => array('type' => 'datetime'),
)
));
$this->db->query($this->db->alterSchema($New->compare($Old), 'alter_posts'));
$this->Dbo->query($this->Dbo->alterSchema($New->compare($Old), 'alter_posts'));
$model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test_suite'));
$result = $model->schema();
@ -671,7 +651,7 @@ class DboPostgresTest extends CakeTestCase {
$this->assertEqual($result['author_id']['null'], true);
$this->assertEqual($result['title']['null'], false);
$this->db->query($this->db->dropSchema($New));
$this->Dbo->query($this->Dbo->dropSchema($New));
}
/**
@ -681,9 +661,9 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testAlterIndexes() {
$this->db->cacheSources = false;
$this->Dbo->cacheSources = false;
$schema1 =& new CakeSchema(array(
$schema1 = new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
@ -693,9 +673,9 @@ class DboPostgresTest extends CakeTestCase {
'group2' => array('type' => 'integer', 'null' => true)
)
));
$this->db->query($this->db->createSchema($schema1));
$this->Dbo->query($this->Dbo->createSchema($schema1));
$schema2 =& new CakeSchema(array(
$schema2 = new CakeSchema(array(
'name' => 'AlterTest2',
'connection' => 'test_suite',
'altertest' => array(
@ -704,20 +684,20 @@ class DboPostgresTest extends CakeTestCase {
'group1' => array('type' => 'integer', 'null' => true),
'group2' => array('type' => 'integer', 'null' => true),
'indexes' => array(
'name_idx' => array('column' => 'name', 'unique' => 0),
'group_idx' => array('column' => 'group1', 'unique' => 0),
'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => 0),
'PRIMARY' => array('column' => 'id', 'unique' => 1)
'name_idx' => array('column' => 'name', 'unique' => false),
'group_idx' => array('column' => 'group1', 'unique' => false),
'compound_idx' => array('column' => array('group1', 'group2'), 'unique' => false),
'PRIMARY' => array('column' => 'id', 'unique' => true)
)
)
));
$this->db->query($this->db->alterSchema($schema2->compare($schema1)));
$this->Dbo->query($this->Dbo->alterSchema($schema2->compare($schema1)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
// Change three indexes, delete one and add another one
$schema3 =& new CakeSchema(array(
$schema3 = new CakeSchema(array(
'name' => 'AlterTest3',
'connection' => 'test_suite',
'altertest' => array(
@ -726,27 +706,27 @@ class DboPostgresTest extends CakeTestCase {
'group1' => array('type' => 'integer', 'null' => true),
'group2' => array('type' => 'integer', 'null' => true),
'indexes' => array(
'name_idx' => array('column' => 'name', 'unique' => 1),
'group_idx' => array('column' => 'group2', 'unique' => 0),
'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => 0),
'another_idx' => array('column' => array('group1', 'name'), 'unique' => 0))
'name_idx' => array('column' => 'name', 'unique' => true),
'group_idx' => array('column' => 'group2', 'unique' => false),
'compound_idx' => array('column' => array('group2', 'group1'), 'unique' => false),
'another_idx' => array('column' => array('group1', 'name'), 'unique' => false))
)));
$this->db->query($this->db->alterSchema($schema3->compare($schema2)));
$this->Dbo->query($this->Dbo->alterSchema($schema3->compare($schema2)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual($schema3->tables['altertest']['indexes'], $indexes);
// Compare us to ourself.
$this->assertEqual($schema3->compare($schema3), array());
// Drop the indexes
$this->db->query($this->db->alterSchema($schema1->compare($schema3)));
$this->Dbo->query($this->Dbo->alterSchema($schema1->compare($schema3)));
$indexes = $this->db->index('altertest');
$indexes = $this->Dbo->index('altertest');
$this->assertEqual(array(), $indexes);
$this->db->query($this->db->dropSchema($schema1));
$this->Dbo->query($this->Dbo->dropSchema($schema1));
}
/*
@ -756,7 +736,7 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testVirtualFields() {
$this->loadFixtures('Article', 'Comment');
$this->loadFixtures('Article', 'Comment', 'User', 'Attachment', 'Tag', 'ArticlesTag');
$Article = new Article;
$Article->virtualFields = array(
'next_id' => 'Article.id + 1',
@ -767,7 +747,7 @@ class DboPostgresTest extends CakeTestCase {
$result = $Article->find('first');
$this->assertEqual($result['Article']['next_id'], 2);
$this->assertEqual($result['Article']['complex'], $result['Article']['title'] . $result['Article']['body']);
$this->assertEqual($result['Article']['functional'], $result['Article']['title']);
$this->assertEqual($result['Article']['functional'], $result['User']['user']);
$this->assertEqual($result['Article']['subquery'], 6);
}
@ -778,7 +758,7 @@ class DboPostgresTest extends CakeTestCase {
* @return void
*/
function testOrderAdditionalParams() {
$result = $this->db->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
$result = $this->Dbo->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
$expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
$this->assertEqual($result, $expected);
}
@ -789,15 +769,15 @@ class DboPostgresTest extends CakeTestCase {
function testQuoteDistinctInFunction() {
$this->loadFixtures('Article');
$Article = new Article;
$result = $this->db->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
$result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT Article.id)'));
$expected = array('COUNT(DISTINCT "Article"."id")');
$this->assertEqual($result, $expected);
$result = $this->db->fields($Article, null, array('COUNT(DISTINCT id)'));
$result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT id)'));
$expected = array('COUNT(DISTINCT "id")');
$this->assertEqual($result, $expected);
$result = $this->db->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
$result = $this->Dbo->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
$expected = array('COUNT(DISTINCT FUNC("id"))');
$this->assertEqual($result, $expected);
}

View file

@ -88,7 +88,7 @@ class DboSqliteTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $db = null;
public $Dbo = null;
/**
* Simulated DB connection used in testing
@ -96,24 +96,7 @@ class DboSqliteTest extends CakeTestCase {
* @var DboSource
* @access public
*/
public $db2 = null;
/**
* Skip if cannot connect to SQLite
*
*/
public function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'sqlite', '%s SQLite connection not available');
}
/**
* Set up test suite database connection
*
*/
public function startTest() {
$this->_initDb();
}
public $Dbo2 = null;
/**
* Sets up a Dbo class instance for testing
@ -121,9 +104,11 @@ class DboSqliteTest extends CakeTestCase {
*/
public function setUp() {
Configure::write('Cache.disable', true);
$this->startTest();
$this->db =& ConnectionManager::getDataSource('test_suite');
$this->db2 = new DboSqliteTestDb($this->db->config, false);
$this->Dbo = ConnectionManager::getDataSource('test_suite');
if ($this->Dbo->config['driver'] !== 'sqlite') {
$this->markTestSkipped('The Sqlite extension is not available.');
}
$this->Dbo2 = new DboSqliteTestDb($this->Dbo->config, false);
}
/**
@ -132,7 +117,7 @@ class DboSqliteTest extends CakeTestCase {
*/
public function tearDown() {
Configure::write('Cache.disable', false);
unset($this->db2);
unset($this->Dbo2);
}
/**
@ -140,13 +125,13 @@ class DboSqliteTest extends CakeTestCase {
*
*/
public function testTableListCacheDisabling() {
$this->assertFalse(in_array('foo_test', $this->db->listSources()));
$this->assertFalse(in_array('foo_test', $this->Dbo->listSources()));
$this->db->query('CREATE TABLE foo_test (test VARCHAR(255));');
$this->assertTrue(in_array('foo_test', $this->db->listSources()));
$this->Dbo->query('CREATE TABLE foo_test (test VARCHAR(255));');
$this->assertTrue(in_array('foo_test', $this->Dbo->listSources()));
$this->db->query('DROP TABLE foo_test;');
$this->assertFalse(in_array('foo_test', $this->db->listSources()));
$this->Dbo->query('DROP TABLE foo_test;');
$this->assertFalse(in_array('foo_test', $this->Dbo->listSources()));
}
/**
@ -156,29 +141,29 @@ class DboSqliteTest extends CakeTestCase {
* @return void
*/
function testIndex() {
$name = $this->db->fullTableName('with_a_key');
$this->db->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );');
$this->db->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
$this->db->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
$name = $this->Dbo->fullTableName('with_a_key');
$this->Dbo->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );');
$this->Dbo->query('CREATE INDEX pointless_bool ON ' . $name . '("bool")');
$this->Dbo->query('CREATE UNIQUE INDEX char_index ON ' . $name . '("small_char")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
'char_index' => array('column' => 'small_char', 'unique' => 1),
);
$result = $this->db->index($name);
$result = $this->Dbo->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
$this->db->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );');
$this->db->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
$this->Dbo->query('CREATE TABLE ' . $name . ' ("id" int(11) PRIMARY KEY, "bool" int(1), "small_char" varchar(50), "description" varchar(40) );');
$this->Dbo->query('CREATE UNIQUE INDEX multi_col ON ' . $name . '("small_char", "bool")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => 1),
);
$result = $this->db->index($name);
$result = $this->Dbo->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
$this->Dbo->query('DROP TABLE ' . $name);
}
/**
@ -191,8 +176,8 @@ class DboSqliteTest extends CakeTestCase {
$dbName = 'db' . rand() . '$(*%&).db';
$this->assertFalse(file_exists(TMP . $dbName));
$config = $this->db->config;
$db = new DboSqlite(array_merge($this->db->config, array('database' => TMP . $dbName)));
$config = $this->Dbo->config;
$db = new DboSqlite(array_merge($this->Dbo->config, array('database' => TMP . $dbName)));
$this->assertTrue(file_exists(TMP . $dbName));
$db->execute("CREATE TABLE test_list (id VARCHAR(255));");
@ -221,7 +206,7 @@ class DboSqliteTest extends CakeTestCase {
'type' => 'integer',
'null' => false,
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"int_field" integer(11) NOT NULL';
$this->assertEqual($result, $expected);
@ -231,7 +216,7 @@ class DboSqliteTest extends CakeTestCase {
'length' => 20,
'null' => false,
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"name" varchar(20) NOT NULL';
$this->assertEqual($result, $expected);
@ -243,7 +228,7 @@ class DboSqliteTest extends CakeTestCase {
'null' => true,
'collate' => 'NOCASE'
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"testName" varchar(20) DEFAULT NULL COLLATE NOCASE';
$this->assertEqual($result, $expected);
@ -254,7 +239,7 @@ class DboSqliteTest extends CakeTestCase {
'default' => 'test-value',
'null' => false,
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"testName" varchar(20) DEFAULT \'test-value\' NOT NULL';
$this->assertEqual($result, $expected);
@ -265,7 +250,7 @@ class DboSqliteTest extends CakeTestCase {
'default' => 10,
'null' => false,
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"testName" integer(10) DEFAULT \'10\' NOT NULL';
$this->assertEqual($result, $expected);
@ -277,7 +262,7 @@ class DboSqliteTest extends CakeTestCase {
'null' => false,
'collate' => 'BADVALUE'
);
$result = $this->db->buildColumn($data);
$result = $this->Dbo->buildColumn($data);
$expected = '"testName" integer(10) DEFAULT \'10\' NOT NULL';
$this->assertEqual($result, $expected);
}
@ -288,8 +273,9 @@ class DboSqliteTest extends CakeTestCase {
* @return void
*/
function testDescribe() {
$Model =& new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users'));
$result = $this->db->describe($Model);
$this->loadFixtures('User');
$Model = new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users'));
$result = $this->Dbo->describe($Model);
$expected = array(
'id' => array(
'type' => 'integer',
@ -333,9 +319,9 @@ class DboSqliteTest extends CakeTestCase {
*/
function testDescribeWithUuidPrimaryKey() {
$tableName = 'uuid_tests';
$this->db->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)");
$Model =& new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests'));
$result = $this->db->describe($Model);
$this->Dbo->query("CREATE TABLE {$tableName} (id VARCHAR(36) PRIMARY KEY, name VARCHAR, created DATETIME, modified DATETIME)");
$Model = new Model(array('name' => 'UuidTest', 'ds' => 'test_suite', 'table' => 'uuid_tests'));
$result = $this->Dbo->describe($Model);
$expected = array(
'type' => 'string',
'length' => 36,
@ -344,6 +330,6 @@ class DboSqliteTest extends CakeTestCase {
'key' => 'primary',
);
$this->assertEqual($result['id'], $expected);
$this->db->query('DROP TABLE ' . $tableName);
$this->Dbo->query('DROP TABLE ' . $tableName);
}
}

View file

@ -1321,13 +1321,13 @@ class DboSourceTest extends CakeTestCase {
}");
}
$this->testDb =& new DboTest($this->__config);
$this->testDb = new DboTest($this->__config);
$this->testDb->cacheSources = false;
$this->testDb->startQuote = '`';
$this->testDb->endQuote = '`';
Configure::write('debug', 1);
$this->debug = Configure::read('debug');
$this->Model =& new TestModel();
$this->Model = new TestModel();
}
/**
@ -1350,10 +1350,10 @@ class DboSourceTest extends CakeTestCase {
*/
function testFieldDoubleEscaping() {
$config = array_merge($this->__config, array('driver' => 'test'));
$test =& ConnectionManager::create('quoteTest', $config);
$test = ConnectionManager::create('quoteTest', $config);
$test->simulated = array();
$this->Model =& new Article2(array('alias' => 'Article', 'ds' => 'quoteTest'));
$this->Model = new Article2(array('alias' => 'Article', 'ds' => 'quoteTest'));
$this->Model->setDataSource('quoteTest');
$this->assertEqual($this->Model->escapeField(), '`Article`.`id`');
@ -1392,26 +1392,26 @@ class DboSourceTest extends CakeTestCase {
*/
function testGenerateAssociationQuerySelfJoin() {
$this->startTime = microtime(true);
$this->Model =& new Article2();
$this->Model = new Article2();
$this->_buildRelatedModels($this->Model);
$this->_buildRelatedModels($this->Model->Category2);
$this->Model->Category2->ChildCat =& new Category2();
$this->Model->Category2->ParentCat =& new Category2();
$this->Model->Category2->ChildCat = new Category2();
$this->Model->Category2->ParentCat = new Category2();
$queryData = array();
foreach ($this->Model->Category2->associations() as $type) {
foreach ($this->Model->Category2->{$type} as $assoc => $assocData) {
$linkModel =& $this->Model->Category2->{$assoc};
$linkModel = $this->Model->Category2->{$assoc};
$external = isset($assocData['external']);
if ($this->Model->Category2->alias == $linkModel->alias && $type != 'hasAndBelongsToMany' && $type != 'hasMany') {
$result = $this->testDb->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
$this->assertTrue($result);
$this->assertFalse(empty($result));
} else {
if ($this->Model->Category2->useDbConfig == $linkModel->useDbConfig) {
$result = $this->testDb->generateAssociationQuery($this->Model->Category2, $linkModel, $type, $assoc, $assocData, $queryData, $external, $null);
$this->assertTrue($result);
$this->assertFalse(empty($result));
}
}
}
@ -1420,7 +1420,7 @@ class DboSourceTest extends CakeTestCase {
$query = $this->testDb->generateAssociationQuery($this->Model->Category2, $null, null, null, null, $queryData, false, $null);
$this->assertPattern('/^SELECT\s+(.+)FROM(.+)`Category2`\.`group_id`\s+=\s+`Group`\.`id`\)\s+LEFT JOIN(.+)WHERE\s+1 = 1\s*$/', $query);
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1436,6 +1436,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertTrue($result);
$expected = array(
'conditions' => array(),
'fields' => array(
'`TestModel4`.`id`',
'`TestModel4`.`name`',
@ -1454,11 +1455,10 @@ class DboSourceTest extends CakeTestCase {
'conditions' => '`TestModel4`.`parent_id` = `TestModel4Parent`.`id`'
)
),
'order' => array(),
'limit' => array(),
'offset' => array(),
'conditions' => array(),
'order' => array(),
'group' => null
'group' => array()
);
$this->assertEqual($queryData, $expected);
@ -1482,10 +1482,10 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateInnerJoinAssociationQuery() {
$this->Model =& new TestModel9();
$test =& ConnectionManager::create('test2', $this->__config);
$this->Model = new TestModel9();
$test = ConnectionManager::create('test2', $this->__config);
$this->Model->setDataSource('test2');
$this->Model->TestModel8 =& new TestModel8();
$this->Model->TestModel8 = new TestModel8();
$this->Model->TestModel8->setDataSource('test2');
$this->testDb->read($this->Model, array('recursive' => 1));
@ -1506,7 +1506,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQuerySelfJoinWithConditionsInHasOneBinding() {
$this->Model =& new TestModel8();
$this->Model = new TestModel8();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1534,7 +1534,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQuerySelfJoinWithConditionsInBelongsToBinding() {
$this->Model =& new TestModel9();
$this->Model = new TestModel9();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1561,7 +1561,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQuerySelfJoinWithConditions() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1581,7 +1581,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertPattern('/\s+ON\s+\(`TestModel4`.`parent_id` = `TestModel4Parent`.`id`\)\s+WHERE/', $result);
$this->assertPattern('/\s+WHERE\s+(?:\()?`TestModel4Parent`.`name`\s+!=\s+\'mariano\'(?:\))?\s*$/', $result);
$this->Featured2 =& new Featured2();
$this->Featured2 = new Featured2();
$this->Featured2->schema();
$this->Featured2->bindModel(array(
@ -1623,7 +1623,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasOne() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1656,7 +1656,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasOneWithConditions() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1686,7 +1686,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryBelongsTo() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1718,7 +1718,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryBelongsToWithConditions() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1750,7 +1750,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasMany() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1780,7 +1780,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasManyWithLimit() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1820,7 +1820,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasManyWithConditions() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1849,7 +1849,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasManyWithOffsetAndLimit() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1887,7 +1887,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasManyWithPageAndLimit() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -1924,7 +1924,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasManyWithFields() {
$this->Model =& new TestModel5();
$this->Model = new TestModel5();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -2050,7 +2050,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasAndBelongsToMany() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -2059,7 +2059,7 @@ class DboSourceTest extends CakeTestCase {
$resultSet = null;
$null = null;
$params =& $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
$params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
$result = $this->testDb->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
$this->assertPattern('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
@ -2081,7 +2081,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasAndBelongsToManyWithConditions() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -2090,7 +2090,7 @@ class DboSourceTest extends CakeTestCase {
$resultSet = null;
$null = null;
$params =& $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
$params = $this->_prepareAssociationQuery($this->Model, $queryData, $binding);
$result = $this->testDb->generateAssociationQuery($this->Model, $params['linkModel'], $params['type'], $params['assoc'], $params['assocData'], $queryData, $params['external'], $resultSet);
$this->assertPattern('/^SELECT\s+`TestModel7`\.`id`, `TestModel7`\.`name`, `TestModel7`\.`created`, `TestModel7`\.`updated`, `TestModel4TestModel7`\.`test_model4_id`, `TestModel4TestModel7`\.`test_model7_id`\s+/', $result);
@ -2110,7 +2110,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasAndBelongsToManyWithOffsetAndLimit() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -2147,7 +2147,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testGenerateAssociationQueryHasAndBelongsToManyWithPageAndLimit() {
$this->Model =& new TestModel4();
$this->Model = new TestModel4();
$this->Model->schema();
$this->_buildRelatedModels($this->Model);
@ -2192,7 +2192,7 @@ class DboSourceTest extends CakeTestCase {
} elseif (isset($assocData['className'])) {
$className = $assocData['className'];
}
$model->$className =& new $className();
$model->$className = new $className();
$model->$className->schema();
}
}
@ -2213,7 +2213,7 @@ class DboSourceTest extends CakeTestCase {
$assocData = $model->{$type}[$assoc];
$className = $assocData['className'];
$linkModel =& $model->{$className};
$linkModel = $model->{$className};
$external = isset($assocData['external']);
$queryData = $this->testDb->__scrubQueryData($queryData);
@ -2506,6 +2506,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testArrayConditionsParsing() {
$this->loadFixtures('Post', 'Author');
$result = $this->testDb->conditions(array('Stereo.type' => 'in dash speakers'));
$this->assertPattern("/^\s+WHERE\s+`Stereo`.`type`\s+=\s+'in dash speakers'/", $result);
@ -2800,7 +2801,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testConditionsWithModel() {
$this->Model =& new Article2();
$this->Model = new Article2();
$result = $this->testDb->conditions(array('Article2.viewed >=' => 0), true, true, $this->Model);
$expected = " WHERE `Article2`.`viewed` >= 0";
@ -3286,7 +3287,8 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testStatements() {
$Article =& ClassRegistry::init('Article');
$this->loadFixtures('Article', 'User', 'Comment', 'Tag', 'Attachment', 'ArticlesTag');
$Article = new Article();
$result = $this->testDb->update($Article, array('field1'), array('value1'));
$this->assertFalse($result);
@ -3317,7 +3319,7 @@ class DboSourceTest extends CakeTestCase {
$this->assertFalse($result);
$result = $this->testDb->insertMulti('articles', array('field'), array('(1)', '(2)'));
$this->assertFalse($result);
$this->assertNull($result);
$result = $this->testDb->getLastQuery();
$this->assertPattern('/^\s*INSERT INTO\s+' . $this->testDb->fullTableName('articles') . '\s+\(`field`\)\s+VALUES\s+\(1\),\s*\(2\)\s*$/', $result);
}
@ -3329,7 +3331,7 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testSchema() {
$Schema =& new CakeSchema();
$Schema = new CakeSchema();
$Schema->tables = array('table' => array(), 'anotherTable' => array());
$this->expectError();
@ -3815,7 +3817,7 @@ class DboSourceTest extends CakeTestCase {
// EMPTY STRING
$result = $this->testDb->value('', 'boolean');
$this->assertEqual($result, "NULL");
$this->assertEqual($result, 0);
// BOOLEAN
@ -3940,10 +3942,10 @@ class DboSourceTest extends CakeTestCase {
* @return void
*/
function testRealQueries() {
$this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag');
$this->loadFixtures('Apple', 'Article', 'User', 'Comment', 'Tag', 'Sample');
$Apple =& ClassRegistry::init('Apple');
$Article =& ClassRegistry::init('Article');
$Apple = ClassRegistry::init('Apple');
$Article = ClassRegistry::init('Article');
$result = $this->db->rawQuery('SELECT color, name FROM ' . $this->db->fullTableName('apples'));
$this->assertTrue(!empty($result));
@ -4172,8 +4174,6 @@ class DboSourceTest extends CakeTestCase {
*/
function testExecute() {
$query = 'SELECT * FROM ' . $this->testDb->fullTableName('articles') . ' WHERE 1 = 1';
$this->db->_result = null;
$this->db->took = null;
$this->db->affected = null;
$result = $this->db->execute($query, array('stats' => false));
@ -4237,7 +4237,7 @@ class DboSourceTest extends CakeTestCase {
function testVirtualFields() {
$this->loadFixtures('Article');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'this_moment' => 'NOW()',
'two' => '1 + 1',
@ -4307,7 +4307,7 @@ class DboSourceTest extends CakeTestCase {
function testVirtualFieldsInConditions() {
$this->loadFixtures('Article');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'this_moment' => 'NOW()',
'two' => '1 + 1',
@ -4343,7 +4343,7 @@ class DboSourceTest extends CakeTestCase {
function testVirtualFieldsInOrder() {
$this->loadFixtures('Article');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'this_moment' => 'NOW()',
'two' => '1 + 1',
@ -4367,7 +4367,7 @@ class DboSourceTest extends CakeTestCase {
function testVirtualFieldsInCalculate() {
$this->loadFixtures('Article');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'this_moment' => 'NOW()',
'two' => '1 + 1',
@ -4392,7 +4392,7 @@ class DboSourceTest extends CakeTestCase {
function testVirtualFieldsFetch() {
$this->loadFixtures('Article', 'Comment');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->virtualFields = array(
'comment_count' => 'SELECT COUNT(*) FROM ' . $this->db->fullTableName('comments') .
' WHERE Article.id = ' . $this->db->fullTableName('comments') . '.article_id'
@ -4415,13 +4415,13 @@ class DboSourceTest extends CakeTestCase {
*/
function testVirtualFieldsInGroup() {
$this->loadFixtures('Article');
$Article =& ClassRegistry::init('Article');
$Article = new Article();
$Article->virtualFields = array(
'this_year' => 'YEAR(Article.created)'
);
$result = $this->db->group('this_year',$Article);
$result = $this->db->group('this_year', $Article);
$expected = " GROUP BY (YEAR(`Article`.`created`))";
$this->assertEqual($expected, $result);
}

View file

@ -376,9 +376,8 @@ class AclNodeTest extends CakeTestCase {
*/
function testNodeAliasParenting() {
$Aco = new DbAcoTest();
$db =& ConnectionManager::getDataSource('test_suite');
$db = ConnectionManager::getDataSource('test_suite');
$db->truncate($Aco);
$db->_queriesLog = array();
$Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => null, 'alias' => 'Application'));
$Aco->save();

View file

@ -20,7 +20,7 @@
App::import('Core', array('AppModel', 'Model'));
require_once dirname(__FILE__) . DS . 'models.php';
SimpleTest::ignore('BaseModelTest');
PHPUnit_Util_Filter::addFileToFilter(__FILE__, 'DEFAULT');
/**
* ModelBaseTest
@ -28,7 +28,7 @@ SimpleTest::ignore('BaseModelTest');
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class BaseModelTest extends CakeTestCase {
abstract class BaseModelTest extends CakeTestCase {
/**
* autoFixtures property
@ -38,6 +38,13 @@ class BaseModelTest extends CakeTestCase {
*/
public $autoFixtures = false;
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @access public
*/
public $backupGlobals = false;
/**
* fixtures property
*
@ -69,35 +76,25 @@ class BaseModelTest extends CakeTestCase {
);
/**
* start method
* setUp method
*
* @access public
* @return void
*/
function start() {
parent::start();
function setUp() {
parent::setUp();
$this->debug = Configure::read('debug');
Configure::write('debug', 2);
}
/**
* end method
* tearDown method
*
* @access public
* @return void
*/
function end() {
parent::end();
function tearDown() {
parent::tearDown();
Configure::write('debug', $this->debug);
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
ClassRegistry::flush();
}
}

View file

@ -22,8 +22,6 @@
App::import('Model', 'AppModel');
require_once dirname(__FILE__) . DS . 'models.php';
Mock::generatePartial('BehaviorCollection', 'MockModelBehaviorCollection', array('cakeError', '_stop'));
/**
* TestBehavior class
*
@ -213,7 +211,7 @@ class TestBehavior extends ModelBehavior {
* @return void
*/
function beforeDelete(&$model, $cascade = true) {
$settings =& $this->settings[$model->alias];
$settings = $this->settings[$model->alias];
if (!isset($settings['beforeDelete']) || $settings['beforeDelete'] == 'off') {
return parent::beforeDelete($model, $cascade);
}
@ -241,7 +239,7 @@ class TestBehavior extends ModelBehavior {
* @return void
*/
function afterDelete(&$model) {
$settings =& $this->settings[$model->alias];
$settings = $this->settings[$model->alias];
if (!isset($settings['afterDelete']) || $settings['afterDelete'] == 'off') {
return parent::afterDelete($model);
}
@ -286,7 +284,7 @@ class TestBehavior extends ModelBehavior {
* @access public
* @return void
*/
function testMethod(&$model, $param = true) {
function testMethod(Model $model, $param = true) {
if ($param === true) {
return 'working';
}
@ -299,7 +297,7 @@ class TestBehavior extends ModelBehavior {
* @access public
* @return void
*/
function testData(&$model) {
function testData(Model $model) {
if (!isset($model->data['Apple']['field'])) {
return false;
}
@ -315,7 +313,7 @@ class TestBehavior extends ModelBehavior {
* @access public
* @return void
*/
function validateField(&$model, $field) {
function validateField(Model $model, $field) {
return current($field) === 'Orange';
}
@ -328,7 +326,7 @@ class TestBehavior extends ModelBehavior {
* @access public
* @return void
*/
function speakEnglish(&$model, $method, $query) {
function speakEnglish(Model $model, $method, $query) {
$method = preg_replace('/look for\s+/', 'Item.name = \'', $method);
$query = preg_replace('/^in\s+/', 'Location.name = \'', $query);
return $method . '\' AND ' . $query . '\'';
@ -532,10 +530,11 @@ class BehaviorTest extends CakeTestCase {
* @return void
*/
function testInvalidBehaviorCausingCakeError() {
$Apple =& new Apple();
$Apple->Behaviors =& new MockModelBehaviorCollection();
$Apple->Behaviors->expectOnce('cakeError');
$Apple->Behaviors->expectAt(0, 'cakeError', array('missingBehaviorFile', '*'));
$Apple = new Apple();
$Apple->Behaviors = $this->getMock('BehaviorCollection', array('cakeError'));
$Apple->Behaviors->expects($this->once())
->method('cakeError')
->with('missingBehaviorFile');
$this->assertFalse($Apple->Behaviors->attach('NoSuchBehavior'));
}
@ -1051,7 +1050,7 @@ class BehaviorTest extends CakeTestCase {
* @return void
*/
function testBehaviorTrigger() {
$Apple =& new Apple();
$Apple = new Apple();
$Apple->Behaviors->attach('Test');
$Apple->Behaviors->attach('Test2');
$Apple->Behaviors->attach('Test3');
@ -1126,7 +1125,7 @@ class BehaviorTest extends CakeTestCase {
* @return void
*/
function testBehaviorAttachAndDetach() {
$Sample =& new Sample();
$Sample = new Sample();
$Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar'));
$Sample->Behaviors->init($Sample->alias, $Sample->actsAs);
$Sample->Behaviors->attach('Test2');

View file

@ -34,9 +34,9 @@ class ModelDeleteTest extends BaseModelTest {
* @return void
*/
function testDeleteHabtmReferenceWithConditions() {
$this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio');
$this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio', 'Syfile', 'Image');
$Portfolio =& new Portfolio();
$Portfolio = new Portfolio();
$Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1);
$result = $Portfolio->find('first', array(
@ -115,7 +115,7 @@ class ModelDeleteTest extends BaseModelTest {
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$this->assertFalse($result);
$this->assertEquals($result, array());
}
/**
@ -125,8 +125,8 @@ class ModelDeleteTest extends BaseModelTest {
* @return void
*/
function testDeleteArticleBLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new ArticleB();
$this->loadFixtures('Article', 'ArticlesTag', 'Tag', 'User');
$TestModel = new ArticleB();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
@ -156,9 +156,9 @@ class ModelDeleteTest extends BaseModelTest {
function testDeleteDependentWithConditions() {
$this->loadFixtures('Cd','Book','OverallFavorite');
$Cd =& new Cd();
$Book =& new Book();
$OverallFavorite =& new OverallFavorite();
$Cd = new Cd();
$Book = new Book();
$OverallFavorite = new OverallFavorite();
$Cd->delete(1);
@ -194,8 +194,8 @@ class ModelDeleteTest extends BaseModelTest {
* @return void
*/
function testDelete() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$this->loadFixtures('Article', 'Comment', 'Attachment');
$TestModel = new Article();
$result = $TestModel->delete(2);
$this->assertTrue($result);
@ -239,7 +239,7 @@ class ModelDeleteTest extends BaseModelTest {
// make sure deleting a non-existent record doesn't break save()
// ticket #6293
$this->loadFixtures('Uuid');
$Uuid =& new Uuid();
$Uuid = new Uuid();
$data = array(
'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3',
'52C8865C-10EE-4302-AE6C-6E7D8E12E2C8',
@ -266,14 +266,15 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($result, $expected);
}
/**
/**
* test that delete() updates the correct records counterCache() records.
*
* @return void
*/
function testDeleteUpdatingCounterCacheCorrectly() {
$this->loadFixtures('CounterCacheUser', 'CounterCachePost');
$User =& new CounterCacheUser();
$User = new CounterCacheUser();
$User->Post->delete(3);
$result = $User->read(null, 301);
@ -283,7 +284,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($result['User']['post_count'], 2);
}
/**
/**
* testDeleteAll method
*
* @access public
@ -291,7 +292,7 @@ class ModelDeleteTest extends BaseModelTest {
*/
function testDeleteAll() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$TestModel = new Article();
$data = array('Article' => array(
'user_id' => 2,
@ -431,7 +432,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertFalse($result, 'deleteAll returned true when find query generated sql error. %s');
}
/**
/**
* testRecursiveDel method
*
* @access public
@ -439,7 +440,7 @@ class ModelDeleteTest extends BaseModelTest {
*/
function testRecursiveDel() {
$this->loadFixtures('Article', 'Comment', 'Attachment');
$TestModel =& new Article();
$TestModel = new Article();
$result = $TestModel->delete(2);
$this->assertTrue($result);
@ -467,7 +468,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($result, 0);
}
/**
/**
* testDependentExclusiveDelete method
*
* @access public
@ -475,7 +476,7 @@ class ModelDeleteTest extends BaseModelTest {
*/
function testDependentExclusiveDelete() {
$this->loadFixtures('Article', 'Comment');
$TestModel =& new Article10();
$TestModel = new Article10();
$result = $TestModel->find('all');
$this->assertEqual(count($result[0]['Comment']), 4);
@ -486,7 +487,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($TestModel->Comment->find('count'), 2);
}
/**
/**
* testDeleteLinks method
*
* @access public
@ -494,7 +495,7 @@ class ModelDeleteTest extends BaseModelTest {
*/
function testDeleteLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new Article();
$TestModel = new Article();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
@ -534,14 +535,14 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s');
}
/**
/**
* test deleteLinks with Multiple habtm associations
*
* @return void
*/
function testDeleteLinksWithMultipleHabtmAssociations() {
$this->loadFixtures('JoinA', 'JoinB', 'JoinC', 'JoinAB', 'JoinAC');
$JoinA =& new JoinA();
$JoinA = new JoinA();
//create two new join records to expose the issue.
$JoinA->JoinAsJoinC->create(array(
@ -569,7 +570,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($joinedBs, 0, 'JoinA/JoinC link records left over. %s');
}
/**
/**
* testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method
*
* @access public
@ -578,7 +579,7 @@ class ModelDeleteTest extends BaseModelTest {
function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() {
$this->loadFixtures('Apple', 'Device', 'ThePaperMonkies');
$ThePaper =& new ThePaper();
$ThePaper = new ThePaper();
$ThePaper->id = 1;
$ThePaper->save(array('Monkey' => array(2, 3)));
@ -598,7 +599,7 @@ class ModelDeleteTest extends BaseModelTest {
));
$this->assertEqual($result['Monkey'], $expected);
$ThePaper =& new ThePaper();
$ThePaper = new ThePaper();
$ThePaper->id = 2;
$ThePaper->save(array('Monkey' => array(2, 3)));
@ -636,14 +637,14 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertEqual($result['Monkey'], $expected);
}
/**
/**
* test that beforeDelete returning false can abort deletion.
*
* @return void
*/
function testBeforeDeleteDeleteAbortion() {
$this->loadFixtures('Post');
$Model =& new CallbackPostTestModel();
$Model = new CallbackPostTestModel();
$Model->beforeDeleteReturn = false;
$result = $Model->delete(1);
@ -653,7 +654,7 @@ class ModelDeleteTest extends BaseModelTest {
$this->assertTrue(is_array($exists));
}
/**
/**
* test for a habtm deletion error that occurs in postgres but should not.
* And should not occur in any dbo.
*
@ -662,10 +663,10 @@ class ModelDeleteTest extends BaseModelTest {
function testDeleteHabtmPostgresFailure() {
$this->loadFixtures('Article', 'Tag', 'ArticlesTag');
$Article =& ClassRegistry::init('Article');
$Article = ClassRegistry::init('Article');
$Article->hasAndBelongsToMany['Tag']['unique'] = true;
$Tag =& ClassRegistry::init('Tag');
$Tag = ClassRegistry::init('Tag');
$Tag->bindModel(array('hasAndBelongsToMany' => array(
'Article' => array(
'className' => 'Article',

Some files were not shown because too many files have changed in this diff Show more