getting cakephp set up with its own web server(s) and docroot

This commit is contained in:
Dan Buch
2011-01-02 23:58:42 -05:00
parent aaa61a737b
commit 4b0cfa88e7
756 changed files with 2844 additions and 4 deletions

View File

@@ -0,0 +1,810 @@
<?php
/**
* BasicsTest 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
* @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 . 'basics.php';
App::import('Core', 'Folder');
/**
* BasicsTest class
*
* @package cake
* @subpackage cake.tests.cases
*/
class BasicsTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function setUp() {
App::build(array(
'locales' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'locale' . DS)
));
$this->_language = Configure::read('Config.language');
}
/**
* tearDown method
*
* @return void
* @access public
*/
function tearDown() {
App::build();
Configure::write('Config.language', $this->_language);
}
/**
* test the array_diff_key compatibility function.
*
* @return void
* @access public
*/
function testArrayDiffKey() {
$one = array('one' => 1, 'two' => 2, 'three' => 3);
$two = array('one' => 'one', 'two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('three' => 3);
$this->assertEqual($result, $expected);
$one = array('one' => array('value', 'value-two'), 'two' => 2, 'three' => 3);
$two = array('two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('one' => array('value', 'value-two'), 'three' => 3);
$this->assertEqual($result, $expected);
$one = array('one' => null, 'two' => 2, 'three' => '', 'four' => 0);
$two = array('two' => 'two');
$result = array_diff_key($one, $two);
$expected = array('one' => null, 'three' => '', 'four' => 0);
$this->assertEqual($result, $expected);
$one = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$two = array('minYear' => null, 'maxYear' => null, 'separator' => '-', 'interval' => 1, 'monthNames' => true);
$result = array_diff_key($one, $two);
$this->assertEqual($result, array());
}
/**
* testHttpBase method
*
* @return void
* @access public
*/
function testEnv() {
$this->skipIf(!function_exists('ini_get') || ini_get('safe_mode') === '1', '%s safe mode is on');
$__SERVER = $_SERVER;
$__ENV = $_ENV;
$_SERVER['HTTP_HOST'] = 'localhost';
$this->assertEqual(env('HTTP_BASE'), '');
$_SERVER['HTTP_HOST'] = 'example.com';
$this->assertEqual(env('HTTP_BASE'), '.example.com');
$_SERVER['HTTP_HOST'] = 'www.example.com';
$this->assertEqual(env('HTTP_BASE'), '.example.com');
$_SERVER['HTTP_HOST'] = 'subdomain.example.com';
$this->assertEqual(env('HTTP_BASE'), '.example.com');
$_SERVER['HTTP_HOST'] = 'double.subdomain.example.com';
$this->assertEqual(env('HTTP_BASE'), '.subdomain.example.com');
$_SERVER = $_ENV = array();
$_SERVER['SCRIPT_NAME'] = '/a/test/test.php';
$this->assertEqual(env('SCRIPT_NAME'), '/a/test/test.php');
$_SERVER = $_ENV = array();
$_ENV['CGI_MODE'] = 'BINARY';
$_ENV['SCRIPT_URL'] = '/a/test/test.php';
$this->assertEqual(env('SCRIPT_NAME'), '/a/test/test.php');
$_SERVER = $_ENV = array();
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = 'on';
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = '1';
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 'I am not empty';
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 1;
$this->assertTrue(env('HTTPS'));
$_SERVER['HTTPS'] = 'off';
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = false;
$this->assertFalse(env('HTTPS'));
$_SERVER['HTTPS'] = '';
$this->assertFalse(env('HTTPS'));
$_SERVER = array();
$_ENV['SCRIPT_URI'] = 'https://domain.test/a/test.php';
$this->assertTrue(env('HTTPS'));
$_ENV['SCRIPT_URI'] = 'http://domain.test/a/test.php';
$this->assertFalse(env('HTTPS'));
$_SERVER = $_ENV = array();
$this->assertFalse(env('TEST_ME'));
$_ENV['TEST_ME'] = 'a';
$this->assertEqual(env('TEST_ME'), 'a');
$_SERVER['TEST_ME'] = 'b';
$this->assertEqual(env('TEST_ME'), 'b');
unset($_ENV['TEST_ME']);
$this->assertEqual(env('TEST_ME'), 'b');
$_SERVER = $__SERVER;
$_ENV = $__ENV;
}
/**
* test uses()
*
* @return void
* @access public
* @deprecated
*/
function testUses() {
$this->skipIf(class_exists('Security') || class_exists('Sanitize'), '%s Security and/or Sanitize class already loaded');
$this->assertFalse(class_exists('Security'));
$this->assertFalse(class_exists('Sanitize'));
uses('Security', 'Sanitize');
$this->assertTrue(class_exists('Security'));
$this->assertTrue(class_exists('Sanitize'));
}
/**
* Test h()
*
* @return void
* @access public
*/
function testH() {
$string = '<foo>';
$result = h($string);
$this->assertEqual('&lt;foo&gt;', $result);
$in = array('this & that', '<p>Which one</p>');
$result = h($in);
$expected = array('this &amp; that', '&lt;p&gt;Which one&lt;/p&gt;');
$this->assertEqual($expected, $result);
}
/**
* Test a()
*
* @return void
* @access public
*/
function testA() {
$result = a('this', 'that', 'bar');
$this->assertEqual(array('this', 'that', 'bar'), $result);
}
/**
* Test aa()
*
* @return void
* @access public
*/
function testAa() {
$result = aa('a', 'b', 'c', 'd');
$expected = array('a' => 'b', 'c' => 'd');
$this->assertEqual($expected, $result);
$result = aa('a', 'b', 'c', 'd', 'e');
$expected = array('a' => 'b', 'c' => 'd', 'e' => null);
$this->assertEqual($result, $expected);
}
/**
* Test am()
*
* @return void
* @access public
*/
function testAm() {
$result = am(array('one', 'two'), 2, 3, 4);
$expected = array('one', 'two', 2, 3, 4);
$this->assertEqual($result, $expected);
$result = am(array('one' => array(2, 3), 'two' => array('foo')), array('one' => array(4, 5)));
$expected = array('one' => array(4, 5),'two' => array('foo'));
$this->assertEqual($result, $expected);
}
/**
* test cache()
*
* @return void
* @access public
*/
function testCache() {
$_cacheDisable = Configure::read('Cache.disable');
if ($this->skipIf($_cacheDisable, 'Cache is disabled, skipping cache() tests. %s')) {
return;
}
Configure::write('Cache.disable', true);
$result = cache('basics_test', 'simple cache write');
$this->assertNull($result);
$result = cache('basics_test');
$this->assertNull($result);
Configure::write('Cache.disable', false);
$result = cache('basics_test', 'simple cache write');
$this->assertTrue($result);
$this->assertTrue(file_exists(CACHE . 'basics_test'));
$result = cache('basics_test');
$this->assertEqual($result, 'simple cache write');
@unlink(CACHE . 'basics_test');
cache('basics_test', 'expired', '+1 second');
sleep(2);
$result = cache('basics_test', null, '+1 second');
$this->assertNull($result);
Configure::write('Cache.disable', $_cacheDisable);
}
/**
* test clearCache()
*
* @return void
* @access public
*/
function testClearCache() {
$cacheOff = Configure::read('Cache.disable');
if ($this->skipIf($cacheOff, 'Cache is disabled, skipping clearCache() tests. %s')) {
return;
}
cache('views' . DS . 'basics_test.cache', 'simple cache write');
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test.cache'));
cache('views' . DS . 'basics_test_2.cache', 'simple cache write 2');
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_2.cache'));
cache('views' . DS . 'basics_test_3.cache', 'simple cache write 3');
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache'));
$result = clearCache(array('basics_test', 'basics_test_2'), 'views', '.cache');
$this->assertTrue($result);
$this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.cache'));
$this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.cache'));
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache'));
$result = clearCache(null, 'views', '.cache');
$this->assertTrue($result);
$this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test_3.cache'));
// Different path from views and with prefix
cache('models' . DS . 'basics_test.cache', 'simple cache write');
$this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test.cache'));
cache('models' . DS . 'basics_test_2.cache', 'simple cache write 2');
$this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test_2.cache'));
cache('models' . DS . 'basics_test_3.cache', 'simple cache write 3');
$this->assertTrue(file_exists(CACHE . 'models' . DS . 'basics_test_3.cache'));
$result = clearCache('basics', 'models', '.cache');
$this->assertTrue($result);
$this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test.cache'));
$this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test_2.cache'));
$this->assertFalse(file_exists(CACHE . 'models' . DS . 'basics_test_3.cache'));
// checking if empty files were not removed
$emptyExists = file_exists(CACHE . 'views' . DS . 'empty');
if (!$emptyExists) {
cache('views' . DS . 'empty', '');
}
cache('views' . DS . 'basics_test.php', 'simple cache write');
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'basics_test.php'));
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'empty'));
$result = clearCache();
$this->assertTrue($result);
$this->assertTrue(file_exists(CACHE . 'views' . DS . 'empty'));
$this->assertFalse(file_exists(CACHE . 'views' . DS . 'basics_test.php'));
if (!$emptyExists) {
unlink(CACHE . 'views' . DS . 'empty');
}
}
/**
* test __()
*
* @return void
* @access public
*/
function test__() {
Configure::write('Config.language', 'rule_1_po');
$result = __('Plural Rule 1', true);
$expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected);
$result = __('Plural Rule 1 (from core)', true);
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
ob_start();
__('Plural Rule 1 (from core)');
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __n()
*
* @return void
* @access public
*/
function test__n() {
Configure::write('Config.language', 'rule_1_po');
$result = __n('%d = 1', '%d = 0 or > 1', 0, true);
$expected = '%d = 0 or > 1 (translated)';
$this->assertEqual($result, $expected);
$result = __n('%d = 1', '%d = 0 or > 1', 1, true);
$expected = '%d = 1 (translated)';
$this->assertEqual($result, $expected);
$result = __n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', 2, true);
$expected = '%d = 0 or > 1 (from core translated)';
$this->assertEqual($result, $expected);
ob_start();
__n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', 2);
$result = ob_get_clean();
$expected = '%d = 0 or > 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __d()
*
* @return void
* @access public
*/
function test__d() {
Configure::write('Config.language', 'rule_1_po');
$result = __d('default', 'Plural Rule 1', true);
$expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected);
$result = __d('core', 'Plural Rule 1', true);
$expected = 'Plural Rule 1';
$this->assertEqual($result, $expected);
$result = __d('core', 'Plural Rule 1 (from core)', true);
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
ob_start();
__d('core', 'Plural Rule 1 (from core)');
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __dn()
*
* @return void
* @access public
*/
function test__dn() {
Configure::write('Config.language', 'rule_1_po');
$result = __dn('default', '%d = 1', '%d = 0 or > 1', 0, true);
$expected = '%d = 0 or > 1 (translated)';
$this->assertEqual($result, $expected);
$result = __dn('core', '%d = 1', '%d = 0 or > 1', 0, true);
$expected = '%d = 0 or > 1';
$this->assertEqual($result, $expected);
$result = __dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 0, true);
$expected = '%d = 0 or > 1 (from core translated)';
$this->assertEqual($result, $expected);
$result = __dn('default', '%d = 1', '%d = 0 or > 1', 1, true);
$expected = '%d = 1 (translated)';
$this->assertEqual($result, $expected);
ob_start();
__dn('core', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 2);
$result = ob_get_clean();
$expected = '%d = 0 or > 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __c()
*
* @return void
* @access public
*/
function test__c() {
Configure::write('Config.language', 'rule_1_po');
$result = __c('Plural Rule 1', 6, true);
$expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected);
$result = __c('Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
ob_start();
__c('Plural Rule 1 (from core)', 6);
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __dc()
*
* @return void
* @access public
*/
function test__dc() {
Configure::write('Config.language', 'rule_1_po');
$result = __dc('default', 'Plural Rule 1', 6, true);
$expected = 'Plural Rule 1 (translated)';
$this->assertEqual($result, $expected);
$result = __dc('default', 'Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
$result = __dc('core', 'Plural Rule 1', 6, true);
$expected = 'Plural Rule 1';
$this->assertEqual($result, $expected);
$result = __dc('core', 'Plural Rule 1 (from core)', 6, true);
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
ob_start();
__dc('default', 'Plural Rule 1 (from core)', 6);
$result = ob_get_clean();
$expected = 'Plural Rule 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test __dcn()
*
* @return void
* @access public
*/
function test__dcn() {
Configure::write('Config.language', 'rule_1_po');
$result = __dcn('default', '%d = 1', '%d = 0 or > 1', 0, 6, true);
$expected = '%d = 0 or > 1 (translated)';
$this->assertEqual($result, $expected);
$result = __dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 6, true);
$expected = '%d = 1 (from core translated)';
$this->assertEqual($result, $expected);
$result = __dcn('core', '%d = 1', '%d = 0 or > 1', 0, 6, true);
$expected = '%d = 0 or > 1';
$this->assertEqual($result, $expected);
ob_start();
__dcn('default', '%d = 1 (from core)', '%d = 0 or > 1 (from core)', 1, 6);
$result = ob_get_clean();
$expected = '%d = 1 (from core translated)';
$this->assertEqual($result, $expected);
}
/**
* test LogError()
*
* @return void
* @access public
*/
function testLogError() {
@unlink(LOGS . 'error.log');
LogError('Testing LogError() basic function');
LogError("Testing with\nmulti-line\nstring");
$result = file_get_contents(LOGS . 'error.log');
$this->assertPattern('/Error: Testing LogError\(\) basic function/', $result);
$this->assertNoPattern("/Error: Testing with\nmulti-line\nstring/", $result);
$this->assertPattern('/Error: Testing with multi-line string/', $result);
}
/**
* test fileExistsInPath()
*
* @return void
* @access public
*/
function testFileExistsInPath() {
$this->skipUnless(function_exists('ini_set'), '%s ini_set function not available');
$_includePath = ini_get('include_path');
$path = TMP . 'basics_test';
$folder1 = $path . DS . 'folder1';
$folder2 = $path . DS . 'folder2';
$file1 = $path . DS . 'file1.php';
$file2 = $folder1 . DS . 'file2.php';
$file3 = $folder1 . DS . 'file3.php';
$file4 = $folder2 . DS . 'file4.php';
new Folder($path, true);
new Folder($folder1, true);
new Folder($folder2, true);
touch($file1);
touch($file2);
touch($file3);
touch($file4);
ini_set('include_path', $path . PATH_SEPARATOR . $folder1);
$this->assertEqual(fileExistsInPath('file1.php'), $file1);
$this->assertEqual(fileExistsInPath('file2.php'), $file2);
$this->assertEqual(fileExistsInPath('folder1' . DS . 'file2.php'), $file2);
$this->assertEqual(fileExistsInPath($file2), $file2);
$this->assertEqual(fileExistsInPath('file3.php'), $file3);
$this->assertEqual(fileExistsInPath($file4), $file4);
$this->assertFalse(fileExistsInPath('file1'));
$this->assertFalse(fileExistsInPath('file4.php'));
$Folder = new Folder($path);
$Folder->delete();
ini_set('include_path', $_includePath);
}
/**
* test convertSlash()
*
* @return void
* @access public
*/
function testConvertSlash() {
$result = convertSlash('\path\to\location\\');
$expected = '\path\to\location\\';
$this->assertEqual($result, $expected);
$result = convertSlash('/path/to/location/');
$expected = 'path_to_location';
$this->assertEqual($result, $expected);
}
/**
* test debug()
*
* @return void
* @access public
*/
function testDebug() {
ob_start();
debug('this-is-a-test');
$result = ob_get_clean();
$pattern = '/.*\>(.+?tests(\/|\\\)cases(\/|\\\)basics\.test\.php|';
$pattern .= preg_quote(substr(__FILE__, 1), '/') . ')';
$pattern .= '.*line.*' . (__LINE__ - 4) . '.*this-is-a-test.*/s';
$this->assertPattern($pattern, $result);
ob_start();
debug('<div>this-is-a-test</div>', true);
$result = ob_get_clean();
$pattern = '/.*\>(.+?tests(\/|\\\)cases(\/|\\\)basics\.test\.php|';
$pattern .= preg_quote(substr(__FILE__, 1), '/') . ')';
$pattern .= '.*line.*' . (__LINE__ - 4) . '.*&lt;div&gt;this-is-a-test&lt;\/div&gt;.*/s';
$this->assertPattern($pattern, $result);
}
/**
* test pr()
*
* @return void
* @access public
*/
function testPr() {
ob_start();
pr('this is a test');
$result = ob_get_clean();
$expected = "<pre>this is a test</pre>";
$this->assertEqual($result, $expected);
ob_start();
pr(array('this' => 'is', 'a' => 'test'));
$result = ob_get_clean();
$expected = "<pre>Array\n(\n [this] => is\n [a] => test\n)\n</pre>";
$this->assertEqual($result, $expected);
}
/**
* test params()
*
* @return void
* @access public
*/
function testParams() {
$this->assertNull(params('weekend'));
$this->assertNull(params(array()));
$this->assertEqual(params(array('weekend')), array('weekend'));
$nested = array(array('weekend'));
$this->assertEqual(params($nested), array('weekend'));
$multiple = array(array('weekend'), 'jean-luc', 'godard');
$this->assertEqual(params($multiple), $multiple);
}
/**
* test stripslashes_deep()
*
* @return void
* @access public
*/
function testStripslashesDeep() {
$this->skipIf(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is on');
$this->assertEqual(stripslashes_deep("tes\'t"), "tes't");
$this->assertEqual(stripslashes_deep('tes\\' . chr(0) .'t'), 'tes' . chr(0) .'t');
$this->assertEqual(stripslashes_deep('tes\"t'), 'tes"t');
$this->assertEqual(stripslashes_deep("tes\'t"), "tes't");
$this->assertEqual(stripslashes_deep('te\\st'), 'test');
$nested = array(
'a' => "tes\'t",
'b' => 'tes\\' . chr(0) .'t',
'c' => array(
'd' => 'tes\"t',
'e' => "te\'s\'t",
array('f' => "tes\'t")
),
'g' => 'te\\st'
);
$expected = array(
'a' => "tes't",
'b' => 'tes' . chr(0) .'t',
'c' => array(
'd' => 'tes"t',
'e' => "te's't",
array('f' => "tes't")
),
'g' => 'test'
);
$this->assertEqual(stripslashes_deep($nested), $expected);
}
/**
* test stripslashes_deep() with magic_quotes_sybase on
*
* @return void
* @access public
*/
function testStripslashesDeepSybase() {
$this->skipUnless(ini_get('magic_quotes_sybase') === '1', '%s magic_quotes_sybase is off');
$this->assertEqual(stripslashes_deep("tes\'t"), "tes\'t");
$nested = array(
'a' => "tes't",
'b' => "tes''t",
'c' => array(
'd' => "tes'''t",
'e' => "tes''''t",
array('f' => "tes''t")
),
'g' => "te'''''st"
);
$expected = array(
'a' => "tes't",
'b' => "tes't",
'c' => array(
'd' => "tes''t",
'e' => "tes''t",
array('f' => "tes't")
),
'g' => "te'''st"
);
$this->assertEqual(stripslashes_deep($nested), $expected);
}
/**
* test ife()
*
* @return void
* @access public
*/
function testIfe() {
$this->assertEqual(ife(true, 'a', 'b'), 'a');
$this->assertEqual(ife(' ', 'a', 'b'), 'a');
$this->assertEqual(ife('test', 'a', 'b'), 'a');
$this->assertEqual(ife(23, 'a', 'b'), 'a');
$this->assertEqual(ife(array('t' => 'est'), 'a', 'b'), 'a');
$this->assertEqual(ife(false, 'a', 'b'), 'b');
$this->assertEqual(ife(null, 'a', 'b'), 'b');
$this->assertEqual(ife('', 'a', 'b'), 'b');
$this->assertEqual(ife(0, 'a', 'b'), 'b');
$this->assertEqual(ife(array(), 'a', 'b'), 'b');
}
/**
* test pluginSplit
*
* @return void
*/
function testPluginSplit() {
$result = pluginSplit('Something.else');
$this->assertEqual($result, array('Something', 'else'));
$result = pluginSplit('Something.else.more.dots');
$this->assertEqual($result, array('Something', 'else.more.dots'));
$result = pluginSplit('Somethingelse');
$this->assertEqual($result, array(null, 'Somethingelse'));
$result = pluginSplit('Something.else', true);
$this->assertEqual($result, array('Something.', 'else'));
$result = pluginSplit('Something.else.more.dots', true);
$this->assertEqual($result, array('Something.', 'else.more.dots'));
$result = pluginSplit('Post', false, 'Blog');
$this->assertEqual($result, array('Blog', 'Post'));
$result = pluginSplit('Blog.Post', false, 'Ultimate');
$this->assertEqual($result, array('Blog', 'Post'));
}
}

View File

@@ -0,0 +1,939 @@
<?php
/**
* ShellDispatcherTest file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2010, Cake Software Foundation, Inc.
*
* 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.
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.console
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CONSOLE_LIBS . 'shell.php';
/**
* TestShellDispatcher class
*
* @package cake
* @subpackage cake.tests.cases.console
*/
class TestShellDispatcher extends ShellDispatcher {
/**
* params property
*
* @var array
* @access public
*/
var $params = array();
/**
* stdout property
*
* @var string
* @access public
*/
var $stdout = '';
/**
* stderr property
*
* @var string
* @access public
*/
var $stderr = '';
/**
* stopped property
*
* @var string
* @access public
*/
var $stopped = null;
/**
* TestShell
*
* @var mixed
* @access public
*/
var $TestShell;
/**
* _initEnvironment method
*
* @return void
* @access protected
*/
function _initEnvironment() {
}
/**
* stderr method
*
* @return void
* @access public
*/
function stderr($string) {
$this->stderr .= rtrim($string, ' ');
}
/**
* stdout method
*
* @return void
* @access public
*/
function stdout($string, $newline = true) {
if ($newline) {
$this->stdout .= rtrim($string, ' ') . "\n";
} else {
$this->stdout .= rtrim($string, ' ');
}
}
/**
* clear method
*
* @return void
* @access public
*/
function clear() {
}
/**
* _stop method
*
* @return void
* @access protected
*/
function _stop($status = 0) {
$this->stopped = 'Stopped with status: ' . $status;
return $status;
}
/**
* getShell
*
* @param mixed $plugin
* @return mixed
* @access public
*/
function getShell($plugin = null) {
return $this->_getShell($plugin);
}
/**
* _getShell
*
* @param mixed $plugin
* @return mixed
* @access protected
*/
function _getShell($plugin = null) {
if (isset($this->TestShell)) {
return $this->TestShell;
}
return parent::_getShell($plugin);
}
}
/**
* ShellDispatcherTest
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ShellDispatcherTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function setUp() {
App::build(array(
'plugins' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS
),
'shells' => array(
CORE_PATH ? CONSOLE_LIBS : ROOT . DS . CONSOLE_LIBS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS
)
), true);
}
/**
* tearDown method
*
* @return void
* @access public
*/
function tearDown() {
App::build();
}
/**
* testParseParams method
*
* @return void
* @access public
*/
function testParseParams() {
$Dispatcher =& new TestShellDispatcher();
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'bake',
'-app',
'new',
'-working',
'/var/www/htdocs'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => '/var/www/htdocs/new',
'root' => '/var/www/htdocs'
);
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array('cake.php');
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'app'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH),
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-app',
'new',
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'new'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH)
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'./cake.php',
'bake',
'-app',
'new',
'-working',
'/cake/1.2.x.x/cake/console'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'new'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH)
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'bake',
'-app',
'new',
'-working',
'/cake/1.2.x.x/cake'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'new'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH)
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'bake',
'-app',
'new',
'-dry',
'-working',
'/cake/1.2.x.x/cake'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'new'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH),
'dry' => 1
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'./console/cake.php',
'-working',
'/cake/1.2.x.x/cake',
'schema',
'run',
'create',
'-dry',
'-f',
'-name',
'DbAcl'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH . DS . 'app'),
'root' => str_replace('\\', '/', CAKE_CORE_INCLUDE_PATH),
'dry' => 1,
'f' => 1,
'name' => 'DbAcl'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$expected = array('./console/cake.php', 'schema', 'run', 'create');
$this->assertEqual($expected, $Dispatcher->args);
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'-working',
'/cake/1.2.x.x/app',
'schema',
'run',
'create',
'-dry',
'-name',
'DbAcl'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => '/cake/1.2.x.x/app',
'root' => '/cake/1.2.x.x',
'dry' => 1,
'name' => 'DbAcl'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$expected = array('/cake/1.2.x.x/cake/console/cake.php', 'schema', 'run', 'create');
$this->assertEqual($expected, $Dispatcher->args);
$params = array(
'cake.php',
'-working',
'C:/wamp/www/cake/app',
'bake',
'-app',
'C:/wamp/www/apps/cake/app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'C:\wamp\www\cake\app',
'bake',
'-app',
'C:\wamp\www\apps\cake\app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'C:\wamp\www\apps',
'bake',
'-app',
'cake\app',
'-url',
'http://example.com/some/url/with/a/path'
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => 'C:\wamp\www\apps\cake\app',
'root' => 'C:\wamp\www\apps\cake',
'url' => 'http://example.com/some/url/with/a/path'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'/home/amelo/dev/cake-common/cake/console/cake.php',
'-root',
'/home/amelo/dev/lsbu-vacancy',
'-working',
'/home/amelo/dev/lsbu-vacancy',
'-app',
'app',
);
$expected = array(
'app' => 'app',
'webroot' => 'webroot',
'working' => '/home/amelo/dev/lsbu-vacancy/app',
'root' => '/home/amelo/dev/lsbu-vacancy',
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
$params = array(
'cake.php',
'-working',
'D:\www',
'bake',
'my_app',
);
$expected = array(
'working' => 'D:\www',
'app' => 'www',
'root' => 'D:',
'webroot' => 'webroot'
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEqual($expected, $Dispatcher->params);
}
/**
* testBuildPaths method
*
* @return void
* @access public
*/
function testBuildPaths() {
$Dispatcher =& new TestShellDispatcher();
$result = $Dispatcher->shellPaths;
$expected = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS . 'vendors' . DS . 'shells' . DS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin_two' . DS . 'vendors' . DS . 'shells' . DS,
APP . 'vendors' . DS . 'shells' . DS,
VENDORS . 'shells' . DS,
CORE_PATH ? CONSOLE_LIBS : ROOT . DS . CONSOLE_LIBS,
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS,
);
$this->assertIdentical(array_diff($result, $expected), array());
$this->assertIdentical(array_diff($expected, $result), array());
}
/**
* Verify loading of (plugin-) shells
*
* @return void
* @access public
*/
function testGetShell() {
$this->skipIf(class_exists('SampleShell'), '%s SampleShell Class already loaded');
$this->skipIf(class_exists('ExampleShell'), '%s ExampleShell Class already loaded');
$Dispatcher =& new TestShellDispatcher();
$Dispatcher->shell = 'sample';
$Dispatcher->shellName = 'Sample';
$Dispatcher->shellClass = 'SampleShell';
$result = $Dispatcher->getShell();
$this->assertIsA($result, 'SampleShell');
$Dispatcher =& new TestShellDispatcher();
$Dispatcher->shell = 'example';
$Dispatcher->shellName = 'Example';
$Dispatcher->shellClass = 'ExampleShell';
$result = $Dispatcher->getShell('test_plugin');
$this->assertIsA($result, 'ExampleShell');
}
/**
* Verify correct dispatch of Shell subclasses with a main method
*
* @return void
* @access public
*/
function testDispatchShellWithMain() {
Mock::generate('Shell', 'MockWithMainShell', array('main', '_secret'));
$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;
$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;
$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;
$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;
$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;
$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;
$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;
$Dispatcher->args = array('mock_with_main', '_secret');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
}
/**
* Verify correct dispatch of Shell subclasses without a main method
*
* @return void
* @access public
*/
function testDispatchShellWithoutMain() {
Mock::generate('Shell', 'MockWithoutMainShell', array('initDb', '_secret'));
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithoutMainShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectOnce('initialize');
$Shell->expectOnce('loadTasks');
$Shell->expectNever('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;
$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;
$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;
$Dispatcher->args = array('mock_without_main', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainShell();
$Shell->expectNever('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;
$Dispatcher->args = array('mock_without_main', '_secret');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
}
/**
* Verify correct dispatch of custom classes with a main method
*
* @return void
* @access public
*/
function testDispatchNotAShellWithMain() {
Mock::generate('Object', 'MockWithMainNotAShell',
array('main', 'initialize', 'loadTasks', 'startup', '_secret'));
$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;
$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;
$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;
$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;
$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;
$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;
$Dispatcher->args = array('mock_with_main_not_a', '_secret');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
}
/**
* Verify correct dispatch of custom classes without a main method
*
* @return void
* @access public
*/
function testDispatchNotAShellWithoutMain() {
Mock::generate('Object', 'MockWithoutMainNotAShell',
array('initDb', 'initialize', 'loadTasks', 'startup', '_secret'));
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('initialize');
$Shell->expectNever('loadTasks');
$Shell->expectNever('startup');
$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;
$Dispatcher->args = array('mock_without_main_not_a', 'hr');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainNotAShell();
$Shell->setReturnValue('initDb', true);
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'dispatch');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainNotAShell();
$Shell->expectNever('startup');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->args = array('mock_without_main_not_a', 'idontexist');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
$Shell = new MockWithoutMainNotAShell();
$Shell->expectNever('startup');
$Shell->expectNever('_secret');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->args = array('mock_without_main_not_a', '_secret');
$result = $Dispatcher->dispatch();
$this->assertFalse($result);
}
/**
* Verify that a task is called instead of the shell if the first arg equals
* the name of the task
*
* @return void
* @access public
*/
function testDispatchTask() {
Mock::generate('Shell', 'MockWeekShell', array('main'));
Mock::generate('Shell', 'MockOnSundayTask', array('execute'));
$Dispatcher =& new TestShellDispatcher();
$Shell = new MockWeekShell();
$Shell->expectOnce('initialize');
$Shell->expectOnce('loadTasks');
$Shell->expectNever('startup');
$Shell->expectNever('main');
$Task = new MockOnSundayTask();
$Task->setReturnValue('execute', true);
$Task->expectOnce('initialize');
$Task->expectOnce('loadTasks');
$Task->expectOnce('startup');
$Task->expectOnce('execute');
$Shell->MockOnSunday =& $Task;
$Shell->taskNames = array('MockOnSunday');
$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->MockOnSunday =& $Task;
$Shell->taskNames = array('MockOnSunday');
$Dispatcher->TestShell =& $Shell;
$Dispatcher->args = array('mock_week', 'mock_on_sunday', 'help');
$result = $Dispatcher->dispatch();
$this->assertTrue($result);
}
/**
* Verify shifting of arguments
*
* @return void
* @access public
*/
function testShiftArgs() {
$Dispatcher =& new TestShellDispatcher();
$Dispatcher->args = array('a', 'b', 'c');
$this->assertEqual($Dispatcher->shiftArgs(), 'a');
$this->assertIdentical($Dispatcher->args, array('b', 'c'));
$Dispatcher->args = array('a' => 'b', 'c', 'd');
$this->assertEqual($Dispatcher->shiftArgs(), 'b');
$this->assertIdentical($Dispatcher->args, array('c', 'd'));
$Dispatcher->args = array('a', 'b' => 'c', 'd');
$this->assertEqual($Dispatcher->shiftArgs(), 'a');
$this->assertIdentical($Dispatcher->args, array('b' => 'c', 'd'));
$Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
$this->assertEqual($Dispatcher->shiftArgs(), 'a');
$this->assertIdentical($Dispatcher->args, array(0 => 'b', 1 => 'c'));
$Dispatcher->args = array();
$this->assertNull($Dispatcher->shiftArgs());
$this->assertIdentical($Dispatcher->args, array());
}
/**
* testHelpCommand method
*
* @return void
* @access public
*/
function testHelpCommand() {
$Dispatcher =& new TestShellDispatcher();
$expected = "/example \[.*TestPlugin, TestPluginTwo.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/welcome \[.*TestPluginTwo.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/acl \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/api \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/bake \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/console \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/i18n \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/schema \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/testsuite \[.*CORE.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
$expected = "/sample \[.*test_app.*\]/";
$this->assertPattern($expected, $Dispatcher->stdout);
}
}

View File

@@ -0,0 +1,346 @@
<?php
/**
* AclShell Test file
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class AclShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.aco', 'core.aro', 'core.aros_aco');
/**
* configure Configure for testcase
*
* @return void
* @access 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
* @access public
*/
function endCase() {
Configure::write('Acl.database', $this->_aclDb);
Configure::write('Acl.classname', $this->_aclClass);
}
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestAclShellMockShellDispatcher();
$this->Task =& new MockAclShell($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->params['datasource'] = 'test_suite';
$this->Task->Acl =& new AclComponent();
$controller = null;
$this->Task->Acl->startup($controller);
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test that model.foreign_key output works when looking at acl rows
*
* @return void
* @access public
*/
function testViewWithModelForeignKeyOutput() {
$this->Task->command = 'view';
$this->Task->startup();
$data = array(
'parent_id' => null,
'model' => 'MyModel',
'foreign_key' => 2,
);
$this->Task->Acl->Aro->create($data);
$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->view();
}
/**
* test view with an argument
*
* @return void
* @access 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->view();
}
/**
* test the method that splits model.foreign key. and that it returns an array.
*
* @return void
* @access public
*/
function testParsingModelAndForeignKey() {
$result = $this->Task->parseIdentifier('Model.foreignKey');
$expected = array('model' => 'Model', 'foreign_key' => 'foreignKey');
$result = $this->Task->parseIdentifier('mySuperUser');
$this->assertEqual($result, 'mySuperUser');
$result = $this->Task->parseIdentifier('111234');
$this->assertEqual($result, '111234');
}
/**
* test creating aro/aco nodes
*
* @return void
* @access public
*/
function testCreate() {
$this->Task->args = array('aro', 'root', 'User.1');
$this->Task->expectAt(0, 'out', array(new PatternExpectation('/created/'), '*'));
$this->Task->create();
$Aro =& ClassRegistry::init('Aro');
$Aro->cacheQueries = false;
$result = $Aro->read();
$this->assertEqual($result['Aro']['model'], 'User');
$this->assertEqual($result['Aro']['foreign_key'], 1);
$this->assertEqual($result['Aro']['parent_id'], null);
$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');
$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');
$result = $Aro->read();
$this->assertEqual($result['Aro']['alias'], 'somealias');
$this->assertEqual($result['Aro']['model'], null);
$this->assertEqual($result['Aro']['foreign_key'], null);
$this->assertEqual($result['Aro']['parent_id'], null);
}
/**
* test the delete method with different node types.
*
* @return void
* @access public
*/
function testDelete() {
$this->Task->args = array('aro', 'AuthUser.1');
$this->Task->expectAt(0, 'out', array(new NoPatternExpectation('/not/'), true));
$this->Task->delete();
$Aro =& ClassRegistry::init('Aro');
$result = $Aro->read(null, 3);
$this->assertFalse($result);
}
/**
* test setParent method.
*
* @return void
* @access public
*/
function testSetParent() {
$this->Task->args = array('aro', 'AuthUser.2', 'root');
$this->Task->setParent();
$Aro =& ClassRegistry::init('Aro');
$result = $Aro->read(null, 4);
$this->assertEqual($result['Aro']['parent_id'], null);
}
/**
* test grant
*
* @return void
* @access 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->grant();
$node = $this->Task->Acl->Aro->read(null, 4);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEqual($node['Aco'][0]['Permission']['_create'], 1);
}
/**
* test deny
*
* @return void
* @access 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->deny();
$node = $this->Task->Acl->Aro->read(null, 4);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEqual($node['Aco'][0]['Permission']['_create'], -1);
}
/**
* test checking allowed and denied perms
*
* @return void
* @access public
*/
function testCheck() {
$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();
}
/**
* test inherit and that it 0's the permission fields.
*
* @return void
* @access public
*/
function testInherit() {
$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);
$this->assertFalse(empty($node['Aco'][0]));
$this->assertEqual($node['Aco'][0]['Permission']['_create'], 0);
}
/**
* test getting the path for an aro/aco
*
* @return void
* @access 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->getPath();
}
/**
* test that initdb makes the correct call.
*
* @return void
*/
function testInitDb() {
$this->Task->Dispatch->expectOnce('dispatch');
$this->Task->initdb();
$this->assertEqual($this->Task->Dispatch->args, array('schema', 'create', 'DbAcl'));
}
}

View File

@@ -0,0 +1,116 @@
<?php
/**
* ApiShellTest file
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ApiShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new ApiShellMockShellDispatcher();
$this->Shell =& new MockApiShell($this->Dispatcher);
$this->Shell->Dispatch =& $this->Dispatcher;
}
/**
* tearDown method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* Test that method names are detected properly including those with no arguments.
*
* @return void
* @access public
*/
function testMethodNameDetection () {
$this->Shell->setReturnValueAt(0, 'in', 'q');
$this->Shell->expectAt(0, 'out', array('Controller'));
$expected = array(
array(
'1. afterFilter()',
'2. beforeFilter()',
'3. beforeRender()',
'4. constructClasses()',
'5. disableCache()',
'6. flash($message, $url, $pause = 1, $layout = \'flash\')',
'7. header($status)',
'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)',
'17. setAction($action)',
'18. shutdownProcess()',
'19. startupProcess()',
'20. validate()',
'21. validateErrors()'
)
);
$this->Shell->expectAt(1, 'out', $expected);
$this->Shell->args = array('controller');
$this->Shell->paths['controller'] = CAKE_CORE_INCLUDE_PATH . DS . LIBS . 'controller' . DS;
$this->Shell->main();
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* BakeShell Test Case
*
*
* PHP versions 4 and 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.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'bake.php';
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 {
var $name = 'Users';
}
}
class BakeShellTestCase extends CakeTestCase {
/**
* fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.user');
/**
* start test
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatch =& new BakeShellMockShellDispatcher();
$this->Shell =& new MockBakeShell();
$this->Shell->Dispatch =& $this->Dispatch;
$this->Shell->Dispatch->shellPaths = App::path('shells');
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Dispatch, $this->Shell);
}
/**
* test bake all
*
* @return void
* @access public
*/
function testAllWithModelName() {
App::import('Model', 'User');
$userExists = class_exists('User');
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->DbConfig->expectOnce('getConfig');
$this->Shell->DbConfig->setReturnValue('getConfig', 'test_suite');
$this->Shell->Model->setReturnValue('bake', true);
$this->Shell->Model->expectNever('getName');
$this->Shell->Model->expectOnce('bake');
$this->Shell->Controller->expectOnce('bake');
$this->Shell->Controller->setReturnValue('bake', true);
$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->params = array();
$this->Shell->args = array('User');
$this->Shell->all();
}
}

View File

@@ -0,0 +1,503 @@
<?php
/**
* SchemaShellTest Test file
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.Shells
* @since CakePHP v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
App::import('Model', 'CakeSchema', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SchemaShellTestSchema extends CakeSchema {
/**
* name property
*
* @var string 'MyApp'
* @access public
*/
var $name = 'SchemaShellTest';
/**
* connection property
*
* @var string 'test_suite'
* @access public
*/
var $connection = 'test_suite';
/**
* comments property
*
* @var array
* @access public
*/
var $comments = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'user_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false, 'length' => 100),
'comment' => array('type' => 'text', 'null' => false, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
/**
* posts property
*
* @var array
* @access public
*/
var $articles = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'user_id' => array('type' => 'integer', 'null' => true, 'default' => ''),
'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'body' => array('type' => 'text', 'null' => true, 'default' => null),
'summary' => array('type' => 'text', 'null' => true),
'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
}
/**
* SchemaShellTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.Shells
*/
class SchemaShellTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author',
'core.comment', 'core.test_plugin_comment'
);
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestSchemaShellMockShellDispatcher();
$this->Shell =& new MockSchemaShell($this->Dispatcher);
$this->Shell->Dispatch =& $this->Dispatcher;
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test startup method
*
* @return void
* @access public
*/
function testStartup() {
$this->Shell->startup();
$this->assertTrue(isset($this->Shell->Schema));
$this->assertTrue(is_a($this->Shell->Schema, 'CakeSchema'));
$this->assertEqual(strtolower($this->Shell->Schema->name), strtolower(APP_DIR));
$this->assertEqual($this->Shell->Schema->file, 'schema.php');
unset($this->Shell->Schema);
$this->Shell->params = array(
'name' => 'TestSchema'
);
$this->Shell->startup();
$this->assertEqual($this->Shell->Schema->name, 'TestSchema');
$this->assertEqual($this->Shell->Schema->file, 'test_schema.php');
$this->assertEqual($this->Shell->Schema->connection, 'default');
$this->assertEqual($this->Shell->Schema->path, APP . 'config' . DS . 'schema');
unset($this->Shell->Schema);
$this->Shell->params = array(
'file' => 'other_file.php',
'connection' => 'test_suite',
'path' => '/test/path'
);
$this->Shell->startup();
$this->assertEqual(strtolower($this->Shell->Schema->name), strtolower(APP_DIR));
$this->assertEqual($this->Shell->Schema->file, 'other_file.php');
$this->assertEqual($this->Shell->Schema->connection, 'test_suite');
$this->assertEqual($this->Shell->Schema->path, '/test/path');
}
/**
* Test View - and that it dumps the schema file to stdout
*
* @return void
* @access public
*/
function testView() {
$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->view();
}
/**
* test that view() can find plugin schema files.
*
* @return void
* @access public
*/
function testViewWithPlugins() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$this->Shell->args = array('TestPlugin.schema');
$this->Shell->startup();
$this->Shell->expectCallCount('_stop', 2);
$this->Shell->expectCallCount('out', 2);
$this->Shell->view();
$this->Shell->args = array();
$this->Shell->params = array('plugin' => 'TestPlugin');
$this->Shell->startup();
$this->Shell->view();
App::build();
}
/**
* test dump() with sql file generation
*
* @return void
* @access public
*/
function testDumpWithFileWriting() {
$this->Shell->params = array(
'name' => 'i18n',
'write' => TMP . 'tests' . DS . 'i18n.sql'
);
$this->Shell->expectOnce('_stop');
$this->Shell->startup();
$this->Shell->dump();
$sql =& new File(TMP . 'tests' . DS . 'i18n.sql');
$contents = $sql->read();
$this->assertPattern('/DROP TABLE/', $contents);
$this->assertPattern('/CREATE TABLE `i18n`/', $contents);
$this->assertPattern('/id/', $contents);
$this->assertPattern('/model/', $contents);
$this->assertPattern('/field/', $contents);
$this->assertPattern('/locale/', $contents);
$this->assertPattern('/foreign_key/', $contents);
$this->assertPattern('/content/', $contents);
$sql->delete();
}
/**
* test that dump() can find and work with plugin schema files.
*
* @return void
* @access public
*/
function testDumpFileWritingWithPlugins() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$this->Shell->args = array('TestPlugin.TestPluginApp');
$this->Shell->params = array(
'connection' => 'test_suite',
'write' => TMP . 'tests' . DS . 'dump_test.sql'
);
$this->Shell->startup();
$this->Shell->expectOnce('_stop');
$this->Shell->dump();
$file =& new File(TMP . 'tests' . DS . 'dump_test.sql');
$contents = $file->read();
$this->assertPattern('/CREATE TABLE `acos`/', $contents);
$this->assertPattern('/id/', $contents);
$this->assertPattern('/model/', $contents);
$file->delete();
App::build();
}
/**
* test generate with snapshot generation
*
* @return void
* @access public
*/
function testGenerateSnaphot() {
$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->expectOnce('read');
$this->Shell->Schema->expectOnce('write', array(array('schema data', 'file' => 'schema_1.php')));
$this->Shell->generate();
}
/**
* test generate without a snapshot.
*
* @return void
* @access public
*/
function testGenerateNoOverwrite() {
touch(TMP . 'schema.php');
$this->Shell->params['file'] = 'schema.php';
$this->Shell->args = array();
$this->Shell->setReturnValue('in', 'q');
$this->Shell->Schema =& new MockSchemaCakeSchema();
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expectNever('read');
$result = $this->Shell->generate();
unlink(TMP . 'schema.php');
}
/**
* test generate with overwriting of the schema files.
*
* @return void
* @access public
*/
function testGenerateOverwrite() {
touch(TMP . 'schema.php');
$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->Schema->expectOnce('read');
$this->Shell->Schema->expectOnce('write', array(array('schema data', 'file' => 'schema.php')));
$this->Shell->generate();
unlink(TMP . 'schema.php');
}
/**
* test that generate() can read plugin dirs and generate schema files for the models
* in a plugin.
*
* @return void
* @access public
*/
function testGenerateWithPlugins() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test_suite'
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$file =& new File(TMP . 'tests' . DS . 'schema.php');
$contents = $file->read();
$this->assertPattern('/class TestPluginSchema/', $contents);
$this->assertPattern('/var \$posts/', $contents);
$this->assertPattern('/var \$auth_users/', $contents);
$this->assertPattern('/var \$authors/', $contents);
$this->assertPattern('/var \$test_plugin_comments/', $contents);
$this->assertNoPattern('/var \$users/', $contents);
$this->assertNoPattern('/var \$articles/', $contents);
$file->delete();
App::build();
}
/**
* Test schema run create with no table args.
*
* @return void
* @access public
*/
function testCreateNoArgs() {
$this->Shell->params = array(
'connection' => 'test_suite',
'path' => APP . 'config' . DS . 'sql'
);
$this->Shell->args = array('i18n');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources));
$schema =& new i18nSchema();
$db->execute($db->dropSchema($schema));
}
/**
* Test schema run create with no table args.
*
* @return void
* @access public
*/
function testCreateWithTableArgs() {
$this->Shell->params = array(
'connection' => 'test_suite',
'name' => 'DbAcl',
'path' => APP . 'config' . DS . 'schema'
);
$this->Shell->args = array('DbAcl', 'acos');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'acos', $sources));
$this->assertFalse(in_array($db->config['prefix'] . 'aros', $sources));
$this->assertFalse(in_array('aros_acos', $sources));
$db->execute('DROP TABLE ' . $db->config['prefix'] . 'acos');
}
/**
* test run update with a table arg.
*
* @return void
* @access public
*/
function testUpdateWithTable() {
$this->Shell->params = array(
'connection' => 'test_suite',
'f' => true
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->setReturnValue('in', '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);
}
/**
* test that the plugin param creates the correct path in the schema object.
*
* @return void
* @access public
*/
function testPluginParam() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test_suite'
);
$this->Shell->startup();
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS . 'config' . DS . 'schema';
$this->assertEqual($this->Shell->Schema->path, $expected);
App::build();
}
/**
* test that using Plugin.name with write.
*
* @return void
* @access public
*/
function testPluginDotSyntaxWithCreate() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$this->Shell->params = array(
'connection' => 'test_suite'
);
$this->Shell->args = array('TestPlugin.TestPluginApp');
$this->Shell->startup();
$this->Shell->setReturnValue('in', 'y');
$this->Shell->create();
$db =& ConnectionManager::getDataSource('test_suite');
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'acos', $sources));
$db->execute('DROP TABLE ' . $db->config['prefix'] . 'acos');
App::build();
}
}

View File

@@ -0,0 +1,501 @@
<?php
/**
* ShellTest file
*
* Test Case for Shell
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Folder');
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
Mock::generatePartial('ShellDispatcher', 'TestShellMockShellDispatcher', array(
'getInput', 'stdout', 'stderr', '_stop', '_initEnvironment'
));
/**
* TestShell class
*
* @package cake
* @subpackage cake.tests.cases.console.libs
*/
class TestShell extends Shell {
/**
* name property
*
* @var name
* @access public
*/
var $name = 'TestShell';
/**
* stopped property
*
* @var integer
* @access public
*/
var $stopped;
/**
* stop method
*
* @param integer $status
* @return void
* @access protected
*/
function _stop($status = 0) {
$this->stopped = $status;
}
}
/**
* TestAppleTask class
*
* @package cake
* @subpackage cake.tests.cases.console.libs
*/
class TestAppleTask extends Shell {
}
/**
* TestBananaTask class
*
* @package cake
* @subpackage cake.tests.cases.console.libs
*/
class TestBananaTask extends Shell {
}
/**
* ShellTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs
*/
class ShellTest extends CakeTestCase {
/**
* Fixtures used in this test case
*
* @var array
* @access public
*/
var $fixtures = array(
'core.post', 'core.comment', 'core.article', 'core.user',
'core.tag', 'core.articles_tag', 'core.attachment'
);
/**
* setUp method
*
* @return void
* @access public
*/
function setUp() {
$this->Dispatcher =& new TestShellMockShellDispatcher();
$this->Shell =& new TestShell($this->Dispatcher);
}
/**
* tearDown method
*
* @return void
* @access public
*/
function tearDown() {
ClassRegistry::flush();
}
/**
* testConstruct method
*
* @return void
* @access public
*/
function testConstruct() {
$this->assertIsA($this->Shell->Dispatch, 'TestShellMockShellDispatcher');
$this->assertEqual($this->Shell->name, 'TestShell');
$this->assertEqual($this->Shell->alias, 'TestShell');
}
/**
* testInitialize method
*
* @return void
* @access public
*/
function testInitialize() {
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)
), true);
$this->Shell->uses = array('TestPlugin.TestPluginPost');
$this->Shell->initialize();
$this->assertTrue(isset($this->Shell->TestPluginPost));
$this->assertIsA($this->Shell->TestPluginPost, 'TestPluginPost');
$this->assertEqual($this->Shell->modelClass, 'TestPluginPost');
$this->Shell->uses = array('Comment');
$this->Shell->initialize();
$this->assertTrue(isset($this->Shell->Comment));
$this->assertIsA($this->Shell->Comment, 'Comment');
$this->assertEqual($this->Shell->modelClass, 'Comment');
$this->Shell->uses = true;
$this->Shell->initialize();
$this->assertTrue(isset($this->Shell->AppModel));
$this->assertIsA($this->Shell->AppModel, 'AppModel');
App::build();
}
/**
* testIn method
*
* @return void
* @access public
*/
function testIn() {
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(0, 'getInput', array('Just a test?', array('y', 'n'), 'n'));
$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');
$this->Shell->interactive = false;
$result = $this->Shell->in('Just a test?', 'y/n', 'n');
$this->assertEqual($result, 'n');
}
/**
* testOut method
*
* @return void
* @access public
*/
function testOut() {
$this->Shell->Dispatch->expectAt(0, 'stdout', array("Just a test\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();
}
/**
* testErr method
*
* @return void
* @access public
*/
function testErr() {
$this->Shell->Dispatch->expectAt(0, 'stderr', array("Just a test\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();
}
/**
* testNl
*
* @return void
* @access public
*/
function testNl() {
$this->assertEqual($this->Shell->nl(), "\n");
$this->assertEqual($this->Shell->nl(true), "\n");
$this->assertEqual($this->Shell->nl(false), "");
$this->assertEqual($this->Shell->nl(2), "\n\n");
$this->assertEqual($this->Shell->nl(1), "\n");
}
/**
* testHr
*
* @return void
* @access 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->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);
}
/**
* testError
*
* @return void
* @access public
*/
function testError() {
$this->Shell->Dispatch->expectAt(0, 'stderr', array("Error: Foo Not Found\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);
}
/**
* testLoadTasks method
*
* @return void
* @access public
*/
function testLoadTasks() {
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = null;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = false;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = true;
$this->assertTrue($this->Shell->loadTasks());
$this->Shell->tasks = array();
$this->assertTrue($this->Shell->loadTasks());
// Fatal Error
// $this->Shell->tasks = 'TestIDontExist';
// $this->assertFalse($this->Shell->loadTasks());
// $this->assertFalse(isset($this->Shell->TestIDontExist));
$this->Shell->tasks = 'TestApple';
$this->assertTrue($this->Shell->loadTasks());
$this->assertIsA($this->Shell->TestApple, 'TestAppleTask');
$this->Shell->tasks = 'TestBanana';
$this->assertTrue($this->Shell->loadTasks());
$this->assertIsA($this->Shell->TestApple, 'TestAppleTask');
$this->assertIsA($this->Shell->TestBanana, 'TestBananaTask');
unset($this->Shell->ShellTestApple, $this->Shell->TestBanana);
$this->Shell->tasks = array('TestApple', 'TestBanana');
$this->assertTrue($this->Shell->loadTasks());
$this->assertIsA($this->Shell->TestApple, 'TestAppleTask');
$this->assertIsA($this->Shell->TestBanana, 'TestBananaTask');
}
/**
* testShortPath method
*
* @return void
* @access public
*/
function testShortPath() {
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd';
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'cd' . DS ;
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = $expected = DS . 'tmp' . DS . 'ab' . DS . 'index.php';
$this->assertEqual($this->Shell->shortPath($path), $expected);
// Shell::shortPath needs Folder::realpath
// $path = DS . 'tmp' . DS . 'ab' . DS . '..' . DS . 'cd';
// $expected = DS . 'tmp' . DS . 'cd';
// $this->assertEqual($this->Shell->shortPath($path), $expected);
$path = DS . 'tmp' . DS . 'ab' . DS . DS . 'cd';
$expected = DS . 'tmp' . DS . 'ab' . DS . 'cd';
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = 'tmp' . DS . 'ab';
$expected = 'tmp' . DS . 'ab';
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = 'tmp' . DS . 'ab';
$expected = 'tmp' . DS . 'ab';
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = APP;
$expected = DS . basename(APP) . DS;
$this->assertEqual($this->Shell->shortPath($path), $expected);
$path = APP . 'index.php';
$expected = DS . basename(APP) . DS . 'index.php';
$this->assertEqual($this->Shell->shortPath($path), $expected);
}
/**
* testCreateFile method
*
* @return void
* @access public
*/
function testCreateFile() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s Not supported on Windows');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$this->Shell->interactive = false;
$contents = "<?php\necho 'test';\n\$te = 'st';\n?>";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$contents = "<?php\necho 'another test';\n\$te = 'st';\n?>";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$this->Shell->interactive = true;
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(1, 'stdout', array('File exists, overwrite?', '*'));
$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);
$Folder->delete();
}
/**
* testCreateFileWindows method
*
* @return void
* @access public
*/
function testCreateFileWindows() {
$this->skipUnless(DIRECTORY_SEPARATOR === '\\', 'testCreateFileWindows supported on Windows only');
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
new Folder($path, true);
$this->Shell->interactive = false;
$contents = "<?php\necho 'test';\r\n\$te = 'st';\r\n?>";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$contents = "<?php\necho 'another test';\r\n\$te = 'st';\r\n?>";
$result = $this->Shell->createFile($file, $contents);
$this->assertTrue($result);
$this->assertTrue(file_exists($file));
$this->assertEqual(file_get_contents($file), $contents);
$this->Shell->interactive = true;
$this->Shell->Dispatch->setReturnValueAt(0, 'getInput', 'n');
$this->Shell->Dispatch->expectAt(1, 'stdout', array('File exists, overwrite?'));
$contents = "<?php\necho 'yet another test';\r\n\$te = 'st';\r\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);
$Folder->delete();
}
}

View File

@@ -0,0 +1,633 @@
<?php
/**
* ControllerTask Test Case
*
* PHP versions 4 and 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.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'ClassRegistry');
App::import('View', 'Helper', false);
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'project.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
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');
$imported = $imported || App::import('Model', 'Tag');
if (!$imported) {
define('ARTICLE_MODEL_CREATED', true);
App::import('Core', 'Model');
class Article extends Model {
var $name = 'Article';
var $hasMany = array('Comment');
var $hasAndBelongsToMany = array('Tag');
}
}
/**
* ControllerTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ControllerTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestControllerTaskMockShellDispatcher();
$this->Task =& new MockControllerTask($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();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test ListAll
*
* @return void
* @access 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'));
$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();
$expected = array('articles', 'articles_tags', 'comments', 'tags');
$this->assertEqual($result, $expected);
}
/**
* Test that getName interacts with the user and returns the controller name.
*
* @return void
* @access public
*/
function testGetName() {
$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);
$result = $this->Task->getName('test_suite');
$expected = 'Comments';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 10);
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
}
/**
* test helper interactions
*
* @return void
* @access public
*/
function testDoHelpers() {
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->doHelpers();
$this->assertEqual($result, array());
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', ' 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, , ');
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$this->assertEqual($result, $expected);
}
/**
* test component interactions
*
* @return void
* @access public
*/
function testDoComponents() {
$this->Task->setReturnValue('in', 'n');
$result = $this->Task->doComponents();
$this->assertEqual($result, array());
$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);
$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);
}
/**
* test Confirming controller user interaction
*
* @return void
* @access public
*/
function testConfirmController() {
$controller = 'Posts';
$scaffold = false;
$helpers = array('Ajax', 'Time');
$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->confirmController($controller, $scaffold, $helpers, $components);
}
/**
* test the bake method
*
* @return void
* @access public
*/
function testBake() {
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$this->Task->setReturnValue('createFile', true);
$result = $this->Task->bake('Articles', '--actions--', $helpers, $components);
$this->assertPattern('/class ArticlesController extends AppController/', $result);
$this->assertPattern('/\$components \= array\(\'Acl\', \'Auth\'\)/', $result);
$this->assertPattern('/\$helpers \= array\(\'Ajax\', \'Time\'\)/', $result);
$this->assertPattern('/\-\-actions\-\-/', $result);
$result = $this->Task->bake('Articles', 'scaffold', $helpers, $components);
$this->assertPattern('/class ArticlesController extends AppController/', $result);
$this->assertPattern('/var \$scaffold/', $result);
$this->assertNoPattern('/helpers/', $result);
$this->assertNoPattern('/components/', $result);
$result = $this->Task->bake('Articles', '--actions--', array(), array());
$this->assertPattern('/class ArticlesController extends AppController/', $result);
$this->assertNoPattern('/components/', $result);
$this->assertNoPattern('/helpers/', $result);
$this->assertPattern('/\-\-actions\-\-/', $result);
}
/**
* test bake() with a -plugin param
*
* @return void
* @access public
*/
function testBakeWithPlugin() {
$this->Task->plugin = 'ControllerTest';
$helpers = array('Ajax', 'Time');
$components = array('Acl', 'Auth');
$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->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());
$this->assertEqual($this->Task->Template->templateVars['plugin'], 'ControllerTest');
}
/**
* test that bakeActions is creating the correct controller Code. (Using sessions)
*
* @return void
* @access public
*/
function testBakeActionsUsingSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Comment & Tag Model to be undefined. %s');
if ($skip) {
return;
}
$result = $this->Task->bakeActions('Articles', null, true);
$this->assertTrue(strpos($result, 'function index() {') !== false);
$this->assertTrue(strpos($result, '$this->Article->recursive = 0;') !== false);
$this->assertTrue(strpos($result, "\$this->set('articles', \$this->paginate());") !== false);
$this->assertTrue(strpos($result, 'function view($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('Invalid article', true));") !== false);
$this->assertTrue(strpos($result, "\$this->set('article', \$this->Article->read(null, \$id)") !== false);
$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->Session->setFlash(__('The article has been saved', true));") !== false);
$this->assertTrue(strpos($result, 'function edit($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('The article could not be saved. Please, try again.', true));") !== false);
$this->assertTrue(strpos($result, 'function delete($id = null)') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->delete($id))') !== false);
$this->assertTrue(strpos($result, "\$this->Session->setFlash(__('Article deleted', true));") !== false);
$result = $this->Task->bakeActions('Articles', 'admin_', true);
$this->assertTrue(strpos($result, 'function admin_index() {') !== false);
$this->assertTrue(strpos($result, 'function admin_add()') !== false);
$this->assertTrue(strpos($result, 'function admin_view($id = null)') !== false);
$this->assertTrue(strpos($result, 'function admin_edit($id = null)') !== false);
$this->assertTrue(strpos($result, 'function admin_delete($id = null)') !== false);
}
/**
* Test baking with Controller::flash() or no sessions.
*
* @return void
* @access public
*/
function testBakeActionsWithNoSessions() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Testing bakeActions requires Article, Tag, Comment Models to be undefined. %s');
if ($skip) {
return;
}
$result = $this->Task->bakeActions('Articles', null, false);
$this->assertTrue(strpos($result, 'function index() {') !== false);
$this->assertTrue(strpos($result, '$this->Article->recursive = 0;') !== false);
$this->assertTrue(strpos($result, "\$this->set('articles', \$this->paginate());") !== false);
$this->assertTrue(strpos($result, 'function view($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('Invalid article', true), array('action' => 'index'))") !== false);
$this->assertTrue(strpos($result, "\$this->set('article', \$this->Article->read(null, \$id)") !== false);
$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.', true), array('action' => 'index'))") !== false);
$this->assertTrue(strpos($result, 'function edit($id = null)') !== false);
$this->assertTrue(strpos($result, "\$this->Article->Tag->find('list')") !== false);
$this->assertTrue(strpos($result, "\$this->set(compact('tags'))") !== false);
$this->assertTrue(strpos($result, 'function delete($id = null)') !== false);
$this->assertTrue(strpos($result, 'if ($this->Article->delete($id))') !== false);
$this->assertTrue(strpos($result, "\$this->flash(__('Article deleted', true), array('action' => 'index'))") !== false);
}
/**
* test baking a test
*
* @return void
* @access public
*/
function testBakeTest() {
$this->Task->plugin = 'ControllerTest';
$this->Task->connection = 'test_suite';
$this->Task->interactive = false;
$this->Task->Test->expectOnce('bake', array('Controller', 'Articles'));
$this->Task->bakeTest('Articles');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Test->connection);
$this->assertEqual($this->Task->interactive, $this->Task->Test->interactive);
}
/**
* test Interactive mode.
*
* @return void
* @access 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->execute();
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
}
/**
* test Interactive mode.
*
* @return void
* @access public
*/
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_');
$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/')));
}
/**
* test that execute runs all when the first arg == all
*
* @return void
* @access public
*/
function testExecuteIntoAll() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute into all could not be run as an Article, Tag or Comment model was already loaded. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$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);
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticlesController/')));
$this->Task->execute();
}
/**
* test that `cake bake controller foos` works.
*
* @return void
* @access public
*/
function testExecuteWithController() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new PatternExpectation('/\$scaffold/')
));
$this->Task->execute();
}
/**
* test that both plural and singular forms work for controller baking.
*
* @return void
* @access public
*/
function testExecuteWithControllerNameVariations() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles');
$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->execute();
}
/**
* test that `cake bake controller foo scaffold` works.
*
* @return void
* @access public
*/
function testExecuteWithPublicParam() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('Articles', 'public');
$filename = '/my/path/articles_controller.php';
$this->Task->expectAt(0, 'createFile', array(
$filename, new NoPatternExpectation('/var \$scaffold/')
));
$this->Task->execute();
}
/**
* test that `cake bake controller foos both` works.
*
* @return void
* @access public
*/
function testExecuteWithControllerAndBoth() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->Project->setReturnValue('getPrefix', '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->execute();
}
/**
* test that `cake bake controller foos admin` works.
*
* @return void
* @access public
*/
function testExecuteWithControllerAndAdmin() {
$skip = $this->skipIf(!defined('ARTICLE_MODEL_CREATED'),
'Execute with scaffold param requires no Article, Tag or Comment model to be defined. %s');
if ($skip) {
return;
}
$this->Task->Project->setReturnValue('getPrefix', '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->execute();
}
}

View File

@@ -0,0 +1,155 @@
<?php
/**
* DBConfigTask Test Case
*
* PHP versions 4 and 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.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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 {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'database_name',
'prefix' => '',
);
var $otherOne = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'login' => 'user',
'password' => 'password',
'database' => 'other_one',
'prefix' => '',
);
}
/**
* DbConfigTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class DbConfigTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestDbConfigTaskMockShellDispatcher();
$this->Task =& new MockDbConfigTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->params['working'] = rtrim(APP, DS);
$this->Task->databaseClassName = 'TEST_DATABASE_CONFIG';
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* Test the getConfig method.
*
* @return void
* @access public
*/
function testGetConfig() {
$this->Task->setReturnValueAt(0, 'in', 'otherOne');
$result = $this->Task->getConfig();
$this->assertEqual($result, 'otherOne');
}
/**
* test that initialize sets the path up.
*
* @return void
* @access public
*/
function testInitialize() {
$this->assertTrue(empty($this->Task->path));
$this->Task->initialize();
$this->assertFalse(empty($this->Task->path));
$this->assertEqual($this->Task->path, APP . 'config' . DS);
}
/**
* test execute and by extension __interactive
*
* @return void
* @access public
*/
function testExecuteIntoInteractive() {
$this->Task->initialize();
$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');
$result = $this->Task->execute();
}
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* ExtractTaskTest file
*
* Test Case for i18n extraction shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Folder');
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'extract.php';
Mock::generatePartial(
'ShellDispatcher', 'TestExtractTaskMockShellDispatcher',
array('getInput', 'stdout', 'stderr', '_stop', '_initEnvironment')
);
/**
* ExtractTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ExtractTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function setUp() {
$this->Dispatcher =& new TestExtractTaskMockShellDispatcher();
$this->Task =& new ExtractTask($this->Dispatcher);
}
/**
* tearDown method
*
* @return void
* @access public
*/
function tearDown() {
ClassRegistry::flush();
}
/**
* testExecute method
*
* @return void
* @access public
*/
function testExecute() {
$path = TMP . 'tests' . DS . 'extract_task_test';
new Folder($path . DS . 'locale', true);
$this->Task->interactive = false;
$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->Task->execute();
$this->assertTrue(file_exists($path . DS . 'default.pot'));
$result = file_get_contents($path . DS . 'default.pot');
$pattern = '/"Content-Type\: text\/plain; charset\=utf-8/';
$this->assertPattern($pattern, $result);
$pattern = '/"Content-Transfer-Encoding\: 8bit/';
$this->assertPattern($pattern, $result);
$pattern = '/"Plural-Forms\: nplurals\=INTEGER; plural\=EXPRESSION;/';
$this->assertPattern($pattern, $result);
// home.ctp
$pattern = '/msgid "Your tmp directory is writable."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Your tmp directory is NOT writable."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "The %s is being used for caching. To change the config edit ';
$pattern .= 'APP\/config\/core.php "\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Your cache is NOT working. Please check ';
$pattern .= 'the settings in APP\/config\/core.php"\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Your database configuration file is present."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Your database configuration file is NOT present."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Rename config\/database.php.default to ';
$pattern .= 'config\/database.php"\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Cake is able to connect to the database."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Cake is NOT able to connect to the database."\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "Editing this Page"\nmsgstr ""\n/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "To change the content of this page, edit: %s.*To change its layout, ';
$pattern .= 'edit: %s.*You can also add some CSS styles for your pages at: %s"\nmsgstr ""/s';
$this->assertPattern($pattern, $result);
// extract.ctp
$pattern = '/\#: (\\\\|\/)extract\.ctp:6\n';
$pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/';
$this->assertPattern($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:7\n';
$pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/';
$this->assertPattern($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:14\n';
$pattern .= '\#: (\\\\|\/)home\.ctp:74\n';
$pattern .= 'msgid "Editing this Page"\nmsgstr ""/';
$this->assertPattern($pattern, $result);
// extract.ctp - reading the domain.pot
$result = file_get_contents($path . DS . 'domain.pot');
$pattern = '/msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/';
$this->assertNoPattern($pattern, $result);
$pattern = '/msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/';
$this->assertNoPattern($pattern, $result);
$pattern = '/msgid "You have %d new message \(domain\)."\nmsgid_plural "You have %d new messages \(domain\)."/';
$this->assertPattern($pattern, $result);
$pattern = '/msgid "You deleted %d message \(domain\)."\nmsgid_plural "You deleted %d messages \(domain\)."/';
$this->assertPattern($pattern, $result);
$Folder = new Folder($path);
$Folder->delete();
}
function getTests() {
return array('start', 'startCase', 'testExtractMultiplePaths', 'endCase', 'end');
}
/**
* test extract can read more than one path.
*
* @return void
*/
function testExtractMultiplePaths() {
$path = TMP . 'tests' . DS . 'extract_task_test';
new Folder($path . DS . 'locale', true);
$this->Task->interactive = false;
$this->Task->params['paths'] =
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'pages,' .
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'posts';
$this->Task->params['output'] = $path . DS;
$this->Task->Dispatch->expectNever('stderr');
$this->Task->Dispatch->expectNever('_stop');
$this->Task->execute();
$result = file_get_contents($path . DS . 'default.pot');
$pattern = '/msgid "Add User"/';
$this->assertPattern($pattern, $result);
}
}

View File

@@ -0,0 +1,353 @@
<?php
/**
* FixtureTask Test case
*
* PHP versions 4 and 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.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class FixtureTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.datatype', 'core.binary_test');
/**
* startTest method
*
* @return void
* @access 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->Task->Dispatch->shellPaths = App::path('shells');
$this->Task->Template->initialize();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test that initialize sets the path
*
* @return void
* @access public
*/
function testConstruct() {
$this->Dispatch->params['working'] = DS . 'my' . DS . 'path';
$Task =& new FixtureTask($this->Dispatch);
$expected = DS . 'my' . DS . 'path' . DS . 'tests' . DS . 'fixtures' . DS;
$this->assertEqual($Task->path, $expected);
}
/**
* test import option array generation
*
* @return void
* @access public
*/
function testImportOptions() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', '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');
$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');
$result = $this->Task->importOptions('Article');
$expected = array('fromTable' => true);
$this->assertEqual($result, $expected);
}
/**
* test generating a fixture with database conditions.
*
* @return void
* @access public
*/
function testImportRecordsFromDatabaseWithConditions() {
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '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));
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$records/', $result);
$this->assertPattern('/var \$import/', $result);
$this->assertPattern("/'title' => 'First Article'/", $result, 'Missing import data %s');
$this->assertPattern('/Second Article/', $result, 'Missing import data %s');
$this->assertPattern('/Third Article/', $result, 'Missing import data %s');
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
* @access public
*/
function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite';
$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->execute();
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
* @access public
*/
function testExecuteWithNamedModelVariations() {
$this->Task->connection = 'test_suite';
$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->execute();
$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();
}
/**
* test that execute runs all() when args[0] = all
*
* @return void
* @access public
*/
function testExecuteIntoAll() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->Model->setReturnValue('listAll', array('articles', 'comments'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
$filename = '/my/path/comment_fixture.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class CommentFixture/')));
$this->Task->execute();
}
/**
* test using all() with -count and -records
*
* @return void
* @access public
*/
function testAllWithCountAndRecordsFlags() {
$this->Task->connection = 'test_suite';
$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'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/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->all();
}
/**
* test interactive mode of execute
*
* @return void
* @access public
*/
function testExecuteInteractive() {
$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'));
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class ArticleFixture/')));
$this->Task->execute();
}
/**
* Test that bake works
*
* @return void
* @access public
*/
function testBake() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article');
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$fields/', $result);
$this->assertPattern('/var \$records/', $result);
$this->assertNoPattern('/var \$import/', $result);
$result = $this->Task->bake('Article', 'comments');
$this->assertPattern('/class ArticleFixture extends CakeTestFixture/', $result);
$this->assertPattern('/var \$name \= \'Article\';/', $result);
$this->assertPattern('/var \$table \= \'comments\';/', $result);
$this->assertPattern('/var \$fields = array\(/', $result);
$result = $this->Task->bake('Article', 'comments', array('records' => true));
$this->assertPattern("/var \\\$import \= array\('records' \=\> true\);/", $result);
$this->assertNoPattern('/var \$records/', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article'));
$this->assertPattern("/var \\\$import \= array\('model' \=\> 'Article'\);/", $result);
$this->assertNoPattern('/var \$fields/', $result);
$result = $this->Task->bake('Article', 'comments', array('schema' => 'Article', 'records' => true));
$this->assertPattern("/var \\\$import \= array\('model' \=\> 'Article'\, 'records' \=\> true\);/", $result);
$this->assertNoPattern('/var \$fields/', $result);
$this->assertNoPattern('/var \$records/', $result);
}
/**
* test record generation with float and binary types
*
* @return void
* @access public
*/
function testRecordGenerationForBinaryAndFloat() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$result = $this->Task->bake('Article', 'datatypes');
$this->assertPattern("/'float_field' => 1/", $result);
$result = $this->Task->bake('Article', 'binary_tests');
$this->assertPattern("/'data' => 'Lorem ipsum dolor sit amet'/", $result);
}
/**
* Test that file generation includes headers and correct path for plugins.
*
* @return void
* @access public
*/
function testGenerateFixtureFile() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$filename = '/my/path/article_fixture.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/Article/')));
$result = $this->Task->generateFixtureFile('Article', array());
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/\<\?php(.*)\?\>/ms')));
$result = $this->Task->generateFixtureFile('Article', array());
}
/**
* test generating files into plugins.
*
* @return void
* @access public
*/
function testGeneratePluginFixtureFile() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$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/')));
$result = $this->Task->generateFixtureFile('Article', array());
}
}

View File

@@ -0,0 +1,909 @@
<?php
/**
* ModelTaskTest file
*
* Test Case for test generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.6
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ModelTaskTest extends CakeTestCase {
/**
* fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag', 'core.category_thread');
/**
* starTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestModelTaskMockShellDispatcher();
$this->Task =& new MockModelTask($this->Dispatcher);
$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();
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* Test that listAll scans the database connection and lists all the tables in it.s
*
* @return void
* @access 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'));
$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');
$this->assertEqual($result, $expected);
}
/**
* Test that getName interacts with the user and returns the model name.
*
* @return void
* @access public
*/
function testGetName() {
$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 = 'Article';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(2, 'in', 4);
$result = $this->Task->getName('test_suite');
$expected = 'Comment';
$this->assertEqual($result, $expected);
$this->Task->setReturnValueAt(3, 'in', 10);
$result = $this->Task->getName('test_suite');
$this->Task->expectOnce('err');
}
/**
* Test table name interactions
*
* @return void
* @access public
*/
function testGetTableName() {
$this->Task->setReturnValueAt(0, 'in', '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');
$result = $this->Task->getTable('Article', 'test_suite');
$expected = 'my_table';
$this->assertEqual($result, $expected);
}
/**
* test that initializing the validations works.
*
* @return void
* @access public
*/
function testInitValidations() {
$result = $this->Task->initValidations();
$this->assertTrue(in_array('notempty', $result));
}
/**
* test that individual field validation works, with interactive = false
* tests the guessing features of validation
*
* @return void
* @access public
*/
function testFieldValidationGuessing() {
$this->Task->interactive = false;
$this->Task->initValidations();
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
$result = $this->Task->fieldValidation('text', array('type' => 'date', 'length' => 10, 'null' => false));
$expected = array('date' => 'date');
$result = $this->Task->fieldValidation('text', array('type' => 'time', 'length' => 10, 'null' => false));
$expected = array('time' => 'time');
$result = $this->Task->fieldValidation('email', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('email' => 'email');
$result = $this->Task->fieldValidation('test', array('type' => 'integer', 'length' => 10, 'null' => false));
$expected = array('numeric' => 'numeric');
$result = $this->Task->fieldValidation('test', array('type' => 'boolean', 'length' => 10, 'null' => false));
$expected = array('numeric' => 'numeric');
}
/**
* test that interactive field validation works and returns multiple validators.
*
* @return void
* @access public
*/
function testInteractiveFieldValidation() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '19');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', '15');
$this->Task->setReturnValueAt(3, 'in', 'n');
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty', 'maxlength' => 'maxlength');
$this->assertEqual($result, $expected);
}
/**
* test that a bogus response doesn't cause errors to bubble up.
*
* @return void
*/
function testInteractiveFieldValidationWithBogusResponse() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '999999');
$this->Task->setReturnValueAt(1, 'in', '19');
$this->Task->setReturnValueAt(2, 'in', 'n');
$this->Task->expectAt(4, 'out', array(new PatternExpectation('/make a valid/')));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
$this->assertEqual($result, $expected);
}
/**
* test that a regular expression can be used for validation.
*
* @return void
*/
function testInteractiveFieldValidationWithRegexp() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->setReturnValueAt(0, 'in', '/^[a-z]{0,9}$/');
$this->Task->setReturnValueAt(1, 'in', 'n');
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('a_z_0_9' => '/^[a-z]{0,9}$/');
$this->assertEqual($result, $expected);
}
/**
* test the validation Generation routine
*
* @return void
* @access public
*/
function testNonInteractiveDoValidation() {
$Model =& new MockModelTaskModel();
$Model->primaryKey = 'id';
$Model->setReturnValue('schema', array(
'id' => array(
'type' => 'integer',
'length' => 11,
'null' => false,
'key' => 'primary',
),
'name' => array(
'type' => 'string',
'length' => 20,
'null' => false,
),
'email' => array(
'type' => 'string',
'length' => 255,
'null' => false,
),
'some_date' => array(
'type' => 'date',
'length' => '',
'null' => false,
),
'some_time' => array(
'type' => 'time',
'length' => '',
'null' => false,
),
'created' => array(
'type' => 'datetime',
'length' => '',
'null' => false,
)
));
$this->Task->interactive = false;
$result = $this->Task->doValidation($Model);
$expected = array(
'name' => array(
'notempty' => 'notempty'
),
'email' => array(
'email' => 'email',
),
'some_date' => array(
'date' => 'date'
),
'some_time' => array(
'time' => 'time'
),
);
$this->assertEqual($result, $expected);
}
/**
* test that finding primary key works
*
* @return void
* @access public
*/
function testFindPrimaryKey() {
$fields = array(
'one' => array(),
'two' => array(),
'key' => array('key' => 'primary')
);
$this->Task->expectAt(0, 'in', array('*', null, 'key'));
$this->Task->setReturnValue('in', 'my_field');
$result = $this->Task->findPrimaryKey($fields);
$expected = 'my_field';
$this->assertEqual($result, $expected);
}
/**
* test finding Display field
*
* @return void
* @access 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');
$result = $this->Task->findDisplayField($fields);
$this->assertFalse($result);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->setReturnValueAt(2, 'in', 2);
$result = $this->Task->findDisplayField($fields);
$this->assertEqual($result, 'tagname');
}
/**
* test that belongsTo generation works.
*
* @return void
* @access public
*/
function testBelongsToGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Comment'));
$result = $this->Task->findBelongsTo($model, array());
$expected = array(
'belongsTo' => array(
array(
'alias' => 'Article',
'className' => 'Article',
'foreignKey' => 'article_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
)
);
$this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findBelongsTo($model, array());
$expected = array(
'belongsTo' => array(
array(
'alias' => 'ParentCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
)
);
$this->assertEqual($result, $expected);
}
/**
* test that hasOne and/or hasMany relations are generated properly.
*
* @return void
* @access public
*/
function testHasManyHasOneGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite';
$this->Task->listAll();
$result = $this->Task->findHasOneAndMany($model, array());
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
'hasOne' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
);
$this->assertEqual($result, $expected);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$result = $this->Task->findHasOneAndMany($model, array());
$expected = array(
'hasOne' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'hasMany' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
)
);
$this->assertEqual($result, $expected);
}
/**
* Test that HABTM generation works
*
* @return void
* @access public
*/
function testHasAndBelongsToManyGeneration() {
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$this->Task->connection = 'test_suite';
$this->Task->listAll();
$result = $this->Task->findHasAndBelongsToMany($model, array());
$expected = array(
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
),
);
$this->assertEqual($result, $expected);
}
/**
* test non interactive doAssociations
*
* @return void
* @access public
*/
function testDoAssociationsNonInteractive() {
$this->Task->connection = 'test_suite';
$this->Task->interactive = false;
$model = new Model(array('ds' => 'test_suite', 'name' => 'Article'));
$result = $this->Task->doAssociations($model);
$expected = array(
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'article_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
),
);
}
/**
* Ensure that the fixutre object is correctly called.
*
* @return void
* @access public
*/
function testBakeFixture() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Fixture->expectAt(0, 'bake', array('Article', 'articles'));
$this->Task->bakeFixture('Article', 'articles');
$this->assertEqual($this->Task->plugin, $this->Task->Fixture->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Fixture->connection);
$this->assertEqual($this->Task->interactive, $this->Task->Fixture->interactive);
}
/**
* Ensure that the test object is correctly called.
*
* @return void
* @access public
*/
function testBakeTest() {
$this->Task->plugin = 'test_plugin';
$this->Task->interactive = true;
$this->Task->Test->expectAt(0, 'bake', array('Model', 'Article'));
$this->Task->bakeTest('Article');
$this->assertEqual($this->Task->plugin, $this->Task->Test->plugin);
$this->assertEqual($this->Task->connection, $this->Task->Test->connection);
$this->assertEqual($this->Task->interactive, $this->Task->Test->interactive);
}
/**
* test confirming of associations, and that when an association is hasMany
* a question for the hasOne is also not asked.
*
* @return void
* @access public
*/
function testConfirmAssociations() {
$associations = array(
'hasOne' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'hasMany' => array(
array(
'alias' => 'ChildCategoryThread',
'className' => 'CategoryThread',
'foreignKey' => 'parent_id',
),
),
'belongsTo' => array(
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
)
);
$model = new Model(array('ds' => 'test_suite', 'name' => 'CategoryThread'));
$this->Task->setReturnValueAt(0, 'in', 'y');
$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']));
}
/**
* test that inOptions generates questions and only accepts a valid answer
*
* @return void
* @access 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->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);
$result = $this->Task->inOptions($options, 'Pick a number');
$this->assertEqual($result, 1);
}
/**
* test baking validation
*
* @return void
* @access public
*/
function testBakeValidation() {
$validate = array(
'name' => array(
'notempty' => 'notempty'
),
'email' => array(
'email' => 'email',
),
'some_date' => array(
'date' => 'date'
),
'some_time' => array(
'time' => 'time'
)
);
$result = $this->Task->bake('Article', compact('validate'));
$this->assertPattern('/class Article extends AppModel \{/', $result);
$this->assertPattern('/\$name \= \'Article\'/', $result);
$this->assertPattern('/\$validate \= array\(/', $result);
$expected = <<< STRINGEND
array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
STRINGEND;
$this->assertPattern('/' . preg_quote(str_replace("\r\n", "\n", $expected), '/') . '/', $result);
}
/**
* test baking relations
*
* @return void
* @access public
*/
function testBakeRelations() {
$associations = array(
'belongsTo' => array(
array(
'alias' => 'SomethingElse',
'className' => 'SomethingElse',
'foreignKey' => 'something_else_id',
),
array(
'alias' => 'User',
'className' => 'User',
'foreignKey' => 'user_id',
),
),
'hasOne' => array(
array(
'alias' => 'OtherModel',
'className' => 'OtherModel',
'foreignKey' => 'other_model_id',
),
),
'hasMany' => array(
array(
'alias' => 'Comment',
'className' => 'Comment',
'foreignKey' => 'parent_id',
),
),
'hasAndBelongsToMany' => array(
array(
'alias' => 'Tag',
'className' => 'Tag',
'foreignKey' => 'article_id',
'joinTable' => 'articles_tags',
'associationForeignKey' => 'tag_id',
),
)
);
$result = $this->Task->bake('Article', compact('associations'));
$this->assertPattern('/\$hasAndBelongsToMany \= array\(/', $result);
$this->assertPattern('/\$hasMany \= array\(/', $result);
$this->assertPattern('/\$belongsTo \= array\(/', $result);
$this->assertPattern('/\$hasOne \= array\(/', $result);
$this->assertPattern('/Tag/', $result);
$this->assertPattern('/OtherModel/', $result);
$this->assertPattern('/SomethingElse/', $result);
$this->assertPattern('/Comment/', $result);
}
/**
* test bake() with a -plugin param
*
* @return void
* @access 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->bake('Article', array(), array());
$this->assertEqual(count(ClassRegistry::keys()), 0);
$this->assertEqual(count(ClassRegistry::mapKeys()), 0);
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
* @access public
*/
function testExecuteWithNamedModel() {
$this->Task->connection = 'test_suite';
$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->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
$this->assertEqual(count(ClassRegistry::mapKeys()), 0);
}
/**
* test that execute passes with different inflections of the same name.
*
* @return void
* @access public
*/
function testExecuteWithNamedModelVariations() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->setReturnValue('_checkUnitTest', 1);
$this->Task->args = array('article');
$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->execute();
}
/**
* test that execute with a model name picks up hasMany associations.
*
* @return void
* @access public
*/
function testExecuteWithNamedModelHasManyCreated() {
$this->Task->connection = 'test_suite';
$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->execute();
}
/**
* test that execute runs all() when args[0] = all
*
* @return void
* @access public
*/
function testExecuteIntoAll() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->Fixture->expectCallCount('bake', 5);
$this->Task->Test->expectCallCount('bake', 5);
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$filename = '/my/path/articles_tag.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticlesTag/')));
$filename = '/my/path/category_thread.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class CategoryThread/')));
$filename = '/my/path/comment.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class Comment/')));
$filename = '/my/path/tag.php';
$this->Task->expectAt(4, 'createFile', array($filename, new PatternExpectation('/class Tag/')));
$this->Task->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
$this->assertEqual(count(ClassRegistry::mapKeys()), 0);
}
/**
* test that skipTables changes how all() works.
*
* @return void
*/
function testSkipTablesAndAll() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->setReturnValue('_checkUnitTest', true);
$this->Task->skipTables = array('tags');
$this->Task->Fixture->expectCallCount('bake', 4);
$this->Task->Test->expectCallCount('bake', 4);
$filename = '/my/path/article.php';
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$filename = '/my/path/articles_tag.php';
$this->Task->expectAt(1, 'createFile', array($filename, new PatternExpectation('/class ArticlesTag/')));
$filename = '/my/path/category_thread.php';
$this->Task->expectAt(2, 'createFile', array($filename, new PatternExpectation('/class CategoryThread/')));
$filename = '/my/path/comment.php';
$this->Task->expectAt(3, 'createFile', array($filename, new PatternExpectation('/class Comment/')));
$this->Task->execute();
}
/**
* test the interactive side of bake.
*
* @return void
* @access public
*/
function testExecuteIntoInteractive() {
$this->Task->connection = 'test_suite';
$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->Test->expectOnce('bake');
$this->Task->Fixture->expectOnce('bake');
$filename = '/my/path/article.php';
$this->Task->expectOnce('createFile');
$this->Task->expectAt(0, 'createFile', array($filename, new PatternExpectation('/class Article/')));
$this->Task->execute();
$this->assertEqual(count(ClassRegistry::keys()), 0);
$this->assertEqual(count(ClassRegistry::mapKeys()), 0);
}
/**
* test using bake interactively with a table that does not exist.
*
* @return void
* @access public
*/
function testExecuteWithNonExistantTableName() {
$this->Task->connection = 'test_suite';
$this->Task->path = '/my/path/';
$this->Task->expectOnce('_stop');
$this->Task->expectOnce('err');
$this->Task->setReturnValueAt(0, 'in', 'Foobar');
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->execute();
}
}

View File

@@ -0,0 +1,263 @@
<?php
/**
* PluginTask Test file
*
* Test Case for plugin generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.3.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class PluginTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access 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->Task->path = TMP . 'tests' . DS;
}
/**
* startCase methods
*
* @return void
* @access public
*/
function startCase() {
$this->_paths = $paths = App::path('plugins');
$this->_testPath = array_push($paths, TMP . 'tests' . DS);
App::build(array('plugins' => $paths));
}
/**
* endCase
*
* @return void
* @access public
*/
function endCase() {
App::build(array('plugins' => $this->_paths));
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test bake()
*
* @return void
* @access public
*/
function testBakeFoldersAndFiles() {
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$this->Task->bake('BakeTestPlugin');
$path = $this->Task->path . 'bake_test_plugin';
$this->assertTrue(is_dir($path), 'No plugin dir %s');
$this->assertTrue(is_dir($path . DS . 'config'), 'No config dir %s');
$this->assertTrue(is_dir($path . DS . 'config' . DS . 'schema'), 'No schema dir %s');
$this->assertTrue(file_exists($path . DS . 'config' . DS . 'schema' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(file_exists($path . DS . 'controllers' . DS . 'components' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(file_exists($path . DS . 'models' . DS . 'behaviors' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'models' . DS . 'datasources'), 'No datasources dir %s');
$this->assertTrue(file_exists($path . DS . 'models' . DS . 'datasources' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(file_exists($path . DS . 'views' . DS . 'helpers' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(
is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'components'), 'No components cases dir %s'
);
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'components' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors'), 'No behaviors cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'helpers'), 'No helpers cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'models'), 'No models cases dir %s');
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(
is_dir($path . DS . 'tests' . DS . 'cases' . DS . 'controllers'),
'No controllers cases dir %s'
);
$this->assertTrue(
file_exists($path . DS . 'tests' . DS . 'cases' . DS . 'controllers' . DS . 'empty'), 'No empty file %s'
);
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(file_exists($path . DS . 'tests' . DS . 'groups' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
$this->assertTrue(file_exists($path . DS . 'tests' . DS . 'fixtures' . DS . 'empty'), 'No empty file %s');
$this->assertTrue(is_dir($path . DS . 'vendors'), 'No vendors dir %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'shells'), 'No vendors shells dir %s');
$this->assertTrue(is_dir($path . DS . 'vendors' . DS . 'shells' . DS . 'tasks'), 'No vendors shells tasks dir %s');
$this->assertTrue(file_exists($path . DS . 'vendors' . DS . 'shells' . DS . 'tasks' . DS . 'empty'), 'No empty file %s');
$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->delete();
}
/**
* test execute with no args, flowing into interactive,
*
* @return void
* @access 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');
$path = $this->Task->path . 'test_plugin';
$file = $path . DS . 'test_plugin_app_controller.php';
$this->Task->expectAt(0, 'createFile', array($file, '*'), 'No AppController %s');
$file = $path . DS . 'test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->args = array();
$this->Task->execute();
$Folder =& new Folder($path);
$Folder->delete();
}
/**
* Test Execute
*
* @return void
* @access 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;
$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');
$file = $path . DS . 'bake_test_plugin_app_model.php';
$this->Task->expectAt(1, 'createFile', array($file, '*'), 'No AppModel %s');
$this->Task->execute();
$Folder =& new Folder($this->Task->path . 'bake_test_plugin');
$Folder->delete();
}
/**
* test execute chaining into MVC parts
*
* @return void
* @access public
*/
function testExecuteWithTwoArgs() {
$this->Task->Model =& new PluginTestMockModelTask();
$this->Task->setReturnValueAt(0, 'in', $this->_testPath);
$this->Task->setReturnValueAt(1, 'in', 'y');
$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->Model->expectOnce('loadTasks');
$this->Task->Model->expectOnce('execute');
$this->Task->execute();
$Folder->delete();
}
}

View File

@@ -0,0 +1,301 @@
<?php
/**
* ProjectTask Test file
*
* Test Case for project generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.3.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ProjectTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestProjectTaskMockShellDispatcher();
$this->Dispatcher->shellPaths = App::path('shells');
$this->Task =& new MockProjectTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->path = TMP . 'tests' . DS;
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
$Folder =& new Folder($this->Task->path . 'bake_test_app');
$Folder->delete();
}
/**
* creates a test project that is used for testing project task.
*
* @return void
* @access 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->bake($this->Task->path . 'bake_test_app', $skel);
}
/**
* test bake() method and directory creation.
*
* @return void
* @access public
*/
function testBake() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
}
/**
* test bake() method with -empty flag, directory creation and empty files.
*
* @return void
* @access public
*/
function testBakeEmptyFlag() {
$this->Task->params['empty'] = true;
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app';
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
$this->assertTrue(is_file($path . DS . 'controllers' . DS .'components' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'locale' . DS . 'eng' . DS . 'LC_MESSAGES' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'models' . DS . 'behaviors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'models' . DS . 'datasources' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'plugins' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'behaviors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'components' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'controllers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'datasources' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'helpers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'cases' . DS . 'shells' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'fixtures' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'tests' . DS . 'groups' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'vendors' . DS . 'shells' . DS . 'tasks' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'errors' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'helpers' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'views' . DS . 'scaffolds' . DS . 'empty'), 'No empty file in dir %s');
$this->assertTrue(is_file($path . DS . 'webroot' . DS . 'js' . DS . 'empty'), 'No empty file in dir %s');
}
/**
* test generation of Security.salt
*
* @return void
* @access public
*/
function testSecuritySaltGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->securitySalt($path);
$this->assertTrue($result);
$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
* @access public
*/
function testSecurityCipherSeedGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->securityCipherSeed($path);
$this->assertTrue($result);
$file =& new File($path . 'config' . DS . 'core.php');
$contents = $file->read();
$this->assertNoPattern('/76859309657453542496749683645/', $contents, 'Default CipherSeed left behind. %s');
}
/**
* Test that index.php is generated correctly.
*
* @return void
* @access public
*/
function testIndexPhpGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$this->Task->corePath($path);
$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');
$contents = $file->read();
$this->assertNoPattern('/define\(\'CAKE_CORE_INCLUDE_PATH\', \'ROOT/', $contents);
}
/**
* test getPrefix method, and that it returns Routing.prefix or writes to config file.
*
* @return void
* @access public
*/
function testGetPrefix() {
Configure::write('Routing.prefixes', array('admin'));
$result = $this->Task->getPrefix();
$this->assertEqual($result, 'admin_');
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');
$result = $this->Task->getPrefix();
$this->assertEqual($result, 'super_duper_admin_');
$file =& new File($this->Task->configPath . 'core.php');
$file->delete();
}
/**
* test cakeAdmin() writing core.php
*
* @return void
* @access public
*/
function testCakeAdmin() {
$file =& new File(CONFIGS . 'core.php');
$contents = $file->read();;
$file =& new File(TMP . 'tests' . DS . 'core.php');
$file->write($contents);
Configure::write('Routing.prefixes', null);
$this->Task->configPath = TMP . 'tests' . DS;
$result = $this->Task->cakeAdmin('my_prefix');
$this->assertTrue($result);
$this->assertEqual(Configure::read('Routing.prefixes'), array('my_prefix'));
$file->delete();
}
/**
* test getting the prefix with more than one prefix setup
*
* @return void
* @access public
*/
function testGetPrefixWithMultiplePrefixes() {
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);
$result = $this->Task->getPrefix();
$this->assertEqual($result, 'ninja_');
}
/**
* Test execute method with one param to destination folder.
*
* @return void
* @access public
*/
function testExecute() {
$this->Task->params['skel'] = CAKE_CORE_INCLUDE_PATH . DS . CAKE . DS . 'console' . DS. 'templates' . DS . 'skel';
$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->execute();
$this->assertTrue(is_dir($path), 'No project dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers'), 'No controllers dir %s');
$this->assertTrue(is_dir($path . DS . 'controllers' . DS .'components'), 'No components dir %s');
$this->assertTrue(is_dir($path . DS . 'models'), 'No models dir %s');
$this->assertTrue(is_dir($path . DS . 'views'), 'No views dir %s');
$this->assertTrue(is_dir($path . DS . 'views' . DS . 'helpers'), 'No helpers dir %s');
$this->assertTrue(is_dir($path . DS . 'tests'), 'No tests dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'cases'), 'No cases dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'groups'), 'No groups dir %s');
$this->assertTrue(is_dir($path . DS . 'tests' . DS . 'fixtures'), 'No fixtures dir %s');
}
}

View File

@@ -0,0 +1,189 @@
<?php
/**
* TemplateTask file
*
* Test Case for TemplateTask generation shell task
*
*
* PHP versions 4 and 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.console.libs.tasks
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TemplateTaskTest extends CakeTestCase {
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestTemplateTaskMockShellDispatcher();
$this->Task =& new MockTemplateTask($this->Dispatcher);
$this->Task->Dispatch =& $this->Dispatcher;
$this->Task->Dispatch->shellPaths = App::path('shells');
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
unset($this->Task, $this->Dispatcher);
ClassRegistry::flush();
}
/**
* test that set sets variables
*
* @return void
* @access public
*/
function testSet() {
$this->Task->set('one', 'two');
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEqual($this->Task->templateVars['one'], 'two');
$this->Task->set(array('one' => 'three', 'four' => 'five'));
$this->assertTrue(isset($this->Task->templateVars['one']));
$this->assertEqual($this->Task->templateVars['one'], 'three');
$this->assertTrue(isset($this->Task->templateVars['four']));
$this->assertEqual($this->Task->templateVars['four'], 'five');
$this->Task->templateVars = array();
$this->Task->set(array(3 => 'three', 4 => 'four'));
$this->Task->set(array(1 => 'one', 2 => 'two'));
$expected = array(3 => 'three', 4 => 'four', 1 => 'one', 2 => 'two');
$this->assertEqual($this->Task->templateVars, $expected);
}
/**
* test finding themes installed in
*
* @return void
* @access public
*/
function testFindingInstalledThemesForBake() {
$consoleLibs = CAKE_CORE_INCLUDE_PATH . DS . CAKE . 'console' . DS;
$this->Task->Dispatch->shellPaths = array($consoleLibs);
$this->Task->initialize();
$this->assertEqual($this->Task->templatePaths, array('default' => $consoleLibs . 'templates' . DS . 'default' . DS));
}
/**
* test getting the correct theme name. Ensure that with only one theme, or a theme param
* that the user is not bugged. If there are more, find and return the correct theme name
*
* @return void
* @access 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);
$result = $this->Task->getThemePath();
$this->assertEqual($result, $defaultTheme);
$this->Task->templatePaths = array('default' => $defaultTheme, 'other' => '/some/path');
$this->Task->params['theme'] = 'other';
$result = $this->Task->getThemePath();
$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');
}
/**
* test generate
*
* @return void
* @access public
*/
function testGenerate() {
App::build(array(
'shells' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS
)
));
$this->Task->initialize();
$this->Task->setReturnValue('in', 1);
$result = $this->Task->generate('classes', 'test_object', array('test' => 'foo'));
$expected = "I got rendered\nfoo";
$this->assertEqual($result, $expected);
}
/**
* test generate with a missing template in the chosen theme.
* ensure fallback to default works.
*
* @return void
* @access public
*/
function testGenerateWithTemplateFallbacks() {
App::build(array(
'shells' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors' . DS . 'shells' . DS,
CAKE_CORE_INCLUDE_PATH . DS . 'console' . DS
)
));
$this->Task->initialize();
$this->Task->params['theme'] = 'test';
$this->Task->set(array(
'model' => 'Article',
'table' => 'articles',
'import' => false,
'records' => false,
'schema' => ''
));
$result = $this->Task->generate('classes', 'fixture');
$this->assertPattern('/ArticleFixture extends CakeTestFixture/', $result);
}
}

View File

@@ -0,0 +1,625 @@
<?php
/**
* TestTaskTest file
*
* Test Case for test generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
App::import('Controller', 'Controller', false);
App::import('Model', 'Model', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskArticle extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskArticle';
/**
* Table name to use
*
* @var string
* @access public
*/
var $useTable = 'articles';
/**
* HasMany Associations
*
* @var array
* @access public
*/
var $hasMany = array(
'Comment' => array(
'className' => 'TestTask.TestTaskComment',
'foreignKey' => 'article_id',
)
);
/**
* Has and Belongs To Many Associations
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'TestTaskTag',
'joinTable' => 'articles_tags',
'foreignKey' => 'article_id',
'associationForeignKey' => 'tag_id'
)
);
/**
* Example public method
*
* @return void
* @access public
*/
function doSomething() {
}
/**
* Example Secondary public method
*
* @return void
* @access public
*/
function doSomethingElse() {
}
/**
* Example protected method
*
* @return void
* @access protected
*/
function _innerMethod() {
}
}
/**
* Tag Testing Model
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskTag extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskTag';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'tags';
/**
* Has and Belongs To Many Associations
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array(
'Article' => array(
'className' => 'TestTaskArticle',
'joinTable' => 'articles_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'article_id'
)
);
}
/**
* Simulated plugin
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskAppModel extends Model {
}
/**
* Testing AppMode (TaskComment)
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskComment extends TestTaskAppModel {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'TestTaskComment';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
* @access public
*/
var $belongsTo = array(
'Article' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
);
}
/**
* Test Task Comments Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskCommentsController extends Controller {
/**
* Controller Name
*
* @var string
* @access public
*/
var $name = 'TestTaskComments';
/**
* Models to use
*
* @var array
* @access public
*/
var $uses = array('TestTaskComment', 'TestTaskTag');
}
/**
* TestTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class TestTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var string
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* startTest method
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestTestTaskMockShellDispatcher();
$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);
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
}
/**
* Test that file path generation doesn't continuously append paths.
*
* @return void
* @access public
*/
function testFilePathGeneration() {
$file = TESTS . 'cases' . DS . 'models' . DS . 'my_class.test.php';
$this->Task->Dispatch->expectNever('stderr');
$this->Task->Dispatch->expectNever('_stop');
$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');
$file = TESTS . 'cases' . DS . 'controllers' . DS . 'comments_controller.test.php';
$this->Task->expectAt(2, 'createFile', array($file, '*'));
$this->Task->bake('Controller', 'Comments');
}
/**
* Test that method introspection pulls all relevant non parent class
* methods into the test case.
*
* @return void
*/
function testMethodIntrospection() {
$result = $this->Task->getTestableMethods('TestTaskArticle');
$expected = array('dosomething', 'dosomethingelse');
$this->assertEqual(array_map('strtolower', $result), $expected);
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
* @access public
*/
function testFixtureArrayGenerationFromModel() {
$subject = ClassRegistry::init('TestTaskArticle');
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEqual(sort($result), sort($expected));
}
/**
* test that the generation of fixtures works correctly.
*
* @return void
* @access public
*/
function testFixtureArrayGenerationFromController() {
$subject = new TestTaskCommentsController();
$result = $this->Task->generateFixtureList($subject);
$expected = array('plugin.test_task.test_task_comment', 'app.articles_tags',
'app.test_task_article', 'app.test_task_tag');
$this->assertEqual(sort($result), sort($expected));
}
/**
* test user interaction to get object type
*
* @return void
* @access public
*/
function testGetObjectType() {
$this->Task->expectOnce('_stop');
$this->Task->setReturnValueAt(0, 'in', 'q');
$this->Task->getObjectType();
$this->Task->setReturnValueAt(1, 'in', 2);
$result = $this->Task->getObjectType();
$this->assertEqual($result, $this->Task->classTypes[1]);
}
/**
* creating test subjects should clear the registry so the registry is always fresh
*
* @return void
* @access public
*/
function testRegistryClearWhenBuildingTestObjects() {
ClassRegistry::flush();
$model = ClassRegistry::init('TestTaskComment');
$model->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'TestTaskArticle',
'foreignKey' => 'article_id',
)
)
));
$keys = ClassRegistry::keys();
$this->assertTrue(in_array('random', $keys));
$object =& $this->Task->buildTestSubject('Model', 'TestTaskComment');
$keys = ClassRegistry::keys();
$this->assertFalse(in_array('random', $keys));
}
/**
* test that getClassName returns the user choice as a classname.
*
* @return void
* @access public
*/
function testGetClassName() {
$objects = App::objects('model');
$skip = $this->skipIf(empty($objects), 'No models in app, this test will fail. %s');
if ($skip) {
return;
}
$this->Task->setReturnValueAt(0, 'in', 'MyCustomClass');
$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]);
}
/**
* Test the user interaction for defining additional fixtures.
*
* @return void
* @access public
*/
function testGetUserFixtures() {
$this->Task->setReturnValueAt(0, 'in', 'y');
$this->Task->setReturnValueAt(1, 'in', 'app.pizza, app.topping, app.side_dish');
$result = $this->Task->getUserFixtures();
$expected = array('app.pizza', 'app.topping', 'app.side_dish');
$this->assertEqual($result, $expected);
}
/**
* test that resolving classnames works
*
* @return void
* @access public
*/
function testGetRealClassname() {
$result = $this->Task->getRealClassname('Model', 'Post');
$this->assertEqual($result, 'Post');
$result = $this->Task->getRealClassname('Controller', 'Posts');
$this->assertEqual($result, 'PostsController');
$result = $this->Task->getRealClassname('Helper', 'Form');
$this->assertEqual($result, 'FormHelper');
$result = $this->Task->getRealClassname('Behavior', 'Containable');
$this->assertEqual($result, 'ContainableBehavior');
$result = $this->Task->getRealClassname('Component', 'Auth');
$this->assertEqual($result, 'AuthComponent');
}
/**
* test baking files. The conditionally run tests are known to fail in PHP4
* as PHP4 classnames are all lower case, breaking the plugin path inflection.
*
* @return void
* @access public
*/
function testBakeModelTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$result = $this->Task->bake('Model', 'TestTaskArticle');
$this->assertPattern('/App::import\(\'Model\', \'TestTaskArticle\'\)/', $result);
$this->assertPattern('/class TestTaskArticleTestCase extends CakeTestCase/', $result);
$this->assertPattern('/function startTest\(\)/', $result);
$this->assertPattern("/\\\$this->TestTaskArticle \=\& ClassRegistry::init\('TestTaskArticle'\)/", $result);
$this->assertPattern('/function endTest\(\)/', $result);
$this->assertPattern('/unset\(\$this->TestTaskArticle\)/', $result);
$this->assertPattern('/function testDoSomething\(\)/i', $result);
$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);
}
/**
* test baking controller test files, ensure that the stub class is generated.
* Conditional assertion is known to fail on PHP4 as classnames are all lower case
* causing issues with inflection of path name from classname.
*
* @return void
* @access public
*/
function testBakeControllerTest() {
$this->Task->setReturnValue('createFile', true);
$this->Task->setReturnValue('isLoadableClass', true);
$result = $this->Task->bake('Controller', 'TestTaskComments');
$this->assertPattern('/App::import\(\'Controller\', \'TestTaskComments\'\)/', $result);
$this->assertPattern('/class TestTaskCommentsControllerTestCase extends CakeTestCase/', $result);
$this->assertPattern('/class TestTestTaskCommentsController extends TestTaskCommentsController/', $result);
$this->assertPattern('/var \$autoRender = false/', $result);
$this->assertPattern('/function redirect\(\$url, \$status = null, \$exit = true\)/', $result);
$this->assertPattern('/function startTest\(\)/', $result);
$this->assertPattern("/\\\$this->TestTaskComments \=\& new TestTestTaskCommentsController\(\)/", $result);
$this->assertPattern("/\\\$this->TestTaskComments->constructClasses\(\)/", $result);
$this->assertPattern('/function endTest\(\)/', $result);
$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);
}
/**
* test Constructor generation ensure that constructClasses is called for controllers
*
* @return void
* @access public
*/
function testGenerateConstructor() {
$result = $this->Task->generateConstructor('controller', 'PostsController');
$expected = "new TestPostsController();\n\t\t\$this->Posts->constructClasses();\n";
$this->assertEqual($result, $expected);
$result = $this->Task->generateConstructor('model', 'Post');
$expected = "ClassRegistry::init('Post');\n";
$this->assertEqual($result, $expected);
$result = $this->Task->generateConstructor('helper', 'FormHelper');
$expected = "new FormHelper();\n";
$this->assertEqual($result, $expected);
}
/**
* Test that mock class generation works for the appropriate classes
*
* @return void
* @access public
*/
function testMockClassGeneration() {
$result = $this->Task->hasMockClass('controller');
$this->assertTrue($result);
}
/**
* test bake() with a -plugin param
*
* @return void
* @access public
*/
function testBakeWithPlugin() {
$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->bake('Helper', 'Form');
}
/**
* Test filename generation for each type + plugins
*
* @return void
* @access public
*/
function testTestCaseFileName() {
$this->Task->path = '/my/path/tests/';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = $this->Task->path . 'cases' . DS . 'models' . DS . 'post.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Helper', 'Form');
$expected = $this->Task->path . 'cases' . DS . 'helpers' . DS . 'form.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Controller', 'Posts');
$expected = $this->Task->path . 'cases' . DS . 'controllers' . DS . 'posts_controller.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Behavior', 'Containable');
$expected = $this->Task->path . 'cases' . DS . 'behaviors' . DS . 'containable.test.php';
$this->assertEqual($result, $expected);
$result = $this->Task->testCaseFileName('Component', 'Auth');
$expected = $this->Task->path . 'cases' . DS . 'components' . DS . 'auth.test.php';
$this->assertEqual($result, $expected);
$this->Task->plugin = 'TestTest';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = APP . 'plugins' . DS . 'test_test' . DS . 'tests' . DS . 'cases' . DS . 'models' . DS . 'post.test.php';
$this->assertEqual($result, $expected);
}
/**
* test execute with a type defined
*
* @return void
* @access 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->execute();
}
/**
* test execute with type and class name defined
*
* @return void
* @access 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->execute();
}
}

View File

@@ -0,0 +1,677 @@
<?php
/**
* ViewTask Test file
*
* Test Case for view generation shell task
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Shell', 'Shell', false);
if (!defined('DISABLE_AUTO_DISPATCH')) {
define('DISABLE_AUTO_DISPATCH', true);
}
if (!class_exists('ShellDispatcher')) {
ob_start();
$argv = false;
require CAKE . 'console' . DS . 'cake.php';
ob_end_clean();
}
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'view.php';
require_once CAKE . 'console' . DS . 'libs' . DS . 'tasks' . DS . 'controller.php';
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
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskComment extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'ViewTaskComment';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'comments';
/**
* Belongs To Associations
*
* @var array
* @access public
*/
var $belongsTo = array(
'Article' => array(
'className' => 'ViewTaskArticle',
'foreignKey' => 'article_id'
)
);
}
/**
* Test View Task Article Model
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskArticle extends Model {
/**
* Model name
*
* @var string
* @access public
*/
var $name = 'ViewTaskArticle';
/**
* Table name
*
* @var string
* @access public
*/
var $useTable = 'articles';
}
/**
* Test View Task Comments Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskCommentsController extends Controller {
/**
* Controller name
*
* @var string
* @access public
*/
var $name = 'ViewTaskComments';
/**
* Testing public controller action
*
* @return void
* @access public
*/
function index() {
}
/**
* Testing public controller action
*
* @return void
* @access public
*/
function add() {
}
}
/**
* Test View Task Articles Controller
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskArticlesController extends Controller {
/**
* Controller name
*
* @var string
* @access public
*/
var $name = 'ViewTaskArticles';
/**
* Test public controller action
*
* @return void
* @access public
*/
function index() {
}
/**
* Test public controller action
*
* @return void
* @access public
*/
function add() {
}
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_index() {
}
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_add() {
}
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_view() {
}
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_edit() {
}
/**
* Test admin prefixed controller action
*
* @return void
* @access public
*/
function admin_delete() {
}
}
/**
* ViewTaskTest class
*
* @package cake
* @subpackage cake.tests.cases.console.libs.tasks
*/
class ViewTaskTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.comment', 'core.articles_tag', 'core.tag');
/**
* startTest method
*
* Ensure that the default theme is used
*
* @return void
* @access public
*/
function startTest() {
$this->Dispatcher =& new TestViewTaskMockShellDispatcher();
$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';
$this->_routing = Configure::read('Routing');
}
/**
* endTest method
*
* @return void
* @access public
*/
function endTest() {
ClassRegistry::flush();
Configure::write('Routing', $this->_routing);
}
/**
* Test getContent and parsing of Templates.
*
* @return void
* @access public
*/
function testGetContent() {
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('view', $vars);
$this->assertPattern('/Delete Test View Model/', $result);
$this->assertPattern('/Edit Test View Model/', $result);
$this->assertPattern('/List Test View Models/', $result);
$this->assertPattern('/New Test View Model/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
}
/**
* test getContent() using an admin_prefixed action.
*
* @return void
* @access public
*/
function testGetContentWithAdminAction() {
$_back = Configure::read('Routing');
Configure::write('Routing.prefixes', array('admin'));
$vars = array(
'modelClass' => 'TestViewModel',
'schema' => array(),
'primaryKey' => 'id',
'displayField' => 'name',
'singularVar' => 'testViewModel',
'pluralVar' => 'testViewModels',
'singularHumanName' => 'Test View Model',
'pluralHumanName' => 'Test View Models',
'fields' => array('id', 'name', 'body'),
'associations' => array()
);
$result = $this->Task->getContent('admin_view', $vars);
$this->assertPattern('/Delete Test View Model/', $result);
$this->assertPattern('/Edit Test View Model/', $result);
$this->assertPattern('/List Test View Models/', $result);
$this->assertPattern('/New Test View Model/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'id\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'name\'\]/', $result);
$this->assertPattern('/testViewModel\[\'TestViewModel\'\]\[\'body\'\]/', $result);
$result = $this->Task->getContent('admin_add', $vars);
$this->assertPattern("/input\('name'\)/", $result);
$this->assertPattern("/input\('body'\)/", $result);
$this->assertPattern('/List Test View Models/', $result);
Configure::write('Routing', $_back);
}
/**
* test Bake method
*
* @return void
* @access public
*/
function testBake() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/View Task Articles/')
));
$this->Task->bake('view', true);
$this->Task->expectAt(1, 'createFile', array(TMP . 'view_task_comments' . DS . 'edit.ctp', '*'));
$this->Task->bake('edit', true);
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/\$viewTaskComment\[\'Article\'\]\[\'title\'\]/')
));
$this->Task->bake('index', true);
}
/**
* test that baking a view with no template doesn't make a file.
*
* @return void
*/
function testBakeWithNoTemplate() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectNever('createFile');
$this->Task->bake('delete', true);
}
/**
* test bake() with a -plugin param
*
* @return void
* @access public
*/
function testBakeWithPlugin() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->plugin = 'TestTest';
$path = APP . 'plugins' . DS . 'test_test' . DS . 'views' . DS . 'view_task_comments' . DS . 'view.ctp';
$this->Task->expectAt(0, 'createFile', array($path, '*'));
$this->Task->bake('view', true);
}
/**
* test bake actions baking multiple actions.
*
* @return void
* @access public
*/
function testBakeActions() {
$this->Task->controllerName = 'ViewTaskComments';
$this->Task->controllerPath = 'view_task_comments';
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'view.ctp',
new PatternExpectation('/View Task Comments/')
));
$this->Task->expectAt(1, 'createFile', array(
TMP . 'view_task_comments' . DS . 'edit.ctp',
new PatternExpectation('/Edit View Task Comment/')
));
$this->Task->expectAt(2, 'createFile', array(
TMP . 'view_task_comments' . DS . 'index.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->bakeActions(array('view', 'edit', 'index'), array());
}
/**
* test baking a customAction (non crud)
*
* @return void
* @access public
*/
function testCustomAction() {
$this->Task->controllerName = 'ViewTaskComments';
$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->customAction();
}
/**
* Test all()
*
* @return void
* @access public
*/
function testExecuteIntoAll() {
$this->Task->args[0] = 'all';
$this->Task->Controller->setReturnValue('listAll', array('view_task_comments'));
$this->Task->Controller->expectOnce('listAll');
$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->execute();
}
/**
* Test all() with action parameter
*
* @return void
* @access 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->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(TMP . 'view_task_comments' . DS . 'index.ctp', '*'));
$this->Task->execute();
}
/**
* test `cake bake view $controller view`
*
* @return void
* @access public
*/
function testExecuteWithActionParam() {
$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->execute();
}
/**
* test `cake bake view $controller`
* Ensure that views are only baked for actions that exist in the controller.
*
* @return void
* @access 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->execute();
}
/**
* test that both plural and singular forms can be used for baking views.
*
* @return void
* @access public
*/
function testExecuteWithControllerVariations() {
$this->Task->args = array('ViewTaskComments');
$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();
$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->execute();
}
/**
* test `cake bake view $controller -admin`
* Which only bakes admin methods, not non-admin methods.
*
* @return void
* @access public
*/
function testExecuteWithControllerAndAdminFlag() {
$_back = Configure::read('Routing');
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->execute();
Configure::write('Routing', $_back);
}
/**
* test execute into interactive.
*
* @return void
* @access public
*/
function testExecuteInteractive() {
$this->Task->connection = 'test_suite';
$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->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
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/')
));
$this->Task->execute();
}
/**
* test `cake bake view posts index list`
*
* @return void
* @access public
*/
function testExecuteWithAlternateTemplates() {
$this->Task->connection = 'test_suite';
$this->Task->args = array('ViewTaskComments', 'index', 'list');
$this->Task->params = array();
$this->Task->expectCallCount('createFile', 1);
$this->Task->expectAt(0, 'createFile', array(
TMP . 'view_task_comments' . DS . 'list.ctp',
new PatternExpectation('/ViewTaskComment/')
));
$this->Task->execute();
}
/**
* test execute into interactive() with admin methods.
*
* @return void
* @access public
*/
function testExecuteInteractiveWithAdmin() {
Configure::write('Routing.prefixes', array('admin'));
$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->expectCallCount('createFile', 4);
$this->Task->expectAt(0, 'createFile', array(
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/')
));
$this->Task->execute();
}
/**
* test getting templates, make sure noTemplateActions works
*
* @return void
*/
function testGetTemplate() {
$result = $this->Task->getTemplate('delete');
$this->assertFalse($result);
$result = $this->Task->getTemplate('add');
$this->assertEqual($result, 'form');
Configure::write('Routing.prefixes', array('admin'));
$result = $this->Task->getTemplate('admin_add');
$this->assertEqual($result, 'form');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,372 @@
<?php
/**
* CacheTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
/**
* CacheTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CacheTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
$this->_defaultCacheConfig = Cache::config('default');
Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_defaultCacheConfig['settings']);
}
/**
* testConfig method
*
* @access public
* @return void
*/
function testConfig() {
$settings = array('engine' => 'File', 'path' => TMP . 'tests', 'prefix' => 'cake_test_');
$results = Cache::config('new', $settings);
$this->assertEqual($results, Cache::config('new'));
$this->assertTrue(isset($results['engine']));
$this->assertTrue(isset($results['settings']));
}
/**
* Check that no fatal errors are issued doing normal things when Cache.disable is true.
*
* @return void
*/
function testNonFatalErrorsWithCachedisable() {
Configure::write('Cache.disable', true);
Cache::config('test', array('engine' => 'File', 'path' => TMP, 'prefix' => 'error_test_'));
Cache::write('no_save', 'Noooo!', 'test');
Cache::read('no_save', 'test');
Cache::delete('no_save', 'test');
Cache::set('duration', '+10 minutes');
Configure::write('Cache.disable', false);
}
/**
* test configuring CacheEngines in App/libs
*
* @return void
*/
function testConfigWithLibAndPluginEngines() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
), true);
$settings = array('engine' => 'TestAppCache', 'path' => TMP, 'prefix' => 'cake_test_');
$result = Cache::config('libEngine', $settings);
$this->assertEqual($result, Cache::config('libEngine'));
$settings = array('engine' => 'TestPlugin.TestPluginCache', 'path' => TMP, 'prefix' => 'cake_test_');
$result = Cache::config('pluginLibEngine', $settings);
$this->assertEqual($result, Cache::config('pluginLibEngine'));
Cache::drop('libEngine');
Cache::drop('pluginLibEngine');
App::build();
}
/**
* testInvalidConfig method
*
* Test that the cache class doesn't cause fatal errors with a partial path
*
* @access public
* @return void
*/
function testInvaidConfig() {
$this->expectError();
Cache::config('invalid', array(
'engine' => 'File',
'duration' => '+1 year',
'prefix' => 'testing_invalid_',
'path' => 'data/',
'serialize' => true,
'random' => 'wii'
));
$read = Cache::read('Test', 'invalid');
$this->assertEqual($read, null);
}
/**
* testConfigChange method
*
* @access public
* @return void
*/
function testConfigChange() {
$_cacheConfigSessions = Cache::config('sessions');
$_cacheConfigTests = Cache::config('tests');
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
$this->assertEqual($result['settings'], Cache::settings('sessions'));
$result = Cache::config('tests', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertEqual($result['settings'], Cache::settings('tests'));
Cache::config('sessions', $_cacheConfigSessions['settings']);
Cache::config('tests', $_cacheConfigTests['settings']);
}
/**
* test that calling config() sets the 'default' configuration up.
*
* @return void
*/
function testConfigSettingDefaultConfigKey() {
Cache::config('test_name', array('engine' => 'File', 'prefix' => 'test_name_'));
Cache::config('test_name');
Cache::write('value_one', 'I am cached');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am cached');
Cache::config('default');
$result = Cache::read('value_one');
$this->assertEqual($result, null);
Cache::write('value_one', 'I am in default config!');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am in default config!');
Cache::config('test_name');
$result = Cache::read('value_one');
$this->assertEqual($result, 'I am cached');
Cache::delete('value_one');
Cache::config('default');
Cache::delete('value_one');
}
/**
* testWritingWithConfig method
*
* @access public
* @return void
*/
function testWritingWithConfig() {
$_cacheConfigSessions = Cache::config('sessions');
Cache::write('test_somthing', 'this is the test data', 'tests');
$expected = array(
'path' => TMP . 'sessions',
'prefix' => 'cake_',
'lock' => false,
'serialize' => true,
'duration' => 3600,
'probability' => 100,
'engine' => 'File',
'isWindows' => DIRECTORY_SEPARATOR == '\\'
);
$this->assertEqual($expected, Cache::settings('sessions'));
Cache::config('sessions', $_cacheConfigSessions['settings']);
}
/**
* test that configured returns an array of the currently configured cache
* settings
*
* @return void
*/
function testConfigured() {
$result = Cache::configured();
$this->assertTrue(in_array('_cake_core_', $result));
$this->assertTrue(in_array('default', $result));
}
/**
* testInitSettings method
*
* @access public
* @return void
*/
function testInitSettings() {
Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
$settings = Cache::settings();
$expecting = array(
'engine' => 'File',
'duration'=> 3600,
'probability' => 100,
'path'=> TMP . 'tests',
'prefix'=> 'cake_',
'lock' => false,
'serialize'=> true,
'isWindows' => DIRECTORY_SEPARATOR == '\\'
);
$this->assertEqual($settings, $expecting);
}
/**
* test that drop removes cache configs, and that further attempts to use that config
* do not work.
*
* @return void
*/
function testDrop() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
), true);
$result = Cache::drop('some_config_that_does_not_exist');
$this->assertFalse($result);
$_testsConfig = Cache::config('tests');
$result = Cache::drop('tests');
$this->assertTrue($result);
Cache::config('unconfigTest', array(
'engine' => 'TestAppCache'
));
$this->assertTrue(Cache::isInitialized('unconfigTest'));
$this->assertTrue(Cache::drop('unconfigTest'));
$this->assertFalse(Cache::isInitialized('TestAppCache'));
Cache::config('tests', $_testsConfig);
App::build();
}
/**
* testWriteEmptyValues method
*
* @access public
* @return void
*/
function testWriteEmptyValues() {
Cache::write('App.falseTest', false);
$this->assertIdentical(Cache::read('App.falseTest'), false);
Cache::write('App.trueTest', true);
$this->assertIdentical(Cache::read('App.trueTest'), true);
Cache::write('App.nullTest', null);
$this->assertIdentical(Cache::read('App.nullTest'), null);
Cache::write('App.zeroTest', 0);
$this->assertIdentical(Cache::read('App.zeroTest'), 0);
Cache::write('App.zeroTest2', '0');
$this->assertIdentical(Cache::read('App.zeroTest2'), '0');
}
/**
* testCacheDisable method
*
* Check that the "Cache.disable" configuration and a change to it
* (even after a cache config has been setup) is taken into account.
*
* @link https://trac.cakephp.org/ticket/6236
* @access public
* @return void
*/
function testCacheDisable() {
Configure::write('Cache.disable', false);
Cache::config('test_cache_disable_1', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertTrue(Cache::write('key_1', 'hello'));
$this->assertIdentical(Cache::read('key_1'), 'hello');
Configure::write('Cache.disable', true);
$this->assertFalse(Cache::write('key_2', 'hello'));
$this->assertFalse(Cache::read('key_2'));
Configure::write('Cache.disable', false);
$this->assertTrue(Cache::write('key_3', 'hello'));
$this->assertIdentical(Cache::read('key_3'), 'hello');
Configure::write('Cache.disable', true);
Cache::config('test_cache_disable_2', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertFalse(Cache::write('key_4', 'hello'));
$this->assertFalse(Cache::read('key_4'));
Configure::write('Cache.disable', false);
$this->assertTrue(Cache::write('key_5', 'hello'));
$this->assertIdentical(Cache::read('key_5'), 'hello');
Configure::write('Cache.disable', true);
$this->assertFalse(Cache::write('key_6', 'hello'));
$this->assertFalse(Cache::read('key_6'));
}
/**
* testSet method
*
* @access public
* @return void
*/
function testSet() {
$_cacheSet = Cache::set();
Cache::set(array('duration' => '+1 year'));
$data = Cache::read('test_cache');
$this->assertFalse($data);
$data = 'this is just a simple test of the cache system';
$write = Cache::write('test_cache', $data);
$this->assertTrue($write);
Cache::set(array('duration' => '+1 year'));
$data = Cache::read('test_cache');
$this->assertEqual($data, 'this is just a simple test of the cache system');
Cache::delete('test_cache');
$global = Cache::settings();
Cache::set($_cacheSet);
}
}

View File

@@ -0,0 +1,196 @@
<?php
/**
* ApcEngineTest 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.cache
* @since CakePHP(tm) v 1.2.0.5434
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
/**
* ApcEngineTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.cache
*/
class ApcEngineTest extends CakeTestCase {
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$skip = true;
if (function_exists('apc_store')) {
$skip = false;
}
$this->skipIf($skip, '%s Apc is not installed or configured properly');
}
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('apc', array('engine' => 'Apc', 'prefix' => 'cake_'));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::drop('apc');
Cache::config('default');
}
/**
* testReadAndWriteCache method
*
* @access public
* @return void
*/
function testReadAndWriteCache() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$expecting = '';
$this->assertEqual($result, $expecting);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('test', $data);
$this->assertTrue($result);
$result = Cache::read('test');
$expecting = $data;
$this->assertEqual($result, $expecting);
Cache::delete('test');
}
/**
* testExpiry method
*
* @access public
* @return void
*/
function testExpiry() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$this->assertFalse($result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::set(array('duration' => 1));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
}
/**
* testDeleteCache method
*
* @access public
* @return void
*/
function testDeleteCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('delete_test', $data);
$this->assertTrue($result);
$result = Cache::delete('delete_test');
$this->assertTrue($result);
}
/**
* testDecrement method
*
* @access public
* @return void
*/
function testDecrement() {
if ($this->skipIf(!function_exists('apc_dec'), 'No apc_dec() function, cannot test decrement() %s')) {
return;
}
$result = Cache::write('test_decrement', 5);
$this->assertTrue($result);
$result = Cache::decrement('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::decrement('test_decrement', 2);
$this->assertEqual(2, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(2, $result);
}
/**
* testIncrement method
*
* @access public
* @return void
*/
function testIncrement() {
if ($this->skipIf(!function_exists('apc_inc'), 'No apc_inc() function, cannot test increment() %s')) {
return;
}
$result = Cache::write('test_increment', 5);
$this->assertTrue($result);
$result = Cache::increment('test_increment');
$this->assertEqual(6, $result);
$result = Cache::read('test_increment');
$this->assertEqual(6, $result);
$result = Cache::increment('test_increment', 2);
$this->assertEqual(8, $result);
$result = Cache::read('test_increment');
$this->assertEqual(8, $result);
}
}

View File

@@ -0,0 +1,404 @@
<?php
/**
* FileEngineTest 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.cache
* @since CakePHP(tm) v 1.2.0.5434
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
/**
* FileEngineTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.cache
*/
class FileEngineTest extends CakeTestCase {
/**
* config property
*
* @var array
* @access public
*/
var $config = array();
/**
* startCase method
*
* @access public
* @return void
*/
function startCase() {
$this->_cacheDisable = Configure::read('Cache.disable');
$this->_cacheConfig = Cache::config('default');
Configure::write('Cache.disable', false);
Cache::config('default', array('engine' => 'File', 'path' => CACHE));
}
/**
* endCase method
*
* @access public
* @return void
*/
function endCase() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_cacheConfig['settings']);
}
/**
* testCacheDirChange method
*
* @access public
* @return void
*/
function testCacheDirChange() {
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'sessions'));
$this->assertEqual($result['settings'], Cache::settings('sessions'));
$result = Cache::config('sessions', array('engine'=> 'File', 'path' => TMP . 'tests'));
$this->assertEqual($result['settings'], Cache::settings('sessions'));
$this->assertNotEqual($result['settings'], Cache::settings('default'));
}
/**
* testReadAndWriteCache method
*
* @access public
* @return void
*/
function testReadAndWriteCache() {
Cache::config('default');
$result = Cache::write(null, 'here');
$this->assertFalse($result);
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$expecting = '';
$this->assertEqual($result, $expecting);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('test', $data);
$this->assertTrue(file_exists(CACHE . 'cake_test'));
$result = Cache::read('test');
$expecting = $data;
$this->assertEqual($result, $expecting);
Cache::delete('test');
}
/**
* testExpiry method
*
* @access public
* @return void
*/
function testExpiry() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$this->assertFalse($result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::set(array('duration' => "+1 second"));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
}
/**
* testDeleteCache method
*
* @access public
* @return void
*/
function testDeleteCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('delete_test', $data);
$this->assertTrue($result);
$result = Cache::delete('delete_test');
$this->assertTrue($result);
$this->assertFalse(file_exists(TMP . 'tests' . DS . 'delete_test'));
$result = Cache::delete('delete_test');
$this->assertFalse($result);
}
/**
* testSerialize method
*
* @access public
* @return void
*/
function testSerialize() {
Cache::config('default', array('engine' => 'File', 'serialize' => true));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test', $data);
$this->assertTrue($write);
Cache::config('default', array('serialize' => false));
$read = Cache::read('serialize_test');
$newread = Cache::read('serialize_test');
$delete = Cache::delete('serialize_test');
$this->assertIdentical($read, serialize($data));
$this->assertIdentical(unserialize($newread), $data);
}
/**
* testClear method
*
* @access public
* @return void
*/
function testClear() {
Cache::config('default', array('engine' => 'File', 'duration' => 1));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test1', $data);
$write = Cache::write('serialize_test2', $data);
$write = Cache::write('serialize_test3', $data);
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test3'));
sleep(2);
$result = Cache::clear(true);
$this->assertTrue($result);
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test3'));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test1', $data);
$write = Cache::write('serialize_test2', $data);
$write = Cache::write('serialize_test3', $data);
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test3'));
$result = Cache::clear();
$this->assertTrue($result);
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test3'));
Cache::config('default', array('engine' => 'File', 'path' => CACHE . 'views'));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('controller_view_1', $data);
$write = Cache::write('controller_view_2', $data);
$write = Cache::write('controller_view_3', $data);
$write = Cache::write('controller_view_10', $data);
$write = Cache::write('controller_view_11', $data);
$write = Cache::write('controller_view_12', $data);
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_1'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_2'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_3'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_10'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_11'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_12'));
clearCache('controller_view_1', 'views', '');
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_1'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_2'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_3'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_10'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_11'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_12'));
clearCache('controller_view', 'views', '');
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_1'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_2'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_3'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_10'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_11'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_12'));
$write = Cache::write('controller_view_1', $data);
$write = Cache::write('controller_view_2', $data);
$write = Cache::write('controller_view_3', $data);
$write = Cache::write('controller_view_10', $data);
$write = Cache::write('controller_view_11', $data);
$write = Cache::write('controller_view_12', $data);
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_1'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_2'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_3'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_10'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_11'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_12'));
clearCache(array('controller_view_2', 'controller_view_11', 'controller_view_12'), 'views', '');
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_1'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_2'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_3'));
$this->assertTrue(file_exists(CACHE . 'views'. DS . 'cake_controller_view_10'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_11'));
$this->assertFalse(file_exists(CACHE . 'views'. DS . 'cake_controller_view_12'));
clearCache('controller_view');
Cache::config('default', array('engine' => 'File', 'path' => CACHE));
}
/**
* test that clear() doesn't wipe files not in the current engine's prefix.
*
* @return void
*/
function testClearWithPrefixes() {
$FileOne =& new FileEngine();
$FileOne->init(array(
'prefix' => 'prefix_one_',
'duration' => DAY
));
$FileTwo =& new FileEngine();
$FileTwo->init(array(
'prefix' => 'prefix_two_',
'duration' => DAY
));
$data1 = $data2 = $expected = 'content to cache';
$FileOne->write('key_one', $data1, DAY);
$FileTwo->write('key_two', $data2, DAY);
$this->assertEqual($FileOne->read('key_one'), $expected);
$this->assertEqual($FileTwo->read('key_two'), $expected);
$FileOne->clear(false);
$this->assertEqual($FileTwo->read('key_two'), $expected, 'secondary config was cleared by accident.');
}
/**
* testKeyPath method
*
* @access public
* @return void
*/
function testKeyPath() {
$result = Cache::write('views.countries.something', 'here');
$this->assertTrue($result);
$this->assertTrue(file_exists(CACHE . 'cake_views_countries_something'));
$result = Cache::read('views.countries.something');
$this->assertEqual($result, 'here');
$result = Cache::clear();
$this->assertTrue($result);
}
/**
* testRemoveWindowsSlashesFromCache method
*
* @access public
* @return void
*/
function testRemoveWindowsSlashesFromCache() {
Cache::config('windows_test', array('engine' => 'File', 'isWindows' => true, 'prefix' => null, 'path' => TMP));
$expected = array (
'C:\dev\prj2\sites\cake\libs' => array(
0 => 'C:\dev\prj2\sites\cake\libs', 1 => 'C:\dev\prj2\sites\cake\libs\view',
2 => 'C:\dev\prj2\sites\cake\libs\view\scaffolds', 3 => 'C:\dev\prj2\sites\cake\libs\view\pages',
4 => 'C:\dev\prj2\sites\cake\libs\view\layouts', 5 => 'C:\dev\prj2\sites\cake\libs\view\layouts\xml',
6 => 'C:\dev\prj2\sites\cake\libs\view\layouts\rss', 7 => 'C:\dev\prj2\sites\cake\libs\view\layouts\js',
8 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email', 9 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\text',
10 => 'C:\dev\prj2\sites\cake\libs\view\layouts\email\html', 11 => 'C:\dev\prj2\sites\cake\libs\view\helpers',
12 => 'C:\dev\prj2\sites\cake\libs\view\errors', 13 => 'C:\dev\prj2\sites\cake\libs\view\elements',
14 => 'C:\dev\prj2\sites\cake\libs\view\elements\email', 15 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\text',
16 => 'C:\dev\prj2\sites\cake\libs\view\elements\email\html', 17 => 'C:\dev\prj2\sites\cake\libs\model',
18 => 'C:\dev\prj2\sites\cake\libs\model\datasources', 19 => 'C:\dev\prj2\sites\cake\libs\model\datasources\dbo',
20 => 'C:\dev\prj2\sites\cake\libs\model\behaviors', 21 => 'C:\dev\prj2\sites\cake\libs\controller',
22 => 'C:\dev\prj2\sites\cake\libs\controller\components', 23 => 'C:\dev\prj2\sites\cake\libs\cache'),
'C:\dev\prj2\sites\main_site\vendors' => array(
0 => 'C:\dev\prj2\sites\main_site\vendors', 1 => 'C:\dev\prj2\sites\main_site\vendors\shells',
2 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates', 3 => 'C:\dev\prj2\sites\main_site\vendors\shells\templates\cdc_project',
4 => 'C:\dev\prj2\sites\main_site\vendors\shells\tasks', 5 => 'C:\dev\prj2\sites\main_site\vendors\js',
6 => 'C:\dev\prj2\sites\main_site\vendors\css'),
'C:\dev\prj2\sites\vendors' => array(
0 => 'C:\dev\prj2\sites\vendors', 1 => 'C:\dev\prj2\sites\vendors\simpletest',
2 => 'C:\dev\prj2\sites\vendors\simpletest\test', 3 => 'C:\dev\prj2\sites\vendors\simpletest\test\support',
4 => 'C:\dev\prj2\sites\vendors\simpletest\test\support\collector', 5 => 'C:\dev\prj2\sites\vendors\simpletest\extensions',
6 => 'C:\dev\prj2\sites\vendors\simpletest\extensions\testdox', 7 => 'C:\dev\prj2\sites\vendors\simpletest\docs',
8 => 'C:\dev\prj2\sites\vendors\simpletest\docs\fr', 9 => 'C:\dev\prj2\sites\vendors\simpletest\docs\en'),
'C:\dev\prj2\sites\main_site\views\helpers' => array(
0 => 'C:\dev\prj2\sites\main_site\views\helpers')
);
Cache::write('test_dir_map', $expected, 'windows_test');
$data = Cache::read('test_dir_map', 'windows_test');
Cache::delete('test_dir_map', 'windows_test');
$this->assertEqual($expected, $data);
Cache::drop('windows_test');
}
/**
* testWriteQuotedString method
*
* @access public
* @return void
*/
function testWriteQuotedString() {
Cache::config('default', array('engine' => 'File', 'path' => TMP . 'tests'));
Cache::write('App.doubleQuoteTest', '"this is a quoted string"');
$this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"');
Cache::write('App.singleQuoteTest', "'this is a quoted string'");
$this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'");
Cache::config('default', array('isWindows' => true, 'path' => TMP . 'tests'));
$this->assertIdentical(Cache::read('App.doubleQuoteTest'), '"this is a quoted string"');
Cache::write('App.singleQuoteTest', "'this is a quoted string'");
$this->assertIdentical(Cache::read('App.singleQuoteTest'), "'this is a quoted string'");
}
/**
* check that FileEngine generates an error when a configured Path does not exist.
*
* @return void
*/
function testErrorWhenPathDoesNotExist() {
if ($this->skipIf(is_dir(TMP . 'tests' . DS . 'file_failure'), 'Cannot run test directory exists. %s')) {
return;
}
$this->expectError();
Cache::config('failure', array(
'engine' => 'File',
'path' => TMP . 'tests' . DS . 'file_failure'
));
Cache::drop('failure');
}
}

View File

@@ -0,0 +1,367 @@
<?php
/**
* MemcacheEngineTest 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.cache
* @since CakePHP(tm) v 1.2.0.5434
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
App::import('Core', 'cache/Memcache');
class TestMemcacheEngine extends MemcacheEngine {
/**
* public accessor to _parseServerString
*
* @param string $server
* @return array
*/
function parseServerString($server) {
return $this->_parseServerString($server);
}
}
/**
* MemcacheEngineTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.cache
*/
class MemcacheEngineTest extends CakeTestCase {
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$skip = true;
if (class_exists('Memcache')) {
$skip = false;
}
$this->skipIf($skip, '%s Memcache is not installed or configured properly.');
}
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('memcache', array(
'engine' => 'Memcache',
'prefix' => 'cake_',
'duration' => 3600
));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::drop('memcache');
Cache::config('default');
}
/**
* testSettings method
*
* @access public
* @return void
*/
function testSettings() {
$settings = Cache::settings();
unset($settings['serialize'], $settings['path']);
$expecting = array(
'prefix' => 'cake_',
'duration'=> 3600,
'probability' => 100,
'servers' => array('127.0.0.1'),
'compress' => false,
'engine' => 'Memcache'
);
$this->assertEqual($settings, $expecting);
}
/**
* testSettings method
*
* @access public
* @return void
*/
function testMultipleServers() {
$servers = array('127.0.0.1:11211', '127.0.0.1:11222');
$available = true;
$Memcache =& new Memcache();
foreach($servers as $server) {
list($host, $port) = explode(':', $server);
if (!@$Memcache->connect($host, $port)) {
$available = false;
}
}
if ($this->skipIf(!$available, '%s Need memcache servers at ' . implode(', ', $servers) . ' to run this test')) {
return;
}
$Memcache =& new MemcacheEngine();
$Memcache->init(array('engine' => 'Memcache', 'servers' => $servers));
$servers = array_keys($Memcache->__Memcache->getExtendedStats());
$settings = $Memcache->settings();
$this->assertEqual($servers, $settings['servers']);
Cache::drop('dual_server');
}
/**
* testConnect method
*
* @access public
* @return void
*/
function testConnect() {
$Memcache =& new MemcacheEngine();
$Memcache->init(Cache::settings('memcache'));
$result = $Memcache->connect('127.0.0.1');
$this->assertTrue($result);
}
/**
* test connecting to an ipv6 server.
*
* @return void
*/
function testConnectIpv6() {
$Memcache =& new MemcacheEngine();
$result = $Memcache->init(array(
'prefix' => 'cake_',
'duration' => 200,
'engine' => 'Memcache',
'servers' => array(
'[::1]:11211'
)
));
$this->assertTrue($result);
}
/**
* test non latin domains.
*
* @return void
*/
function testParseServerStringNonLatin() {
$Memcache =& new TestMemcacheEngine();
$result = $Memcache->parseServerString('schülervz.net:13211');
$this->assertEqual($result, array('schülervz.net', '13211'));
$result = $Memcache->parseServerString('sülül:1111');
$this->assertEqual($result, array('sülül', '1111'));
}
/**
* testReadAndWriteCache method
*
* @access public
* @return void
*/
function testReadAndWriteCache() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$expecting = '';
$this->assertEqual($result, $expecting);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('test', $data);
$this->assertTrue($result);
$result = Cache::read('test');
$expecting = $data;
$this->assertEqual($result, $expecting);
Cache::delete('test');
}
/**
* testExpiry method
*
* @access public
* @return void
*/
function testExpiry() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$this->assertFalse($result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::set(array('duration' => "+1 second"));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::config('memcache', array('duration' => '+1 second'));
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::config('memcache', array('duration' => '+29 days'));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('long_expiry_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('long_expiry_test');
$expecting = $data;
$this->assertEqual($result, $expecting);
Cache::config('memcache', array('duration' => 3600));
}
/**
* testDeleteCache method
*
* @access public
* @return void
*/
function testDeleteCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('delete_test', $data);
$this->assertTrue($result);
$result = Cache::delete('delete_test');
$this->assertTrue($result);
}
/**
* testDecrement method
*
* @access public
* @return void
*/
function testDecrement() {
$result = Cache::write('test_decrement', 5);
$this->assertTrue($result);
$result = Cache::decrement('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::decrement('test_decrement', 2);
$this->assertEqual(2, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(2, $result);
}
/**
* testIncrement method
*
* @access public
* @return void
*/
function testIncrement() {
$result = Cache::write('test_increment', 5);
$this->assertTrue($result);
$result = Cache::increment('test_increment');
$this->assertEqual(6, $result);
$result = Cache::read('test_increment');
$this->assertEqual(6, $result);
$result = Cache::increment('test_increment', 2);
$this->assertEqual(8, $result);
$result = Cache::read('test_increment');
$this->assertEqual(8, $result);
}
/**
* test that configurations don't conflict, when a file engine is declared after a memcache one.
*
* @return void
*/
function testConfigurationConflict() {
Cache::config('long_memcache', array(
'engine' => 'Memcache',
'duration'=> '+2 seconds',
'servers' => array('127.0.0.1:11211'),
));
Cache::config('short_memcache', array(
'engine' => 'Memcache',
'duration'=> '+1 seconds',
'servers' => array('127.0.0.1:11211'),
));
Cache::config('some_file', array('engine' => 'File'));
$this->assertTrue(Cache::write('duration_test', 'yay', 'long_memcache'));
$this->assertTrue(Cache::write('short_duration_test', 'boo', 'short_memcache'));
$this->assertEqual(Cache::read('duration_test', 'long_memcache'), 'yay', 'Value was not read %s');
$this->assertEqual(Cache::read('short_duration_test', 'short_memcache'), 'boo', 'Value was not read %s');
sleep(1);
$this->assertEqual(Cache::read('duration_test', 'long_memcache'), 'yay', 'Value was not read %s');
sleep(2);
$this->assertFalse(Cache::read('short_duration_test', 'short_memcache'), 'Cache was not invalidated %s');
$this->assertFalse(Cache::read('duration_test', 'long_memcache'), 'Value did not expire %s');
Cache::delete('duration_test', 'long_memcache');
Cache::delete('short_duration_test', 'short_memcache');
}
/**
* test that a 0 duration can succesfully write.
*
* @return void
*/
function testZeroDuration() {
Cache::config('memcache', array('duration' => 0));
$result = Cache::write('test_key', 'written!', 'memcache');
$this->assertTrue($result, 'Could not write with duration 0');
$result = Cache::read('test_key', 'memcache');
$this->assertEqual($result, 'written!');
}
}

View File

@@ -0,0 +1,222 @@
<?php
/**
* XcacheEngineTest 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.cache
* @since CakePHP(tm) v 1.2.0.5434
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('Cache')) {
require LIBS . 'cache.php';
}
/**
* XcacheEngineTest class
*
* @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');
}
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
Cache::config('xcache', array('engine' => 'Xcache', 'prefix' => 'cake_'));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default');
}
/**
* testSettings method
*
* @access public
* @return void
*/
function testSettings() {
$settings = Cache::settings();
$expecting = array(
'prefix' => 'cake_',
'duration'=> 3600,
'probability' => 100,
'engine' => 'Xcache',
);
$this->assertTrue(isset($settings['PHP_AUTH_USER']));
$this->assertTrue(isset($settings['PHP_AUTH_PW']));
unset($settings['PHP_AUTH_USER'], $settings['PHP_AUTH_PW']);
$this->assertEqual($settings, $expecting);
}
/**
* testReadAndWriteCache method
*
* @access public
* @return void
*/
function testReadAndWriteCache() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$expecting = '';
$this->assertEqual($result, $expecting);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('test', $data);
$this->assertTrue($result);
$result = Cache::read('test');
$expecting = $data;
$this->assertEqual($result, $expecting);
Cache::delete('test');
}
/**
* testExpiry method
*
* @access public
* @return void
*/
function testExpiry() {
Cache::set(array('duration' => 1));
$result = Cache::read('test');
$this->assertFalse($result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
Cache::set(array('duration' => "+1 second"));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data);
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test');
$this->assertFalse($result);
}
/**
* testDeleteCache method
*
* @access public
* @return void
*/
function testDeleteCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('delete_test', $data);
$this->assertTrue($result);
$result = Cache::delete('delete_test');
$this->assertTrue($result);
}
/**
* testClearCache method
*
* @access public
* @return void
*/
function testClearCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('clear_test_1', $data);
$this->assertTrue($result);
$result = Cache::write('clear_test_2', $data);
$this->assertTrue($result);
$result = Cache::clear();
$this->assertTrue($result);
}
/**
* testDecrement method
*
* @access public
* @return void
*/
function testDecrement() {
$result = Cache::write('test_decrement', 5);
$this->assertTrue($result);
$result = Cache::decrement('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(4, $result);
$result = Cache::decrement('test_decrement', 2);
$this->assertEqual(2, $result);
$result = Cache::read('test_decrement');
$this->assertEqual(2, $result);
}
/**
* testIncrement method
*
* @access public
* @return void
*/
function testIncrement() {
$result = Cache::write('test_increment', 5);
$this->assertTrue($result);
$result = Cache::increment('test_increment');
$this->assertEqual(6, $result);
$result = Cache::read('test_increment');
$this->assertEqual(6, $result);
$result = Cache::increment('test_increment', 2);
$this->assertEqual(8, $result);
$result = Cache::read('test_increment');
$this->assertEqual(8, $result);
}
}

View File

@@ -0,0 +1,183 @@
<?php
/**
* CakeLogTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Log');
App::import('Core', 'log/FileLog');
/**
* CakeLogTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CakeLogTest extends CakeTestCase {
/**
* Start test callback, clears all streams enabled.
*
* @return void
*/
function startTest() {
$streams = CakeLog::configured();
foreach ($streams as $stream) {
CakeLog::drop($stream);
}
}
/**
* test importing loggers from app/libs and plugins.
*
* @return void
*/
function testImportingLoggers() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
), true);
$result = CakeLog::config('libtest', array(
'engine' => 'TestAppLog'
));
$this->assertTrue($result);
$this->assertEqual(CakeLog::configured(), array('libtest'));
$result = CakeLog::config('plugintest', array(
'engine' => 'TestPlugin.TestPluginLog'
));
$this->assertTrue($result);
$this->assertEqual(CakeLog::configured(), array('libtest', 'plugintest'));
App::build();
}
/**
* test all the errors from failed logger imports
*
* @return void
*/
function testImportingLoggerFailure() {
$this->expectError('Missing logger classname');
CakeLog::config('fail', array());
$this->expectError('Could not load logger class born to fail');
CakeLog::config('fail', array('engine' => 'born to fail'));
$this->expectError('logger class stdClass does not implement a write method.');
CakeLog::config('fail', array('engine' => 'stdClass'));
}
/**
* Test that CakeLog autoconfigures itself to use a FileLogger with the LOGS dir.
* When no streams are there.
*
* @return void
*/
function testAutoConfig() {
@unlink(LOGS . 'error.log');
CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertTrue(file_exists(LOGS . 'error.log'));
$result = CakeLog::configured();
$this->assertEqual($result, array('default'));
unlink(LOGS . 'error.log');
}
/**
* test configuring log streams
*
* @return void
*/
function testConfig() {
CakeLog::config('file', array(
'engine' => 'FileLog',
'path' => LOGS
));
$result = CakeLog::configured();
$this->assertEqual($result, array('file'));
@unlink(LOGS . 'error.log');
CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertTrue(file_exists(LOGS . 'error.log'));
$result = file_get_contents(LOGS . 'error.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result);
unlink(LOGS . 'error.log');
}
/**
* explict tests for drop()
*
* @return void
**/
function testDrop() {
CakeLog::config('file', array(
'engine' => 'FileLog',
'path' => LOGS
));
$result = CakeLog::configured();
$this->assertEqual($result, array('file'));
CakeLog::drop('file');
$result = CakeLog::configured();
$this->assertEqual($result, array());
}
/**
* testLogFileWriting method
*
* @access public
* @return void
*/
function testLogFileWriting() {
@unlink(LOGS . 'error.log');
$result = CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertTrue($result);
$this->assertTrue(file_exists(LOGS . 'error.log'));
unlink(LOGS . 'error.log');
CakeLog::write(LOG_WARNING, 'Test warning 1');
CakeLog::write(LOG_WARNING, 'Test warning 2');
$result = file_get_contents(LOGS . 'error.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1/', $result);
$this->assertPattern('/2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 2$/', $result);
unlink(LOGS . 'error.log');
}
/**
* Test logging with the error handler.
*
* @return void
*/
function testLoggingWithErrorHandling() {
@unlink(LOGS . 'debug.log');
Configure::write('log', E_ALL & ~E_DEPRECATED);
Configure::write('debug', 0);
set_error_handler(array('CakeLog', 'handleError'));
$out .= '';
$result = file(LOGS . 'debug.log');
$this->assertEqual(count($result), 1);
$this->assertPattern(
'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} Notice: Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
$result[0]
);
@unlink(LOGS . 'debug.log');
}
}

View File

@@ -0,0 +1,477 @@
<?php
/**
* SessionTest 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
*/
if (!class_exists('CakeSession')) {
App::import('Core', 'CakeSession');
}
/**
* CakeSessionTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CakeSessionTest extends CakeTestCase {
/**
* Fixtures used in the SessionTest
*
* @var array
* @access public
*/
var $fixtures = array('core.session');
/**
* startCase method
*
* @access public
* @return void
*/
function startCase() {
// Make sure garbage colector will be called
$this->__gc_divisor = ini_get('session.gc_divisor');
ini_set('session.gc_divisor', '1');
}
/**
* endCase method
*
* @access public
* @return void
*/
function endCase() {
// Revert to the default setting
ini_set('session.gc_divisor', $this->__gc_divisor);
}
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Session =& new CakeSession();
$this->Session->start();
$this->Session->_checkValid();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($_SESSION);
session_destroy();
}
/**
* testSessionPath
*
* @access public
* @return void
*/
function testSessionPath() {
$Session = new CakeSession('/index.php');
$this->assertEqual('/', $Session->path);
$Session = new CakeSession('/sub_dir/index.php');
$this->assertEqual('/sub_dir/', $Session->path);
$Session = new CakeSession('');
$this->assertEqual('/', $Session->path, 'Session path is empty, with "" as $base needs to be / %s');
}
/**
* testCheck method
*
* @access public
* @return void
*/
function testCheck() {
$this->Session->write('SessionTestCase', 'value');
$this->assertTrue($this->Session->check('SessionTestCase'));
$this->assertFalse($this->Session->check('NotExistingSessionTestCase'), false);
}
/**
* testSimpleRead method
*
* @access public
* @return void
*/
function testSimpleRead() {
$this->Session->write('testing', '1,2,3');
$result = $this->Session->read('testing');
$this->assertEqual($result, '1,2,3');
$this->Session->write('testing', array('1' => 'one', '2' => 'two','3' => 'three'));
$result = $this->Session->read('testing.1');
$this->assertEqual($result, 'one');
$result = $this->Session->read('testing');
$this->assertEqual($result, array('1' => 'one', '2' => 'two', '3' => 'three'));
$result = $this->Session->read();
$this->assertTrue(isset($result['testing']));
$this->assertTrue(isset($result['Config']));
$this->assertTrue(isset($result['Config']['userAgent']));
$this->Session->write('This.is.a.deep.array.my.friend', 'value');
$result = $this->Session->read('This.is.a.deep.array.my.friend');
$this->assertEqual('value', $result);
}
/**
* testId method
*
* @access public
* @return void
*/
function testId() {
$expected = session_id();
$result = $this->Session->id();
$this->assertEqual($result, $expected);
$this->Session->id('MySessionId');
$result = $this->Session->id();
$this->assertEqual($result, 'MySessionId');
}
/**
* testStarted method
*
* @access public
* @return void
*/
function testStarted() {
$this->assertTrue($this->Session->started());
unset($_SESSION);
$_SESSION = null;
$this->assertFalse($this->Session->started());
$this->assertTrue($this->Session->start());
$session = new CakeSession(null, false);
$this->assertTrue($session->started());
unset($session);
}
/**
* testError method
*
* @access public
* @return void
*/
function testError() {
$this->Session->read('Does.not.exist');
$result = $this->Session->error();
$this->assertEqual($result, "Does.not.exist doesn't exist");
$this->Session->delete('Failing.delete');
$result = $this->Session->error();
$this->assertEqual($result, "Failing.delete doesn't exist");
}
/**
* testDel method
*
* @access public
* @return void
*/
function testDelete() {
$this->assertTrue($this->Session->write('Delete.me', 'Clearing out'));
$this->assertTrue($this->Session->delete('Delete.me'));
$this->assertFalse($this->Session->check('Delete.me'));
$this->assertTrue($this->Session->check('Delete'));
$this->assertTrue($this->Session->write('Clearing.sale', 'everything must go'));
$this->assertTrue($this->Session->delete('Clearing'));
$this->assertFalse($this->Session->check('Clearing.sale'));
$this->assertFalse($this->Session->check('Clearing'));
}
/**
* testWatchVar method
*
* @access public
* @return void
*/
function testWatchVar() {
$this->assertFalse($this->Session->watch(null));
$this->Session->write('Watching', "I'm watching you");
$this->Session->watch('Watching');
$this->expectError('Writing session key {Watching}: "They found us!"');
$this->Session->write('Watching', 'They found us!');
$this->expectError('Deleting session key {Watching}');
$this->Session->delete('Watching');
$this->assertFalse($this->Session->watch('Invalid.key'));
}
/**
* testIgnore method
*
* @access public
* @return void
*/
function testIgnore() {
$this->Session->write('Watching', "I'm watching you");
$this->Session->watch('Watching');
$this->Session->ignore('Watching');
$this->assertTrue($this->Session->write('Watching', 'They found us!'));
}
/**
* testDestroy method
*
* @access public
* @return void
*/
function testDestroy() {
$this->Session->write('bulletProof', 'invicible');
$id = $this->Session->id();
$this->Session->destroy();
$this->assertFalse($this->Session->check('bulletProof'));
$this->assertNotEqual($id, $this->Session->id());
$this->assertTrue($this->Session->started());
$this->Session->cookieLifeTime = 'test';
$this->Session->destroy();
$this->assertNotEqual('test', $this->Session->cookieLifeTime);
}
/**
* testCheckingSavedEmpty method
*
* @access public
* @return void
*/
function testCheckingSavedEmpty() {
$this->assertTrue($this->Session->write('SessionTestCase', 0));
$this->assertTrue($this->Session->check('SessionTestCase'));
$this->assertTrue($this->Session->write('SessionTestCase', '0'));
$this->assertTrue($this->Session->check('SessionTestCase'));
$this->assertTrue($this->Session->write('SessionTestCase', false));
$this->assertTrue($this->Session->check('SessionTestCase'));
$this->assertTrue($this->Session->write('SessionTestCase', null));
$this->assertFalse($this->Session->check('SessionTestCase'));
}
/**
* testCheckKeyWithSpaces method
*
* @access public
* @return void
*/
function testCheckKeyWithSpaces() {
$this->assertTrue($this->Session->write('Session Test', "test"));
$this->assertEqual($this->Session->check('Session Test'), 'test');
$this->Session->delete('Session Test');
$this->assertTrue($this->Session->write('Session Test.Test Case', "test"));
$this->assertTrue($this->Session->check('Session Test.Test Case'));
}
/**
* test key exploitation
*
* @return void
*/
function testKeyExploit() {
$key = "a'] = 1; phpinfo(); \$_SESSION['a";
$result = $this->Session->write($key, 'haxored');
$this->assertTrue($result);
$result = $this->Session->read($key);
$this->assertEqual($result, 'haxored');
}
/**
* testReadingSavedEmpty method
*
* @access public
* @return void
*/
function testReadingSavedEmpty() {
$this->Session->write('SessionTestCase', 0);
$this->assertEqual($this->Session->read('SessionTestCase'), 0);
$this->Session->write('SessionTestCase', '0');
$this->assertEqual($this->Session->read('SessionTestCase'), '0');
$this->assertFalse($this->Session->read('SessionTestCase') === 0);
$this->Session->write('SessionTestCase', false);
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->Session->write('SessionTestCase', null);
$this->assertEqual($this->Session->read('SessionTestCase'), null);
}
/**
* testCheckUserAgentFalse method
*
* @access public
* @return void
*/
function testCheckUserAgentFalse() {
Configure::write('Session.checkAgent', false);
$this->Session->_userAgent = md5('http://randomdomainname.com' . Configure::read('Security.salt'));
$this->assertTrue($this->Session->valid());
}
/**
* testCheckUserAgentTrue method
*
* @access public
* @return void
*/
function testCheckUserAgentTrue() {
Configure::write('Session.checkAgent', true);
$this->Session->_userAgent = md5('http://randomdomainname.com' . Configure::read('Security.salt'));
$this->assertFalse($this->Session->valid());
}
/**
* testReadAndWriteWithDatabaseStorage method
*
* @access public
* @return void
*/
function testReadAndWriteWithCakeStorage() {
unset($_SESSION);
session_destroy();
ini_set('session.save_handler', 'files');
Configure::write('Session.save', 'cake');
$this->setUp();
$this->Session->write('SessionTestCase', 0);
$this->assertEqual($this->Session->read('SessionTestCase'), 0);
$this->Session->write('SessionTestCase', '0');
$this->assertEqual($this->Session->read('SessionTestCase'), '0');
$this->assertFalse($this->Session->read('SessionTestCase') === 0);
$this->Session->write('SessionTestCase', false);
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->Session->write('SessionTestCase', null);
$this->assertEqual($this->Session->read('SessionTestCase'), null);
$this->Session->write('SessionTestCase', 'This is a Test');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This is a Test');
$this->Session->write('SessionTestCase', 'This is a Test');
$this->Session->write('SessionTestCase', 'This was updated');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
}
/**
* testReadAndWriteWithDatabaseStorage method
*
* @access public
* @return void
*/
function testReadAndWriteWithCacheStorage() {
unset($_SESSION);
session_destroy();
ini_set('session.save_handler', 'files');
Configure::write('Session.save', 'cache');
$this->setUp();
$this->Session->write('SessionTestCase', 0);
$this->assertEqual($this->Session->read('SessionTestCase'), 0);
$this->Session->write('SessionTestCase', '0');
$this->assertEqual($this->Session->read('SessionTestCase'), '0');
$this->assertFalse($this->Session->read('SessionTestCase') === 0);
$this->Session->write('SessionTestCase', false);
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->Session->write('SessionTestCase', null);
$this->assertEqual($this->Session->read('SessionTestCase'), null);
$this->Session->write('SessionTestCase', 'This is a Test');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This is a Test');
$this->Session->write('SessionTestCase', 'This is a Test');
$this->Session->write('SessionTestCase', 'This was updated');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This was updated');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
}
/**
* testReadAndWriteWithDatabaseStorage method
*
* @access public
* @return void
*/
function testReadAndWriteWithDatabaseStorage() {
unset($_SESSION);
session_destroy();
Configure::write('Session.table', 'sessions');
Configure::write('Session.model', 'Session');
Configure::write('Session.database', 'test_suite');
Configure::write('Session.save', 'database');
$this->setUp();
$this->Session->write('SessionTestCase', 0);
$this->assertEqual($this->Session->read('SessionTestCase'), 0);
$this->Session->write('SessionTestCase', '0');
$this->assertEqual($this->Session->read('SessionTestCase'), '0');
$this->assertFalse($this->Session->read('SessionTestCase') === 0);
$this->Session->write('SessionTestCase', false);
$this->assertFalse($this->Session->read('SessionTestCase'));
$this->Session->write('SessionTestCase', null);
$this->assertEqual($this->Session->read('SessionTestCase'), null);
$this->Session->write('SessionTestCase', 'This is a Test');
$this->assertEqual($this->Session->read('SessionTestCase'), 'This is a Test');
$this->Session->write('SessionTestCase', 'Some additional data');
$this->assertEqual($this->Session->read('SessionTestCase'), 'Some additional data');
$this->Session->destroy();
$this->assertFalse($this->Session->read('SessionTestCase'));
session_write_close();
unset($_SESSION);
ini_set('session.save_handler', 'files');
Configure::write('Session.save', 'php');
$this->setUp();
}
}

View File

@@ -0,0 +1,192 @@
<?php
/**
* SocketTest 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
*/
App::import('Core', 'CakeSocket');
/**
* SocketTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CakeSocketTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Socket = new CakeSocket();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Socket);
}
/**
* testConstruct method
*
* @access public
* @return void
*/
function testConstruct() {
$this->Socket->__construct();
$baseConfig = $this->Socket->_baseConfig;
$this->assertIdentical($baseConfig, array(
'persistent' => false,
'host' => 'localhost',
'protocol' => 'tcp',
'port' => 80,
'timeout' => 30
));
$this->Socket->reset();
$this->Socket->__construct(array('host' => 'foo-bar'));
$baseConfig['host'] = 'foo-bar';
$baseConfig['protocol'] = getprotobyname($baseConfig['protocol']);
$this->assertIdentical($this->Socket->config, $baseConfig);
$this->Socket = new CakeSocket(array('host' => 'www.cakephp.org', 'port' => 23, 'protocol' => 'udp'));
$baseConfig = $this->Socket->_baseConfig;
$baseConfig['host'] = 'www.cakephp.org';
$baseConfig['port'] = 23;
$baseConfig['protocol'] = 17;
$this->assertIdentical($this->Socket->config, $baseConfig);
}
/**
* testSocketConnection method
*
* @access public
* @return void
*/
function testSocketConnection() {
$this->assertFalse($this->Socket->connected);
$this->Socket->disconnect();
$this->assertFalse($this->Socket->connected);
$this->Socket->connect();
$this->assertTrue($this->Socket->connected);
$this->Socket->connect();
$this->assertTrue($this->Socket->connected);
$this->Socket->disconnect();
$config = array('persistent' => true);
$this->Socket = new CakeSocket($config);
$this->Socket->connect();
$this->assertTrue($this->Socket->connected);
}
/**
* testSocketHost method
*
* @access public
* @return void
*/
function testSocketHost() {
$this->Socket = new CakeSocket();
$this->Socket->connect();
$this->assertEqual($this->Socket->address(), '127.0.0.1');
$this->assertEqual(gethostbyaddr('127.0.0.1'), $this->Socket->host());
$this->assertEqual($this->Socket->lastError(), null);
$this->assertTrue(in_array('127.0.0.1', $this->Socket->addresses()));
$this->Socket = new CakeSocket(array('host' => '127.0.0.1'));
$this->Socket->connect();
$this->assertEqual($this->Socket->address(), '127.0.0.1');
$this->assertEqual(gethostbyaddr('127.0.0.1'), $this->Socket->host());
$this->assertEqual($this->Socket->lastError(), null);
$this->assertTrue(in_array('127.0.0.1', $this->Socket->addresses()));
}
/**
* testSocketWriting method
*
* @access public
* @return void
*/
function testSocketWriting() {
$request = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n";
$this->assertTrue($this->Socket->write($request));
}
/**
* testSocketReading method
*
* @access public
* @return void
*/
function testSocketReading() {
$this->Socket = new CakeSocket(array('timeout' => 5));
$this->Socket->connect();
$this->assertEqual($this->Socket->read(26), null);
$config = array('host' => 'www.cakephp.org', 'timeout' => 1);
$this->Socket = new CakeSocket($config);
$this->assertTrue($this->Socket->connect());
$this->assertFalse($this->Socket->read(1024 * 1024));
$this->assertEqual($this->Socket->lastError(), '2: ' . __('Connection timed out', true));
$config = array('host' => 'www.cakephp.org', 'timeout' => 30);
$this->Socket = new CakeSocket($config);
$this->assertTrue($this->Socket->connect());
$this->assertEqual($this->Socket->read(26), null);
$this->assertEqual($this->Socket->lastError(), null);
}
/**
* testLastError method
*
* @access public
* @return void
*/
function testLastError() {
$this->Socket = new CakeSocket();
$this->Socket->setLastError(4, 'some error here');
$this->assertEqual($this->Socket->lastError(), '4: some error here');
}
/**
* testReset method
*
* @access public
* @return void
*/
function testReset() {
$config = array(
'persistent' => true,
'host' => '127.0.0.1',
'protocol' => 'udp',
'port' => 80,
'timeout' => 20
);
$anotherSocket = new CakeSocket($config);
$anotherSocket->reset();
$this->assertEqual(array(), $anotherSocket->config);
}
}

View File

@@ -0,0 +1,502 @@
<?php
/**
* CakeTestCaseTest file
*
* Test Case for CakeTestCase class
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.cake.libs.
* @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';
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
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
* @access public
*/
function testDummy() {
}
}
/**
* CakeTestCaseTest
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CakeTestCaseTest extends CakeTestCase {
/**
* setUp
*
* @access public
* @return void
*/
function setUp() {
$this->_debug = Configure::read('debug');
$this->Case =& new SubjectCakeTestCase();
$reporter =& new MockCakeHtmlReporter();
$this->Case->setReporter($reporter);
$this->Reporter = $reporter;
}
/**
* tearDown
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('debug', $this->_debug);
unset($this->Case);
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');
}
/**
* testNumericValuesInExpectationForAssertTags
*
* @access public
* @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));
}
/**
* testBadAssertTags
*
* @access public
* @return void
*/
function testBadAssertTags() {
$this->Reporter->expectAtLeastOnce('paintFail');
$this->Reporter->expectNever('paintPass');
$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->__truncated);
$this->Case->fixtures = array('core.post');
$this->Case->before('start');
$this->Case->start();
$this->Case->after('testDummy');
$this->assertTrue($this->Case->__truncated);
}
/**
* testLoadFixtures
*
* @access public
* @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();
}
/**
* testGetTests Method
*
* @return void
* @access 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
*
* @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('/^\s*This is the TestsAppsController index view\s*$/i', $result);
$result = $this->Case->testAction('/tests_apps/index', array('return' => 'contents'));
$this->assertPattern('/\bThis is the TestsAppsController index view\b/i', $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);
}
/**
* testSkipIf
*
* @return void
*/
function testSkipIf() {
$this->assertTrue($this->Case->skipIf(true));
$this->assertFalse($this->Case->skipIf(false));
}
/**
* 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));
}
}

View File

@@ -0,0 +1,408 @@
<?php
/**
* CakeTestFixture 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.cake.tests.libs
* @since CakePHP(tm) v 1.2.0.4667
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Datasource', 'DboSource', false);
/**
* CakeTestFixtureTestFixture class
*
* @package cake
* @subpackage cake.cake.tests.cases.libs
*/
class CakeTestFixtureTestFixture extends CakeTestFixture {
/**
* name Property
*
* @var string
*/
var $name = 'FixtureTest';
/**
* table property
*
* @var string
*/
var $table = 'fixture_tests';
/**
* Fields array
*
* @var array
*/
var $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'name' => array('type' => 'string', 'length' => '255'),
'created' => array('type' => 'datetime')
);
/**
* Records property
*
* @var array
*/
var $records = array(
array('name' => 'Gandalf', 'created' => '2009-04-28 19:20:00'),
array('name' => 'Captain Picard', 'created' => '2009-04-28 19:20:00'),
array('name' => 'Chewbacca', 'created' => '2009-04-28 19:20:00')
);
}
/**
* CakeTestFixtureImportFixture class
*
* @package cake
* @subpackage cake.cake.tests.cases.libs
*/
class CakeTestFixtureImportFixture extends CakeTestFixture {
/**
* Name property
*
* @var string
*/
var $name = 'ImportFixture';
/**
* Import property
*
* @var mixed
*/
var $import = array('table' => 'fixture_tests', 'connection' => 'test_suite');
}
/**
* CakeTestFixtureDefaultImportFixture class
*
* @package cake
* @subpackage cake.cake.tests.cases.libs
*/
class CakeTestFixtureDefaultImportFixture extends CakeTestFixture {
/**
* Name property
*
* @var string
*/
var $name = 'ImportFixture';
}
/**
* FixtureImportTestModel class
*
* @package default
* @subpackage cake.cake.tests.cases.libs.
*/
class FixtureImportTestModel extends Model {
var $name = 'FixtureImport';
var $useTable = 'fixture_tests';
var $useDbConfig = 'test_suite';
}
class FixturePrefixTest extends Model {
var $name = 'FixturePrefix';
var $useTable = '_tests';
var $tablePrefix = 'fixture';
var $useDbConfig = 'test_suite';
}
Mock::generate('DboSource', 'FixtureMockDboSource');
/**
* Test case for CakeTestFixture
*
* @package cake
* @subpackage cake.cake.tests.cases.libs
*/
class CakeTestFixtureTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->criticDb =& new FixtureMockDboSource();
$this->criticDb->fullDebug = true;
}
/**
* tearDown
*
* @access public
* @return void
*/
function tearDown() {
unset($this->criticDb);
}
/**
* testInit
*
* @access public
* @return void
*/
function testInit() {
$Fixture =& new CakeTestFixtureTestFixture();
unset($Fixture->table);
$Fixture->init();
$this->assertEqual($Fixture->table, 'fixture_tests');
$this->assertEqual($Fixture->primaryKey, 'id');
$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);
$Fixture =& new CakeTestFixtureImportFixture();
$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);
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('table' => 'fixture_tests', 'connection' => 'test_suite', 'records' => true);
$Fixture->init();
$this->assertEqual(count($Fixture->records), count($Source->records));
$Fixture =& new CakeTestFixtureImportFixture();
$Fixture->fields = $Fixture->records = $Fixture->table = null;
$Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test_suite');
$Fixture->init();
$this->assertEqual(array_keys($Fixture->fields), array('id', 'name', 'created'));
$this->assertEqual($Fixture->table, 'fixture_tests');
$keys = array_flip(ClassRegistry::keys());
$this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
$Source->drop($this->db);
}
/**
* test that fixtures don't duplicate the test db prefix.
*
* @return void
*/
function testInitDbPrefixDuplication() {
$this->_initDb();
$backPrefix = $this->db->config['prefix'];
$this->db->config['prefix'] = 'cake_fixture_test_';
$Source =& new CakeTestFixtureTestFixture();
$Source->create($this->db);
$Source->insert($this->db);
$Fixture =& new CakeTestFixtureImportFixture();
$Fixture->fields = $Fixture->records = $Fixture->table = null;
$Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'test_suite');
$Fixture->init();
$this->assertEqual(array_keys($Fixture->fields), array('id', 'name', 'created'));
$this->assertEqual($Fixture->table, 'fixture_tests');
$Source->drop($this->db);
$this->db->config['prefix'] = $backPrefix;
}
/**
* test init with a model that has a tablePrefix declared.
*
* @return void
*/
function testInitModelTablePrefix() {
$this->_initDb();
$hasPrefix = !empty($this->db->config['prefix']);
if ($this->skipIf($hasPrefix, 'Cannot run this test, you have a database connection prefix.')) {
return;
}
$Source =& new CakeTestFixtureTestFixture();
$Source->create($this->db);
$Source->insert($this->db);
$Fixture =& new CakeTestFixtureImportFixture();
unset($Fixture->table);
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('model' => 'FixturePrefixTest', 'connection' => 'test_suite', 'records' => false);
$Fixture->init();
$this->assertEqual($Fixture->table, 'fixture_tests');
$keys = array_flip(ClassRegistry::keys());
$this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
$Source->drop($this->db);
}
/**
* testImport
*
* @access public
* @return void
*/
function testImport() {
$this->_initDb();
$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');
$Source =& new CakeTestFixtureTestFixture();
$Source->create($newTestSuiteDb);
$Source->insert($newTestSuiteDb);
$defaultDb->config = $newTestSuiteDb->config;
$Fixture =& new CakeTestFixtureDefaultImportFixture();
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array('model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite');
$Fixture->init();
$this->assertEqual(array_keys($Fixture->fields), array('id', 'name', 'created'));
$defaultDb->config = $defaultConfig;
$keys = array_flip(ClassRegistry::keys());
$this->assertFalse(array_key_exists('fixtureimporttestmodel', $keys));
$Source->drop($newTestSuiteDb);
}
/**
* test that importing with records works. Make sure to try with postgres as its
* handling of aliases is a workaround at best.
*
* @return void
*/
function testImportWithRecords() {
$this->_initDb();
$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');
$Source =& new CakeTestFixtureTestFixture();
$Source->create($newTestSuiteDb);
$Source->insert($newTestSuiteDb);
$defaultDb->config = $newTestSuiteDb->config;
$Fixture =& new CakeTestFixtureDefaultImportFixture();
$Fixture->fields = $Fixture->records = null;
$Fixture->import = array(
'model' => 'FixtureImportTestModel', 'connection' => 'new_test_suite', 'records' => true
);
$Fixture->init();
$this->assertEqual(array_keys($Fixture->fields), array('id', 'name', 'created'));
$this->assertFalse(empty($Fixture->records[0]), 'No records loaded on importing fixture.');
$this->assertTrue(isset($Fixture->records[0]['name']), 'No name loaded for first record');
$defaultDb->config = $defaultConfig;
$Source->drop($newTestSuiteDb);
}
/**
* test create method
*
* @access public
* @return void
*/
function testCreate() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->expectAtLeastOnce('execute');
$this->criticDb->expectAtLeastOnce('createSchema');
$return = $Fixture->create($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
$this->assertTrue($return);
unset($Fixture->fields);
$return = $Fixture->create($this->criticDb);
$this->assertFalse($return);
}
/**
* test the insert method
*
* @access public
* @return void
*/
function testInsert() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->setReturnValue('insertMulti', true);
$this->criticDb->expectAtLeastOnce('insertMulti');
$return = $Fixture->insert($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
$this->assertTrue($return);
}
/**
* Test the drop method
*
* @access public
* @return void
*/
function testDrop() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->setReturnValueAt(0, 'execute', true);
$this->criticDb->expectAtLeastOnce('execute');
$this->criticDb->expectAtLeastOnce('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);
}
/**
* Test the truncate method.
*
* @access public
* @return void
*/
function testTruncate() {
$Fixture =& new CakeTestFixtureTestFixture();
$this->criticDb->expectAtLeastOnce('truncate');
$Fixture->truncate($this->criticDb);
$this->assertTrue($this->criticDb->fullDebug);
}
}

View File

@@ -0,0 +1,325 @@
<?php
/**
* ClassRegistryTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'ClassRegistry');
/**
* ClassRegisterModel class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ClassRegisterModel extends CakeTestModel {
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
}
/**
* RegisterArticle class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RegisterArticle extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticle'
* @access public
*/
var $name = 'RegisterArticle';
}
/**
* RegisterArticleFeatured class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RegisterArticleFeatured extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleFeatured'
* @access public
*/
var $name = 'RegisterArticleFeatured';
}
/**
* RegisterArticleTag class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RegisterArticleTag extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleTag'
* @access public
*/
var $name = 'RegisterArticleTag';
}
/**
* RegistryPluginAppModel class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RegistryPluginAppModel extends ClassRegisterModel {
/**
* tablePrefix property
*
* @var string 'something_'
* @access public
*/
var $tablePrefix = 'something_';
}
/**
* TestRegistryPluginModel class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class TestRegistryPluginModel extends RegistryPluginAppModel {
/**
* name property
*
* @var string 'TestRegistryPluginModel'
* @access public
*/
var $name = 'TestRegistryPluginModel';
}
/**
* RegisterCategory class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RegisterCategory extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterCategory'
* @access public
*/
var $name = 'RegisterCategory';
}
/**
* ClassRegistryTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ClassRegistryTest extends CakeTestCase {
/**
* testAddModel method
*
* @access public
* @return void
*/
function testAddModel() {
if (PHP5) {
$Tag = ClassRegistry::init('RegisterArticleTag');
} else {
$Tag =& ClassRegistry::init('RegisterArticleTag');
}
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$TagCopy = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertTrue($TagCopy);
$Tag->name = 'SomeNewName';
if (PHP5) {
$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
} else {
$TagCopy =& ClassRegistry::getObject('RegisterArticleTag');
}
$this->assertTrue(is_a($TagCopy, 'RegisterArticleTag'));
$this->assertIdentical($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);
$NewTag->name = 'SomeOtherName';
$this->assertNotIdentical($Tag, $NewTag);
$this->assertIdentical($NewTag, $NewTagCopy);
$Tag->name = 'SomeOtherName';
$this->assertNotIdentical($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);
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->assertNotEqual($Category->alias, $ParentCategory->alias);
$this->assertEqual('RegisterCategory', $Category->alias);
$this->assertEqual('ParentCategory', $ParentCategory->alias);
}
/**
* testClassRegistryFlush method
*
* @access public
* @return void
*/
function testClassRegistryFlush() {
$ArticleTag = ClassRegistry::getObject('RegisterArticleTag');
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
ClassRegistry::flush();
$NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertFalse($NoArticleTag);
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
}
/**
* testAddMultipleModels method
*
* @access public
* @return void
*/
function testAddMultipleModels() {
$Article = ClassRegistry::isKeySet('Article');
$this->assertFalse($Article);
$Featured = ClassRegistry::isKeySet('Featured');
$this->assertFalse($Featured);
$Tag = ClassRegistry::isKeySet('Tag');
$this->assertFalse($Tag);
$models = array(array('class' => 'RegisterArticle', 'alias' => 'Article'),
array('class' => 'RegisterArticleFeatured', 'alias' => 'Featured'),
array('class' => 'RegisterArticleTag', 'alias' => 'Tag'));
$added = ClassRegistry::init($models);
$this->assertTrue($added);
$Article = ClassRegistry::isKeySet('Article');
$this->assertTrue($Article);
$Featured = ClassRegistry::isKeySet('Featured');
$this->assertTrue($Featured);
$Tag = ClassRegistry::isKeySet('Tag');
$this->assertTrue($Tag);
$Article = ClassRegistry::getObject('Article');
$this->assertTrue(is_a($Article, 'RegisterArticle'));
$Featured = ClassRegistry::getObject('Featured');
$this->assertTrue(is_a($Featured, 'RegisterArticleFeatured'));
$Tag = ClassRegistry::getObject('Tag');
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
}
/**
* testPluginAppModel method
*
* @access public
* @return void
*/
function testPluginAppModel() {
$TestRegistryPluginModel = ClassRegistry::isKeySet('TestRegistryPluginModel');
$this->assertFalse($TestRegistryPluginModel);
$TestRegistryPluginModel = ClassRegistry::init('RegistryPlugin.TestRegistryPluginModel');
$this->assertTrue(is_a($TestRegistryPluginModel, 'TestRegistryPluginModel'));
$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);
}
}

View File

@@ -0,0 +1,516 @@
<?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
*
* @access 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.
*
* @access 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
* @access 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
* @access 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

@@ -0,0 +1,833 @@
<?php
/**
* ConfigureTest file
*
* Holds several tests
*
* 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Configure');
/**
* ConfigureTest
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ConfigureTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_cacheDisable = Configure::read('Cache.disable');
$this->_debug = Configure::read('debug');
Configure::write('Cache.disable', true);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_core_paths');
}
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_dir_map')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_dir_map');
}
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_file_map')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_file_map');
}
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_object_map')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'cake_core_object_map');
}
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.config.php')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.config.php');
}
if (file_exists(TMP . 'cache' . DS . 'persistent' . DS . 'test.php')) {
unlink(TMP . 'cache' . DS . 'persistent' . DS . 'test.php');
}
Configure::write('debug', $this->_debug);
Configure::write('Cache.disable', $this->_cacheDisable);
}
/**
* testRead method
*
* @access public
* @return void
*/
function testRead() {
$expected = 'ok';
Configure::write('level1.level2.level3_1', $expected);
Configure::write('level1.level2.level3_2', 'something_else');
$result = Configure::read('level1.level2.level3_1');
$this->assertEqual($expected, $result);
$result = Configure::read('level1.level2.level3_2');
$this->assertEqual($result, 'something_else');
$result = Configure::read('debug');
$this->assertTrue($result >= 0);
}
/**
* testWrite method
*
* @access public
* @return void
*/
function testWrite() {
$writeResult = Configure::write('SomeName.someKey', 'myvalue');
$this->assertTrue($writeResult);
$result = Configure::read('SomeName.someKey');
$this->assertEqual($result, 'myvalue');
$writeResult = Configure::write('SomeName.someKey', null);
$this->assertTrue($writeResult);
$result = Configure::read('SomeName.someKey');
$this->assertEqual($result, null);
$expected = array('One' => array('Two' => array('Three' => array('Four' => array('Five' => 'cool')))));
$writeResult = Configure::write('Key', $expected);
$this->assertTrue($writeResult);
$result = Configure::read('Key');
$this->assertEqual($expected, $result);
$result = Configure::read('Key.One');
$this->assertEqual($expected['One'], $result);
$result = Configure::read('Key.One.Two');
$this->assertEqual($expected['One']['Two'], $result);
$result = Configure::read('Key.One.Two.Three.Four.Five');
$this->assertEqual('cool', $result);
}
/**
* testSetErrorReporting Level
*
* @return void
*/
function testSetErrorReportingLevel() {
Configure::write('log', false);
Configure::write('debug', 0);
$result = ini_get('error_reporting');
$this->assertEqual($result, 0);
Configure::write('debug', 2);
$result = ini_get('error_reporting');
$this->assertEqual($result, E_ALL & ~E_DEPRECATED);
$result = ini_get('display_errors');
$this->assertEqual($result, 1);
Configure::write('debug', 0);
$result = ini_get('error_reporting');
$this->assertEqual($result, 0);
}
/**
* test that log and debug configure values interact well.
*
* @return void
*/
function testInteractionOfDebugAndLog() {
Configure::write('log', false);
Configure::write('debug', 0);
$this->assertEqual(ini_get('error_reporting'), 0);
$this->assertEqual(ini_get('display_errors'), 0);
Configure::write('log', E_WARNING);
Configure::write('debug', 0);
$this->assertEqual(ini_get('error_reporting'), E_WARNING);
$this->assertEqual(ini_get('display_errors'), 0);
Configure::write('debug', 2);
$this->assertEqual(ini_get('error_reporting'), E_ALL & ~E_DEPRECATED);
$this->assertEqual(ini_get('display_errors'), 1);
Configure::write('debug', 0);
Configure::write('log', false);
$this->assertEqual(ini_get('error_reporting'), 0);
$this->assertEqual(ini_get('display_errors'), 0);
}
/**
* testDelete method
*
* @access public
* @return void
*/
function testDelete() {
Configure::write('SomeName.someKey', 'myvalue');
$result = Configure::read('SomeName.someKey');
$this->assertEqual($result, 'myvalue');
Configure::delete('SomeName.someKey');
$result = Configure::read('SomeName.someKey');
$this->assertTrue($result === null);
Configure::write('SomeName', array('someKey' => 'myvalue', 'otherKey' => 'otherValue'));
$result = Configure::read('SomeName.someKey');
$this->assertEqual($result, 'myvalue');
$result = Configure::read('SomeName.otherKey');
$this->assertEqual($result, 'otherValue');
Configure::delete('SomeName');
$result = Configure::read('SomeName.someKey');
$this->assertTrue($result === null);
$result = Configure::read('SomeName.otherKey');
$this->assertTrue($result === null);
}
/**
* testLoad method
*
* @access public
* @return void
*/
function testLoad() {
$result = Configure::load('non_existing_configuration_file');
$this->assertFalse($result);
$result = Configure::load('config');
$this->assertTrue($result);
$result = Configure::load('../../index');
$this->assertFalse($result);
}
/**
* testLoad method
*
* @access public
* @return void
*/
function testLoadPlugin() {
App::build(array('plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)), true);
$result = Configure::load('test_plugin.load');
$this->assertTrue($result);
$expected = '/test_app/plugins/test_plugin/config/load.php';
$config = Configure::read('plugin_load');
$this->assertEqual($config, $expected);
$result = Configure::load('test_plugin.more.load');
$this->assertTrue($result);
$expected = '/test_app/plugins/test_plugin/config/more.load.php';
$config = Configure::read('plugin_more_load');
$this->assertEqual($config, $expected);
}
/**
* testStore method
*
* @access public
* @return void
*/
function testStoreAndLoad() {
Configure::write('Cache.disable', false);
$expected = array('data' => 'value with backslash \, \'singlequote\' and "doublequotes"');
Configure::store('SomeExample', 'test', $expected);
Configure::load('test');
$config = Configure::read('SomeExample');
$this->assertEqual($config, $expected);
$expected = array(
'data' => array('first' => 'value with backslash \, \'singlequote\' and "doublequotes"', 'second' => 'value2'),
'data2' => 'value'
);
Configure::store('AnotherExample', 'test_config', $expected);
Configure::load('test_config');
$config = Configure::read('AnotherExample');
$this->assertEqual($config, $expected);
}
/**
* testVersion method
*
* @access public
* @return void
*/
function testVersion() {
$result = Configure::version();
$this->assertTrue(version_compare($result, '1.2', '>='));
}
}
/**
* AppImportTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AppImportTest extends CakeTestCase {
/**
* testBuild method
*
* @access public
* @return void
*/
function testBuild() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')));
$new = App::path('models');
$expected = array(
'/path/to/models/',
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testBuildWithReset method
*
* @access public
* @return void
*/
function testBuildWithReset() {
$old = App::path('models');
$expected = array(
APP . 'models' . DS,
APP,
ROOT . DS . LIBS . 'model' . DS
);
$this->assertEqual($expected, $old);
App::build(array('models' => array('/path/to/models/')), true);
$new = App::path('models');
$expected = array(
'/path/to/models/'
);
$this->assertEqual($expected, $new);
App::build(); //reset defaults
$defaults = App::path('models');
$this->assertEqual($old, $defaults);
}
/**
* testCore method
*
* @access public
* @return void
*/
function testCore() {
$model = App::core('models');
$this->assertEqual(array(ROOT . DS . LIBS . 'model' . DS), $model);
$view = App::core('views');
$this->assertEqual(array(ROOT . DS . LIBS . 'view' . DS), $view);
$controller = App::core('controllers');
$this->assertEqual(array(ROOT . DS . LIBS . 'controller' . DS), $controller);
}
/**
* testListObjects method
*
* @access public
* @return void
*/
function testListObjects() {
$result = App::objects('class', TEST_CAKE_CORE_INCLUDE_PATH . 'libs');
$this->assertTrue(in_array('Xml', $result));
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('HttpSocket', $result));
$result = App::objects('behavior');
$this->assertTrue(in_array('Tree', $result));
$result = App::objects('controller');
$this->assertTrue(in_array('Pages', $result));
$result = App::objects('component');
$this->assertTrue(in_array('Auth', $result));
$result = App::objects('view');
$this->assertTrue(in_array('Media', $result));
$result = App::objects('helper');
$this->assertTrue(in_array('Html', $result));
$result = App::objects('model');
$notExpected = array('AppModel', 'ModelBehavior', 'ConnectionManager', 'DbAcl', 'Model', 'CakeSchema');
foreach ($notExpected as $class) {
$this->assertFalse(in_array($class, $result));
}
$result = App::objects('file');
$this->assertFalse($result);
$result = App::objects('file', 'non_existing_configure');
$expected = array();
$this->assertEqual($result, $expected);
$result = App::objects('NonExistingType');
$this->assertFalse($result);
App::build(array(
'plugins' => array(
TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS
)
));
$result = App::objects('plugin', null, false);
$this->assertTrue(in_array('Cache', $result));
$this->assertTrue(in_array('Log', $result));
App::build();
}
/**
* test that pluginPath can find paths for plugins.
*
* @return void
*/
function testPluginPath() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$path = App::pluginPath('test_plugin');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS;
$this->assertEqual($path, $expected);
$path = App::pluginPath('TestPlugin');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin' . DS;
$this->assertEqual($path, $expected);
$path = App::pluginPath('TestPluginTwo');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS . 'test_plugin_two' . DS;
$this->assertEqual($path, $expected);
App::build();
}
/**
* test that pluginPath can find paths for plugins.
*
* @return void
*/
function testThemePath() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS)
));
$path = App::themePath('test_theme');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'themed' . DS . 'test_theme' . DS;
$this->assertEqual($path, $expected);
$path = App::themePath('TestTheme');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'themed' . DS . 'test_theme' . DS;
$this->assertEqual($path, $expected);
App::build();
}
/**
* testClassLoading method
*
* @access public
* @return void
*/
function testClassLoading() {
$file = App::import();
$this->assertTrue($file);
$file = App::import('Model', 'Model', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Model'));
$file = App::import('Controller', 'Controller', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Controller'));
$file = App::import('Component', 'Component', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Component'));
$file = App::import('Shell', 'Shell', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('Shell'));
$file = App::import('Model', 'SomeRandomModelThatDoesNotExist', false);
$this->assertFalse($file);
$file = App::import('Model', 'AppModel', false);
$this->assertTrue($file);
$this->assertTrue(class_exists('AppModel'));
$file = App::import('WrongType', null, true, array(), '');
$this->assertTrue($file);
$file = App::import('Model', 'NonExistingPlugin.NonExistingModel', false);
$this->assertFalse($file);
$file = App::import('Core', 'NonExistingPlugin.NonExistingModel', false);
$this->assertFalse($file);
$file = App::import('Model', array('NonExistingPlugin.NonExistingModel'), false);
$this->assertFalse($file);
$file = App::import('Core', array('NonExistingPlugin.NonExistingModel'), false);
$this->assertFalse($file);
$file = App::import('Core', array('NonExistingPlugin.NonExistingModel.AnotherChild'), false);
$this->assertFalse($file);
if (!class_exists('AppController')) {
$classes = array_flip(get_declared_classes());
if (PHP5) {
$this->assertFalse(isset($classes['PagesController']));
$this->assertFalse(isset($classes['AppController']));
} else {
$this->assertFalse(isset($classes['pagescontroller']));
$this->assertFalse(isset($classes['appcontroller']));
}
$file = App::import('Controller', 'Pages');
$this->assertTrue($file);
$this->assertTrue(class_exists('PagesController'));
$classes = array_flip(get_declared_classes());
if (PHP5) {
$this->assertTrue(isset($classes['PagesController']));
$this->assertTrue(isset($classes['AppController']));
} else {
$this->assertTrue(isset($classes['pagescontroller']));
$this->assertTrue(isset($classes['appcontroller']));
}
$file = App::import('Behavior', 'Containable');
$this->assertTrue($file);
$this->assertTrue(class_exists('ContainableBehavior'));
$file = App::import('Component', 'RequestHandler');
$this->assertTrue($file);
$this->assertTrue(class_exists('RequestHandlerComponent'));
$file = App::import('Helper', 'Form');
$this->assertTrue($file);
$this->assertTrue(class_exists('FormHelper'));
$file = App::import('Model', 'NonExistingModel');
$this->assertFalse($file);
$file = App::import('Datasource', 'DboSource');
$this->assertTrue($file);
$this->assertTrue(class_exists('DboSource'));
}
App::build();
}
/**
* test import() with plugins
*
* @return void
*/
function testPluginImporting() {
App::build(array(
'libs' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'libs' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$result = App::import('Controller', 'TestPlugin.Tests');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginAppController'));
$this->assertTrue(class_exists('TestsController'));
$result = App::import('Lib', 'TestPlugin.TestPluginLibrary');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginLibrary'));
$result = App::import('Lib', 'Library');
$this->assertTrue($result);
$this->assertTrue(class_exists('Library'));
$result = App::import('Helper', 'TestPlugin.OtherHelper');
$this->assertTrue($result);
$this->assertTrue(class_exists('OtherHelperHelper'));
$result = App::import('Helper', 'TestPlugin.TestPluginApp');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestPluginAppHelper'));
$result = App::import('Datasource', 'TestPlugin.TestSource');
$this->assertTrue($result);
$this->assertTrue(class_exists('TestSource'));
App::build();
}
/**
* test that building helper paths actually works.
*
* @return void
* @link http://cakephp.lighthouseapp.com/projects/42648/tickets/410
*/
function testImportingHelpersFromAlternatePaths() {
App::build();
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper exists, cannot test importing it.');
App::import('Helper', 'Banana');
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper was not found because the path does not exist.');
App::build(array(
'helpers' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS . 'helpers' . DS)
));
App::build(array('vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH)));
$this->assertFalse(class_exists('BananaHelper'), 'BananaHelper exists, cannot test importing it.');
App::import('Helper', 'Banana');
$this->assertTrue(class_exists('BananaHelper'), 'BananaHelper was not loaded.');
App::build();
}
/**
* testFileLoading method
*
* @access public
* @return void
*/
function testFileLoading () {
$file = App::import('File', 'RealFile', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php');
$this->assertTrue($file);
$file = App::import('File', 'NoFile', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'cake' . DS . 'config.php');
$this->assertFalse($file);
}
// import($type = null, $name = null, $parent = true, $file = null, $search = array(), $return = false) {
/**
* testFileLoadingWithArray method
*
* @access public
* @return void
*/
function testFileLoadingWithArray() {
$type = array('type' => 'File', 'name' => 'SomeName', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . DS . 'config' . DS . 'config.php');
$file = App::import($type);
$this->assertTrue($file);
$type = array('type' => 'File', 'name' => 'NoFile', 'parent' => false,
'file' => TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'cake' . DS . 'config.php');
$file = App::import($type);
$this->assertFalse($file);
}
/**
* testFileLoadingReturnValue method
*
* @access public
* @return void
*/
function testFileLoadingReturnValue () {
$file = App::import('File', 'Name', false, array(), TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php', true);
$this->assertTrue($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(isset($file['Cake.version']));
}
/**
* testLoadingWithSearch method
*
* @access public
* @return void
*/
function testLoadingWithSearch () {
$file = App::import('File', 'NewName', false, array(TEST_CAKE_CORE_INCLUDE_PATH ), 'config.php');
$this->assertTrue($file);
$file = App::import('File', 'AnotherNewName', false, array(LIBS), 'config.php');
$this->assertFalse($file);
}
/**
* testLoadingWithSearchArray method
*
* @access public
* @return void
*/
function testLoadingWithSearchArray () {
$type = array('type' => 'File', 'name' => 'RandomName', 'parent' => false, 'file' => 'config.php', 'search' => array(TEST_CAKE_CORE_INCLUDE_PATH ));
$file = App::import($type);
$this->assertTrue($file);
$type = array('type' => 'File', 'name' => 'AnotherRandomName', 'parent' => false, 'file' => 'config.php', 'search' => array(LIBS));
$file = App::import($type);
$this->assertFalse($file);
}
/**
* testMultipleLoading method
*
* @access public
* @return void
*/
function testMultipleLoading() {
$toLoad = array('I18n', 'CakeSocket');
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['i18n']));
$this->assertFalse(isset($classes['CakeSocket']));
$load = App::import($toLoad);
$this->assertTrue($load);
$classes = array_flip(get_declared_classes());
if (PHP5) {
$this->assertTrue(isset($classes['I18n']));
} else {
$this->assertTrue(isset($classes['i18n']));
}
$load = App::import(array('I18n', 'SomeNotFoundClass', 'CakeSocket'));
$this->assertFalse($load);
$load = App::import($toLoad);
$this->assertTrue($load);
}
/**
* This test only works if you have plugins/my_plugin set up.
* plugins/my_plugin/models/my_plugin.php and other_model.php
*/
/*
function testMultipleLoadingByType() {
$classes = array_flip(get_declared_classes());
$this->assertFalse(isset($classes['OtherPlugin']));
$this->assertFalse(isset($classes['MyPlugin']));
$load = App::import('Model', array('MyPlugin.OtherPlugin', 'MyPlugin.MyPlugin'));
$this->assertTrue($load);
$classes = array_flip(get_declared_classes());
$this->assertTrue(isset($classes['OtherPlugin']));
$this->assertTrue(isset($classes['MyPlugin']));
}
*/
function testLoadingVendor() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'vendors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'vendors'. DS),
), true);
ob_start();
$result = App::import('Vendor', 'TestPlugin.TestPluginAsset', array('ext' => 'css'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'this is the test plugin asset css file');
ob_start();
$result = App::import('Vendor', 'TestAsset', array('ext' => 'css'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'this is the test asset css file');
$result = App::import('Vendor', 'TestPlugin.SamplePlugin');
$this->assertTrue($result);
$this->assertTrue(class_exists('SamplePluginClassTestName'));
$result = App::import('Vendor', 'ConfigureTestVendorSample');
$this->assertTrue($result);
$this->assertTrue(class_exists('ConfigureTestVendorSample'));
ob_start();
$result = App::import('Vendor', 'SomeName', array('file' => 'some.name.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is a file with dot in file name');
ob_start();
$result = App::import('Vendor', 'TestHello', array('file' => 'Test'.DS.'hello.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the hello.php file in Test directory');
ob_start();
$result = App::import('Vendor', 'MyTest', array('file' => 'Test'.DS.'MyTest.php'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the MyTest.php file');
ob_start();
$result = App::import('Vendor', 'Welcome');
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the welcome.php file in vendors directory');
ob_start();
$result = App::import('Vendor', 'TestPlugin.Welcome');
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEqual($text, 'This is the welcome.php file in test_plugin/vendors directory');
}
}

View File

@@ -0,0 +1,587 @@
<?php
/**
* ComponentTest 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.controller
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Controller', 'Controller', false);
App::import('Controller', 'Component', false);
if (!class_exists('AppController')) {
/**
* AppController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class AppController extends Controller {
/**
* name property
*
* @var string 'App'
* @access public
*/
var $name = 'App';
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array();
/**
* helpers property
*
* @var array
* @access public
*/
var $helpers = array();
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Orange' => array('colour' => 'blood orange'));
}
} elseif (!defined('APP_CONTROLLER_EXISTS')){
define('APP_CONTROLLER_EXISTS', true);
}
/**
* ParamTestComponent
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ParamTestComponent extends Object {
/**
* name property
*
* @var string 'ParamTest'
* @access public
*/
var $name = 'ParamTest';
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Banana' => array('config' => 'value'));
/**
* initialize method
*
* @param mixed $controller
* @param mixed $settings
* @access public
* @return void
*/
function initialize(&$controller, $settings) {
foreach ($settings as $key => $value) {
if (is_numeric($key)) {
$this->{$value} = true;
} else {
$this->{$key} = $value;
}
}
}
}
/**
* ComponentTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ComponentTestController extends AppController {
/**
* name property
*
* @var string 'ComponentTest'
* @access public
*/
var $name = 'ComponentTest';
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array();
}
/**
* AppleComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class AppleComponent extends Object {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Orange');
/**
* testName property
*
* @var mixed null
* @access public
*/
var $testName = null;
/**
* startup method
*
* @param mixed $controller
* @access public
* @return void
*/
function startup(&$controller) {
$this->testName = $controller->name;
}
}
/**
* OrangeComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class OrangeComponent extends Object {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Banana');
/**
* initialize method
*
* @param mixed $controller
* @access public
* @return void
*/
function initialize(&$controller, $settings) {
$this->Controller = $controller;
$this->Banana->testField = 'OrangeField';
$this->settings = $settings;
}
/**
* startup method
*
* @param Controller $controller
* @return string
* @access public
*/
function startup(&$controller) {
$controller->foo = 'pass';
}
}
/**
* BananaComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class BananaComponent extends Object {
/**
* testField property
*
* @var string 'BananaField'
* @access public
*/
var $testField = 'BananaField';
/**
* startup method
*
* @param Controller $controller
* @return string
* @access public
*/
function startup(&$controller) {
$controller->bar = 'fail';
}
}
/**
* MutuallyReferencingOneComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class MutuallyReferencingOneComponent extends Object {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('MutuallyReferencingTwo');
}
/**
* MutuallyReferencingTwoComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class MutuallyReferencingTwoComponent extends Object {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('MutuallyReferencingOne');
}
/**
* SomethingWithEmailComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class SomethingWithEmailComponent extends Object {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Email');
}
Mock::generate('Object', 'ComponentMockComponent', array('startup', 'beforeFilter', 'beforeRender', 'other'));
/**
* ComponentTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ComponentTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_pluginPaths = App::path('plugins');
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
App::build();
ClassRegistry::flush();
}
/**
* testLoadComponents method
*
* @access public
* @return void
*/
function testLoadComponents() {
$Controller =& new ComponentTestController();
$Controller->components = array('RequestHandler');
$Component =& new Component();
$Component->init($Controller);
$this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent'));
$Controller =& new ComponentTestController();
$Controller->plugin = 'test_plugin';
$Controller->components = array('RequestHandler', 'TestPluginComponent');
$Component =& new Component();
$Component->init($Controller);
$this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent'));
$this->assertTrue(is_a($Controller->TestPluginComponent, 'TestPluginComponentComponent'));
$this->assertTrue(is_a(
$Controller->TestPluginComponent->TestPluginOtherComponent,
'TestPluginOtherComponentComponent'
));
$this->assertFalse(isset($Controller->TestPluginOtherComponent));
$Controller =& new ComponentTestController();
$Controller->components = array('Security');
$Component =& new Component();
$Component->init($Controller);
$this->assertTrue(is_a($Controller->Security, 'SecurityComponent'));
$this->assertTrue(is_a($Controller->Security->Session, 'SessionComponent'));
$Controller =& new ComponentTestController();
$Controller->components = array('Security', 'Cookie', 'RequestHandler');
$Component =& new Component();
$Component->init($Controller);
$this->assertTrue(is_a($Controller->Security, 'SecurityComponent'));
$this->assertTrue(is_a($Controller->Security->RequestHandler, 'RequestHandlerComponent'));
$this->assertTrue(is_a($Controller->RequestHandler, 'RequestHandlerComponent'));
$this->assertTrue(is_a($Controller->Cookie, 'CookieComponent'));
}
/**
* test component loading
*
* @return void
*/
function testNestedComponentLoading() {
$Controller =& new ComponentTestController();
$Controller->components = array('Apple');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$this->assertTrue(is_a($Controller->Apple, 'AppleComponent'));
$this->assertTrue(is_a($Controller->Apple->Orange, 'OrangeComponent'));
$this->assertTrue(is_a($Controller->Apple->Orange->Banana, 'BananaComponent'));
$this->assertTrue(is_a($Controller->Apple->Orange->Controller, 'ComponentTestController'));
$this->assertTrue(empty($Controller->Apple->Session));
$this->assertTrue(empty($Controller->Apple->Orange->Session));
}
/**
* Tests Component::startup() and only running callbacks for components directly attached to
* the controller.
*
* @return void
*/
function testComponentStartup() {
$Controller =& new ComponentTestController();
$Controller->components = array('Apple');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$Controller->beforeFilter();
$Controller->Component->startup($Controller);
$this->assertTrue(is_a($Controller->Apple, 'AppleComponent'));
$this->assertEqual($Controller->Apple->testName, 'ComponentTest');
$expected = !(defined('APP_CONTROLLER_EXISTS') && APP_CONTROLLER_EXISTS);
$this->assertEqual(isset($Controller->foo), $expected);
$this->assertFalse(isset($Controller->bar));
}
/**
* test that triggerCallbacks fires methods on all the components, and can trigger any method.
*
* @return void
*/
function testTriggerCallback() {
$Controller =& new ComponentTestController();
$Controller->components = array('ComponentMock');
$Controller->uses = null;
$Controller->constructClasses();
$Controller->ComponentMock->expectOnce('beforeRender');
$Controller->Component->triggerCallback('beforeRender', $Controller);
$Controller->ComponentMock->expectNever('beforeFilter');
$Controller->ComponentMock->enabled = false;
$Controller->Component->triggerCallback('beforeFilter', $Controller);
}
/**
* test a component being used more than once.
*
* @return void
*/
function testMultipleComponentInitialize() {
$Controller =& new ComponentTestController();
$Controller->uses = false;
$Controller->components = array('Orange', 'Banana');
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$this->assertEqual($Controller->Banana->testField, 'OrangeField');
$this->assertEqual($Controller->Orange->Banana->testField, 'OrangeField');
}
/**
* Test Component declarations with Parameters
* tests merging of component parameters and merging / construction of components.
*
* @return void
*/
function testComponentsWithParams() {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$Controller =& new ComponentTestController();
$Controller->components = array('ParamTest' => array('test' => 'value', 'flag'), 'Apple');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$this->assertTrue(is_a($Controller->ParamTest, 'ParamTestComponent'));
$this->assertTrue(is_a($Controller->ParamTest->Banana, 'BananaComponent'));
$this->assertTrue(is_a($Controller->Orange, 'OrangeComponent'));
$this->assertFalse(isset($Controller->Session));
$this->assertEqual($Controller->Orange->settings, array('colour' => 'blood orange'));
$this->assertEqual($Controller->ParamTest->test, 'value');
$this->assertEqual($Controller->ParamTest->flag, true);
//Settings are merged from app controller and current controller.
$Controller =& new ComponentTestController();
$Controller->components = array(
'ParamTest' => array('test' => 'value'),
'Orange' => array('ripeness' => 'perfect')
);
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$expected = array('colour' => 'blood orange', 'ripeness' => 'perfect');
$this->assertEqual($Controller->Orange->settings, $expected);
$this->assertEqual($Controller->ParamTest->test, 'value');
}
/**
* Ensure that settings are not duplicated when passed into component initialize.
*
* @return void
*/
function testComponentParamsNoDuplication() {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$Controller =& new ComponentTestController();
$Controller->components = array('Orange' => array('setting' => array('itemx')));
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$expected = array('setting' => array('itemx'), 'colour' => 'blood orange');
$this->assertEqual($Controller->Orange->settings, $expected, 'Params duplication has occured %s');
}
/**
* Test mutually referencing components.
*
* @return void
*/
function testMutuallyReferencingComponents() {
$Controller =& new ComponentTestController();
$Controller->components = array('MutuallyReferencingOne');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$this->assertTrue(is_a(
$Controller->MutuallyReferencingOne,
'MutuallyReferencingOneComponent'
));
$this->assertTrue(is_a(
$Controller->MutuallyReferencingOne->MutuallyReferencingTwo,
'MutuallyReferencingTwoComponent'
));
$this->assertTrue(is_a(
$Controller->MutuallyReferencingOne->MutuallyReferencingTwo->MutuallyReferencingOne,
'MutuallyReferencingOneComponent'
));
}
/**
* Test mutually referencing components.
*
* @return void
*/
function testSomethingReferencingEmailComponent() {
$Controller =& new ComponentTestController();
$Controller->components = array('SomethingWithEmail');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Component->initialize($Controller);
$Controller->beforeFilter();
$Controller->Component->startup($Controller);
$this->assertTrue(is_a(
$Controller->SomethingWithEmail,
'SomethingWithEmailComponent'
));
$this->assertTrue(is_a(
$Controller->SomethingWithEmail->Email,
'EmailComponent'
));
$this->assertTrue(is_a(
$Controller->SomethingWithEmail->Email->Controller,
'ComponentTestController'
));
}
/**
* Test that SessionComponent doesn't get added if its already in the components array.
*
* @return void
* @access public
*/
function testDoubleLoadingOfSessionComponent() {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
$Controller =& new ComponentTestController();
$Controller->uses = false;
$Controller->components = array('Session');
$Controller->constructClasses();
$this->assertEqual($Controller->components, array('Session' => '', 'Orange' => array('colour' => 'blood orange')));
}
}

View File

@@ -0,0 +1,646 @@
<?php
/**
* AclComponentTest 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.controller.components
* @since CakePHP(tm) v 1.2.0.5435
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import(array('controller' .DS . 'components' . DS . 'acl', 'model' . DS . 'db_acl'));
/**
* AclNodeTwoTestBase class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AclNodeTwoTestBase extends AclNode {
/**
* useDbConfig property
*
* @var string 'test_suite'
* @access public
*/
var $useDbConfig = 'test_suite';
/**
* cacheSources property
*
* @var bool false
* @access public
*/
var $cacheSources = false;
}
/**
* AroTwoTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AroTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string 'AroTwoTest'
* @access public
*/
var $name = 'AroTwoTest';
/**
* useTable property
*
* @var string 'aro_twos'
* @access public
*/
var $useTable = 'aro_twos';
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('AcoTwoTest' => array('with' => 'PermissionTwoTest'));
}
/**
* AcoTwoTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AcoTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string 'AcoTwoTest'
* @access public
*/
var $name = 'AcoTwoTest';
/**
* useTable property
*
* @var string 'aco_twos'
* @access public
*/
var $useTable = 'aco_twos';
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('AroTwoTest' => array('with' => 'PermissionTwoTest'));
}
/**
* PermissionTwoTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class PermissionTwoTest extends CakeTestModel {
/**
* name property
*
* @var string 'PermissionTwoTest'
* @access public
*/
var $name = 'PermissionTwoTest';
/**
* useTable property
*
* @var string 'aros_aco_twos'
* @access public
*/
var $useTable = 'aros_aco_twos';
/**
* cacheQueries property
*
* @var bool false
* @access public
*/
var $cacheQueries = false;
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array('AroTwoTest' => array('foreignKey' => 'aro_id'), 'AcoTwoTest' => array('foreignKey' => 'aco_id'));
/**
* actsAs property
*
* @var mixed null
* @access public
*/
var $actsAs = null;
}
/**
* DbAclTwoTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAclTwoTest extends DbAcl {
/**
* construct method
*
* @access private
* @return void
*/
function __construct() {
$this->Aro =& new AroTwoTest();
$this->Aro->Permission =& new PermissionTwoTest();
$this->Aco =& new AcoTwoTest();
$this->Aro->Permission =& new PermissionTwoTest();
}
}
/**
* IniAclTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class IniAclTest extends IniAcl {
}
/**
* ACL Component Text case
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AclComponentTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.aro_two', 'core.aco_two', 'core.aros_aco_two');
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->Acl =& new AclComponent();
}
/**
* before method
*
* @param mixed $method
* @access public
* @return void
*/
function before($method) {
Configure::write('Acl.classname', 'DbAclTwoTest');
Configure::write('Acl.database', 'test_suite');
parent::before($method);
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Acl);
}
/**
* testAclCreate method
*
* @access public
* @return void
*/
function testAclCreate() {
$this->Acl->Aro->create(array('alias' => 'Chotchkey'));
$this->assertTrue($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->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Stapler'));
$this->assertTrue($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->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'PiecesOfFlair'));
$this->assertTrue($this->Acl->Aco->save());
}
/**
* testAclCreateWithParent method
*
* @access public
* @return void
*/
function testAclCreateWithParent() {
$parent = $this->Acl->Aro->findByAlias('Peter', null, null, -1);
$this->Acl->Aro->create();
$this->Acl->Aro->save(array(
'alias' => 'Subordinate',
'model' => 'User',
'foreign_key' => 7,
'parent_id' => $parent['AroTwoTest']['id']
));
$result = $this->Acl->Aro->findByAlias('Subordinate', null, null, -1);
$this->assertEqual($result['AroTwoTest']['lft'], 16);
$this->assertEqual($result['AroTwoTest']['rght'], 17);
}
/**
* testDbAclAllow method
*
* @access public
* @return void
*/
function testDbAclAllow() {
$this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->allow('Micheal', 'tpsReports', array('read', 'delete', 'update')));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'update'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'create'));
$this->assertTrue($this->Acl->allow('Micheal', 'ROOT/tpsReports', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->allow('Micheal', 'printers', 'create'));
// Michael no longer has his delete permission for tpsReports!
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->check('Micheal', 'printers', 'create'));
$this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view'));
$this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/view', '*'));
$this->assertTrue($this->Acl->check('Samir', 'view', 'read'));
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update'));
$this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update','*'));
$this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/update', '*'));
$this->assertTrue($this->Acl->check('Samir', 'update', 'read'));
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', 'update'));
// 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->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->assertFalse($this->Acl->allow('Homer', 'tpsReports', 'create'));
}
/**
* testDbAclCheck method
*
* @access public
* @return void
*/
function testDbAclCheck() {
$this->assertTrue($this->Acl->check('Samir', 'print', 'read'));
$this->assertTrue($this->Acl->check('Lumbergh', 'current', 'read'));
$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'));
$this->assertTrue($this->Acl->check('Bobs', 'ROOT/tpsReports/view/current', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'ROOT/tpsReports/update', 'read'));
$this->assertFalse($this->Acl->check('root/users/Milton', 'smash', 'delete'));
}
/**
* testDbAclCascadingDeny function
*
* Setup the acl permissions such that Bobs inherits from admin.
* deny Admin delete access to a specific resource, check the permisssions are inherited.
*
* @access public
* @return void
*/
function testDbAclCascadingDeny() {
$this->Acl->inherit('Bobs', 'ROOT', '*');
$this->assertTrue($this->Acl->check('admin', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'delete'));
$this->Acl->deny('admin', 'tpsReports', 'delete');
$this->assertFalse($this->Acl->check('admin', 'tpsReports', 'delete'));
$this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'delete'));
}
/**
* testDbAclDeny method
*
* @access public
* @return void
*/
function testDbAclDeny() {
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'delete'));
$this->Acl->deny('Micheal', 'smash', 'delete');
$this->assertFalse($this->Acl->check('Micheal', 'smash', 'delete'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'update'));
$this->assertFalse($this->Acl->check('Micheal', 'smash', '*'));
$this->assertTrue($this->Acl->check('Samir', 'refill', '*'));
$this->Acl->deny('Samir', 'refill', '*');
$this->assertFalse($this->Acl->check('Samir', 'refill', 'create'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'update'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'delete'));
$result = $this->Acl->Aro->Permission->find('all', array('conditions' => array('AroTwoTest.alias' => 'Samir')));
$expected = '-1';
$this->assertEqual($result[0]['PermissionTwoTest']['_delete'], $expected);
$this->expectError('DbAcl::allow() - Invalid node');
$this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
/**
* testAclNodeLookup method
*
* @access public
* @return void
*/
function testAclNodeLookup() {
$result = $this->Acl->Aro->node('root/users/Samir');
$expected = array(
array('AroTwoTest' => array('id' => '7', 'parent_id' => '4', 'model' => 'User', 'foreign_key' => 3, 'alias' => 'Samir')),
array('AroTwoTest' => array('id' => '4', 'parent_id' => '1', 'model' => 'Group', 'foreign_key' => 3, 'alias' => 'users')),
array('AroTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'root'))
);
$this->assertEqual($result, $expected);
$result = $this->Acl->Aco->node('ROOT/tpsReports/view/current');
$expected = array(
array('AcoTwoTest' => array('id' => '4', 'parent_id' => '3', 'model' => null, 'foreign_key' => null, 'alias' => 'current')),
array('AcoTwoTest' => array('id' => '3', 'parent_id' => '2', 'model' => null, 'foreign_key' => null, 'alias' => 'view')),
array('AcoTwoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports')),
array('AcoTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT')),
);
$this->assertEqual($result, $expected);
}
/**
* testDbInherit method
*
* @access public
* @return void
*/
function testDbInherit() {
//parent doesn't have access inherit should still deny
$this->assertFalse($this->Acl->check('Milton', 'smash', 'delete'));
$this->Acl->inherit('Milton', 'smash', 'delete');
$this->assertFalse($this->Acl->check('Milton', 'smash', 'delete'));
//inherit parent
$this->assertFalse($this->Acl->check('Milton', 'smash', 'read'));
$this->Acl->inherit('Milton', 'smash', 'read');
$this->assertTrue($this->Acl->check('Milton', 'smash', 'read'));
}
/**
* testDbGrant method
*
* @access public
* @return void
*/
function testDbGrant() {
$this->assertFalse($this->Acl->check('Samir', 'tpsReports', 'create'));
$this->Acl->grant('Samir', 'tpsReports', 'create');
$this->assertTrue($this->Acl->check('Samir', 'tpsReports', 'create'));
$this->assertFalse($this->Acl->check('Micheal', 'view', 'read'));
$this->Acl->grant('Micheal', 'view', array('read', 'create', 'update'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'update'));
$this->assertFalse($this->Acl->check('Micheal', 'view', 'delete'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->assertFalse($this->Acl->grant('Peter', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
/**
* testDbRevoke method
*
* @access public
* @return void
*/
function testDbRevoke() {
$this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'read'));
$this->Acl->revoke('Bobs', 'tpsReports', 'read');
$this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->check('users', 'printers', 'read'));
$this->Acl->revoke('users', 'printers', 'read');
$this->assertFalse($this->Acl->check('users', 'printers', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'printers', 'read'));
$this->assertFalse($this->Acl->check('Peter', 'printers', 'read'));
$this->expectError('DbAcl::allow() - Invalid node');
$this->assertFalse($this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create'));
}
/**
* testStartup method
*
* @access public
* @return void
*/
function testStartup() {
$controller = new Controller();
$this->assertTrue($this->Acl->startup($controller));
}
/**
* testIniReadConfigFile
*
* @access public
* @return void
*/
function testIniReadConfigFile() {
Configure::write('Acl.classname', 'IniAclTest');
unset($this->Acl);
$this->Acl = new AclComponent();
$iniFile = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'config'. DS . 'acl.ini.php';
$result = $this->Acl->_Instance->readConfigFile($iniFile);
$expected = array(
'admin' => array(
'groups' => 'administrators',
'allow' => '',
'deny' => 'ads',
),
'paul' => array(
'groups' => 'users',
'allow' =>'',
'deny' => '',
),
'jenny' => array(
'groups' => 'users',
'allow' => 'ads',
'deny' => 'images, files',
),
'nobody' => array(
'groups' => 'anonymous',
'allow' => '',
'deny' => '',
),
'administrators' => array(
'deny' => '',
'allow' => 'posts, comments, images, files, stats, ads',
),
'users' => array(
'allow' => 'posts, comments, images, files',
'deny' => 'stats, ads',
),
'anonymous' => array(
'allow' => '',
'deny' => 'posts, comments, images, files, stats, ads',
),
);
$this->assertEqual($result, $expected);
}
/**
* testIniCheck method
*
* @access public
* @return void
*/
function testIniCheck() {
Configure::write('Acl.classname', 'IniAclTest');
unset($this->Acl);
$iniFile = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'config'. DS . 'acl.ini.php';
$this->Acl = new AclComponent();
$this->Acl->_Instance->config= $this->Acl->_Instance->readConfigFile($iniFile);
$this->assertFalse($this->Acl->check('admin', 'ads'));
$this->assertTrue($this->Acl->check('admin', 'posts'));
$this->assertTrue($this->Acl->check('jenny', 'posts'));
$this->assertTrue($this->Acl->check('jenny', 'ads'));
$this->assertTrue($this->Acl->check('paul', 'posts'));
$this->assertFalse($this->Acl->check('paul', 'ads'));
$this->assertFalse($this->Acl->check('nobody', 'comments'));
}
/**
* debug function - to help editing/creating test cases for the ACL component
*
* To check the overal ACL status at any time call $this->__debug();
* Generates a list of the current aro and aco structures and a grid dump of the permissions that are defined
* Only designed to work with the db based ACL
*
* @param bool $treesToo
* @access private
* @return void
*/
function __debug ($printTreesToo = false) {
$this->Acl->Aro->displayField = 'alias';
$this->Acl->Aco->displayField = 'alias';
$aros = $this->Acl->Aro->find('list', array('order' => 'lft'));
$acos = $this->Acl->Aco->find('list', array('order' => 'lft'));
$rights = array('*', 'create', 'read', 'update', 'delete');
$permissions['Aros v Acos >'] = $acos;
foreach ($aros as $aro) {
$row = array();
foreach ($acos as $aco) {
$perms = '';
foreach ($rights as $right) {
if ($this->Acl->check($aro, $aco, $right)) {
if ($right == '*') {
$perms .= '****';
break;
}
$perms .= $right[0];
} elseif ($right != '*') {
$perms .= ' ';
}
}
$row[] = $perms;
}
$permissions[$aro] = $row;
}
foreach ($permissions as $key => $values) {
array_unshift($values, $key);
$values = array_map(array(&$this, '__pad'), $values);
$permissions[$key] = implode (' ', $values);
}
$permisssions = array_map(array(&$this, '__pad'), $permissions);
array_unshift($permissions, 'Current Permissions :');
if ($printTreesToo) {
debug (array('aros' => $this->Acl->Aro->generateTreeList(), 'acos' => $this->Acl->Aco->generateTreeList()));
}
debug (implode("\r\n", $permissions));
}
/**
* pad function
* Used by debug to format strings used in the data dump
*
* @param string $string
* @param int $len
* @access private
* @return void
*/
function __pad($string = '', $len = 14) {
return str_pad($string, $len);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,468 @@
<?php
/**
* CookieComponentTest 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.controller.components
* @since CakePHP(tm) v 1.2.0.5435
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Controller', array('Component', 'Controller'), false);
App::import('Component', 'Cookie');
/**
* CookieComponentTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class CookieComponentTestController extends Controller {
/**
* components property
*
* @var array
* @access public
*/
var $components = array('Cookie');
/**
* beforeFilter method
*
* @access public
* @return void
*/
function beforeFilter() {
$this->Cookie->name = 'CakeTestCookie';
$this->Cookie->time = 10;
$this->Cookie->path = '/';
$this->Cookie->domain = '';
$this->Cookie->secure = false;
$this->Cookie->key = 'somerandomhaskey';
}
}
/**
* CookieComponentTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class CookieComponentTest extends CakeTestCase {
/**
* Controller property
*
* @var CookieComponentTestController
* @access public
*/
var $Controller;
/**
* start
*
* @access public
* @return void
*/
function start() {
$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();
}
/**
* end
*
* @access public
* @return void
*/
function end() {
$this->Controller->Cookie->destroy();
}
/**
* test that initialize sets settings from components array
*
* @return void
*/
function testInitialize() {
$settings = array(
'time' => '5 days',
'path' => '/'
);
$this->Controller->Cookie->initialize($this->Controller, $settings);
$this->assertEqual($this->Controller->Cookie->time, $settings['time']);
$this->assertEqual($this->Controller->Cookie->path, $settings['path']);
}
/**
* testCookieName
*
* @access public
* @return void
*/
function testCookieName() {
$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
*
* @access public
* @return void
*/
function testReadEncryptedCookieData() {
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$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
*
* @access public
* @return void
*/
function testReadPlainCookieData() {
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
}
/**
* testWritePlainCookieArray
*
* @access public
* @return void
*/
function testWritePlainCookieArray() {
$this->Controller->Cookie->write(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'), null, false);
$this->assertEqual($this->Controller->Cookie->read('name'), 'CakePHP');
$this->assertEqual($this->Controller->Cookie->read('version'), '1.2.0.x');
$this->assertEqual($this->Controller->Cookie->read('tag'), 'CakePHP Rocks!');
$this->Controller->Cookie->delete('name');
$this->Controller->Cookie->delete('version');
$this->Controller->Cookie->delete('tag');
}
/**
* testReadingCookieValue
*
* @access public
* @return void
*/
function testReadingCookieValue() {
$data = $this->Controller->Cookie->read();
$expected = array(
'Encrytped_array' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Encrytped_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Plain_array' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$this->assertEqual($data, $expected);
}
/**
* testDeleteCookieValue
*
* @access public
* @return void
*/
function testDeleteCookieValue() {
$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!');
$this->assertEqual($data, $expected);
$this->Controller->Cookie->delete('Encrytped_array');
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$this->assertEqual($data, $expected);
$this->Controller->Cookie->delete('Plain_multi_cookies.name');
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array('version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$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);
}
/**
* testReadingCookieArray
*
* @access public
* @return void
*/
function testReadingCookieArray() {
$data = $this->Controller->Cookie->read('Encrytped_array.name');
$expected = 'CakePHP';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_array.version');
$expected = '1.2.0.x';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_array.tag');
$expected = 'CakePHP Rocks!';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.name');
$expected = 'CakePHP';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.version');
$expected = '1.2.0.x';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies.tag');
$expected = 'CakePHP Rocks!';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array.name');
$expected = 'CakePHP';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array.version');
$expected = '1.2.0.x';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array.tag');
$expected = 'CakePHP Rocks!';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies.name');
$expected = 'CakePHP';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies.version');
$expected = '1.2.0.x';
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies.tag');
$expected = 'CakePHP Rocks!';
$this->assertEqual($data, $expected);
}
/**
* testReadingCookieDataOnStartup
*
* @access public
* @return void
*/
function testReadingCookieDataOnStartup() {
$this->Controller->Cookie->destroy();
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->__encrypt('CakePHP'),
'version' => $this->__encrypt('1.2.0.x'),
'tag' => $this->__encrypt('CakePHP Rocks!')),
'Plain_array' => 'name|CakePHP,version|1.2.0.x,tag|CakePHP Rocks!',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$this->Controller->Cookie->startup();
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$this->Controller->Cookie->destroy();
unset($_COOKIE['CakeTestCookie']);
}
/**
* testReadingCookieDataWithoutStartup
*
* @access public
* @return void
*/
function testReadingCookieDataWithoutStartup() {
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array();
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array();
$this->assertEqual($data, $expected);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->__encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->__encrypt('CakePHP'),
'version' => $this->__encrypt('1.2.0.x'),
'tag' => $this->__encrypt('CakePHP Rocks!')),
'Plain_array' => 'name|CakePHP,version|1.2.0.x,tag|CakePHP Rocks!',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$data = $this->Controller->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$data = $this->Controller->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' =>'CakePHP Rocks!');
$this->assertEqual($data, $expected);
$this->Controller->Cookie->destroy();
unset($_COOKIE['CakeTestCookie']);
}
/**
* encrypt method
*
* @param mixed $value
* @return string
* @access private
*/
function __encrypt($value) {
if (is_array($value)) {
$value = $this->__implode($value);
}
return "Q2FrZQ==." . base64_encode(Security::cipher($value, $this->Controller->Cookie->key));
}
/**
* implode method
*
* @param array $value
* @return string
* @access private
*/
function __implode($array) {
$string = '';
foreach ($array as $key => $value) {
$string .= ',' . $key . '|' . $value;
}
return substr($string, 1);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,731 @@
<?php
/**
* RequestHandlerComponentTest 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.controller.components
* @since CakePHP(tm) v 1.2.0.5435
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Controller', 'Controller', false);
App::import('Component', array('RequestHandler'));
Mock::generatePartial('RequestHandlerComponent', 'NoStopRequestHandler', array('_stop', '_header'));
Mock::generatePartial('Controller', 'RequestHandlerMockController', array('header'));
/**
* RequestHandlerTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class RequestHandlerTestController extends Controller {
/**
* name property
*
* @var string
* @access public
*/
var $name = 'RequestHandlerTest';
/**
* uses property
*
* @var mixed null
* @access public
*/
var $uses = null;
/**
* construct method
*
* @param array $params
* @access private
* @return void
*/
function __construct($params = array()) {
foreach ($params as $key => $val) {
$this->{$key} = $val;
}
parent::__construct();
}
/**
* test method for ajax redirection
*
* @return void
*/
function destination() {
$this->viewPath = 'posts';
$this->render('index');
}
/**
* test method for ajax redirection + parameter parsing
*
* @return void
*/
function param_method($one = null, $two = null) {
echo "one: $one two: $two";
$this->autoRender = false;
}
/**
* test method for testing layout rendering when isAjax()
*
* @return void
*/
function ajax2_layout() {
if ($this->autoLayout) {
$this->layout = 'ajax2';
}
$this->destination();
}
}
/**
* RequestHandlerTestDisabledController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class RequestHandlerTestDisabledController extends Controller {
/**
* uses property
*
* @var mixed null
* @access public
*/
var $uses = null;
/**
* construct method
*
* @param array $params
* @access private
* @return void
*/
function __construct($params = array()) {
foreach ($params as $key => $val) {
$this->{$key} = $val;
}
parent::__construct();
}
/**
* beforeFilter method
*
* @return void
* @access public
*/
function beforeFilter() {
$this->RequestHandler->enabled = false;
}
}
/**
* RequestHandlerComponentTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class RequestHandlerComponentTest extends CakeTestCase {
/**
* Controller property
*
* @var RequestHandlerTestController
* @access public
*/
var $Controller;
/**
* RequestHandler property
*
* @var RequestHandlerComponent
* @access public
*/
var $RequestHandler;
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->_init();
}
/**
* init method
*
* @access protected
* @return void
*/
function _init() {
$this->Controller = new RequestHandlerTestController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->RequestHandler =& $this->Controller->RequestHandler;
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
unset($this->RequestHandler);
unset($this->Controller);
if (!headers_sent()) {
header('Content-type: text/html'); //reset content type.
}
App::build();
}
/**
* testInitializeCallback method
*
* @access public
* @return void
*/
function testInitializeCallback() {
$this->assertNull($this->RequestHandler->ext);
$this->_init();
$this->Controller->params['url']['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->assertEqual($this->RequestHandler->ext, 'rss');
$settings = array(
'ajaxLayout' => 'test_ajax'
);
$this->RequestHandler->initialize($this->Controller, $settings);
$this->assertEqual($this->RequestHandler->ajaxLayout, 'test_ajax');
}
/**
* testDisabling method
*
* @access public
* @return void
*/
function testDisabling() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
$this->Controller->Component->initialize($this->Controller);
$this->Controller->beforeFilter();
$this->Controller->Component->startup($this->Controller);
$this->assertEqual($this->Controller->params, array('isAjax' => true));
$this->Controller = new RequestHandlerTestDisabledController(array('components' => array('RequestHandler')));
$this->Controller->constructClasses();
$this->Controller->Component->initialize($this->Controller);
$this->Controller->beforeFilter();
$this->Controller->Component->startup($this->Controller);
$this->assertEqual($this->Controller->params, array());
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
}
/**
* testAutoResponseType method
*
* @access public
* @return void
*/
function testAutoResponseType() {
$this->Controller->ext = '.thtml';
$this->Controller->params['url']['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->Controller->ext, '.ctp');
}
/**
* testAutoAjaxLayout method
*
* @access public
* @return void
*/
function testAutoAjaxLayout() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->RequestHandler->startup($this->Controller);
$this->assertTrue($this->Controller->layout, $this->RequestHandler->ajaxLayout);
$this->_init();
$this->Controller->params['url']['ext'] = 'js';
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertNotEqual($this->Controller->layout, 'ajax');
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
}
/**
* testStartupCallback method
*
* @access public
* @return void
*/
function testStartupCallback() {
$_SERVER['REQUEST_METHOD'] = 'PUT';
$_SERVER['CONTENT_TYPE'] = 'application/xml';
$this->RequestHandler->startup($this->Controller);
$this->assertTrue(is_array($this->Controller->data));
$this->assertFalse(is_object($this->Controller->data));
}
/**
* testStartupCallback with charset.
*
* @return void
*/
function testStartupCallbackCharset() {
$_SERVER['REQUEST_METHOD'] = 'PUT';
$_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
$this->RequestHandler->startup($this->Controller);
$this->assertTrue(is_array($this->Controller->data));
$this->assertFalse(is_object($this->Controller->data));
}
/**
* testNonAjaxRedirect method
*
* @access public
* @return void
*/
function testNonAjaxRedirect() {
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertNull($this->RequestHandler->beforeRedirect($this->Controller, '/'));
}
/**
* testRenderAs method
*
* @access public
* @return void
*/
function testRenderAs() {
$this->assertFalse(in_array('Xml', $this->Controller->helpers));
$this->RequestHandler->renderAs($this->Controller, 'xml');
$this->assertTrue(in_array('Xml', $this->Controller->helpers));
$this->Controller->viewPath = 'request_handler_test\\xml';
$this->RequestHandler->renderAs($this->Controller, 'js');
$this->assertEqual($this->Controller->viewPath, 'request_handler_test' . DS . 'js');
}
/**
* test that respondAs works as expected.
*
* @return void
*/
function testRespondAs() {
$RequestHandler = new NoStopRequestHandler();
$RequestHandler->expectAt(0, '_header', array('Content-Type: application/json'));
$RequestHandler->expectAt(1, '_header', array('Content-Type: text/xml'));
$result = $RequestHandler->respondAs('json');
$this->assertTrue($result);
$result = $RequestHandler->respondAs('text/xml');
$this->assertTrue($result);
}
/**
* test that attachment headers work with respondAs
*
* @return void
*/
function testRespondAsWithAttachment() {
$RequestHandler = new NoStopRequestHandler();
$RequestHandler->expectAt(0, '_header', array('Content-Disposition: attachment; filename="myfile.xml"'));
$RequestHandler->expectAt(1, '_header', array('Content-Type: text/xml'));
$result = $RequestHandler->respondAs('xml', array('attachment' => 'myfile.xml'));
$this->assertTrue($result);
}
/**
* test that calling renderAs() more than once continues to work.
*
* @link #6466
* @return void
*/
function testRenderAsCalledTwice() {
$this->RequestHandler->renderAs($this->Controller, 'xml');
$this->assertEqual($this->Controller->viewPath, 'request_handler_test' . DS . 'xml');
$this->assertEqual($this->Controller->layoutPath, 'xml');
$this->assertTrue(in_array('Xml', $this->Controller->helpers));
$this->RequestHandler->renderAs($this->Controller, 'js');
$this->assertEqual($this->Controller->viewPath, 'request_handler_test' . DS . 'js');
$this->assertEqual($this->Controller->layoutPath, 'js');
$this->assertTrue(in_array('Js', $this->Controller->helpers));
}
/**
* testRequestClientTypes method
*
* @access public
* @return void
*/
function testRequestClientTypes() {
$this->assertFalse($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Shockwave Flash';
$this->assertTrue($this->RequestHandler->isFlash());
unset($_SERVER['HTTP_USER_AGENT'], $_SERVER['HTTP_X_REQUESTED_WITH']);
$this->assertFalse($this->RequestHandler->isAjax());
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$_SERVER['HTTP_X_PROTOTYPE_VERSION'] = '1.5';
$this->assertTrue($this->RequestHandler->isAjax());
$this->assertEqual($this->RequestHandler->getAjaxVersion(), '1.5');
unset($_SERVER['HTTP_X_REQUESTED_WITH'], $_SERVER['HTTP_X_PROTOTYPE_VERSION']);
$this->assertFalse($this->RequestHandler->isAjax());
$this->assertFalse($this->RequestHandler->getAjaxVersion());
}
/**
* Tests the detection of various Flash versions
*
* @access public
* @return void
*/
function testFlashDetection() {
$_agent = env('HTTP_USER_AGENT');
$_SERVER['HTTP_USER_AGENT'] = 'Shockwave Flash';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash Player 9';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Adobe Flash Player 10';
$this->assertTrue($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = 'Shock Flash';
$this->assertFalse($this->RequestHandler->isFlash());
$_SERVER['HTTP_USER_AGENT'] = $_agent;
}
/**
* testRequestContentTypes method
*
* @access public
* @return void
*/
function testRequestContentTypes() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->assertNull($this->RequestHandler->requestedWith());
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['CONTENT_TYPE'] = 'application/json';
$this->assertEqual($this->RequestHandler->requestedWith(), 'json');
$result = $this->RequestHandler->requestedWith(array('json', 'xml'));
$this->assertEqual($result, 'json');
$result =$this->RequestHandler->requestedWith(array('rss', 'atom'));
$this->assertFalse($result);
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isXml());
$this->assertFalse($this->RequestHandler->isAtom());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isAtom());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertFalse($this->RequestHandler->isAtom());
$this->assertTrue($this->RequestHandler->isRSS());
$this->assertFalse($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertTrue($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
}
/**
* testResponseContentType method
*
* @access public
* @return void
*/
function testResponseContentType() {
$this->assertNull($this->RequestHandler->responseType());
$this->assertTrue($this->RequestHandler->respondAs('atom'));
$this->assertEqual($this->RequestHandler->responseType(), 'atom');
}
/**
* testMobileDeviceDetection method
*
* @access public
* @return void
*/
function testMobileDeviceDetection() {
$this->assertFalse($this->RequestHandler->isMobile());
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3';
$this->assertTrue($this->RequestHandler->isMobile());
$_SERVER['HTTP_USER_AGENT'] = 'Some imaginary UA';
$this->RequestHandler->mobileUA []= 'imaginary';
$this->assertTrue($this->RequestHandler->isMobile());
array_pop($this->RequestHandler->mobileUA);
}
/**
* testRequestProperties method
*
* @access public
* @return void
*/
function testRequestProperties() {
$_SERVER['HTTPS'] = 'on';
$this->assertTrue($this->RequestHandler->isSSL());
unset($_SERVER['HTTPS']);
$this->assertFalse($this->RequestHandler->isSSL());
$_ENV['SCRIPT_URI'] = 'https://localhost/';
$s = $_SERVER;
$_SERVER = array();
$this->assertTrue($this->RequestHandler->isSSL());
$_SERVER = $s;
}
/**
* testRequestMethod method
*
* @access public
* @return void
*/
function testRequestMethod() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->assertTrue($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertTrue($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'PUT';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertTrue($this->RequestHandler->isPut());
$this->assertFalse($this->RequestHandler->isDelete());
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$this->assertFalse($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertFalse($this->RequestHandler->isPut());
$this->assertTrue($this->RequestHandler->isDelete());
}
/**
* testClientContentPreference method
*
* @access public
* @return void
*/
function testClientContentPreference() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->_init();
$this->assertNotEqual($this->RequestHandler->prefers(), 'rss');
$this->RequestHandler->ext = 'rss';
$this->assertEqual($this->RequestHandler->prefers(), 'rss');
$this->assertFalse($this->RequestHandler->prefers('xml'));
$this->assertEqual($this->RequestHandler->prefers(array('js', 'xml', 'xhtml')), 'xml');
$this->assertTrue($this->RequestHandler->accepts('xml'));
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->_init();
$this->assertEqual($this->RequestHandler->prefers(), 'xml');
$this->assertEqual($this->RequestHandler->accepts(array('js', 'xml', 'html')), 'xml');
$this->assertFalse($this->RequestHandler->accepts(array('gif', 'jpeg', 'foo')));
$_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5';
$this->_init();
$this->assertEqual($this->RequestHandler->prefers(), 'html');
$this->assertFalse($this->RequestHandler->prefers('rss'));
$this->assertFalse($this->RequestHandler->accepts('rss'));
}
/**
* testCustomContent method
*
* @access public
* @return void
*/
function testCustomContent() {
$_SERVER['HTTP_ACCEPT'] = 'text/x-mobile,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5';
$this->_init();
$this->RequestHandler->setContent('mobile', 'text/x-mobile');
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->RequestHandler->prefers(), 'mobile');
$this->_init();
$this->RequestHandler->setContent(array('mobile' => 'text/x-mobile'));
$this->RequestHandler->startup($this->Controller);
$this->assertEqual($this->RequestHandler->prefers(), 'mobile');
}
/**
* testClientProperties method
*
* @access public
* @return void
*/
function testClientProperties() {
$_SERVER['HTTP_HOST'] = 'localhost:80';
$this->assertEqual($this->RequestHandler->getReferer(), 'localhost');
$_SERVER['HTTP_HOST'] = null;
$_SERVER['HTTP_X_FORWARDED_HOST'] = 'cakephp.org';
$this->assertEqual($this->RequestHandler->getReferer(), 'cakephp.org');
$_SERVER['HTTP_X_FORWARDED_FOR'] = '192.168.1.5, 10.0.1.1, proxy.com';
$_SERVER['HTTP_CLIENT_IP'] = '192.168.1.2';
$_SERVER['REMOTE_ADDR'] = '192.168.1.3';
$this->assertEqual($this->RequestHandler->getClientIP(false), '192.168.1.5');
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.2');
unset($_SERVER['HTTP_X_FORWARDED_FOR']);
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.2');
unset($_SERVER['HTTP_CLIENT_IP']);
$this->assertEqual($this->RequestHandler->getClientIP(), '192.168.1.3');
$_SERVER['HTTP_CLIENTADDRESS'] = '10.0.1.2, 10.0.1.1';
$this->assertEqual($this->RequestHandler->getClientIP(), '10.0.1.2');
}
/**
* test that ajax requests involving redirects trigger requestAction instead.
*
* @return void
*/
function testAjaxRedirectAsRequestAction() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
$this->Controller->RequestHandler = new NoStopRequestHandler($this);
$this->Controller->RequestHandler->expectOnce('_stop');
ob_start();
$this->Controller->RequestHandler->beforeRedirect(
$this->Controller, array('controller' => 'request_handler_test', 'action' => 'destination')
);
$result = ob_get_clean();
$this->assertPattern('/posts index/', $result, 'RequestAction redirect failed.');
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
App::build();
}
/**
* test that ajax requests involving redirects don't force no layout
* this would cause the ajax layout to not be rendered.
*
* @return void
*/
function testAjaxRedirectAsRequestActionStillRenderingLayout() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
$this->Controller->RequestHandler = new NoStopRequestHandler($this);
$this->Controller->RequestHandler->expectOnce('_stop');
ob_start();
$this->Controller->RequestHandler->beforeRedirect(
$this->Controller, array('controller' => 'request_handler_test', 'action' => 'ajax2_layout')
);
$result = ob_get_clean();
$this->assertPattern('/posts index/', $result, 'RequestAction redirect failed.');
$this->assertPattern('/Ajax!/', $result, 'Layout was not rendered.');
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
App::build();
}
/**
* test that the beforeRedirect callback properly converts
* array urls into their correct string ones, and adds base => false so
* the correct urls are generated.
*
* @link http://cakephp.lighthouseapp.com/projects/42648-cakephp-1x/tickets/276
* @return void
*/
function testBeforeRedirectCallbackWithArrayUrl() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'named' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')),
array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/')
));
$RequestHandler =& new NoStopRequestHandler();
ob_start();
$RequestHandler->beforeRedirect(
$this->Controller,
array('controller' => 'request_handler_test', 'action' => 'param_method', 'first', 'second')
);
$result = ob_get_clean();
$this->assertEqual($result, 'one: first two: second');
}
/**
* assure that beforeRedirect with a status code will correctly set the status header
*
* @return void
*/
function testBeforeRedirectCallingHeader() {
$controller =& new RequestHandlerMockController();
$RequestHandler =& new NoStopRequestHandler();
$controller->expectOnce('header', array('HTTP/1.1 403 Forbidden'));
ob_start();
$RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403);
$result = ob_get_clean();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,385 @@
<?php
/**
* SessionComponentTest 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.controller.components
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Controller', 'Controller', false);
App::import('Component', 'Session');
/**
* SessionTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class SessionTestController extends Controller {
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array();
/**
* session_id method
*
* @return string
* @access public
*/
function session_id() {
return $this->Session->id();
}
}
/**
* OrangeSessionTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class OrangeSessionTestController extends Controller {
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array();
/**
* session_id method
*
* @return string
* @access public
*/
function session_id() {
return $this->Session->id();
}
}
/**
* SessionComponentTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class SessionComponentTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->_session = Configure::read('Session');
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('Session', $this->_session);
}
/**
* testSessionAutoStart method
*
* @access public
* @return void
*/
function testSessionAutoStart() {
Configure::write('Session.start', false);
$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);
$this->assertFalse($Session->started());
$Session->startup(new SessionTestController());
$this->assertTrue(isset($_SESSION));
$Object = new Object();
$Session =& new SessionComponent();
$Session->start();
$expected = $Session->id();
$result = $Object->requestAction('/session_test/session_id');
$this->assertEqual($result, $expected);
$result = $Object->requestAction('/orange_session_test/session_id');
$this->assertEqual($result, $expected);
}
/**
* testSessionActivate method
*
* @access public
* @return void
*/
function testSessionActivate() {
$Session =& new SessionComponent();
$this->assertTrue($Session->__active);
$this->assertNull($Session->activate());
$this->assertTrue($Session->__active);
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$this->assertNull($Session->activate());
$this->assertTrue($Session->__active);
Configure::write('Session.start', true);
$Session->destroy();
}
/**
* testSessionValid method
*
* @access public
* @return void
*/
function testSessionValid() {
$Session =& new SessionComponent();
$this->assertTrue($Session->valid());
$Session->_userAgent = 'rweerw';
$this->assertFalse($Session->valid());
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$this->assertFalse($Session->valid());
Configure::write('Session.start', true);
$Session =& new SessionComponent();
$Session->time = $Session->read('Config.time') + 1;
$this->assertFalse($Session->valid());
Configure::write('Session.checkAgent', false);
$Session =& new SessionComponent();
$Session->time = $Session->read('Config.time') + 1;
$this->assertFalse($Session->valid());
Configure::write('Session.checkAgent', true);
}
/**
* testSessionError method
*
* @access public
* @return void
*/
function testSessionError() {
$Session =& new SessionComponent();
$this->assertFalse($Session->error());
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->__active);
$this->assertFalse($Session->error());
Configure::write('Session.start', true);
}
/**
* testSessionReadWrite method
*
* @access public
* @return void
*/
function testSessionReadWrite() {
$Session =& new SessionComponent();
$this->assertFalse($Session->read('Test'));
$this->assertTrue($Session->write('Test', 'some value'));
$this->assertEqual($Session->read('Test'), 'some value');
$this->assertFalse($Session->write('Test.key', 'some value'));
$Session->delete('Test');
$this->assertTrue($Session->write('Test.key.path', 'some value'));
$this->assertEqual($Session->read('Test.key.path'), 'some value');
$this->assertEqual($Session->read('Test.key'), array('path' => 'some value'));
$this->assertTrue($Session->write('Test.key.path2', 'another value'));
$this->assertEqual($Session->read('Test.key'), array('path' => 'some value', 'path2' => 'another value'));
$Session->delete('Test');
$array = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
$this->assertTrue($Session->write('Test', $array));
$this->assertEqual($Session->read('Test'), $array);
$Session->delete('Test');
$this->assertFalse($Session->write(array('Test'), 'some value'));
$this->assertTrue($Session->write(array('Test' => 'some value')));
$this->assertEqual($Session->read('Test'), 'some value');
$Session->delete('Test');
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$this->assertFalse($Session->write('Test', 'some value'));
$Session->write('Test', 'some value');
$this->assertFalse($Session->read('Test'));
Configure::write('Session.start', true);
}
/**
* testSessionDelete method
*
* @access public
* @return void
*/
function testSessionDelete() {
$Session =& new SessionComponent();
$this->assertFalse($Session->delete('Test'));
$Session->write('Test', 'some value');
$this->assertTrue($Session->delete('Test'));
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$Session->write('Test', 'some value');
$this->assertFalse($Session->delete('Test'));
Configure::write('Session.start', true);
}
/**
* testSessionCheck method
*
* @access public
* @return void
*/
function testSessionCheck() {
$Session =& new SessionComponent();
$this->assertFalse($Session->check('Test'));
$Session->write('Test', 'some value');
$this->assertTrue($Session->check('Test'));
$Session->delete('Test');
Configure::write('Session.start', false);
$Session =& new SessionComponent();
$Session->write('Test', 'some value');
$this->assertFalse($Session->check('Test'));
Configure::write('Session.start', true);
}
/**
* testSessionFlash method
*
* @access public
* @return void
*/
function testSessionFlash() {
$Session =& new SessionComponent();
$this->assertNull($Session->read('Message.flash'));
$Session->setFlash('This is a test message');
$this->assertEqual($Session->read('Message.flash'), array('message' => 'This is a test message', 'element' => 'default', 'params' => array()));
$Session->setFlash('This is a test message', 'test', array('name' => 'Joel Moss'));
$this->assertEqual($Session->read('Message.flash'), array('message' => 'This is a test message', 'element' => 'test', 'params' => array('name' => 'Joel Moss')));
$Session->setFlash('This is a test message', 'default', array(), 'myFlash');
$this->assertEqual($Session->read('Message.myFlash'), array('message' => 'This is a test message', 'element' => 'default', 'params' => array()));
$Session->setFlash('This is a test message', 'non_existing_layout');
$this->assertEqual($Session->read('Message.myFlash'), array('message' => 'This is a test message', 'element' => 'default', 'params' => array()));
$Session->delete('Message');
}
/**
* testSessionId method
*
* @access public
* @return void
*/
function testSessionId() {
unset($_SESSION);
$Session =& new SessionComponent();
$this->assertNull($Session->id());
}
/**
* testSessionDestroy method
*
* @access public
* @return void
*/
function testSessionDestroy() {
$Session =& new SessionComponent();
$Session->write('Test', 'some value');
$this->assertEqual($Session->read('Test'), 'some value');
$Session->destroy('Test');
$this->assertNull($Session->read('Test'));
}
/**
* testSessionTimeout method
*
* @access public
* @return void
*/
function testSessionTimeout() {
Configure::write('debug', 2);
Configure::write('Security.level', 'low');
session_destroy();
$Session =& new SessionComponent();
$Session->destroy();
$Session->write('Test', 'some value');
$this->assertEqual($Session->sessionTime, time() + (300 * Configure::read('Session.timeout')));
$this->assertEqual($_SESSION['Config']['timeout'], 10);
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);
$this->assertEqual($Session->time, time());
$this->assertEqual($_SESSION['Config']['time'], $Session->time + (300 * Configure::read('Session.timeout')));
Configure::write('Security.level', 'medium');
$Session =& new SessionComponent();
$Session->destroy();
$Session->write('Test', 'some value');
$this->assertEqual($Session->sessionTime, mktime() + (100 * Configure::read('Session.timeout')));
$this->assertEqual($_SESSION['Config']['timeout'], 10);
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);
$this->assertEqual($Session->time, time());
$this->assertEqual($_SESSION['Config']['time'], $Session->time + (Security::inactiveMins() * Configure::read('Session.timeout')));
Configure::write('Security.level', 'high');
$Session =& new SessionComponent();
$Session->destroy();
$Session->write('Test', 'some value');
$this->assertEqual($Session->sessionTime, time() + (10 * Configure::read('Session.timeout')));
$this->assertEqual($_SESSION['Config']['timeout'], 10);
$this->assertEqual($_SESSION['Config']['time'], $Session->sessionTime);
$this->assertEqual($Session->time, time());
$this->assertEqual($_SESSION['Config']['time'], $Session->time + (Security::inactiveMins() * Configure::read('Session.timeout')));
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,238 @@
<?php
/**
* Controller Merge vars Test file
*
* Isolated from the Controller and Component test as to not pollute their AppController class
*
* 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.controller
* @since CakePHP(tm) v 1.2.3
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('AppController')) {
/**
* Test case AppController
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class AppController extends Controller {
/**
* components
*
* @var array
*/
var $components = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
/**
* helpers
*
* @var array
*/
var $helpers = array('MergeVar' => array('format' => 'html', 'terse'));
}
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
/**
* MergeVar Component
*
* @package cake.tests.cases.libs.controller
*/
class MergeVarComponent extends Object {
}
/**
* Additional controller for testing
*
* @package cake.tests.cases.libs.controller
*/
class MergeVariablesController extends AppController {
/**
* name
*
* @var string
*/
var $name = 'MergeVariables';
/**
* uses
*
* @var arrays
*/
var $uses = array();
}
/**
* MergeVarPlugin App Controller
*
* @package cake.tests.cases.libs.controller
*/
class MergeVarPluginAppController extends AppController {
/**
* components
*
* @var array
*/
var $components = array('Auth' => array('setting' => 'val', 'otherVal'));
/**
* helpers
*
* @var array
*/
var $helpers = array('Javascript');
}
/**
* MergePostsController
*
* @package cake.tests.cases.libs.controller
*/
class MergePostsController extends MergeVarPluginAppController {
/**
* name
*
* @var string
*/
var $name = 'MergePosts';
/**
* uses
*
* @var array
*/
var $uses = array();
}
/**
* Test Case for Controller Merging of Vars.
*
* @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');
}
/**
* end test
*
* @return void
*/
function endTest() {
ClassRegistry::flush();
}
/**
* test that component settings are not duplicated when merging component settings
*
* @return void
*/
function testComponentParamMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
$this->assertEqual($Controller->components, $expected, 'Duplication of settings occured. %s');
}
/**
* test component merges with redeclared components
*
* @return void
*/
function testComponentMergingWithRedeclarations() {
$Controller =& new MergeVariablesController();
$Controller->components['MergeVar'] = array('remote', 'redirect' => true);
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => true, 'remote'));
$this->assertEqual($Controller->components, $expected, 'Merging of settings is wrong. %s');
}
/**
* test merging of helpers array, ensure no duplication occurs
*
* @return void
*/
function testHelperSettingMergingNoDuplication() {
$Controller =& new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('format' => 'html', 'terse'));
$this->assertEqual($Controller->helpers, $expected, 'Duplication of settings occured. %s');
}
/**
* test merging of vars with plugin
*
* @return void
*/
function testMergeVarsWithPlugin() {
$Controller =& new MergePostsController();
$Controller->components = array('Email' => array('ports' => 'open'));
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
'Email' => array('ports' => 'open')
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
$expected = array(
'Javascript',
'MergeVar' => array('format' => 'html', 'terse')
);
$this->assertEqual($Controller->helpers, $expected, 'Helpers are unexpected %s');
$Controller =& new MergePostsController();
$Controller->components = array();
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
);
$this->assertEqual($Controller->components, $expected, 'Components are unexpected %s');
}
/**
* Ensure that __mergeVars is not being greedy and merging with
* AppController when you make an instance of Controller
*
* @return void
*/
function testMergeVarsNotGreedy() {
$Controller =& new Controller();
$Controller->components = array();
$Controller->uses = array();
$Controller->constructClasses();
$this->assertFalse(isset($Controller->Session));
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* PagesControllerTest 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.controller
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!class_exists('AppController')) {
require_once LIBS . 'controller' . DS . 'app_controller.php';
} elseif (!defined('APP_CONTROLLER_EXISTS')) {
define('APP_CONTROLLER_EXISTS', true);
}
App::import('Controller', 'Pages');
/**
* PagesControllerTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class PagesControllerTest extends CakeTestCase {
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testDisplay method
*
* @access public
* @return void
*/
function testDisplay() {
if ($this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController')) {
return;
}
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS, TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)
));
$Pages =& new PagesController();
$Pages->viewPath = 'posts';
$Pages->display('index');
$this->assertPattern('/posts index/', $Pages->output);
$this->assertEqual($Pages->viewVars['page'], 'index');
$Pages->viewPath = 'themed';
$Pages->display('test_theme', 'posts', 'index');
$this->assertPattern('/posts index themed view/', $Pages->output);
$this->assertEqual($Pages->viewVars['page'], 'test_theme');
$this->assertEqual($Pages->viewVars['subpage'], 'posts');
}
}

View File

@@ -0,0 +1,897 @@
<?php
/**
* ScaffoldTest 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.controller
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Scaffold');
/**
* ScaffoldMockController class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldMockController extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
* @access public
*/
var $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
* @access public
*/
var $scaffold;
}
/**
* ScaffoldMockControllerWithFields class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldMockControllerWithFields extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
* @access public
*/
var $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
* @access public
*/
var $scaffold;
/**
* function _beforeScaffold
*
* @param string method
*/
function _beforeScaffold($method) {
$this->set('scaffoldFields', array('title'));
return true;
}
}
/**
* TestScaffoldMock class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class TestScaffoldMock extends Scaffold {
/**
* Overload __scaffold
*
* @param unknown_type $params
*/
function __scaffold($params) {
$this->_params = $params;
}
/**
* Get Params from the Controller.
*
* @return unknown
*/
function getParams() {
return $this->_params;
}
}
/**
* ScaffoldMock class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldMock extends CakeTestModel {
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'articles';
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'User' => array(
'className' => 'ScaffoldUser',
'foreignKey' => 'user_id',
)
);
/**
* hasMany property
*
* @var array
* @access public
*/
var $hasMany = array(
'Comment' => array(
'className' => 'ScaffoldComment',
'foreignKey' => 'article_id',
)
);
/**
* hasAndBelongsToMany property
*
* @var string
*/
var $hasAndBelongsToMany = array(
'ScaffoldTag' => array(
'className' => 'ScaffoldTag',
'foreignKey' => 'something_id',
'associationForeignKey' => 'something_else_id',
'joinTable' => 'join_things'
)
);
}
/**
* ScaffoldUser class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldUser extends CakeTestModel {
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'users';
/**
* hasMany property
*
* @var array
* @access public
*/
var $hasMany = array(
'Article' => array(
'className' => 'ScaffoldMock',
'foreignKey' => 'article_id',
)
);
}
/**
* ScaffoldComment class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldComment extends CakeTestModel {
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'comments';
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'Article' => array(
'className' => 'ScaffoldMock',
'foreignKey' => 'article_id',
)
);
}
/**
* ScaffoldTag class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldTag extends CakeTestModel {
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'tags';
}
/**
* TestScaffoldView class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class TestScaffoldView extends ScaffoldView {
/**
* testGetFilename method
*
* @param mixed $action
* @access public
* @return void
*/
function testGetFilename($action) {
return $this->_getViewFileName($action);
}
}
/**
* ScaffoldViewTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldViewTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag');
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->Controller =& new ScaffoldMockController();
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
unset($this->Controller);
App::build();
}
/**
* testGetViewFilename method
*
* @access public
* @return void
*/
function testGetViewFilename() {
$_admin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$this->Controller->action = 'index';
$ScaffoldView =& new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'index.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('edit');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('add');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('view');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'view.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('admin_index');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'index.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('admin_view');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'view.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('admin_edit');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('admin_add');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS . 'scaffolds' . DS . 'edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('error');
$expected = 'cake' . DS . 'libs' . DS . 'view' . DS . 'errors' . DS . 'scaffold_error.ctp';
$this->assertEqual($result, $expected);
$Controller =& new ScaffoldMockController();
$Controller->scaffold = 'admin';
$Controller->viewPath = 'posts';
$Controller->action = 'admin_edit';
$ScaffoldView =& new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_edit');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('edit');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' .DS . 'views' . DS . 'posts' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
$Controller =& new ScaffoldMockController();
$Controller->scaffold = 'admin';
$Controller->viewPath = 'tests';
$Controller->plugin = 'test_plugin';
$Controller->action = 'admin_add';
$ScaffoldView =& new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_add');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'
. DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
$result = $ScaffoldView->testGetFilename('add');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'
. DS .'test_plugin' . DS . 'views' . DS . 'tests' . DS . 'scaffold.edit.ctp';
$this->assertEqual($result, $expected);
Configure::write('Routing.prefixes', $_admin);
}
/**
* test getting the view file name for themed scaffolds.
*
* @return void
*/
function testGetViewFileNameWithTheme() {
$this->Controller->action = 'index';
$this->Controller->viewPath = 'posts';
$this->Controller->theme = 'test_theme';
$ScaffoldView =& new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS
. 'themed' . DS . 'test_theme' . DS . 'posts' . DS . 'scaffold.index.ctp';
$this->assertEqual($result, $expected);
}
/**
* test default index scaffold generation
*
* @access public
* @return void
*/
function testIndexScaffold() {
$this->Controller->action = 'index';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'index',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('#<h2>Scaffold Mock</h2>#', $result);
$this->assertPattern('#<table cellpadding="0" cellspacing="0">#', $result);
$this->assertPattern('#<a href="/scaffold_users/view/1">1</a>#', $result); //belongsTo links
$this->assertPattern('#<li><a href="/scaffold_mock/add">New Scaffold Mock</a></li>#', $result);
$this->assertPattern('#<li><a href="/scaffold_users">List Scaffold Users</a></li>#', $result);
$this->assertPattern('#<li><a href="/scaffold_comments/add">New Comment</a></li>#', $result);
}
/**
* test default view scaffold generation
*
* @access public
* @return void
*/
function testViewScaffold() {
$this->Controller->action = 'view';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'view',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<h2>View Scaffold Mock<\/h2>/', $result);
$this->assertPattern('/<dl>/', $result);
//TODO: add specific tests for fields.
$this->assertPattern('/<a href="\/scaffold_users\/view\/1">1<\/a>/', $result); //belongsTo links
$this->assertPattern('/<li><a href="\/scaffold_mock\/edit\/1">Edit Scaffold Mock<\/a>\s<\/li>/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/delete\/1"[^>]*>Delete Scaffold Mock<\/a>\s*<\/li>/', $result);
//check related table
$this->assertPattern('/<div class="related">\s*<h3>Related Scaffold Comments<\/h3>\s*<table cellpadding="0" cellspacing="0">/', $result);
$this->assertPattern('/<li><a href="\/scaffold_comments\/add">New Comment<\/a><\/li>/', $result);
$this->assertNoPattern('/<th>JoinThing<\/th>/', $result);
}
/**
* test default view scaffold generation
*
* @access public
* @return void
*/
function testEditScaffold() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<form id="ScaffoldMockEditForm" method="post" action="\/scaffold_mock\/edit\/1"/', $result);
$this->assertPattern('/<legend>Edit Scaffold Mock<\/legend>/', $result);
$this->assertPattern('/input type="hidden" name="data\[ScaffoldMock\]\[id\]" value="1" id="ScaffoldMockId"/', $result);
$this->assertPattern('/select name="data\[ScaffoldMock\]\[user_id\]" id="ScaffoldMockUserId"/', $result);
$this->assertPattern('/input name="data\[ScaffoldMock\]\[title\]" type="text" maxlength="255" value="First Article" id="ScaffoldMockTitle"/', $result);
$this->assertPattern('/input name="data\[ScaffoldMock\]\[published\]" type="text" maxlength="1" value="Y" id="ScaffoldMockPublished"/', $result);
$this->assertPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
$this->assertPattern('/<li><a href="\/scaffold_mock\/delete\/1"[^>]*>Delete<\/a>\s*<\/li>/', $result);
}
/**
* Test Admin Index Scaffolding.
*
* @access public
* @return void
*/
function testAdminIndexScaffold() {
$_backAdmin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'prefix' => 'admin',
'url' => array('url' =>'admin/scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'admin_index',
'admin' => 1,
);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'admin_index';
$this->Controller->here = '/tests/admin/scaffold_mock';
$this->Controller->webroot = '/';
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<h2>Scaffold Mock<\/h2>/', $result);
$this->assertPattern('/<table cellpadding="0" cellspacing="0">/', $result);
//TODO: add testing for table generation
$this->assertPattern('/<li><a href="\/admin\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
Configure::write('Routing.prefixes', $_backAdmin);
}
/**
* Test Admin Index Scaffolding.
*
* @access public
* @return void
*/
function testAdminEditScaffold() {
$_backAdmin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'prefix' => 'admin',
'url' => array('url' =>'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => 1,
);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/admin/scaffold_mock/edit', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'admin_index';
$this->Controller->here = '/tests/admin/scaffold_mock';
$this->Controller->webroot = '/';
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('#admin/scaffold_mock/edit/1#', $result);
$this->assertPattern('#Scaffold Mock#', $result);
Configure::write('Routing.prefixes', $_backAdmin);
}
/**
* Test Admin Index Scaffolding.
*
* @access public
* @return void
*/
function testMultiplePrefixScaffold() {
$_backAdmin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin', 'member'));
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'prefix' => 'member',
'url' => array('url' =>'member/scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'member_index',
'member' => 1,
);
//reset, and set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/member/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->action = 'member_index';
$this->Controller->here = '/tests/member/scaffold_mock';
$this->Controller->webroot = '/';
$this->Controller->scaffold = 'member';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/<h2>Scaffold Mock<\/h2>/', $result);
$this->assertPattern('/<table cellpadding="0" cellspacing="0">/', $result);
//TODO: add testing for table generation
$this->assertPattern('/<li><a href="\/member\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
Configure::write('Routing.prefixes', $_backAdmin);
}
}
/**
* Scaffold Test class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller
*/
class ScaffoldTest extends CakeTestCase {
/**
* Controller property
*
* @var SecurityTestController
* @access public
*/
var $Controller;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag');
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->Controller =& new ScaffoldMockController();
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
unset($this->Controller);
}
/**
* Test the correct Generation of Scaffold Params.
* This ensures that the correct action and view will be generated
*
* @access public
* @return void
*/
function testScaffoldParams() {
$this->Controller->action = 'admin_edit';
$this->Controller->here = '/admin/scaffold_mock/edit';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' =>'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => true,
);
//set router.
Router::setRequestInfo(array($params, array('base' => '/', 'here' => 'admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$result = $Scaffold->getParams();
$this->assertEqual($result['action'], 'admin_edit');
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
*/
function testScaffoldVariableSetting() {
$this->Controller->action = 'admin_edit';
$this->Controller->here = '/admin/scaffold_mock/edit';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' =>'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => true,
);
//set router.
Router::setRequestInfo(array($params, array('base' => '/', 'here' => 'admin/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, $params);
$result = $Scaffold->controller->viewVars;
$this->assertEqual($result['title_for_layout'], 'Scaffold :: Admin Edit :: Scaffold Mock');
$this->assertEqual($result['singularHumanName'], 'Scaffold Mock');
$this->assertEqual($result['pluralHumanName'], 'Scaffold Mock');
$this->assertEqual($result['modelClass'], 'ScaffoldMock');
$this->assertEqual($result['primaryKey'], 'id');
$this->assertEqual($result['displayField'], 'title');
$this->assertEqual($result['singularVar'], 'scaffoldMock');
$this->assertEqual($result['pluralVar'], 'scaffoldMock');
$this->assertEqual($result['scaffoldFields'], array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'));
}
function getTests() {
return array('start', 'startCase', 'testScaffoldChangingViewProperty', 'endCase', 'end');
}
/**
* test that Scaffold overrides the view property even if its set to 'Theme'
*
* @return void
*/
function testScaffoldChangingViewProperty() {
$this->Controller->action = 'edit';
$this->Controller->theme = 'test_theme';
$this->Controller->view = 'Theme';
$this->Controller->constructClasses();
$Scaffold =& new TestScaffoldMock($this->Controller, array());
$this->assertEqual($this->Controller->view, 'Scaffold');
}
/**
* test that scaffold outputs flash messages when sessions are unset.
*
* @return void
*/
function testScaffoldFlashMessages() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->data = array(
'ScaffoldMock' => array(
'id' => 1,
'title' => 'New title',
'body' => 'new body'
)
);
$this->Controller->constructClasses();
unset($this->Controller->Session);
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/Scaffold Mock has been updated/', $result);
}
/**
* test that habtm relationship keys get added to scaffoldFields.
*
* @see http://code.cakephp.org/tickets/view/48
* @return void
*/
function testHabtmFieldAdditionWithScaffoldForm() {
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertPattern('/name="data\[ScaffoldTag\]\[ScaffoldTag\]"/', $result);
$result = $Scaffold->controller->viewVars;
$this->assertEqual($result['scaffoldFields'], array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated', 'ScaffoldTag'));
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
*/
function testEditScaffoldWithScaffoldFields() {
$this->Controller = new ScaffoldMockControllerWithFields();
$this->Controller->action = 'edit';
$this->Controller->here = '/scaffold_mock';
$this->Controller->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' =>'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
//set router.
Router::reload();
Router::setRequestInfo(array($params, array('base' => '/', 'here' => '/scaffold_mock', 'webroot' => '/')));
$this->Controller->params = $params;
$this->Controller->controller = 'scaffold_mock';
$this->Controller->base = '/';
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $params);
$result = ob_get_clean();
$this->assertNoPattern('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
}
}

View File

@@ -0,0 +1,336 @@
<?php
/**
* DebuggerTest file
*
* PHP versions 4 and 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 Project
* @package cake
* @subpackage cake.tests.cases.libs
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'Debugger');
/**
* DebugggerTestCaseDebuggger class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class DebuggerTestCaseDebugger extends Debugger {
}
/**
* DebuggerTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class DebuggerTest extends CakeTestCase {
// !!!
// !!! Be careful with changing code below as it may
// !!! change line numbers which are used in the tests
// !!!
/**
* setUp method
*
* @access public
* @return void
*/
function 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');
}
}
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
Configure::write('log', true);
}
/**
* testDocRef method
*
* @access public
* @return void
*/
function testDocRef() {
ini_set('docref_root', '');
$this->assertEqual(ini_get('docref_root'), '');
$debugger = new Debugger();
$this->assertEqual(ini_get('docref_root'), 'http://php.net/');
}
/**
* test Excerpt writing
*
* @access public
* @return void
*/
function testExcerpt() {
$result = Debugger::excerpt(__FILE__, __LINE__, 2);
$this->assertTrue(is_array($result));
$this->assertEqual(count($result), 5);
$this->assertPattern('/function(.+)testExcerpt/', $result[1]);
$result = Debugger::excerpt(__FILE__, 2, 2);
$this->assertTrue(is_array($result));
$this->assertEqual(count($result), 4);
$expected = '<code><span style="color: #000000">&lt;?php';
$expected .= '</span></code>';
$this->assertEqual($result[0], $expected);
$return = Debugger::excerpt('[internal]', 2, 2);
$this->assertTrue(empty($return));
}
/**
* testOutput method
*
* @access public
* @return void
*/
function testOutput() {
Debugger::invoke(Debugger::getInstance());
$result = Debugger::output(false);
$this->assertEqual($result, '');
$out .= '';
$result = Debugger::output(true);
$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');
$other .= '';
$result = ob_get_clean();
$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');
$wrong .= '';
$result = ob_get_clean();
$this->assertPattern('/<pre class="cake-debug">.+<\/pre>/', $result);
$this->assertPattern('/<b>Notice<\/b>/', $result);
$this->assertPattern('/variable:\s+wrong/', $result);
ob_start();
Debugger::output('js');
$buzz .= '';
$result = explode('</a>', ob_get_clean());
$this->assertTags($result[0], array(
'pre' => array('class' => 'cake-debug'),
'a' => array(
'href' => "javascript:void(0);",
'onclick' => "document.getElementById('cakeErr4-trace').style.display = " .
"(document.getElementById('cakeErr4-trace').style.display == 'none'" .
" ? '' : 'none');"
),
'b' => array(), 'Notice', '/b', ' (8)',
));
$this->assertPattern('/Undefined variable:\s+buzz/', $result[1]);
$this->assertPattern('/<a[^>]+>Code/', $result[1]);
$this->assertPattern('/<a[^>]+>Context/', $result[2]);
set_error_handler('simpleTestErrorHandler');
}
/**
* Tests that changes in output formats using Debugger::output() change the templates used.
*
* @return void
*/
function testChangeOutputFormats() {
Debugger::invoke(Debugger::getInstance());
Debugger::output('js', array(
'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
'&line={:line}">{:path}</a>, line {:line}'
));
$result = Debugger::trace();
$this->assertPattern('/' . preg_quote('txmt://open?url=file:///', '/') . '/', $result);
Debugger::output('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
'context' => "<context>{:context}</context>",
'trace' => "<stack>{:trace}</stack>",
));
Debugger::output('xml');
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',
'preg:/Undefined variable:\s+foo/',
'/error'
);
$this->assertTags($result, $data, true);
}
/**
* testTrimPath method
*
* @access public
* @return void
*/
function testTrimPath() {
$this->assertEqual(Debugger::trimPath(APP), 'APP' . DS);
$this->assertEqual(Debugger::trimPath(CAKE_CORE_INCLUDE_PATH), 'CORE');
}
/**
* testExportVar method
*
* @access public
* @return void
*/
function testExportVar() {
App::import('Controller');
$Controller = new Controller();
$Controller->helpers = array('Html', 'Form');
$View = new View($Controller);
$result = Debugger::exportVar($View);
$expected = 'ViewView::$base = NULL
View::$here = NULL
View::$plugin = NULL
View::$name = ""
View::$action = NULL
View::$params = array
View::$passedArgs = array
View::$data = array
View::$helpers = array
View::$viewPath = ""
View::$viewVars = array
View::$layout = "default"
View::$layoutPath = NULL
View::$autoRender = true
View::$autoLayout = true
View::$ext = ".ctp"
View::$subDir = NULL
View::$theme = NULL
View::$cacheAction = false
View::$validationErrors = array
View::$hasRendered = false
View::$loaded = array
View::$modelScope = false
View::$model = NULL
View::$association = NULL
View::$field = NULL
View::$fieldSuffix = NULL
View::$modelId = NULL
View::$uuids = array
View::$output = false
View::$__passedVars = array
View::$__scripts = array
View::$__paths = array
View::$webroot = NULL';
$result = str_replace(array("\t", "\r\n", "\n"), "", strtolower($result));
$expected = str_replace(array("\t", "\r\n", "\n"), "", strtolower($expected));
$this->assertEqual($result, $expected);
}
/**
* testLog method
*
* @access public
* @return void
*/
function testLog() {
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
Debugger::log('cool');
$result = file_get_contents(LOGS . 'debug.log');
$this->assertPattern('/DebuggerTest\:\:testLog/i', $result);
$this->assertPattern('/"cool"/', $result);
unlink(TMP . 'logs' . DS . 'debug.log');
Debugger::log(array('whatever', 'here'));
$result = file_get_contents(TMP . 'logs' . DS . 'debug.log');
$this->assertPattern('/DebuggerTest\:\:testLog/i', $result);
$this->assertPattern('/\[main\]/', $result);
$this->assertPattern('/array/', $result);
$this->assertPattern('/"whatever",/', $result);
$this->assertPattern('/"here"/', $result);
}
/**
* testDump method
*
* @access public
* @return void
*/
function testDump() {
$var = array('People' => array(
array(
'name' => 'joeseph',
'coat' => 'technicolor',
'hair_color' => 'brown'
),
array(
'name' => 'Shaft',
'coat' => 'black',
'hair' => 'black'
)
)
);
ob_start();
Debugger::dump($var);
$result = ob_get_clean();
$expected = "<pre>array(\n\t\"People\" => array()\n)</pre>";
$this->assertEqual($expected, $result);
}
/**
* test getInstance.
*
* @access public
* @return void
*/
function testGetInstance() {
$result =& Debugger::getInstance();
$this->assertIsA($result, 'Debugger');
$result =& Debugger::getInstance('DebuggerTestCaseDebugger');
$this->assertIsA($result, 'DebuggerTestCaseDebugger');
$result =& Debugger::getInstance();
$this->assertIsA($result, 'DebuggerTestCaseDebugger');
$result =& Debugger::getInstance('Debugger');
$this->assertIsA($result, 'Debugger');
}
}

View File

@@ -0,0 +1,630 @@
<?php
/**
* ErrorHandlerTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (class_exists('TestErrorHandler')) {
return;
}
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
/**
* BlueberryComponent class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class BlueberryComponent extends Object {
/**
* testName property
*
* @access public
* @return void
*/
var $testName = null;
/**
* initialize method
*
* @access public
* @return void
*/
function initialize(&$controller) {
$this->testName = 'BlueberryComponent';
}
}
/**
* BlueberryDispatcher class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class BlueberryDispatcher extends Dispatcher {
/**
* cakeError method
*
* @access public
* @return void
*/
function cakeError($method, $messages = array()) {
$error = new TestErrorHandler($method, $messages);
return $error;
}
}
/**
* Short description for class.
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AuthBlueberryUser extends CakeTestModel {
/**
* name property
*
* @var string 'AuthBlueberryUser'
* @access public
*/
var $name = 'AuthBlueberryUser';
/**
* useTable property
*
* @var string
* @access public
*/
var $useTable = false;
}
if (!class_exists('AppController')) {
/**
* AppController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class AppController extends Controller {
/**
* components property
*
* @access public
* @return void
*/
var $components = array('Blueberry');
/**
* beforeRender method
*
* @access public
* @return void
*/
function beforeRender() {
echo $this->Blueberry->testName;
}
/**
* header method
*
* @access public
* @return void
*/
function header($header) {
echo $header;
}
/**
* _stop method
*
* @access public
* @return void
*/
function _stop($status = 0) {
echo 'Stopped with status: ' . $status;
}
}
} elseif (!defined('APP_CONTROLLER_EXISTS')){
define('APP_CONTROLLER_EXISTS', true);
}
App::import('Core', array('Error', 'Controller'));
/**
* TestErrorController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class TestErrorController extends AppController {
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array();
/**
* index method
*
* @access public
* @return void
*/
function index() {
$this->autoRender = false;
return 'what up';
}
}
/**
* BlueberryController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class BlueberryController extends AppController {
/**
* name property
*
* @access public
* @return void
*/
var $name = 'BlueberryController';
/**
* uses property
*
* @access public
* @return void
*/
var $uses = array('AuthBlueberryUser');
/**
* components property
*
* @access public
* @return void
*/
var $components = array('Auth');
}
/**
* MyCustomErrorHandler class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class MyCustomErrorHandler extends ErrorHandler {
/**
* custom error message type.
*
* @return void
*/
function missingWidgetThing() {
echo 'widget thing is missing';
}
/**
* stop method
*
* @access public
* @return void
*/
function _stop() {
return;
}
}
/**
* TestErrorHandler class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class TestErrorHandler extends ErrorHandler {
/**
* stop method
*
* @access public
* @return void
*/
function _stop() {
return;
}
}
/**
* ErrorHandlerTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ErrorHandlerTest extends CakeTestCase {
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$this->skipIf(PHP_SAPI === 'cli', '%s Cannot be run from console');
}
/**
* test that methods declared in an ErrorHandler subclass are not converted
* into error404 when debug == 0
*
* @return void
*/
function testSubclassMethodsNotBeingConvertedToError() {
$back = Configure::read('debug');
Configure::write('debug', 2);
ob_start();
$ErrorHandler =& new MyCustomErrorHandler('missingWidgetThing', array('message' => 'doh!'));
$result = ob_get_clean();
$this->assertEqual($result, 'widget thing is missing');
Configure::write('debug', 0);
ob_start();
$ErrorHandler =& new MyCustomErrorHandler('missingWidgetThing', array('message' => 'doh!'));
$result = ob_get_clean();
$this->assertEqual($result, 'widget thing is missing', 'Method declared in subclass converted to error404. %s');
Configure::write('debug', 0);
ob_start();
$ErrorHandler =& new MyCustomErrorHandler('missingController', array(
'className' => 'Missing', 'message' => 'Page not found'
));
$result = ob_get_clean();
$this->assertPattern('/Not Found/', $result, 'Method declared in error handler not converted to error404. %s');
Configure::write('debug', $back);
}
/**
* testError method
*
* @access public
* @return void
*/
function testError() {
ob_start();
$TestErrorHandler = new TestErrorHandler('error404', array('message' => 'Page not found'));
ob_clean();
ob_start();
$TestErrorHandler->error(array(
'code' => 404,
'message' => 'Page not Found',
'name' => "Couldn't find what you were looking for"
));
$result = ob_get_clean();
$this->assertPattern("/<h2>Couldn't find what you were looking for<\/h2>/", $result);
$this->assertPattern('/Page not Found/', $result);
}
/**
* testError404 method
*
* @access public
* @return void
*/
function testError404() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'libs' . DS . 'view' . DS)
), true);
ob_start();
$TestErrorHandler = new TestErrorHandler('error404', array('message' => 'Page not found', 'url' => '/test_error'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Not Found<\/h2>/', $result);
$this->assertPattern("/<strong>'\/test_error'<\/strong>/", $result);
ob_start();
$TestErrorHandler =& new TestErrorHandler('error404', array('message' => 'Page not found'));
ob_get_clean();
ob_start();
$TestErrorHandler->error404(array(
'url' => 'pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>',
'message' => 'Page not found'
));
$result = ob_get_clean();
$this->assertNoPattern('#<script>#', $result);
$this->assertNoPattern('#</script>#', $result);
App::build();
}
/**
* testError500 method
*
* @access public
* @return void
*/
function testError500() {
ob_start();
$TestErrorHandler = new TestErrorHandler('error500', array(
'message' => 'An Internal Error Has Occurred'
));
$result = ob_get_clean();
$this->assertPattern('/<h2>An Internal Error Has Occurred<\/h2>/', $result);
ob_start();
$TestErrorHandler = new TestErrorHandler('error500', array(
'message' => 'An Internal Error Has Occurred',
'code' => '500'
));
$result = ob_get_clean();
$this->assertPattern('/<h2>An Internal Error Has Occurred<\/h2>/', $result);
}
/**
* testMissingController method
*
* @access public
* @return void
*/
function testMissingController() {
$this->skipIf(defined('APP_CONTROLLER_EXISTS'), '%s Need a non-existent AppController');
ob_start();
$TestErrorHandler = new TestErrorHandler('missingController', array('className' => 'PostsController'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Controller<\/h2>/', $result);
$this->assertPattern('/<em>PostsController<\/em>/', $result);
$this->assertPattern('/BlueberryComponent/', $result);
}
/**
* testMissingAction method
*
* @access public
* @return void
*/
function testMissingAction() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingAction', array('className' => 'PostsController', 'action' => 'index'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Method in PostsController<\/h2>/', $result);
$this->assertPattern('/<em>PostsController::<\/em><em>index\(\)<\/em>/', $result);
ob_start();
$dispatcher = new BlueberryDispatcher('/blueberry/inexistent');
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Method in BlueberryController<\/h2>/', $result);
$this->assertPattern('/<em>BlueberryController::<\/em><em>inexistent\(\)<\/em>/', $result);
$this->assertNoPattern('/Location: (.*)\/users\/login/', $result);
$this->assertNoPattern('/Stopped with status: 0/', $result);
}
/**
* testPrivateAction method
*
* @access public
* @return void
*/
function testPrivateAction() {
ob_start();
$TestErrorHandler = new TestErrorHandler('privateAction', array('className' => 'PostsController', 'action' => '_secretSauce'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Private Method in PostsController<\/h2>/', $result);
$this->assertPattern('/<em>PostsController::<\/em><em>_secretSauce\(\)<\/em>/', $result);
}
/**
* testMissingTable method
*
* @access public
* @return void
*/
function testMissingTable() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingTable', array('className' => 'Article', 'table' => 'articles'));
$result = ob_get_clean();
$this->assertPattern('/HTTP\/1\.0 500 Internal Server Error/', $result);
$this->assertPattern('/<h2>Missing Database Table<\/h2>/', $result);
$this->assertPattern('/table <em>articles<\/em> for model <em>Article<\/em>/', $result);
}
/**
* testMissingDatabase method
*
* @access public
* @return void
*/
function testMissingDatabase() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingDatabase', array());
$result = ob_get_clean();
$this->assertPattern('/HTTP\/1\.0 500 Internal Server Error/', $result);
$this->assertPattern('/<h2>Missing Database Connection<\/h2>/', $result);
$this->assertPattern('/Confirm you have created the file/', $result);
}
/**
* testMissingView method
*
* @access public
* @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);
}
/**
* testMissingLayout method
*
* @access public
* @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);
}
/**
* testMissingConnection method
*
* @access public
* @return void
*/
function testMissingConnection() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingConnection', array('className' => 'Article'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Database Connection<\/h2>/', $result);
$this->assertPattern('/Article requires a database connection/', $result);
}
/**
* testMissingHelperFile method
*
* @access public
* @return void
*/
function testMissingHelperFile() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingHelperFile', array('helper' => 'MyCustom', 'file' => 'my_custom.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Helper File<\/h2>/', $result);
$this->assertPattern('/Create the class below in file:/', $result);
$this->assertPattern('/(\/|\\\)my_custom.php/', $result);
}
/**
* testMissingHelperClass method
*
* @access public
* @return void
*/
function testMissingHelperClass() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingHelperClass', array('helper' => 'MyCustom', 'file' => 'my_custom.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Helper Class<\/h2>/', $result);
$this->assertPattern('/The helper class <em>MyCustomHelper<\/em> can not be found or does not exist./', $result);
$this->assertPattern('/(\/|\\\)my_custom.php/', $result);
}
/**
* test missingBehaviorFile method
*
* @access public
* @return void
*/
function testMissingBehaviorFile() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingBehaviorFile', array('behavior' => 'MyCustom', 'file' => 'my_custom.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Behavior File<\/h2>/', $result);
$this->assertPattern('/Create the class below in file:/', $result);
$this->assertPattern('/(\/|\\\)my_custom.php/', $result);
}
/**
* test MissingBehaviorClass method
*
* @access public
* @return void
*/
function testMissingBehaviorClass() {
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);
}
/**
* testMissingComponentFile method
*
* @access public
* @return void
*/
function testMissingComponentFile() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingComponentFile', array('className' => 'PostsController', 'component' => 'Sidebox', 'file' => 'sidebox.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Component File<\/h2>/', $result);
$this->assertPattern('/Create the class <em>SideboxComponent<\/em> in file:/', $result);
$this->assertPattern('/(\/|\\\)sidebox.php/', $result);
}
/**
* testMissingComponentClass method
*
* @access public
* @return void
*/
function testMissingComponentClass() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingComponentClass', array('className' => 'PostsController', 'component' => 'Sidebox', 'file' => 'sidebox.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Component Class<\/h2>/', $result);
$this->assertPattern('/Create the class <em>SideboxComponent<\/em> in file:/', $result);
$this->assertPattern('/(\/|\\\)sidebox.php/', $result);
}
/**
* testMissingModel method
*
* @access public
* @return void
*/
function testMissingModel() {
ob_start();
$TestErrorHandler = new TestErrorHandler('missingModel', array('className' => 'Article', 'file' => 'article.php'));
$result = ob_get_clean();
$this->assertPattern('/<h2>Missing Model<\/h2>/', $result);
$this->assertPattern('/<em>Article<\/em> could not be found./', $result);
$this->assertPattern('/(\/|\\\)article.php/', $result);
}
/**
* testing that having a code => 500 in the cakeError call makes an
* internal server error.
*
* @return void
*/
function testThatCode500Works() {
Configure::write('debug', 0);
ob_start();
$TestErrorHandler = new TestErrorHandler('missingTable', array(
'className' => 'Article',
'table' => 'articles',
'code' => 500
));
$result = ob_get_clean();
$this->assertPattern('/<h2>An Internal Error Has Occurred<\/h2>/', $result);
}
}

View File

@@ -0,0 +1,472 @@
<?php
/**
* FileTest 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
*/
App::import('Core', 'File');
/**
* FileTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class FileTest extends CakeTestCase {
/**
* File property
*
* @var mixed null
* @access public
*/
var $File = null;
/**
* testBasic method
*
* @access public
* @return void
*/
function testBasic() {
$file = __FILE__;
$this->File =& new File($file);
$result = $this->File->pwd();
$expecting = $file;
$this->assertEqual($result, $expecting);
$result = $this->File->name;
$expecting = basename(__FILE__);
$this->assertEqual($result, $expecting);
$result = $this->File->info();
$expecting = array(
'dirname' => dirname(__FILE__), 'basename' => basename(__FILE__),
'extension' => 'php', 'filename' =>'file.test'
);
$this->assertEqual($result, $expecting);
$result = $this->File->ext();
$expecting = 'php';
$this->assertEqual($result, $expecting);
$result = $this->File->name();
$expecting = 'file.test';
$this->assertEqual($result, $expecting);
$result = $this->File->md5();
$expecting = md5_file($file);
$this->assertEqual($result, $expecting);
$result = $this->File->md5(true);
$expecting = md5_file($file);
$this->assertEqual($result, $expecting);
$result = $this->File->size();
$expecting = filesize($file);
$this->assertEqual($result, $expecting);
$result = $this->File->owner();
$expecting = fileowner($file);
$this->assertEqual($result, $expecting);
$result = $this->File->group();
$expecting = filegroup($file);
$this->assertEqual($result, $expecting);
$result = $this->File->Folder();
$this->assertIsA($result, 'Folder');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', '%s File permissions tests not supported on Windows');
$result = $this->File->perms();
$expecting = '0644';
$this->assertEqual($result, $expecting);
}
/**
* testRead method
*
* @access public
* @return void
*/
function testRead() {
$file = __FILE__;
$this->File =& new File($file);
$result = $this->File->read();
$expecting = file_get_contents(__FILE__);
$this->assertEqual($result, $expecting);
$this->assertTrue(!is_resource($this->File->handle));
$this->File->lock = true;
$result = $this->File->read();
$expecting = file_get_contents(__FILE__);
$this->assertEqual($result, trim($expecting));
$this->File->lock = null;
$data = $expecting;
$expecting = substr($data, 0, 3);
$result = $this->File->read(3);
$this->assertEqual($result, $expecting);
$this->assertTrue(is_resource($this->File->handle));
$expecting = substr($data, 3, 3);
$result = $this->File->read(3);
$this->assertEqual($result, $expecting);
}
/**
* testOffset method
*
* @access public
* @return void
*/
function testOffset() {
$this->File->close();
$result = $this->File->offset();
$this->assertFalse($result);
$this->assertFalse(is_resource($this->File->handle));
$success = $this->File->offset(0);
$this->assertTrue($success);
$this->assertTrue(is_resource($this->File->handle));
$result = $this->File->offset();
$expecting = 0;
$this->assertIdentical($result, $expecting);
$data = file_get_contents(__FILE__);
$success = $this->File->offset(5);
$expecting = substr($data, 5, 3);
$result = $this->File->read(3);
$this->assertTrue($success);
$this->assertEqual($result, $expecting);
$result = $this->File->offset();
$expecting = 5+3;
$this->assertIdentical($result, $expecting);
}
/**
* testOpen method
*
* @access public
* @return void
*/
function testOpen() {
$this->File->handle = null;
$r = $this->File->open();
$this->assertTrue(is_resource($this->File->handle));
$this->assertTrue($r);
$handle = $this->File->handle;
$r = $this->File->open();
$this->assertTrue($r);
$this->assertTrue($handle === $this->File->handle);
$this->assertTrue(is_resource($this->File->handle));
$r = $this->File->open('r', true);
$this->assertTrue($r);
$this->assertFalse($handle === $this->File->handle);
$this->assertTrue(is_resource($this->File->handle));
}
/**
* testClose method
*
* @access public
* @return void
*/
function testClose() {
$this->File->handle = null;
$this->assertFalse(is_resource($this->File->handle));
$this->assertTrue($this->File->close());
$this->assertFalse(is_resource($this->File->handle));
$this->File->handle = fopen(__FILE__, 'r');
$this->assertTrue(is_resource($this->File->handle));
$this->assertTrue($this->File->close());
$this->assertFalse(is_resource($this->File->handle));
}
/**
* testCreate method
*
* @access public
* @return void
*/
function testCreate() {
$tmpFile = TMP.'tests'.DS.'cakephp.file.test.tmp';
$File =& new File($tmpFile, true, 0777);
$this->assertTrue($File->exists());
}
/**
* testOpeningNonExistantFileCreatesIt method
*
* @access public
* @return void
*/
function testOpeningNonExistantFileCreatesIt() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertEqual($someFile->read(), '');
$someFile->close();
$someFile->delete();
}
/**
* testPrepare method
*
* @access public
* @return void
*/
function testPrepare() {
$string = "some\nvery\ncool\r\nteststring here\n\n\nfor\r\r\n\n\r\n\nhere";
if (DS == '\\') {
$expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n";
$expected .= "for\r\n\r\n\r\n\r\n\r\nhere";
} else {
$expected = "some\nvery\ncool\nteststring here\n\n\nfor\n\n\n\n\nhere";
}
$this->assertIdentical(File::prepare($string), $expected);
$expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n";
$expected .= "for\r\n\r\n\r\n\r\n\r\nhere";
$this->assertIdentical(File::prepare($string, true), $expected);
}
/**
* testReadable method
*
* @access public
* @return void
*/
function testReadable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->readable());
$someFile->close();
$someFile->delete();
}
/**
* testWritable method
*
* @access public
* @return void
*/
function testWritable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->writable());
$someFile->close();
$someFile->delete();
}
/**
* testExecutable method
*
* @access public
* @return void
*/
function testExecutable() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertFalse($someFile->executable());
$someFile->close();
$someFile->delete();
}
/**
* testLastAccess method
*
* @access public
* @return void
*/
function testLastAccess() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastAccess());
$this->assertTrue($someFile->open());
$this->assertEqual($someFile->lastAccess(), time());
$someFile->close();
$someFile->delete();
}
/**
* testLastChange method
*
* @access public
* @return void
*/
function testLastChange() {
$someFile =& new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastChange());
$this->assertTrue($someFile->open('r+'));
$this->assertEqual($someFile->lastChange(), time());
$someFile->write('something');
$this->assertEqual($someFile->lastChange(), time());
$someFile->close();
$someFile->delete();
}
/**
* testWrite method
*
* @access public
* @return void
*/
function testWrite() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
$TmpFile =& new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$this->assertFalse(is_resource($TmpFile->handle));
$testData = array('CakePHP\'s', ' test suite', ' was here ...', '');
foreach ($testData as $data) {
$r = $TmpFile->write($data);
$this->assertTrue($r);
$this->assertTrue(file_exists($tmpFile));
$this->assertEqual($data, file_get_contents($tmpFile));
$this->assertTrue(is_resource($TmpFile->handle));
$TmpFile->close();
}
unlink($tmpFile);
}
/**
* testAppend method
*
* @access public
* @return void
*/
function testAppend() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
$TmpFile =& new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$fragments = array('CakePHP\'s', ' test suite', ' was here ...', '');
$data = null;
foreach ($fragments as $fragment) {
$r = $TmpFile->append($fragment);
$this->assertTrue($r);
$this->assertTrue(file_exists($tmpFile));
$data = $data.$fragment;
$this->assertEqual($data, file_get_contents($tmpFile));
$TmpFile->close();
}
}
/**
* testDelete method
*
* @access public
* @return void
*/
function testDelete() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
if (!file_exists($tmpFile)) {
touch($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');
$result = $TmpFile->delete();
$this->assertFalse($result);
}
/**
* testCopy method
*
* @access public
* @return void
*/
function testCopy() {
$dest = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
$file = __FILE__;
$this->File =& new File($file);
$result = $this->File->copy($dest);
$this->assertTrue($result);
$result = $this->File->copy($dest, true);
$this->assertTrue($result);
$result = $this->File->copy($dest, false);
$this->assertFalse($result);
$this->File->close();
unlink($dest);
$TmpFile =& new File('/this/does/not/exist');
$result = $TmpFile->copy($dest);
$this->assertFalse($result);
$TmpFile->close();
}
/**
* getTmpFile method
*
* @param bool $paintSkip
* @access protected
* @return void
*/
function _getTmpFile($paintSkip = true) {
$tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
if (is_writable(dirname($tmpFile)) && (!file_exists($tmpFile) || is_writable($tmpFile))) {
return $tmpFile;
};
if ($paintSkip) {
$caller = 'test';
if (function_exists('debug_backtrace')) {
$trace = debug_backtrace();
$caller = $trace[1]['function'] . '()';
}
$assertLine = new SimpleStackTrace(array(__FUNCTION__));
$assertLine = $assertLine->traceMethod();
$shortPath = substr($tmpFile, strlen(ROOT));
$message = '[FileTest] Skipping %s because "%s" not writeable!';
$message = sprintf(__($message, true), $caller, $shortPath) . $assertLine;
$this->_reporter->paintSkip($message);
}
return false;
}
}

View File

@@ -0,0 +1,792 @@
<?php
/**
* FolderTest 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
*/
App::import('Core', 'File');
/**
* FolderTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class FolderTest extends CakeTestCase {
/**
* testBasic method
*
* @access public
* @return void
*/
function testBasic() {
$path = dirname(__FILE__);
$Folder =& new Folder($path);
$result = $Folder->pwd();
$this->assertEqual($result, $path);
$result = Folder::addPathElement($path, 'test');
$expected = $path . DS . 'test';
$this->assertEqual($result, $expected);
$result = $Folder->cd(ROOT);
$expected = ROOT;
$this->assertEqual($result, $expected);
$result = $Folder->cd(ROOT . DS . 'non-existent');
$this->assertFalse($result);
}
/**
* testInPath method
*
* @access public
* @return void
*/
function testInPath() {
$path = dirname(dirname(__FILE__));
$inside = dirname($path) . DS;
$Folder =& new Folder($path);
$result = $Folder->pwd();
$this->assertEqual($result, $path);
$result = Folder::isSlashTerm($inside);
$this->assertTrue($result);
$result = $Folder->realpath('tests/');
$this->assertEqual($result, $path . DS .'tests' . DS);
$result = $Folder->inPath('tests' . DS);
$this->assertTrue($result);
$result = $Folder->inPath(DS . 'non-existing' . $inside);
$this->assertFalse($result);
}
/**
* test creation of single and mulitple paths.
*
* @return void
*/
function testCreation() {
$folder =& new Folder(TMP . 'tests');
$result = $folder->create(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third');
$this->assertTrue($result);
rmdir(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third');
rmdir(TMP . 'tests' . DS . 'first' . DS . 'second');
rmdir(TMP . 'tests' . DS . 'first');
$folder =& new Folder(TMP . 'tests');
$result = $folder->create(TMP . 'tests' . DS . 'first');
$this->assertTrue($result);
rmdir(TMP . 'tests' . DS . 'first');
}
/**
* test that creation of folders with trailing ds works
*
* @return void
*/
function testCreateWithTrailingDs() {
$folder =& new Folder(TMP);
$path = TMP . 'tests' . DS . 'trailing' . DS . 'dir' . DS;
$result = $folder->create($path);
$this->assertTrue($result);
$this->assertTrue(is_dir($path), 'Folder was not made');
$folder =& new Folder(TMP . 'tests' . DS . 'trailing');
$this->assertTrue($folder->delete());
}
/**
* test recurisve directory create failure.
*
* @return void
*/
function testRecursiveCreateFailure() {
if ($this->skipIf(DS == '\\', 'Cant perform operations using permissions on windows. %s')) {
return;
}
$path = TMP . 'tests' . DS . 'one';
mkdir($path);
chmod($path, '0444');
$this->expectError();
$folder =& new Folder($path);
$result = $folder->create($path . DS . 'two' . DS . 'three');
$this->assertFalse($result);
chmod($path, '0777');
rmdir($path);
}
/**
* testOperations method
*
* @access public
* @return void
*/
function testOperations() {
$path = TEST_CAKE_CORE_INCLUDE_PATH . 'console' . DS . 'templates' . DS . 'skel';
$Folder =& new Folder($path);
$result = is_dir($Folder->pwd());
$this->assertTrue($result);
$new = TMP . 'test_folder_new';
$result = $Folder->create($new);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->copy($copy);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->copy($copy);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->chmod($copy, 0755, false);
$this->assertTrue($result);
$result = $Folder->cd($copy);
$this->assertTrue($result);
$mv = TMP . 'test_folder_mv';
$result = $Folder->move($mv);
$this->assertTrue($result);
$mv = TMP . 'test_folder_mv_2';
$result = $Folder->move($mv);
$this->assertTrue($result);
$result = $Folder->delete($new);
$this->assertTrue($result);
$result = $Folder->delete($mv);
$this->assertTrue($result);
$result = $Folder->delete($mv);
$this->assertTrue($result);
$new = APP . 'index.php';
$result = $Folder->create($new);
$this->assertFalse($result);
$expected = $new . ' is a file';
$result = array_pop($Folder->errors());
$this->assertEqual($result, $expected);
$new = TMP . 'test_folder_new';
$result = $Folder->create($new);
$this->assertTrue($result);
$result = $Folder->cd($new);
$this->assertTrue($result);
$result = $Folder->delete();
$this->assertTrue($result);
$Folder =& new Folder('non-existent');
$result = $Folder->pwd();
$this->assertNull($result);
}
/**
* testChmod method
*
* @return void
* @access public
*/
function testChmod() {
$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);
$subdir = 'test_folder_new';
$new = TMP . $subdir;
$this->assertTrue($Folder->create($new));
$this->assertTrue($Folder->create($new . DS . 'test1'));
$this->assertTrue($Folder->create($new . DS . 'test2'));
$filePath = $new . DS . 'test1.php';
$File =& new File($filePath);
$this->assertTrue($File->create());
$copy = TMP . 'test_folder_copy';
$this->assertTrue($Folder->chmod($new, 0777, true));
$this->assertEqual($File->perms(), '0777');
$Folder->delete($new);
}
/**
* testRealPathForWebroot method
*
* @access public
* @return void
*/
function testRealPathForWebroot() {
$Folder = new Folder('files/');
$this->assertEqual(realpath('files/'), $Folder->path);
}
/**
* testZeroAsDirectory method
*
* @access public
* @return void
*/
function testZeroAsDirectory() {
$Folder =& new Folder(TMP);
$new = TMP . '0';
$this->assertTrue($Folder->create($new));
$result = $Folder->read(true, true);
$expected = array('0', 'cache', 'logs', 'sessions', 'tests');
$this->assertEqual($expected, $result[0]);
$result = $Folder->read(true, array('.', '..', 'logs', '.svn'));
$expected = array('0', 'cache', 'sessions', 'tests');
$this->assertEqual($expected, $result[0]);
$result = $Folder->delete($new);
$this->assertTrue($result);
}
/**
* test Adding path elements to a path
*
* @return void
*/
function testAddPathElement() {
$result = Folder::addPathElement(DS . 'some' . DS . 'dir', 'another_path');
$this->assertEqual($result, DS . 'some' . DS . 'dir' . DS . 'another_path');
$result = Folder::addPathElement(DS . 'some' . DS . 'dir' . DS, 'another_path');
$this->assertEqual($result, DS . 'some' . DS . 'dir' . DS . 'another_path');
}
/**
* testFolderRead method
*
* @access public
* @return void
*/
function testFolderRead() {
$Folder =& new Folder(TMP);
$expected = array('cache', 'logs', 'sessions', 'tests');
$result = $Folder->read(true, true);
$this->assertEqual($result[0], $expected);
$Folder->path = TMP . DS . 'non-existent';
$expected = array(array(), array());
$result = $Folder->read(true, true);
$this->assertEqual($result, $expected);
}
/**
* testFolderTree method
*
* @access public
* @return void
*/
function testFolderTree() {
$Folder =& new Folder();
$expected = array(
array(
TEST_CAKE_CORE_INCLUDE_PATH . 'config',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding'
),
array(
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'paths.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0080_00ff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0100_017f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0180_024F.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0250_02af.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0370_03ff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0400_04ff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0500_052f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '0530_058f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '1e00_1eff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '1f00_1fff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2100_214f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2150_218f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2460_24ff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c00_2c5f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c60_2c7f.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c80_2cff.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'unicode' . DS . 'casefolding' . DS . 'ff00_ffef.php'
)
);
$result = $Folder->tree(TEST_CAKE_CORE_INCLUDE_PATH . 'config', false);
$this->assertIdentical(array_diff($expected[0], $result[0]), array());
$this->assertIdentical(array_diff($result[0], $expected[0]), array());
$result = $Folder->tree(TEST_CAKE_CORE_INCLUDE_PATH . 'config', false, 'dir');
$this->assertIdentical(array_diff($expected[0], $result), array());
$this->assertIdentical(array_diff($result, $expected[0]), array());
$result = $Folder->tree(TEST_CAKE_CORE_INCLUDE_PATH . 'config', false, 'files');
$this->assertIdentical(array_diff($expected[1], $result), array());
$this->assertIdentical(array_diff($result, $expected[1]), array());
}
/**
* testWindowsPath method
*
* @access public
* @return void
*/
function testWindowsPath() {
$this->assertFalse(Folder::isWindowsPath('0:\\cake\\is\\awesome'));
$this->assertTrue(Folder::isWindowsPath('C:\\cake\\is\\awesome'));
$this->assertTrue(Folder::isWindowsPath('d:\\cake\\is\\awesome'));
}
/**
* testIsAbsolute method
*
* @access public
* @return void
*/
function testIsAbsolute() {
$this->assertFalse(Folder::isAbsolute('path/to/file'));
$this->assertFalse(Folder::isAbsolute('cake/'));
$this->assertFalse(Folder::isAbsolute('path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('\\path/to/file'));
$this->assertFalse(Folder::isAbsolute('\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('/usr/local'));
$this->assertTrue(Folder::isAbsolute('//path/to/file'));
$this->assertTrue(Folder::isAbsolute('C:\\cake'));
$this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file'));
}
/**
* testIsSlashTerm method
*
* @access public
* @return void
*/
function testIsSlashTerm() {
$this->assertFalse(Folder::isSlashTerm('cake'));
$this->assertTrue(Folder::isSlashTerm('C:\\cake\\'));
$this->assertTrue(Folder::isSlashTerm('/usr/local/'));
}
/**
* testStatic method
*
* @access public
* @return void
*/
function testSlashTerm() {
$result = Folder::slashTerm('/path/to/file');
$this->assertEqual($result, '/path/to/file/');
}
/**
* testNormalizePath method
*
* @access public
* @return void
*/
function testNormalizePath() {
$path = '/path/to/file';
$result = Folder::normalizePath($path);
$this->assertEqual($result, '/');
$path = '\\path\\\to\\\file';
$result = Folder::normalizePath($path);
$this->assertEqual($result, '/');
$path = 'C:\\path\\to\\file';
$result = Folder::normalizePath($path);
$this->assertEqual($result, '\\');
}
/**
* correctSlashFor method
*
* @access public
* @return void
*/
function testCorrectSlashFor() {
$path = '/path/to/file';
$result = Folder::correctSlashFor($path);
$this->assertEqual($result, '/');
$path = '\\path\\to\\file';
$result = Folder::correctSlashFor($path);
$this->assertEqual($result, '/');
$path = 'C:\\path\to\\file';
$result = Folder::correctSlashFor($path);
$this->assertEqual($result, '\\');
}
/**
* testInCakePath method
*
* @access public
* @return void
*/
function testInCakePath() {
$Folder =& new Folder();
$Folder->cd(ROOT);
$path = 'C:\\path\\to\\file';
$result = $Folder->inCakePath($path);
$this->assertFalse($result);
$path = ROOT;
$Folder->cd(ROOT);
$result = $Folder->inCakePath($path);
$this->assertFalse($result);
// WHY DOES THIS FAIL ??
$path = DS . 'cake' . DS . 'config';
$Folder->cd(ROOT . DS . 'cake' . DS . 'config');
$result = $Folder->inCakePath($path);
$this->assertTrue($result);
}
/**
* testFind method
*
* @access public
* @return void
*/
function testFind() {
$Folder =& new Folder();
$Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH . 'config');
$result = $Folder->find();
$expected = array('config.php', 'paths.php');
$this->assertIdentical(array_diff($expected, $result), array());
$this->assertIdentical(array_diff($result, $expected), array());
$result = $Folder->find('.*', true);
$expected = array('config.php', 'paths.php');
$this->assertIdentical($result, $expected);
$result = $Folder->find('.*\.php');
$expected = array('config.php', 'paths.php');
$this->assertIdentical(array_diff($expected, $result), array());
$this->assertIdentical(array_diff($result, $expected), array());
$result = $Folder->find('.*\.php', true);
$expected = array('config.php', 'paths.php');
$this->assertIdentical($result, $expected);
$result = $Folder->find('.*ig\.php');
$expected = array('config.php');
$this->assertIdentical($result, $expected);
$result = $Folder->find('paths\.php');
$expected = array('paths.php');
$this->assertIdentical($result, $expected);
$Folder->cd(TMP);
$file = new File($Folder->pwd() . DS . 'paths.php', true);
$Folder->create($Folder->pwd() . DS . 'testme');
$Folder->cd('testme');
$result = $Folder->find('paths\.php');
$expected = array();
$this->assertIdentical($result, $expected);
$Folder->cd($Folder->pwd() . '/..');
$result = $Folder->find('paths\.php');
$expected = array('paths.php');
$this->assertIdentical($result, $expected);
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . DS . 'testme');
$file->delete();
}
/**
* testFindRecursive method
*
* @access public
* @return void
*/
function testFindRecursive() {
$Folder =& new Folder();
$Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH);
$result = $Folder->findRecursive('(config|paths)\.php');
$expected = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'paths.php'
);
$this->assertIdentical(array_diff($expected, $result), array());
$this->assertIdentical(array_diff($result, $expected), array());
$result = $Folder->findRecursive('(config|paths)\.php', true);
$expected = array(
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'config.php',
TEST_CAKE_CORE_INCLUDE_PATH . 'config' . DS . 'paths.php'
);
$this->assertIdentical($result, $expected);
$Folder->cd(TMP);
$Folder->create($Folder->pwd() . DS . 'testme');
$Folder->cd('testme');
$File =& new File($Folder->pwd() . DS . 'paths.php');
$File->create();
$Folder->cd(TMP . 'sessions');
$result = $Folder->findRecursive('paths\.php');
$expected = array();
$this->assertIdentical($result, $expected);
$Folder->cd(TMP . 'testme');
$File =& new File($Folder->pwd() . DS . 'my.php');
$File->create();
$Folder->cd($Folder->pwd() . '/../..');
$result = $Folder->findRecursive('(paths|my)\.php');
$expected = array(
TMP . 'testme' . DS . 'my.php',
TMP . 'testme' . DS . 'paths.php'
);
$this->assertIdentical(array_diff($expected, $result), array());
$this->assertIdentical(array_diff($result, $expected), array());
$result = $Folder->findRecursive('(paths|my)\.php', true);
$expected = array(
TMP . 'testme' . DS . 'my.php',
TMP . 'testme' . DS . 'paths.php'
);
$this->assertIdentical($result, $expected);
$Folder->cd(TEST_CAKE_CORE_INCLUDE_PATH . 'config');
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . DS . 'testme');
$File->delete();
}
/**
* testConstructWithNonExistantPath method
*
* @access public
* @return void
*/
function testConstructWithNonExistantPath() {
$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');
}
/**
* testDirSize method
*
* @access public
* @return void
*/
function testDirSize() {
$Folder =& new Folder(TMP . 'config_non_existant', true);
$this->assertEqual($Folder->dirSize(), 0);
$File =& new File($Folder->pwd() . DS . 'my.php', true, 0777);
$File->create();
$File->write('something here');
$File->close();
$this->assertEqual($Folder->dirSize(), 14);
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . 'config_non_existant');
}
/**
* testDelete method
*
* @access public
* @return void
*/
function testDelete() {
$path = TMP . 'folder_delete_test';
$Folder =& new Folder($path, true);
touch(TMP . 'folder_delete_test' . DS . 'file1');
touch(TMP . 'folder_delete_test' . DS . 'file2');
$return = $Folder->delete();
$this->assertTrue($return);
$messages = $Folder->messages();
$errors = $Folder->errors();
$this->assertEqual($errors, array());
$expected = array(
$path . ' created',
$path . DS . 'file1 removed',
$path . DS . 'file2 removed',
$path . ' removed'
);
$this->assertEqual($expected, $messages);
}
/**
* testCopy method
*
* Verify that directories and files are copied recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
* @access public
* @link https://trac.cakephp.org/ticket/6259
*/
function testCopy() {
$path = TMP . 'folder_test';
$folder1 = $path . DS . 'folder1';
$folder2 = $folder1 . DS . 'folder2';
$folder3 = $path . DS . 'folder3';
$file1 = $folder1 . DS . 'file1.php';
$file2 = $folder2 . DS . 'file2.php';
new Folder($path, true);
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
touch($file1);
touch($file2);
$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->delete();
$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->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);
$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->delete();
}
/**
* testMove method
*
* Verify that directories and files are moved recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
* @access public
* @link https://trac.cakephp.org/ticket/6259
*/
function testMove() {
$path = TMP . 'folder_test';
$folder1 = $path . DS . 'folder1';
$folder2 = $folder1 . DS . 'folder2';
$folder3 = $path . DS . 'folder3';
$file1 = $folder1 . DS . 'file1.php';
$file2 = $folder2 . DS . 'file2.php';
new Folder($path, true);
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(is_dir($folder3 . DS . 'folder2'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
new Folder($folder2, true);
touch($file1);
touch($file2);
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertTrue(is_dir($folder3 . DS . 'folder2'));
$this->assertTrue(file_exists($folder3 . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($folder3);
$Folder->delete();
new Folder($folder1, true);
new Folder($folder2, true);
new Folder($folder3, true);
new Folder($folder3 . DS . 'folder2', true);
touch($file1);
touch($file2);
file_put_contents($folder3 . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder =& new Folder($folder1);
$result = $Folder->move($folder3);
$this->assertTrue($result);
$this->assertTrue(file_exists($folder3 . DS . 'file1.php'));
$this->assertEqual(file_get_contents($folder3 . DS . 'folder2' . DS . 'file2.php'), 'untouched');
$this->assertFalse(file_exists($file1));
$this->assertFalse(file_exists($folder2));
$this->assertFalse(file_exists($file2));
$Folder =& new Folder($path);
$Folder->delete();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,465 @@
<?php
/**
* InflectorTest
*
* InflectorTest is used to test cases on the Inflector class
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* 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
* @package cake.tests
* @subpackage cake.tests.cases.libs
* @since CakePHP(tm) v 1.2.0.4206
* @license Open Group Test Suite License (http://www.opensource.org/licenses/opengroup.php)
*/
/**
* Included libraries.
*
*/
App::import('Core', 'Inflector');
/**
* Short description for class.
*
* @package cake.tests
* @subpackage cake.tests.cases.libs
*/
class InflectorTest extends CakeTestCase {
/**
* Inflector property
*
* @var mixed null
* @access public
*/
var $Inflector = null;
/**
* testInstantiation method
*
* @access public
* @return void
*/
function testInstantiation() {
$Inflector =& Inflector::getInstance();
$this->assertEqual(Inflector::getInstance(), $Inflector);
}
/**
* testInflectingSingulars method
*
* @access public
* @return void
*/
function testInflectingSingulars() {
$this->assertEqual(Inflector::singularize('categorias'), 'categoria');
$this->assertEqual(Inflector::singularize('menus'), 'menu');
$this->assertEqual(Inflector::singularize('news'), 'news');
$this->assertEqual(Inflector::singularize('food_menus'), 'food_menu');
$this->assertEqual(Inflector::singularize('Menus'), 'Menu');
$this->assertEqual(Inflector::singularize('FoodMenus'), 'FoodMenu');
$this->assertEqual(Inflector::singularize('houses'), 'house');
$this->assertEqual(Inflector::singularize('powerhouses'), 'powerhouse');
$this->assertEqual(Inflector::singularize('quizzes'), 'quiz');
$this->assertEqual(Inflector::singularize('Buses'), 'Bus');
$this->assertEqual(Inflector::singularize('buses'), 'bus');
$this->assertEqual(Inflector::singularize('matrix_rows'), 'matrix_row');
$this->assertEqual(Inflector::singularize('matrices'), 'matrix');
$this->assertEqual(Inflector::singularize('vertices'), 'vertex');
$this->assertEqual(Inflector::singularize('indices'), 'index');
$this->assertEqual(Inflector::singularize('Aliases'), 'Alias');
$this->assertEqual(Inflector::singularize('Alias'), 'Alias');
$this->assertEqual(Inflector::singularize('Media'), 'Media');
$this->assertEqual(Inflector::singularize('alumni'), 'alumnus');
$this->assertEqual(Inflector::singularize('bacilli'), 'bacillus');
$this->assertEqual(Inflector::singularize('cacti'), 'cactus');
$this->assertEqual(Inflector::singularize('foci'), 'focus');
$this->assertEqual(Inflector::singularize('fungi'), 'fungus');
$this->assertEqual(Inflector::singularize('nuclei'), 'nucleus');
$this->assertEqual(Inflector::singularize('octopuses'), 'octopus');
$this->assertEqual(Inflector::singularize('radii'), 'radius');
$this->assertEqual(Inflector::singularize('stimuli'), 'stimulus');
$this->assertEqual(Inflector::singularize('syllabi'), 'syllabus');
$this->assertEqual(Inflector::singularize('termini'), 'terminus');
$this->assertEqual(Inflector::singularize('viri'), 'virus');
$this->assertEqual(Inflector::singularize('people'), 'person');
$this->assertEqual(Inflector::singularize('gloves'), 'glove');
$this->assertEqual(Inflector::singularize('doves'), 'dove');
$this->assertEqual(Inflector::singularize('lives'), 'life');
$this->assertEqual(Inflector::singularize('knives'), 'knife');
$this->assertEqual(Inflector::singularize('wolves'), 'wolf');
$this->assertEqual(Inflector::singularize('slaves'), 'slave');
$this->assertEqual(Inflector::singularize('shelves'), 'shelf');
$this->assertEqual(Inflector::singularize('taxis'), 'taxi');
$this->assertEqual(Inflector::singularize('taxes'), 'tax');
$this->assertEqual(Inflector::singularize('Taxes'), 'Tax');
$this->assertEqual(Inflector::singularize('AwesomeTaxes'), 'AwesomeTax');
$this->assertEqual(Inflector::singularize('faxes'), 'fax');
$this->assertEqual(Inflector::singularize('waxes'), 'wax');
$this->assertEqual(Inflector::singularize('niches'), 'niche');
$this->assertEqual(Inflector::singularize('waves'), 'wave');
$this->assertEqual(Inflector::singularize('bureaus'), 'bureau');
$this->assertEqual(Inflector::singularize('genetic_analyses'), 'genetic_analysis');
$this->assertEqual(Inflector::singularize('doctor_diagnoses'), 'doctor_diagnosis');
$this->assertEqual(Inflector::singularize('parantheses'), 'paranthesis');
$this->assertEqual(Inflector::singularize('Causes'), 'Cause');
$this->assertEqual(Inflector::singularize('colossuses'), 'colossus');
$this->assertEqual(Inflector::singularize('diagnoses'), 'diagnosis');
$this->assertEqual(Inflector::singularize('bases'), 'basis');
$this->assertEqual(Inflector::singularize('analyses'), 'analysis');
$this->assertEqual(Inflector::singularize(''), '');
}
/**
* testInflectingPlurals method
*
* @access public
* @return void
*/
function testInflectingPlurals() {
$this->assertEqual(Inflector::pluralize('categoria'), 'categorias');
$this->assertEqual(Inflector::pluralize('house'), 'houses');
$this->assertEqual(Inflector::pluralize('powerhouse'), 'powerhouses');
$this->assertEqual(Inflector::pluralize('Bus'), 'Buses');
$this->assertEqual(Inflector::pluralize('bus'), 'buses');
$this->assertEqual(Inflector::pluralize('menu'), 'menus');
$this->assertEqual(Inflector::pluralize('news'), 'news');
$this->assertEqual(Inflector::pluralize('food_menu'), 'food_menus');
$this->assertEqual(Inflector::pluralize('Menu'), 'Menus');
$this->assertEqual(Inflector::pluralize('FoodMenu'), 'FoodMenus');
$this->assertEqual(Inflector::pluralize('quiz'), 'quizzes');
$this->assertEqual(Inflector::pluralize('matrix_row'), 'matrix_rows');
$this->assertEqual(Inflector::pluralize('matrix'), 'matrices');
$this->assertEqual(Inflector::pluralize('vertex'), 'vertices');
$this->assertEqual(Inflector::pluralize('index'), 'indices');
$this->assertEqual(Inflector::pluralize('Alias'), 'Aliases');
$this->assertEqual(Inflector::pluralize('Aliases'), 'Aliases');
$this->assertEqual(Inflector::pluralize('Media'), 'Media');
$this->assertEqual(Inflector::pluralize('alumnus'), 'alumni');
$this->assertEqual(Inflector::pluralize('bacillus'), 'bacilli');
$this->assertEqual(Inflector::pluralize('cactus'), 'cacti');
$this->assertEqual(Inflector::pluralize('focus'), 'foci');
$this->assertEqual(Inflector::pluralize('fungus'), 'fungi');
$this->assertEqual(Inflector::pluralize('nucleus'), 'nuclei');
$this->assertEqual(Inflector::pluralize('octopus'), 'octopuses');
$this->assertEqual(Inflector::pluralize('radius'), 'radii');
$this->assertEqual(Inflector::pluralize('stimulus'), 'stimuli');
$this->assertEqual(Inflector::pluralize('syllabus'), 'syllabi');
$this->assertEqual(Inflector::pluralize('terminus'), 'termini');
$this->assertEqual(Inflector::pluralize('virus'), 'viri');
$this->assertEqual(Inflector::pluralize('person'), 'people');
$this->assertEqual(Inflector::pluralize('people'), 'people');
$this->assertEqual(Inflector::pluralize('glove'), 'gloves');
$this->assertEqual(Inflector::pluralize('crisis'), 'crises');
$this->assertEqual(Inflector::pluralize('tax'), 'taxes');
$this->assertEqual(Inflector::pluralize('wave'), 'waves');
$this->assertEqual(Inflector::pluralize('bureau'), 'bureaus');
$this->assertEqual(Inflector::pluralize(''), '');
}
/**
* testInflectorSlug method
*
* @access public
* @return void
*/
function testInflectorSlug() {
$result = Inflector::slug('Foo Bar: Not just for breakfast any-more');
$expected = 'Foo_Bar_Not_just_for_breakfast_any_more';
$this->assertEqual($result, $expected);
$result = Inflector::slug('this/is/a/path');
$expected = 'this_is_a_path';
$this->assertEqual($result, $expected);
$result = Inflector::slug('Foo Bar: Not just for breakfast any-more', "-");
$expected = 'Foo-Bar-Not-just-for-breakfast-any-more';
$this->assertEqual($result, $expected);
$result = Inflector::slug('Foo Bar: Not just for breakfast any-more', "+");
$expected = 'Foo+Bar+Not+just+for+breakfast+any+more';
$this->assertEqual($result, $expected);
$result = Inflector::slug('Äpfel Über Öl grün ärgert groß öko', '-');
$expected = 'Aepfel-Ueber-Oel-gruen-aergert-gross-oeko';
$this->assertEqual($result, $expected);
$result = Inflector::slug('The truth - and- more- news', '-');
$expected = 'The-truth-and-more-news';
$this->assertEqual($result, $expected);
$result = Inflector::slug('The truth: and more news', '-');
$expected = 'The-truth-and-more-news';
$this->assertEqual($result, $expected);
$result = Inflector::slug('La langue française est un attribut de souveraineté en France', '-');
$expected = 'La-langue-francaise-est-un-attribut-de-souverainete-en-France';
$this->assertEqual($result, $expected);
$result = Inflector::slug('!@$#exciting stuff! - what !@-# was that?', '-');
$expected = 'exciting-stuff-what-was-that';
$this->assertEqual($result, $expected);
$result = Inflector::slug('20% of profits went to me!', '-');
$expected = '20-of-profits-went-to-me';
$this->assertEqual($result, $expected);
$result = Inflector::slug('#this melts your face1#2#3', '-');
$expected = 'this-melts-your-face1-2-3';
$this->assertEqual($result, $expected);
$result = Inflector::slug('controller/action/りんご/1');
$expected = 'controller_action_りんご_1';
$this->assertEqual($result, $expected);
$result = Inflector::slug('の話が出たので大丈夫かなあと');
$expected = 'の話が出たので大丈夫かなあと';
$this->assertEqual($result, $expected);
$result = Inflector::slug('posts/view/한국어/page:1/sort:asc');
$expected = 'posts_view_한국어_page_1_sort_asc';
$this->assertEqual($result, $expected);
}
/**
* testInflectorSlugWithMap method
*
* @access public
* @return void
*/
function testInflectorSlugWithMap() {
$result = Inflector::slug('replace every r', array('/r/' => '1'));
$expected = '1eplace_eve1y_1';
$this->assertEqual($result, $expected);
$result = Inflector::slug('replace every r', '_', array('/r/' => '1'));
$expected = '1eplace_eve1y_1';
$this->assertEqual($result, $expected);
}
/**
* testInflectorSlugWithMapOverridingDefault method
*
* @access public
* @return void
*/
function testInflectorSlugWithMapOverridingDefault() {
$result = Inflector::slug('Testing æ ø å', '-', array('/å/' => 'aa', '/ø/' => 'oe'));
$expected = 'Testing-ae-oe-aa';
$this->assertEqual($result, $expected);
}
/**
* testInflectorUnderscore method
*
* @return void
* @access public
*/
function testInflectorUnderscore() {
$this->assertIdentical(Inflector::underscore('TestThing'), 'test_thing');
$this->assertIdentical(Inflector::underscore('testThing'), 'test_thing');
$this->assertIdentical(Inflector::underscore('TestThingExtra'), 'test_thing_extra');
$this->assertIdentical(Inflector::underscore('testThingExtra'), 'test_thing_extra');
// Identical checks test the cache code path.
$this->assertIdentical(Inflector::underscore('TestThing'), 'test_thing');
$this->assertIdentical(Inflector::underscore('testThing'), 'test_thing');
$this->assertIdentical(Inflector::underscore('TestThingExtra'), 'test_thing_extra');
$this->assertIdentical(Inflector::underscore('testThingExtra'), 'test_thing_extra');
// Test stupid values
$this->assertIdentical(Inflector::underscore(''), '');
$this->assertIdentical(Inflector::underscore(0), '0');
$this->assertIdentical(Inflector::underscore(false), '');
}
/**
* testVariableNaming method
*
* @access public
* @return void
*/
function testVariableNaming() {
$this->assertEqual(Inflector::variable('test_field'), 'testField');
$this->assertEqual(Inflector::variable('test_fieLd'), 'testFieLd');
$this->assertEqual(Inflector::variable('test field'), 'testField');
$this->assertEqual(Inflector::variable('Test_field'), 'testField');
}
/**
* testClassNaming method
*
* @access public
* @return void
*/
function testClassNaming() {
$this->assertEqual(Inflector::classify('artists_genres'), 'ArtistsGenre');
$this->assertEqual(Inflector::classify('file_systems'), 'FileSystem');
$this->assertEqual(Inflector::classify('news'), 'News');
$this->assertEqual(Inflector::classify('bureaus'), 'Bureau');
}
/**
* testTableNaming method
*
* @access public
* @return void
*/
function testTableNaming() {
$this->assertEqual(Inflector::tableize('ArtistsGenre'), 'artists_genres');
$this->assertEqual(Inflector::tableize('FileSystem'), 'file_systems');
$this->assertEqual(Inflector::tableize('News'), 'news');
$this->assertEqual(Inflector::tableize('Bureau'), 'bureaus');
}
/**
* testHumanization method
*
* @access public
* @return void
*/
function testHumanization() {
$this->assertEqual(Inflector::humanize('posts'), 'Posts');
$this->assertEqual(Inflector::humanize('posts_tags'), 'Posts Tags');
$this->assertEqual(Inflector::humanize('file_systems'), 'File Systems');
}
/**
* This test if run in isolation should not cause errors in PHP4.
*
* @return void
*/
function testRulesNoErrorPHP4() {
Inflector::rules('plural', array(
'rules' => array(),
'irregular' => array(),
'uninflected' => array('pays')
));
}
/**
* testCustomPluralRule method
*
* @access public
* @return void
*/
function testCustomPluralRule() {
Inflector::rules('plural', array('/^(custom)$/i' => '\1izables'));
$this->assertEqual(Inflector::pluralize('custom'), 'customizables');
Inflector::rules('plural', array('uninflected' => array('uninflectable')));
$this->assertEqual(Inflector::pluralize('uninflectable'), 'uninflectable');
Inflector::rules('plural', array(
'rules' => array('/^(alert)$/i' => '\1ables'),
'uninflected' => array('noflect', 'abtuse'),
'irregular' => array('amaze' => 'amazable', 'phone' => 'phonezes')
));
$this->assertEqual(Inflector::pluralize('noflect'), 'noflect');
$this->assertEqual(Inflector::pluralize('abtuse'), 'abtuse');
$this->assertEqual(Inflector::pluralize('alert'), 'alertables');
$this->assertEqual(Inflector::pluralize('amaze'), 'amazable');
$this->assertEqual(Inflector::pluralize('phone'), 'phonezes');
}
/**
* testCustomSingularRule method
*
* @access public
* @return void
*/
function testCustomSingularRule() {
Inflector::rules('singular', array('/(eple)r$/i' => '\1', '/(jente)r$/i' => '\1'));
$this->assertEqual(Inflector::singularize('epler'), 'eple');
$this->assertEqual(Inflector::singularize('jenter'), 'jente');
Inflector::rules('singular', array(
'rules' => array('/^(bil)er$/i' => '\1', '/^(inflec|contribu)tors$/i' => '\1ta'),
'uninflected' => array('singulars'),
'irregular' => array('spins' => 'spinor')
));
$this->assertEqual(Inflector::singularize('inflectors'), 'inflecta');
$this->assertEqual(Inflector::singularize('contributors'), 'contributa');
$this->assertEqual(Inflector::singularize('spins'), 'spinor');
$this->assertEqual(Inflector::singularize('singulars'), 'singulars');
}
/**
* testCustomTransliterationRule method
*
* @access public
* @return void
*/
function testCustomTransliterationRule() {
$this->assertEqual(Inflector::slug('Testing æ ø å'), 'Testing_ae_o_a');
Inflector::rules('transliteration', array('/å/' => 'aa', '/ø/' => 'oe'));
$this->assertEqual(Inflector::slug('Testing æ ø å'), 'Testing_ae_oe_aa');
Inflector::rules('transliteration', array('/ä|æ/' => 'ae', '/å/' => 'aa'), true);
$this->assertEqual(Inflector::slug('Testing æ ø å'), 'Testing_ae_ø_aa');
$this->assertEqual(Inflector::slug('Testing æ ø å', '-', array('/ø/' => 'oe')), 'Testing-ae-oe-aa');
}
/**
* test that setting new rules clears the inflector caches.
*
* @return void
*/
function testRulesClearsCaches() {
$this->assertEqual(Inflector::singularize('Bananas'), 'Banana');
$this->assertEqual(Inflector::tableize('Banana'), 'bananas');
$this->assertEqual(Inflector::pluralize('Banana'), 'Bananas');
Inflector::rules('singular', array(
'rules' => array('/(.*)nas$/i' => '\1zzz')
));
$this->assertEqual(Inflector::singularize('Bananas'), 'Banazzz', 'Was inflected with old rules. %s');
Inflector::rules('plural', array(
'rules' => array('/(.*)na$/i' => '\1zzz')
));
$this->assertEqual(Inflector::pluralize('Banana'), 'Banazzz', 'Was inflected with old rules. %s');
}
/**
* Test resetting inflection rules.
*
* @return void
*/
function testCustomRuleWithReset() {
$uninflected = array('atlas', 'lapis', 'onibus', 'pires', 'virus', '.*x');
$pluralIrregular = array('as' => 'ases');
Inflector::rules('singular', array(
'rules' => array('/^(.*)(a|e|o|u)is$/i' => '\1\2l'),
'uninflected' => $uninflected,
), true);
Inflector::rules('plural', array(
'rules' => array(
'/^(.*)(a|e|o|u)l$/i' => '\1\2is',
),
'uninflected' => $uninflected,
'irregular' => $pluralIrregular
), true);
$this->assertEqual(Inflector::pluralize('Alcool'), 'Alcoois');
$this->assertEqual(Inflector::pluralize('Atlas'), 'Atlas');
$this->assertEqual(Inflector::singularize('Alcoois'), 'Alcool');
$this->assertEqual(Inflector::singularize('Atlas'), 'Atlas');
}
}

View File

@@ -0,0 +1,958 @@
<?php
/**
* L10nTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'l10n');
/**
* L10nTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class L10nTest extends CakeTestCase {
/**
* testGet method
*
* @access public
* @return void
*/
function testGet() {
$l10n =& new L10n();
// Catalog Entry
$l10n->get('en');
$this->assertEqual($l10n->language, 'English');
$this->assertEqual($l10n->languagePath, array('eng', 'eng'));
$this->assertEqual($l10n->locale, 'eng');
// Map Entry
$l10n->get('eng');
$this->assertEqual($l10n->language, 'English');
$this->assertEqual($l10n->languagePath, array('eng', 'eng'));
$this->assertEqual($l10n->locale, 'eng');
// Catalog Entry
$l10n->get('en-ca');
$this->assertEqual($l10n->language, 'English (Canadian)');
$this->assertEqual($l10n->languagePath, array('en_ca', 'eng'));
$this->assertEqual($l10n->locale, 'en_ca');
// Default Entry
define('DEFAULT_LANGUAGE', 'en-us');
$l10n->get('use_default');
$this->assertEqual($l10n->language, 'English (United States)');
$this->assertEqual($l10n->languagePath, array('en_us', 'eng'));
$this->assertEqual($l10n->locale, 'en_us');
$l10n->get('es');
$l10n->get('');
$this->assertEqual($l10n->lang, 'en-us');
// Using $this->default
$l10n = new L10n();
$l10n->get('use_default');
$this->assertEqual($l10n->language, 'English (United States)');
$this->assertEqual($l10n->languagePath, array('en_us', 'eng', 'eng'));
$this->assertEqual($l10n->locale, 'en_us');
}
/**
* testGetAutoLanguage method
*
* @access public
* @return void
*/
function testGetAutoLanguage() {
$__SERVER = $_SERVER;
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'inexistent,en-ca';
$l10n =& new L10n();
$l10n->get();
$this->assertEqual($l10n->language, 'English (Canadian)');
$this->assertEqual($l10n->languagePath, array('en_ca', 'eng', 'eng'));
$this->assertEqual($l10n->locale, 'en_ca');
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es_mx';
$l10n->get();
$this->assertEqual($l10n->language, 'Spanish (Mexican)');
$this->assertEqual($l10n->languagePath, array('es_mx', 'spa', 'eng'));
$this->assertEqual($l10n->locale, 'es_mx');
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en_xy,en_ca';
$l10n->get();
$this->assertEqual($l10n->language, 'English');
$this->assertEqual($l10n->languagePath, array('eng', 'eng', 'eng'));
$this->assertEqual($l10n->locale, 'eng');
$_SERVER = $__SERVER;
}
/**
* testMap method
*
* @access public
* @return void
*/
function testMap() {
$l10n =& new L10n();
$result = $l10n->map(array('afr', 'af'));
$expected = array('afr' => 'af', 'af' => 'afr');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('alb', 'sq'));
$expected = array('alb' => 'sq', 'sq' => 'alb');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ara', 'ar'));
$expected = array('ara' => 'ar', 'ar' => 'ara');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('hye', 'hy'));
$expected = array('hye' => 'hy', 'hy' => 'hye');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('baq', 'eu'));
$expected = array('baq' => 'eu', 'eu' => 'baq');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('baq', 'eu'));
$expected = array('baq' => 'eu', 'eu' => 'baq');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('bos', 'bs'));
$expected = array('bos' => 'bs', 'bs' => 'bos');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('bul', 'bg'));
$expected = array('bul' => 'bg', 'bg' => 'bul');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('bel', 'be'));
$expected = array('bel' => 'be', 'be' => 'bel');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('cat', 'ca'));
$expected = array('cat' => 'ca', 'ca' => 'cat');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('chi', 'zh'));
$expected = array('chi' => 'zh', 'zh' => 'chi');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('zho', 'zh'));
$expected = array('zho' => 'zh', 'zh' => 'chi');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('hrv', 'hr'));
$expected = array('hrv' => 'hr', 'hr' => 'hrv');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ces', 'cs'));
$expected = array('ces' => 'cs', 'cs' => 'cze');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('cze', 'cs'));
$expected = array('cze' => 'cs', 'cs' => 'cze');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('dan', 'da'));
$expected = array('dan' => 'da', 'da' => 'dan');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('dut', 'nl'));
$expected = array('dut' => 'nl', 'nl' => 'dut');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('nld', 'nl'));
$expected = array('nld' => 'nl', 'nl' => 'dut');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('nld'));
$expected = array('nld' => 'nl');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('eng', 'en'));
$expected = array('eng' => 'en', 'en' => 'eng');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('est', 'et'));
$expected = array('est' => 'et', 'et' => 'est');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('fao', 'fo'));
$expected = array('fao' => 'fo', 'fo' => 'fao');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('fas', 'fa'));
$expected = array('fas' => 'fa', 'fa' => 'fas');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('per', 'fa'));
$expected = array('per' => 'fa', 'fa' => 'fas');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('fin', 'fi'));
$expected = array('fin' => 'fi', 'fi' => 'fin');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('fra', 'fr'));
$expected = array('fra' => 'fr', 'fr' => 'fre');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('fre', 'fr'));
$expected = array('fre' => 'fr', 'fr' => 'fre');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('gla', 'gd'));
$expected = array('gla' => 'gd', 'gd' => 'gla');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('glg', 'gl'));
$expected = array('glg' => 'gl', 'gl' => 'glg');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('deu', 'de'));
$expected = array('deu' => 'de', 'de' => 'deu');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ger', 'de'));
$expected = array('ger' => 'de', 'de' => 'deu');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ell', 'el'));
$expected = array('ell' => 'el', 'el' => 'gre');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('gre', 'el'));
$expected = array('gre' => 'el', 'el' => 'gre');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('heb', 'he'));
$expected = array('heb' => 'he', 'he' => 'heb');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('hin', 'hi'));
$expected = array('hin' => 'hi', 'hi' => 'hin');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('hun', 'hu'));
$expected = array('hun' => 'hu', 'hu' => 'hun');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ice', 'is'));
$expected = array('ice' => 'is', 'is' => 'ice');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('isl', 'is'));
$expected = array('isl' => 'is', 'is' => 'ice');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ind', 'id'));
$expected = array('ind' => 'id', 'id' => 'ind');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('gle', 'ga'));
$expected = array('gle' => 'ga', 'ga' => 'gle');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ita', 'it'));
$expected = array('ita' => 'it', 'it' => 'ita');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('jpn', 'ja'));
$expected = array('jpn' => 'ja', 'ja' => 'jpn');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('kor', 'ko'));
$expected = array('kor' => 'ko', 'ko' => 'kor');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('lav', 'lv'));
$expected = array('lav' => 'lv', 'lv' => 'lav');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('lit', 'lt'));
$expected = array('lit' => 'lt', 'lt' => 'lit');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('mac', 'mk'));
$expected = array('mac' => 'mk', 'mk' => 'mac');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('mkd', 'mk'));
$expected = array('mkd' => 'mk', 'mk' => 'mac');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('may', 'ms'));
$expected = array('may' => 'ms', 'ms' => 'may');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('msa', 'ms'));
$expected = array('msa' => 'ms', 'ms' => 'may');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('mlt', 'mt'));
$expected = array('mlt' => 'mt', 'mt' => 'mlt');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('nor', 'no'));
$expected = array('nor' => 'no', 'no' => 'nor');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('nob', 'nb'));
$expected = array('nob' => 'nb', 'nb' => 'nob');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('nno', 'nn'));
$expected = array('nno' => 'nn', 'nn' => 'nno');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('pol', 'pl'));
$expected = array('pol' => 'pl', 'pl' => 'pol');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('por', 'pt'));
$expected = array('por' => 'pt', 'pt' => 'por');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('roh', 'rm'));
$expected = array('roh' => 'rm', 'rm' => 'roh');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ron', 'ro'));
$expected = array('ron' => 'ro', 'ro' => 'rum');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('rum', 'ro'));
$expected = array('rum' => 'ro', 'ro' => 'rum');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('rus', 'ru'));
$expected = array('rus' => 'ru', 'ru' => 'rus');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('smi', 'sz'));
$expected = array('smi' => 'sz', 'sz' => 'smi');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('scc', 'sr'));
$expected = array('scc' => 'sr', 'sr' => 'scc');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('srp', 'sr'));
$expected = array('srp' => 'sr', 'sr' => 'scc');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('slk', 'sk'));
$expected = array('slk' => 'sk', 'sk' => 'slo');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('slo', 'sk'));
$expected = array('slo' => 'sk', 'sk' => 'slo');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('slv', 'sl'));
$expected = array('slv' => 'sl', 'sl' => 'slv');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('wen', 'sb'));
$expected = array('wen' => 'sb', 'sb' => 'wen');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('spa', 'es'));
$expected = array('spa' => 'es', 'es' => 'spa');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('swe', 'sv'));
$expected = array('swe' => 'sv', 'sv' => 'swe');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('tha', 'th'));
$expected = array('tha' => 'th', 'th' => 'tha');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('tso', 'ts'));
$expected = array('tso' => 'ts', 'ts' => 'tso');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('tsn', 'tn'));
$expected = array('tsn' => 'tn', 'tn' => 'tsn');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('tur', 'tr'));
$expected = array('tur' => 'tr', 'tr' => 'tur');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ukr', 'uk'));
$expected = array('ukr' => 'uk', 'uk' => 'ukr');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('urd', 'ur'));
$expected = array('urd' => 'ur', 'ur' => 'urd');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('ven', 've'));
$expected = array('ven' => 've', 've' => 'ven');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('vie', 'vi'));
$expected = array('vie' => 'vi', 'vi' => 'vie');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('xho', 'xh'));
$expected = array('xho' => 'xh', 'xh' => 'xho');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('cy', 'cym'));
$expected = array('cym' => 'cy', 'cy' => 'cym');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('yid', 'yi'));
$expected = array('yid' => 'yi', 'yi' => 'yid');
$this->assertEqual($result, $expected);
$result = $l10n->map(array('zul', 'zu'));
$expected = array('zul' => 'zu', 'zu' => 'zul');
$this->assertEqual($result, $expected);
}
/**
* testCatalog method
*
* @access public
* @return void
*/
function testCatalog() {
$l10n =& new L10n();
$result = $l10n->catalog(array('af'));
$expected = array(
'af' => array('language' => 'Afrikaans', 'locale' => 'afr', 'localeFallback' => 'afr', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ar', 'ar-ae', 'ar-bh', 'ar-dz', 'ar-eg', 'ar-iq', 'ar-jo', 'ar-kw', 'ar-lb', 'ar-ly', 'ar-ma',
'ar-om', 'ar-qa', 'ar-sa', 'ar-sy', 'ar-tn', 'ar-ye'));
$expected = array(
'ar' => array('language' => 'Arabic', 'locale' => 'ara', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-ae' => array('language' => 'Arabic (U.A.E.)', 'locale' => 'ar_ae', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-bh' => array('language' => 'Arabic (Bahrain)', 'locale' => 'ar_bh', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-dz' => array('language' => 'Arabic (Algeria)', 'locale' => 'ar_dz', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-eg' => array('language' => 'Arabic (Egypt)', 'locale' => 'ar_eg', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-iq' => array('language' => 'Arabic (Iraq)', 'locale' => 'ar_iq', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-jo' => array('language' => 'Arabic (Jordan)', 'locale' => 'ar_jo', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-kw' => array('language' => 'Arabic (Kuwait)', 'locale' => 'ar_kw', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-lb' => array('language' => 'Arabic (Lebanon)', 'locale' => 'ar_lb', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-ly' => array('language' => 'Arabic (Libya)', 'locale' => 'ar_ly', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-ma' => array('language' => 'Arabic (Morocco)', 'locale' => 'ar_ma', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-om' => array('language' => 'Arabic (Oman)', 'locale' => 'ar_om', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-qa' => array('language' => 'Arabic (Qatar)', 'locale' => 'ar_qa', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-sa' => array('language' => 'Arabic (Saudi Arabia)', 'locale' => 'ar_sa', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-sy' => array('language' => 'Arabic (Syria)', 'locale' => 'ar_sy', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-tn' => array('language' => 'Arabic (Tunisia)', 'locale' => 'ar_tn', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'ar-ye' => array('language' => 'Arabic (Yemen)', 'locale' => 'ar_ye', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('be'));
$expected = array(
'be' => array('language' => 'Byelorussian', 'locale' => 'bel', 'localeFallback' => 'bel', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('bg'));
$expected = array(
'bg' => array('language' => 'Bulgarian', 'locale' => 'bul', 'localeFallback' => 'bul', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('bs'));
$expected = array(
'bs' => array('language' => 'Bosnian', 'locale' => 'bos', 'localeFallback' => 'bos', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ca'));
$expected = array(
'ca' => array('language' => 'Catalan', 'locale' => 'cat', 'localeFallback' => 'cat', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('cs'));
$expected = array(
'cs' => array('language' => 'Czech', 'locale' => 'cze', 'localeFallback' => 'cze', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('da'));
$expected = array(
'da' => array('language' => 'Danish', 'locale' => 'dan', 'localeFallback' => 'dan', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('de', 'de-at', 'de-ch', 'de-de', 'de-li', 'de-lu'));
$expected = array(
'de' => array('language' => 'German (Standard)', 'locale' => 'deu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'de-at' => array('language' => 'German (Austria)', 'locale' => 'de_at', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'de-ch' => array('language' => 'German (Swiss)', 'locale' => 'de_ch', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'de-de' => array('language' => 'German (Germany)', 'locale' => 'de_de', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'de-li' => array('language' => 'German (Liechtenstein)', 'locale' => 'de_li', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'de-lu' => array('language' => 'German (Luxembourg)', 'locale' => 'de_lu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('e', 'el'));
$expected = array(
'e' => array('language' => 'Greek', 'locale' => 'gre', 'localeFallback' => 'gre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'el' => array('language' => 'Greek', 'locale' => 'gre', 'localeFallback' => 'gre', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('en', 'en-au', 'en-bz', 'en-ca', 'en-gb', 'en-ie', 'en-jm', 'en-nz', 'en-tt', 'en-us', 'en-za'));
$expected = array(
'en' => array('language' => 'English', 'locale' => 'eng', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-au' => array('language' => 'English (Australian)', 'locale' => 'en_au', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-bz' => array('language' => 'English (Belize)', 'locale' => 'en_bz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-ca' => array('language' => 'English (Canadian)', 'locale' => 'en_ca', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-gb' => array('language' => 'English (British)', 'locale' => 'en_gb', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-ie' => array('language' => 'English (Ireland)', 'locale' => 'en_ie', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-jm' => array('language' => 'English (Jamaica)', 'locale' => 'en_jm', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-nz' => array('language' => 'English (New Zealand)', 'locale' => 'en_nz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-tt' => array('language' => 'English (Trinidad)', 'locale' => 'en_tt', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-us' => array('language' => 'English (United States)', 'locale' => 'en_us', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'en-za' => array('language' => 'English (South Africa)', 'locale' => 'en_za', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('es', 'es-ar', 'es-bo', 'es-cl', 'es-co', 'es-cr', 'es-do', 'es-ec', 'es-es', 'es-gt', 'es-hn',
'es-mx', 'es-ni', 'es-pa', 'es-pe', 'es-pr', 'es-py', 'es-sv', 'es-uy', 'es-ve'));
$expected = array(
'es' => array('language' => 'Spanish (Spain - Traditional)', 'locale' => 'spa', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-ar' => array('language' => 'Spanish (Argentina)', 'locale' => 'es_ar', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-bo' => array('language' => 'Spanish (Bolivia)', 'locale' => 'es_bo', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-cl' => array('language' => 'Spanish (Chile)', 'locale' => 'es_cl', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-co' => array('language' => 'Spanish (Colombia)', 'locale' => 'es_co', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-cr' => array('language' => 'Spanish (Costa Rica)', 'locale' => 'es_cr', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-do' => array('language' => 'Spanish (Dominican Republic)', 'locale' => 'es_do', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-ec' => array('language' => 'Spanish (Ecuador)', 'locale' => 'es_ec', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-es' => array('language' => 'Spanish (Spain)', 'locale' => 'es_es', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-gt' => array('language' => 'Spanish (Guatemala)', 'locale' => 'es_gt', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-hn' => array('language' => 'Spanish (Honduras)', 'locale' => 'es_hn', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-mx' => array('language' => 'Spanish (Mexican)', 'locale' => 'es_mx', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-ni' => array('language' => 'Spanish (Nicaragua)', 'locale' => 'es_ni', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-pa' => array('language' => 'Spanish (Panama)', 'locale' => 'es_pa', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-pe' => array('language' => 'Spanish (Peru)', 'locale' => 'es_pe', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-pr' => array('language' => 'Spanish (Puerto Rico)', 'locale' => 'es_pr', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-py' => array('language' => 'Spanish (Paraguay)', 'locale' => 'es_py', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-sv' => array('language' => 'Spanish (El Salvador)', 'locale' => 'es_sv', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-uy' => array('language' => 'Spanish (Uruguay)', 'locale' => 'es_uy', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-ve' => array('language' => 'Spanish (Venezuela)', 'locale' => 'es_ve', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('et'));
$expected = array(
'et' => array('language' => 'Estonian', 'locale' => 'est', 'localeFallback' => 'est', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('eu'));
$expected = array(
'eu' => array('language' => 'Basque', 'locale' => 'baq', 'localeFallback' => 'baq', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('fa'));
$expected = array(
'fa' => array('language' => 'Farsi', 'locale' => 'per', 'localeFallback' => 'per', 'charset' => 'utf-8', 'direction' => 'rtl')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('fi'));
$expected = array(
'fi' => array('language' => 'Finnish', 'locale' => 'fin', 'localeFallback' => 'fin', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('fo'));
$expected = array(
'fo' => array('language' => 'Faeroese', 'locale' => 'fao', 'localeFallback' => 'fao', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('fr', 'fr-be', 'fr-ca', 'fr-ch', 'fr-fr', 'fr-lu'));
$expected = array(
'fr' => array('language' => 'French (Standard)', 'locale' => 'fre', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-be' => array('language' => 'French (Belgium)', 'locale' => 'fr_be', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-ca' => array('language' => 'French (Canadian)', 'locale' => 'fr_ca', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-ch' => array('language' => 'French (Swiss)', 'locale' => 'fr_ch', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-fr' => array('language' => 'French (France)', 'locale' => 'fr_fr', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-lu' => array('language' => 'French (Luxembourg)', 'locale' => 'fr_lu', 'localeFallback' => 'fre', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ga'));
$expected = array(
'ga' => array('language' => 'Irish', 'locale' => 'gle', 'localeFallback' => 'gle', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('gd', 'gd-ie'));
$expected = array(
'gd' => array('language' => 'Gaelic (Scots)', 'locale' => 'gla', 'localeFallback' => 'gla', 'charset' => 'utf-8', 'direction' => 'ltr'),
'gd-ie' => array('language' => 'Gaelic (Irish)', 'locale' => 'gd_ie', 'localeFallback' => 'gla', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('gl'));
$expected = array(
'gl' => array('language' => 'Galician', 'locale' => 'glg', 'localeFallback' => 'glg', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('he'));
$expected = array(
'he' => array('language' => 'Hebrew', 'locale' => 'heb', 'localeFallback' => 'heb', 'charset' => 'utf-8', 'direction' => 'rtl')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('hi'));
$expected = array(
'hi' => array('language' => 'Hindi', 'locale' => 'hin', 'localeFallback' => 'hin', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('hr'));
$expected = array(
'hr' => array('language' => 'Croatian', 'locale' => 'hrv', 'localeFallback' => 'hrv', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('hu'));
$expected = array(
'hu' => array('language' => 'Hungarian', 'locale' => 'hun', 'localeFallback' => 'hun', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('hy'));
$expected = array(
'hy' => array('language' => 'Armenian - Armenia', 'locale' => 'hye', 'localeFallback' => 'hye', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('id', 'in'));
$expected = array(
'id' => array('language' => 'Indonesian', 'locale' => 'ind', 'localeFallback' => 'ind', 'charset' => 'utf-8', 'direction' => 'ltr'),
'in' => array('language' => 'Indonesian', 'locale' => 'ind', 'localeFallback' => 'ind', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('is'));
$expected = array(
'is' => array('language' => 'Icelandic', 'locale' => 'ice', 'localeFallback' => 'ice', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('it', 'it-ch'));
$expected = array(
'it' => array('language' => 'Italian', 'locale' => 'ita', 'localeFallback' => 'ita', 'charset' => 'utf-8', 'direction' => 'ltr'),
'it-ch' => array('language' => 'Italian (Swiss) ', 'locale' => 'it_ch', 'localeFallback' => 'ita', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ja'));
$expected = array(
'ja' => array('language' => 'Japanese', 'locale' => 'jpn', 'localeFallback' => 'jpn', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ko', 'ko-kp', 'ko-kr'));
$expected = array(
'ko' => array('language' => 'Korean', 'locale' => 'kor', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr'),
'ko-kp' => array('language' => 'Korea (North)', 'locale' => 'ko_kp', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr'),
'ko-kr' => array('language' => 'Korea (South)', 'locale' => 'ko_kr', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('koi8-r', 'ru', 'ru-mo'));
$expected = array(
'koi8-r' => array('language' => 'Russian', 'locale' => 'koi8_r', 'localeFallback' => 'rus', 'charset' => 'koi8-r', 'direction' => 'ltr'),
'ru' => array('language' => 'Russian', 'locale' => 'rus', 'localeFallback' => 'rus', 'charset' => 'utf-8', 'direction' => 'ltr'),
'ru-mo' => array('language' => 'Russian (Moldavia)', 'locale' => 'ru_mo', 'localeFallback' => 'rus', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('lt'));
$expected = array(
'lt' => array('language' => 'Lithuanian', 'locale' => 'lit', 'localeFallback' => 'lit', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('lv'));
$expected = array(
'lv' => array('language' => 'Latvian', 'locale' => 'lav', 'localeFallback' => 'lav', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('mk', 'mk-mk'));
$expected = array(
'mk' => array('language' => 'FYRO Macedonian', 'locale' => 'mk', 'localeFallback' => 'mac', 'charset' => 'utf-8', 'direction' => 'ltr'),
'mk-mk' => array('language' => 'Macedonian', 'locale' => 'mk_mk', 'localeFallback' => 'mac', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ms'));
$expected = array(
'ms' => array('language' => 'Malaysian', 'locale' => 'may', 'localeFallback' => 'may', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('mt'));
$expected = array(
'mt' => array('language' => 'Maltese', 'locale' => 'mlt', 'localeFallback' => 'mlt', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('n', 'nl', 'nl-be'));
$expected = array(
'n' => array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'),
'nl' => array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr'),
'nl-be' => array('language' => 'Dutch (Belgium)', 'locale' => 'nl_be', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog('nl');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEqual($result, $expected);
$result = $l10n->catalog('nld');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEqual($result, $expected);
$result = $l10n->catalog('dut');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('nb'));
$expected = array(
'nb' => array('language' => 'Norwegian Bokmal', 'locale' => 'nob', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('nn', 'no'));
$expected = array(
'nn' => array('language' => 'Norwegian Nynorsk', 'locale' => 'nno', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr'),
'no' => array('language' => 'Norwegian', 'locale' => 'nor', 'localeFallback' => 'nor', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('p', 'pl'));
$expected = array(
'p' => array('language' => 'Polish', 'locale' => 'pol', 'localeFallback' => 'pol', 'charset' => 'utf-8', 'direction' => 'ltr'),
'pl' => array('language' => 'Polish', 'locale' => 'pol', 'localeFallback' => 'pol', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('pt', 'pt-br'));
$expected = array(
'pt' => array('language' => 'Portuguese (Portugal)', 'locale' => 'por', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr'),
'pt-br' => array('language' => 'Portuguese (Brazil)', 'locale' => 'pt_br', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('rm'));
$expected = array(
'rm' => array('language' => 'Rhaeto-Romanic', 'locale' => 'roh', 'localeFallback' => 'roh', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ro', 'ro-mo'));
$expected = array(
'ro' => array('language' => 'Romanian', 'locale' => 'rum', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr'),
'ro-mo' => array('language' => 'Romanian (Moldavia)', 'locale' => 'ro_mo', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sb'));
$expected = array(
'sb' => array('language' => 'Sorbian', 'locale' => 'wen', 'localeFallback' => 'wen', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sk'));
$expected = array(
'sk' => array('language' => 'Slovak', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sl'));
$expected = array(
'sl' => array('language' => 'Slovenian', 'locale' => 'slv', 'localeFallback' => 'slv', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sq'));
$expected = array(
'sq' => array('language' => 'Albanian', 'locale' => 'alb', 'localeFallback' => 'alb', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sr'));
$expected = array(
'sr' => array('language' => 'Serbian', 'locale' => 'scc', 'localeFallback' => 'scc', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sv', 'sv-fi'));
$expected = array(
'sv' => array('language' => 'Swedish', 'locale' => 'swe', 'localeFallback' => 'swe', 'charset' => 'utf-8', 'direction' => 'ltr'),
'sv-fi' => array('language' => 'Swedish (Finland)', 'locale' => 'sv_fi', 'localeFallback' => 'swe', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sx'));
$expected = array(
'sx' => array('language' => 'Sutu', 'locale' => 'sx', 'localeFallback' => 'sx', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('sz'));
$expected = array(
'sz' => array('language' => 'Sami (Lappish)', 'locale' => 'smi', 'localeFallback' => 'smi', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('th'));
$expected = array(
'th' => array('language' => 'Thai', 'locale' => 'tha', 'localeFallback' => 'tha', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('tn'));
$expected = array(
'tn' => array('language' => 'Tswana', 'locale' => 'tsn', 'localeFallback' => 'tsn', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('tr'));
$expected = array(
'tr' => array('language' => 'Turkish', 'locale' => 'tur', 'localeFallback' => 'tur', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ts'));
$expected = array(
'ts' => array('language' => 'Tsonga', 'locale' => 'tso', 'localeFallback' => 'tso', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('uk'));
$expected = array(
'uk' => array('language' => 'Ukrainian', 'locale' => 'ukr', 'localeFallback' => 'ukr', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ur'));
$expected = array(
'ur' => array('language' => 'Urdu', 'locale' => 'urd', 'localeFallback' => 'urd', 'charset' => 'utf-8', 'direction' => 'rtl')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('ve'));
$expected = array(
've' => array('language' => 'Venda', 'locale' => 'ven', 'localeFallback' => 'ven', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('vi'));
$expected = array(
'vi' => array('language' => 'Vietnamese', 'locale' => 'vie', 'localeFallback' => 'vie', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('cy'));
$expected = array(
'cy' => array('language' => 'Welsh', 'locale' => 'cym', 'localeFallback' => 'cym', 'charset' => 'utf-8',
'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('xh'));
$expected = array(
'xh' => array('language' => 'Xhosa', 'locale' => 'xho', 'localeFallback' => 'xho', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('yi'));
$expected = array(
'yi' => array('language' => 'Yiddish', 'locale' => 'yid', 'localeFallback' => 'yid', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('zh', 'zh-cn', 'zh-hk', 'zh-sg', 'zh-tw'));
$expected = array(
'zh' => array('language' => 'Chinese', 'locale' => 'chi', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-cn' => array('language' => 'Chinese (PRC)', 'locale' => 'zh_cn', 'localeFallback' => 'chi', 'charset' => 'GB2312', 'direction' => 'ltr'),
'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-sg' => array('language' => 'Chinese (Singapore)', 'locale' => 'zh_sg', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-tw' => array('language' => 'Chinese (Taiwan)', 'locale' => 'zh_tw', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('zu'));
$expected = array(
'zu' => array('language' => 'Zulu', 'locale' => 'zul', 'localeFallback' => 'zul', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('en-nz', 'es-do', 'sz', 'ar-lb', 'zh-hk', 'pt-br'));
$expected = array(
'en-nz' => array('language' => 'English (New Zealand)', 'locale' => 'en_nz', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'es-do' => array('language' => 'Spanish (Dominican Republic)', 'locale' => 'es_do', 'localeFallback' => 'spa', 'charset' => 'utf-8', 'direction' => 'ltr'),
'sz' => array('language' => 'Sami (Lappish)', 'locale' => 'smi', 'localeFallback' => 'smi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'ar-lb' => array('language' => 'Arabic (Lebanon)', 'locale' => 'ar_lb', 'localeFallback' => 'ara', 'charset' => 'utf-8', 'direction' => 'rtl'),
'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'pt-br' => array('language' => 'Portuguese (Brazil)', 'locale' => 'pt_br', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
$result = $l10n->catalog(array('eng', 'deu', 'zho', 'rum', 'zul', 'yid'));
$expected = array(
'eng' => array('language' => 'English', 'locale' => 'eng', 'localeFallback' => 'eng', 'charset' => 'utf-8', 'direction' => 'ltr'),
'deu' => array('language' => 'German (Standard)', 'locale' => 'deu', 'localeFallback' => 'deu', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zho' => array('language' => 'Chinese', 'locale' => 'chi', 'localeFallback' => 'chi', 'charset' => 'utf-8', 'direction' => 'ltr'),
'rum' => array('language' => 'Romanian', 'locale' => 'rum', 'localeFallback' => 'rum', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zul' => array('language' => 'Zulu', 'locale' => 'zul', 'localeFallback' => 'zul', 'charset' => 'utf-8', 'direction' => 'ltr'),
'yid' => array('language' => 'Yiddish', 'locale' => 'yid', 'localeFallback' => 'yid', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,79 @@
<?php
/**
* FileLogTest 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.
*
* @filesource
* @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.log
* @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';
/**
* CakeLogTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class FileLogTest extends CakeTestCase {
/**
* testLogFileWriting method
*
* @access public
* @return void
*/
function testLogFileWriting() {
@unlink(LOGS . 'error.log');
$log =& new FileLog();
$log->write('warning', 'Test warning');
$this->assertTrue(file_exists(LOGS . 'error.log'));
$result = file_get_contents(LOGS . 'error.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning/', $result);
unlink(LOGS . 'error.log');
@unlink(LOGS . 'debug.log');
$log->write('debug', 'Test warning');
$this->assertTrue(file_exists(LOGS . 'debug.log'));
$result = file_get_contents(LOGS . 'debug.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Debug: Test warning/', $result);
unlink(LOGS . 'debug.log');
@unlink(LOGS . 'random.log');
$log->write('random', 'Test warning');
$this->assertTrue(file_exists(LOGS . 'random.log'));
$result = file_get_contents(LOGS . 'random.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Random: Test warning/', $result);
unlink(LOGS . 'random.log');
}
/**
* test using the path setting to write logs in other places.
*
* @return void
*/
function testPathSetting() {
$path = TMP . 'tests' . DS;
@unlink($path . 'error.log');
$log =& new FileLog(compact('path'));
$log->write('warning', 'Test warning');
$this->assertTrue(file_exists($path . 'error.log'));
unlink($path . 'error.log');
}
}

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,462 @@
<?php
/**
* AclBehaviorTest file
*
* Test the Acl Behavior
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake
* @subpackage cake.cake.libs.tests.model.behaviors.acl
* @since CakePHP v 1.2.0.4487
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Behavior', 'Acl');
App::import('Core', 'db_acl');
/**
* Test Person class - self joined model
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class AclPerson extends CakeTestModel {
/**
* name property
*
* @var string
* @access public
*/
var $name = 'AclPerson';
/**
* useTable property
*
* @var string
* @access public
*/
var $useTable = 'people';
/**
* actsAs property
*
* @var array
* @access public
*/
var $actsAs = array('Acl' => 'requester');
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'Mother' => array(
'className' => 'AclPerson',
'foreignKey' => 'mother_id',
)
);
/**
* hasMany property
*
* @var array
* @access public
*/
var $hasMany = array(
'Child' => array(
'className' => 'AclPerson',
'foreignKey' => 'mother_id'
)
);
/**
* parentNode method
*
* @return void
* @access public
*/
function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
if (isset($this->data['AclPerson']['mother_id'])) {
$motherId = $this->data['AclPerson']['mother_id'];
} else {
$motherId = $this->field('mother_id');
}
if (!$motherId) {
return null;
} else {
return array('AclPerson' => array('id' => $motherId));
}
}
}
/**
* AclUser class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class AclUser extends CakeTestModel {
/**
* name property
*
* @var string
* @access public
*/
var $name = 'User';
/**
* useTable property
*
* @var string
* @access public
*/
var $useTable = 'users';
/**
* actsAs property
*
* @var array
* @access public
*/
var $actsAs = array('Acl');
/**
* parentNode
*
* @access public
*/
function parentNode() {
return null;
}
}
/**
* AclPost class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class AclPost extends CakeTestModel {
/**
* name property
*
* @var string
* @access public
*/
var $name = 'Post';
/**
* useTable property
*
* @var string
* @access public
*/
var $useTable = 'posts';
/**
* actsAs property
*
* @var array
* @access public
*/
var $actsAs = array('Acl' => 'Controlled');
/**
* parentNode
*
* @access public
*/
function parentNode() {
return null;
}
}
/**
* AclBehaviorTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class AclBehaviorTestCase extends CakeTestCase {
/**
* Aco property
*
* @var Aco
* @access public
*/
var $Aco;
/**
* Aro property
*
* @var Aro
* @access public
*/
var $Aro;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.person', 'core.user', 'core.post', 'core.aco', 'core.aro', 'core.aros_aco');
/**
* Set up the test
*
* @return void
* @access public
*/
function startTest() {
Configure::write('Acl.database', 'test_suite');
$this->Aco =& new Aco();
$this->Aro =& new Aro();
}
/**
* tearDown method
*
* @return void
* @access public
*/
function tearDown() {
ClassRegistry::flush();
unset($this->Aro, $this->Aco);
}
/**
* Test Setup of AclBehavior
*
* @return void
* @access public
*/
function testSetup() {
$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();
$this->assertTrue(isset($Post->Behaviors->Acl->settings['Post']));
$this->assertEqual($Post->Behaviors->Acl->settings['Post']['type'], 'controlled');
$this->assertTrue(is_object($Post->Aco));
}
/**
* test After Save
*
* @return void
* @access public
*/
function testAfterSave() {
$Post =& new AclPost();
$data = array(
'Post' => array(
'author_id' => 1,
'title' => 'Acl Post',
'body' => 'post body',
'published' => 1
),
);
$Post->save($data);
$result = $this->Aco->find('first', array(
'conditions' => array('Aco.model' => 'Post', 'Aco.foreign_key' => $Post->id)
));
$this->assertTrue(is_array($result));
$this->assertEqual($result['Aco']['model'], 'Post');
$this->assertEqual($result['Aco']['foreign_key'], $Post->id);
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',
'foreign_key' => 2,
'parent_id' => null
)
);
$this->Aro->save($aroData);
$Person =& new AclPerson();
$data = array(
'AclPerson' => array(
'name' => 'Trent',
'mother_id' => 2,
'father_id' => 3,
),
);
$Person->save($data);
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id)
));
$this->assertTrue(is_array($result));
$this->assertEqual($result['Aro']['parent_id'], 5);
$node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8));
$this->assertEqual(count($node), 2);
$this->assertEqual($node[0]['Aro']['parent_id'], 5);
$this->assertEqual($node[1]['Aro']['parent_id'], null);
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',
'foreign_key' => 1,
'parent_id' => null
)
);
$this->Aro->create();
$this->Aro->save($aroData);
$Person->read(null, 8);
$Person->set('mother_id', 1);
$Person->save();
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id)
));
$this->assertTrue(is_array($result));
$this->assertEqual($result['Aro']['parent_id'], 7);
$node = $Person->node(array('model' => 'AclPerson', 'foreign_key' => 8));
$this->assertEqual(sizeof($node), 2);
$this->assertEqual($node[0]['Aro']['parent_id'], 7);
$this->assertEqual($node[1]['Aro']['parent_id'], null);
}
/**
* test that an afterSave on an update does not cause parent_id to become null.
*
* @return void
*/
function testAfterSaveUpdateParentIdNotNull() {
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',
'foreign_key' => 2,
'parent_id' => null
)
);
$this->Aro->save($aroData);
$Person =& new AclPerson();
$data = array(
'AclPerson' => array(
'name' => 'Trent',
'mother_id' => 2,
'father_id' => 3,
),
);
$Person->save($data);
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id)
));
$this->assertTrue(is_array($result));
$this->assertEqual($result['Aro']['parent_id'], 5);
$Person->save(array('id' => $Person->id, 'name' => 'Bruce'));
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $Person->id)
));
$this->assertEqual($result['Aro']['parent_id'], 5);
}
/**
* Test After Delete
*
* @return void
* @access public
*/
function testAfterDelete() {
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',
'foreign_key' => 2,
'parent_id' => null
)
);
$this->Aro->save($aroData);
$Person =& new AclPerson();
$data = array(
'AclPerson' => array(
'name' => 'Trent',
'mother_id' => 2,
'father_id' => 3,
),
);
$Person->save($data);
$id = $Person->id;
$node = $Person->node();
$this->assertEqual(count($node), 2);
$this->assertEqual($node[0]['Aro']['parent_id'], 5);
$this->assertEqual($node[1]['Aro']['parent_id'], null);
$Person->delete($id);
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id)
));
$this->assertTrue(empty($result));
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2)
));
$this->assertFalse(empty($result));
$data = array(
'AclPerson' => array(
'name' => 'Trent',
'mother_id' => 2,
'father_id' => 3,
),
);
$Person->save($data);
$id = $Person->id;
$Person->delete(2);
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => $id)
));
$this->assertTrue(empty($result));
$result = $this->Aro->find('first', array(
'conditions' => array('Aro.model' => 'AclPerson', 'Aro.foreign_key' => 2)
));
$this->assertTrue(empty($result));
}
/**
* Test Node()
*
* @return void
* @access public
*/
function testNode() {
$Person =& new AclPerson();
$aroData = array(
'Aro' => array(
'model' => 'AclPerson',
'foreign_key' => 2,
'parent_id' => null
)
);
$this->Aro->save($aroData);
$Person->id = 2;
$result = $Person->node();
$this->assertTrue(is_array($result));
$this->assertEqual(count($result), 1);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,898 @@
<?php
/**
* TranslateBehaviorTest 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.model.behaviors
* @since CakePHP(tm) v 1.2.0.5669
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Core', array('AppModel', 'Model'));
require_once(dirname(dirname(__FILE__)) . DS . 'models.php');
/**
* TranslateBehaviorTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.behaviors
*/
class TranslateBehaviorTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
* @access public
*/
var $autoFixtures = false;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array(
'core.translated_item', 'core.translate', 'core.translate_table',
'core.translated_article', 'core.translate_article', 'core.user', 'core.comment', 'core.tag', 'core.articles_tag',
'core.translate_with_prefix'
);
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
ClassRegistry::flush();
}
/**
* testTranslateModel method
*
* @access public
* @return void
*/
function testTranslateModel() {
$TestModel =& new Tag();
$TestModel->translateTable = 'another_i18n';
$TestModel->Behaviors->attach('Translate', array('title'));
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'I18nModel');
$this->assertEqual($translateModel->useTable, 'another_i18n');
$TestModel =& new User();
$TestModel->Behaviors->attach('Translate', array('title'));
$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);
$this->assertEqual($translateModel->name, 'TranslateArticleModel');
$this->assertEqual($translateModel->useTable, 'article_i18n');
$TestModel =& new TranslatedItem();
$translateModel =& $TestModel->Behaviors->Translate->translateModel($TestModel);
$this->assertEqual($translateModel->name, 'TranslateTestModel');
$this->assertEqual($translateModel->useTable, 'i18n');
}
/**
* testLocaleFalsePlain method
*
* @access public
* @return void
*/
function testLocaleFalsePlain() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = false;
$result = $TestModel->read(null, 1);
$expected = array('TranslatedItem' => array('id' => 1, 'slug' => 'first_translated'));
$this->assertEqual($result, $expected);
$result = $TestModel->find('all', array('fields' => array('slug')));
$expected = array(
array('TranslatedItem' => array('slug' => 'first_translated')),
array('TranslatedItem' => array('slug' => 'second_translated')),
array('TranslatedItem' => array('slug' => 'third_translated'))
);
$this->assertEqual($result, $expected);
}
/**
* testLocaleFalseAssociations method
*
* @access public
* @return void
*/
function testLocaleFalseAssociations() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = false;
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated'),
'Title' => array(
array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'),
array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'),
array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1')
),
'Content' => array(
array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'),
array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'),
array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1')
)
);
$this->assertEqual($result, $expected);
$TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content');
$TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng';
$result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug')));
$expected = array(
array(
'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated'),
'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')),
'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1'))
),
array(
'TranslatedItem' => array('id' => 2, 'slug' => 'second_translated'),
'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')),
'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2'))
),
array(
'TranslatedItem' => array('id' => 3, 'slug' => 'third_translated'),
'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')),
'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3'))
)
);
$this->assertEqual($result, $expected);
}
/**
* testLocaleSingle method
*
* @access public
* @return void
*/
function testLocaleSingle() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Title #1',
'content' => 'Content #1'
)
);
$this->assertEqual($result, $expected);
$result = $TestModel->find('all');
$expected = array(
array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Title #1',
'content' => 'Content #1'
)
),
array(
'TranslatedItem' => array(
'id' => 2,
'slug' => 'second_translated',
'locale' => 'eng',
'title' => 'Title #2',
'content' => 'Content #2'
)
),
array(
'TranslatedItem' => array(
'id' => 3,
'slug' => 'third_translated',
'locale' => 'eng',
'title' => 'Title #3',
'content' => 'Content #3'
)
)
);
$this->assertEqual($result, $expected);
}
/**
* testLocaleSingleWithConditions method
*
* @access public
* @return void
*/
function testLocaleSingleWithConditions() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->find('all', array('conditions' => array('slug' => 'first_translated')));
$expected = array(
array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Title #1',
'content' => 'Content #1'
)
)
);
$this->assertEqual($result, $expected);
$result = $TestModel->find('all', array('conditions' => "TranslatedItem.slug = 'first_translated'"));
$expected = array(
array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Title #1',
'content' => 'Content #1'
)
)
);
$this->assertEqual($result, $expected);
}
/**
* testLocaleSingleAssociations method
*
* @access public
* @return void
*/
function testLocaleSingleAssociations() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Title #1',
'content' => 'Content #1'
),
'Title' => array(
array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Title #1'),
array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'),
array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1')
),
'Content' => array(
array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'),
array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'),
array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Obsah #1')
)
);
$this->assertEqual($result, $expected);
$TestModel->hasMany['Title']['fields'] = $TestModel->hasMany['Content']['fields'] = array('content');
$TestModel->hasMany['Title']['conditions']['locale'] = $TestModel->hasMany['Content']['conditions']['locale'] = 'eng';
$result = $TestModel->find('all', array('fields' => array('TranslatedItem.title')));
$expected = array(
array(
'TranslatedItem' => array('id' => 1, 'locale' => 'eng', 'title' => 'Title #1'),
'Title' => array(array('foreign_key' => 1, 'content' => 'Title #1')),
'Content' => array(array('foreign_key' => 1, 'content' => 'Content #1'))
),
array(
'TranslatedItem' => array('id' => 2, 'locale' => 'eng', 'title' => 'Title #2'),
'Title' => array(array('foreign_key' => 2, 'content' => 'Title #2')),
'Content' => array(array('foreign_key' => 2, 'content' => 'Content #2'))
),
array(
'TranslatedItem' => array('id' => 3, 'locale' => 'eng', 'title' => 'Title #3'),
'Title' => array(array('foreign_key' => 3, 'content' => 'Title #3')),
'Content' => array(array('foreign_key' => 3, 'content' => 'Content #3'))
)
);
$this->assertEqual($result, $expected);
}
/**
* testLocaleMultiple method
*
* @access public
* @return void
*/
function testLocaleMultiple() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = array('deu', 'eng', 'cze');
$delete = array(
array('locale' => 'deu'),
array('foreign_key' => 1, 'field' => 'title', 'locale' => 'eng'),
array('foreign_key' => 1, 'field' => 'content', 'locale' => 'cze'),
array('foreign_key' => 2, 'field' => 'title', 'locale' => 'cze'),
array('foreign_key' => 2, 'field' => 'content', 'locale' => 'eng'),
array('foreign_key' => 3, 'field' => 'title')
);
$I18nModel =& ClassRegistry::getObject('TranslateTestModel');
$I18nModel->deleteAll(array('or' => $delete));
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'deu',
'title' => 'Titulek #1',
'content' => 'Content #1'
)
);
$this->assertEqual($result, $expected);
$result = $TestModel->find('all', array('fields' => array('slug', 'title', 'content')));
$expected = array(
array(
'TranslatedItem' => array(
'slug' => 'first_translated',
'locale' => 'deu',
'title' => 'Titulek #1',
'content' => 'Content #1'
)
),
array(
'TranslatedItem' => array(
'slug' => 'second_translated',
'locale' => 'deu',
'title' => 'Title #2',
'content' => 'Obsah #2'
)
),
array(
'TranslatedItem' => array(
'slug' => 'third_translated',
'locale' => 'deu',
'title' => '',
'content' => 'Content #3'
)
)
);
$this->assertEqual($result, $expected);
}
/**
* testMissingTranslation method
*
* @access public
* @return void
*/
function testMissingTranslation() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'rus';
$result = $TestModel->read(null, 1);
$this->assertFalse($result);
$TestModel->locale = array('rus');
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'rus',
'title' => '',
'content' => ''
)
);
$this->assertEqual($result, $expected);
}
/**
* testTranslatedFindList method
*
* @access public
* @return void
*/
function testTranslatedFindList() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'deu';
$TestModel->displayField = 'title';
$result = $TestModel->find('list', array('recursive' => 1));
$expected = array(1 => 'Titel #1', 2 => 'Titel #2', 3 => 'Titel #3');
$this->assertEqual($result, $expected);
// MSSQL trigger an error and stops the page even if the debug = 0
if ($this->db->config['driver'] != 'mssql') {
$debug = Configure::read('debug');
Configure::write('debug', 0);
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => false));
$this->assertEqual($result, array());
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'after'));
$this->assertEqual($result, array());
Configure::write('debug', $debug);
}
$result = $TestModel->find('list', array('recursive' => 1, 'callbacks' => 'before'));
$expected = array(1 => null, 2 => null, 3 => null);
$this->assertEqual($result, $expected);
}
/**
* testReadSelectedFields method
*
* @access public
* @return void
*/
function testReadSelectedFields() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$result = $TestModel->find('all', array('fields' => array('slug', 'TranslatedItem.content')));
$expected = array(
array('TranslatedItem' => array('slug' => 'first_translated', 'locale' => 'eng', 'content' => 'Content #1')),
array('TranslatedItem' => array('slug' => 'second_translated', 'locale' => 'eng', 'content' => 'Content #2')),
array('TranslatedItem' => array('slug' => 'third_translated', 'locale' => 'eng', 'content' => 'Content #3'))
);
$this->assertEqual($result, $expected);
$result = $TestModel->find('all', array('fields' => array('TranslatedItem.slug', 'content')));
$this->assertEqual($result, $expected);
$TestModel->locale = array('eng', 'deu', 'cze');
$delete = array(array('locale' => 'deu'), array('field' => 'content', 'locale' => 'eng'));
$I18nModel =& ClassRegistry::getObject('TranslateTestModel');
$I18nModel->deleteAll(array('or' => $delete));
$result = $TestModel->find('all', array('fields' => array('title', 'content')));
$expected = array(
array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #1', 'content' => 'Obsah #1')),
array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #2', 'content' => 'Obsah #2')),
array('TranslatedItem' => array('locale' => 'eng', 'title' => 'Title #3', 'content' => 'Obsah #3'))
);
$this->assertEqual($result, $expected);
}
/**
* testSaveCreate method
*
* @access public
* @return void
*/
function testSaveCreate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'spa';
$data = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4', 'content' => 'Contenido #4');
$TestModel->create($data);
$TestModel->save();
$result = $TestModel->read();
$expected = array('TranslatedItem' => array_merge($data, array('id' => $TestModel->id, 'locale' => 'spa')));
$this->assertEqual($result, $expected);
}
/**
* testSaveUpdate method
*
* @access public
* @return void
*/
function testSaveUpdate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'spa';
$oldData = array('slug' => 'fourth_translated', 'title' => 'Leyenda #4');
$TestModel->create($oldData);
$TestModel->save();
$id = $TestModel->id;
$newData = array('id' => $id, 'content' => 'Contenido #4');
$TestModel->create($newData);
$TestModel->save();
$result = $TestModel->read(null, $id);
$expected = array('TranslatedItem' => array_merge($oldData, $newData, array('locale' => 'spa')));
$this->assertEqual($result, $expected);
}
/**
* testMultipleCreate method
*
* @access public
* @return void
*/
function testMultipleCreate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'deu';
$data = array(
'slug' => 'new_translated',
'title' => array('eng' => 'New title', 'spa' => 'Nuevo leyenda'),
'content' => array('eng' => 'New content', 'spa' => 'Nuevo contenido')
);
$TestModel->create($data);
$TestModel->save();
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$TestModel->locale = array('eng', 'spa');
$result = $TestModel->read();
$expected = array(
'TranslatedItem' => array('id' => 4, 'slug' => 'new_translated', 'locale' => 'eng', 'title' => 'New title', 'content' => 'New content'),
'Title' => array(
array('id' => 21, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'New title'),
array('id' => 22, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'title', 'content' => 'Nuevo leyenda')
),
'Content' => array(
array('id' => 19, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'New content'),
array('id' => 20, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 4, 'field' => 'content', 'content' => 'Nuevo contenido')
)
);
$this->assertEqual($result, $expected);
}
/**
* testMultipleUpdate method
*
* @access public
* @return void
*/
function testMultipleUpdate() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->validate['title'] = 'notEmpty';
$data = array('TranslatedItem' => array(
'id' => 1,
'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'),
'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1')
));
$TestModel->create();
$TestModel->save($data);
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array('id' => '1', 'slug' => 'first_translated', 'locale' => 'eng', 'title' => 'New Title #1', 'content' => 'New Content #1'),
'Title' => array(
array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'New Title #1'),
array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Neue Titel #1'),
array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Novy Titulek #1')
),
'Content' => array(
array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'New Content #1'),
array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Neue Inhalt #1'),
array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Novy Obsah #1')
)
);
$this->assertEqual($result, $expected);
$TestModel->unbindTranslation($translations);
$TestModel->bindTranslation(array('title', 'content'), false);
}
/**
* testMixedCreateUpdateWithArrayLocale method
*
* @access public
* @return void
*/
function testMixedCreateUpdateWithArrayLocale() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = array('cze', 'deu');
$data = array('TranslatedItem' => array(
'id' => 1,
'title' => array('eng' => 'Updated Title #1', 'spa' => 'Nuevo leyenda #1'),
'content' => 'Upraveny obsah #1'
));
$TestModel->create();
$TestModel->save($data);
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItem' => array('id' => 1, 'slug' => 'first_translated', 'locale' => 'cze', 'title' => 'Titulek #1', 'content' => 'Upraveny obsah #1'),
'Title' => array(
array('id' => 1, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Updated Title #1'),
array('id' => 3, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titel #1'),
array('id' => 5, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Titulek #1'),
array('id' => 19, 'locale' => 'spa', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'title', 'content' => 'Nuevo leyenda #1')
),
'Content' => array(
array('id' => 2, 'locale' => 'eng', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Content #1'),
array('id' => 4, 'locale' => 'deu', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Inhalt #1'),
array('id' => 6, 'locale' => 'cze', 'model' => 'TranslatedItem', 'foreign_key' => 1, 'field' => 'content', 'content' => 'Upraveny obsah #1')
)
);
$this->assertEqual($result, $expected);
}
/**
* testValidation method
*
* @access public
* @return void
*/
function testValidation() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->locale = 'eng';
$TestModel->validate['title'] = '/Only this title/';
$data = array('TranslatedItem' => array(
'id' => 1,
'title' => array('eng' => 'New Title #1', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'),
'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1')
));
$TestModel->create();
$this->assertFalse($TestModel->save($data));
$this->assertEqual($TestModel->validationErrors['title'], 'This field cannot be left blank');
$TestModel->locale = 'eng';
$TestModel->validate['title'] = '/Only this title/';
$data = array('TranslatedItem' => array(
'id' => 1,
'title' => array('eng' => 'Only this title', 'deu' => 'Neue Titel #1', 'cze' => 'Novy Titulek #1'),
'content' => array('eng' => 'New Content #1', 'deu' => 'Neue Inhalt #1', 'cze' => 'Novy Obsah #1')
));
$TestModel->create();
$this->assertTrue($TestModel->save($data));
}
/**
* testAttachDetach method
*
* @access public
* @return void
*/
function testAttachDetach() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$Behavior =& $this->Model->Behaviors->Translate;
$TestModel->unbindTranslation();
$translations = array('title' => 'Title', 'content' => 'Content');
$TestModel->bindTranslation($translations, false);
$result = array_keys($TestModel->hasMany);
$expected = array('Title', 'Content');
$this->assertEqual($result, $expected);
$TestModel->Behaviors->detach('Translate');
$result = array_keys($TestModel->hasMany);
$expected = array();
$this->assertEqual($result, $expected);
$result = isset($TestModel->Behaviors->Translate);
$this->assertFalse($result);
$result = isset($Behavior->settings[$TestModel->alias]);
$this->assertFalse($result);
$result = isset($Behavior->runtime[$TestModel->alias]);
$this->assertFalse($result);
$TestModel->Behaviors->attach('Translate', array('title' => 'Title', 'content' => 'Content'));
$result = array_keys($TestModel->hasMany);
$expected = array('Title', 'Content');
$this->assertEqual($result, $expected);
$result = isset($TestModel->Behaviors->Translate);
$this->assertTrue($result);
$Behavior = $TestModel->Behaviors->Translate;
$result = isset($Behavior->settings[$TestModel->alias]);
$this->assertTrue($result);
$result = isset($Behavior->runtime[$TestModel->alias]);
$this->assertTrue($result);
}
/**
* testAnotherTranslateTable method
*
* @access public
* @return void
*/
function testAnotherTranslateTable() {
$this->loadFixtures('Translate', 'TranslatedItem', 'TranslateTable');
$TestModel =& new TranslatedItemWithTable();
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedItemWithTable' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'title' => 'Another Title #1',
'content' => 'Another Content #1'
)
);
$this->assertEqual($result, $expected);
}
/**
* testTranslateWithAssociations method
*
* @access public
* @return void
*/
function testTranslateWithAssociations() {
$this->loadFixtures('TranslateArticle', 'TranslatedArticle', 'User', 'Comment', 'ArticlesTag', 'Tag');
$TestModel =& new TranslatedArticle();
$TestModel->locale = 'eng';
$recursive = $TestModel->recursive;
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedArticle' => array(
'id' => 1,
'user_id' => 1,
'published' => 'Y',
'created' => '2007-03-18 10:39:23',
'updated' => '2007-03-18 10:41:31',
'locale' => 'eng',
'title' => 'Title (eng) #1',
'body' => 'Body (eng) #1'
),
'User' => array(
'id' => 1,
'user' => 'mariano',
'password' => '5f4dcc3b5aa765d61d8327deb882cf99',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
)
);
$this->assertEqual($result, $expected);
$result = $TestModel->find('all', array('recursive' => -1));
$expected = array(
array(
'TranslatedArticle' => array(
'id' => 1,
'user_id' => 1,
'published' => 'Y',
'created' => '2007-03-18 10:39:23',
'updated' => '2007-03-18 10:41:31',
'locale' => 'eng',
'title' => 'Title (eng) #1',
'body' => 'Body (eng) #1'
)
),
array(
'TranslatedArticle' => array(
'id' => 2,
'user_id' => 3,
'published' => 'Y',
'created' => '2007-03-18 10:41:23',
'updated' => '2007-03-18 10:43:31',
'locale' => 'eng',
'title' => 'Title (eng) #2',
'body' => 'Body (eng) #2'
)
),
array(
'TranslatedArticle' => array(
'id' => 3,
'user_id' => 1,
'published' => 'Y',
'created' => '2007-03-18 10:43:23',
'updated' => '2007-03-18 10:45:31',
'locale' => 'eng',
'title' => 'Title (eng) #3',
'body' => 'Body (eng) #3'
)
)
);
$this->assertEqual($result, $expected);
$this->assertEqual($TestModel->recursive, $recursive);
$TestModel->recursive = -1;
$result = $TestModel->read(null, 1);
$expected = array(
'TranslatedArticle' => array(
'id' => 1,
'user_id' => 1,
'published' => 'Y',
'created' => '2007-03-18 10:39:23',
'updated' => '2007-03-18 10:41:31',
'locale' => 'eng',
'title' => 'Title (eng) #1',
'body' => 'Body (eng) #1'
)
);
$this->assertEqual($result, $expected);
}
/**
* testTranslateTableWithPrefix method
* Tests that is possible to have a translation model with a custom tablePrefix
*
* @access public
* @return void
*/
function testTranslateTableWithPrefix() {
$this->loadFixtures('TranslateWithPrefix', 'TranslatedItem');
$TestModel =& new TranslatedItem2;
$TestModel->locale = 'eng';
$result = $TestModel->read(null, 1);
$expected = array('TranslatedItem' => array(
'id' => 1,
'slug' => 'first_translated',
'locale' => 'eng',
'content' => 'Content #1',
'title' => 'Title #1'
));
$this->assertEqual($result, $expected);
}
/**
* Test infinite loops not occuring with unbindTranslation()
*
* @return void
*/
function testUnbindTranslationInfinteLoop() {
$this->loadFixtures('Translate', 'TranslatedItem');
$TestModel =& new TranslatedItem();
$TestModel->Behaviors->detach('Translate');
$TestModel->actsAs = array();
$TestModel->Behaviors->attach('Translate');
$TestModel->bindTranslation(array('title', 'content'), true);
$result = $TestModel->unbindTranslation();
$this->assertFalse($result);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,979 @@
<?php
/**
* Test for Schema database management
*
*
* 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.5550
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Model', 'CakeSchema', false);
/**
* Test for Schema database management
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class MyAppSchema extends CakeSchema {
/**
* name property
*
* @var string 'MyApp'
* @access public
*/
var $name = 'MyApp';
/**
* connection property
*
* @var string 'test_suite'
* @access public
*/
var $connection = 'test_suite';
/**
* comments property
*
* @var array
* @access public
*/
var $comments = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'user_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false, 'length' => 100),
'comment' => array('type' => 'text', 'null' => false, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
/**
* posts property
*
* @var array
* @access public
*/
var $posts = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => true, 'default' => ''),
'title' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'body' => array('type' => 'text', 'null' => true, 'default' => null),
'summary' => array('type' => 'text', 'null' => true),
'published' => array('type' => 'string', 'null' => true, 'default' => 'Y', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
/**
* setup method
*
* @param mixed $version
* @access public
* @return void
*/
function setup($version) {
}
/**
* teardown method
*
* @param mixed $version
* @access public
* @return void
*/
function teardown($version) {
}
}
/**
* TestAppSchema class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class TestAppSchema extends CakeSchema {
/**
* name property
*
* @var string 'MyApp'
* @access public
*/
var $name = 'MyApp';
/**
* comments property
*
* @var array
* @access public
*/
var $comments = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0,'key' => 'primary'),
'article_id' => array('type' => 'integer', 'null' => false),
'user_id' => array('type' => 'integer', 'null' => false),
'comment' => array('type' => 'text', 'null' => true, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
'tableParameters' => array(),
);
/**
* posts property
*
* @var array
* @access public
*/
var $posts = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false),
'body' => array('type' => 'text', 'null' => true, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
'tableParameters' => array(),
);
/**
* posts_tags property
*
* @var array
* @access public
*/
var $posts_tags = array(
'post_id' => array('type' => 'integer', 'null' => false, 'key' => 'primary'),
'tag_id' => array('type' => 'string', 'null' => false, 'key' => 'primary'),
'indexes' => array('posts_tag' => array('column' => array('tag_id', 'post_id'), 'unique' => 1)),
'tableParameters' => array()
);
/**
* tags property
*
* @var array
* @access public
*/
var $tags = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'tag' => array('type' => 'string', 'null' => false),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
'tableParameters' => array()
);
/**
* datatypes property
*
* @var array
* @access public
*/
var $datatypes = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'float_field' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => ''),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
'tableParameters' => array()
);
/**
* setup method
*
* @param mixed $version
* @access public
* @return void
*/
function setup($version) {
}
/**
* teardown method
*
* @param mixed $version
* @access public
* @return void
*/
function teardown($version) {
}
}
/**
* SchmeaPost class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaPost extends CakeTestModel {
/**
* name property
*
* @var string 'SchemaPost'
* @access public
*/
var $name = 'SchemaPost';
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'posts';
/**
* hasMany property
*
* @var array
* @access public
*/
var $hasMany = array('SchemaComment');
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('SchemaTag');
}
/**
* SchemaComment class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaComment extends CakeTestModel {
/**
* name property
*
* @var string 'SchemaComment'
* @access public
*/
var $name = 'SchemaComment';
/**
* useTable property
*
* @var string 'comments'
* @access public
*/
var $useTable = 'comments';
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array('SchemaPost');
}
/**
* SchemaTag class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaTag extends CakeTestModel {
/**
* name property
*
* @var string 'SchemaTag'
* @access public
*/
var $name = 'SchemaTag';
/**
* useTable property
*
* @var string 'tags'
* @access public
*/
var $useTable = 'tags';
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('SchemaPost');
}
/**
* SchemaDatatype class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaDatatype extends CakeTestModel {
/**
* name property
*
* @var string 'SchemaDatatype'
* @access public
*/
var $name = 'SchemaDatatype';
/**
* useTable property
*
* @var string 'datatypes'
* @access public
*/
var $useTable = 'datatypes';
}
/**
* Testdescribe class
*
* This class is defined purely to inherit the cacheSources variable otherwise
* testSchemaCreatTable will fail if listSources has already been called and
* its source cache populated - I.e. if the test is run within a group
*
* @uses CakeTestModel
* @package
* @subpackage cake.tests.cases.libs.model
*/
class Testdescribe extends CakeTestModel {
/**
* name property
*
* @var string 'Testdescribe'
* @access public
*/
var $name = 'Testdescribe';
}
/**
* SchemaCrossDatabase class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaCrossDatabase extends CakeTestModel {
/**
* name property
*
* @var string 'SchemaCrossDatabase'
* @access public
*/
var $name = 'SchemaCrossDatabase';
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'cross_database';
/**
* useDbConfig property
*
* @var string 'test2'
* @access public
*/
var $useDbConfig = 'test2';
}
/**
* SchemaCrossDatabaseFixture class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaCrossDatabaseFixture extends CakeTestFixture {
/**
* name property
*
* @var string 'CrossDatabase'
* @access public
*/
var $name = 'CrossDatabase';
/**
* table property
*
* @access public
*/
var $table = 'cross_database';
/**
* fields property
*
* @var array
* @access public
*/
var $fields = array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'name' => 'string'
);
/**
* records property
*
* @var array
* @access public
*/
var $records = array(
array('id' => 1, 'name' => 'First'),
array('id' => 2, 'name' => 'Second'),
);
}
/**
* SchemaPrefixAuthUser class
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class SchemaPrefixAuthUser extends CakeTestModel {
/**
* name property
*
* @var string
*/
var $name = 'SchemaPrefixAuthUser';
/**
* table prefix
*
* @var string
*/
var $tablePrefix = 'auth_';
/**
* useTable
*
* @var string
*/
var $useTable = 'users';
}
/**
* CakeSchemaTest
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class CakeSchemaTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array(
'core.post', 'core.tag', 'core.posts_tag', 'core.test_plugin_comment',
'core.datatype', 'core.auth_user', 'core.author',
'core.test_plugin_article', 'core.user', 'core.comment'
);
/**
* setUp method
*
* @access public
* @return void
*/
function startTest() {
$this->Schema = new TestAppSchema();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
@unlink(TMP . 'tests' . DS .'schema.php');
unset($this->Schema);
ClassRegistry::flush();
}
/**
* testSchemaName method
*
* @access public
* @return void
*/
function testSchemaName() {
$Schema = new CakeSchema();
$this->assertEqual(strtolower($Schema->name), strtolower(APP_DIR));
Configure::write('App.dir', 'Some.name.with.dots');
$Schema = new CakeSchema();
$this->assertEqual($Schema->name, 'SomeNameWithDots');
Configure::write('App.dir', 'app');
}
/**
* testSchemaRead method
*
* @access public
* @return void
*/
function testSchemaRead() {
$read = $this->Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => array('SchemaPost', 'SchemaComment', 'SchemaTag', 'SchemaDatatype')
));
unset($read['tables']['missing']);
$expected = array('comments', 'datatypes', 'posts', 'posts_tags', 'tags');
$this->assertEqual(array_keys($read['tables']), $expected);
foreach ($read['tables'] as $table => $fields) {
$this->assertEqual(array_keys($fields), array_keys($this->Schema->tables[$table]));
}
$this->assertEqual(
$read['tables']['datatypes']['float_field'],
$this->Schema->tables['datatypes']['float_field']
);
$SchemaPost =& ClassRegistry::init('SchemaPost');
$SchemaPost->table = 'sts';
$SchemaPost->tablePrefix = 'po';
$read = $this->Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => array('SchemaPost')
));
$this->assertFalse(isset($read['tables']['missing']['posts']), 'Posts table was not read from tablePrefix %s');
$read = $this->Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => array('SchemaComment', 'SchemaTag', 'SchemaPost')
));
$this->assertFalse(isset($read['tables']['missing']['posts_tags']), 'Join table marked as missing %s');
}
/**
* test read() with tablePrefix properties.
*
* @return void
*/
function testSchemaReadWithTablePrefix() {
$model =& new SchemaPrefixAuthUser();
$Schema =& new CakeSchema();
$read = $Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => array('SchemaPrefixAuthUser')
));
unset($read['tables']['missing']);
$this->assertTrue(isset($read['tables']['auth_users']), 'auth_users key missing %s');
}
/**
* test reading schema with config prefix.
*
* @return void
*/
function testSchemaReadWithConfigPrefix() {
$db =& ConnectionManager::getDataSource('test_suite');
$config = $db->config;
$config['prefix'] = 'schema_test_prefix_';
ConnectionManager::create('schema_prefix', $config);
$read = $this->Schema->read(array('connection' => 'schema_prefix', 'models' => false));
$this->assertTrue(empty($read['tables']));
}
/**
* test reading schema from plugins.
*
* @return void
*/
function testSchemaReadWithPlugins() {
App::objects('model', null, false);
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$Schema =& new CakeSchema();
$Schema->plugin = 'TestPlugin';
$read = $Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => true
));
unset($read['tables']['missing']);
$this->assertTrue(isset($read['tables']['auth_users']));
$this->assertTrue(isset($read['tables']['authors']));
$this->assertTrue(isset($read['tables']['test_plugin_comments']));
$this->assertTrue(isset($read['tables']['posts']));
$this->assertEqual(count($read['tables']), 4);
App::build();
}
/**
* test reading schema with tables from another database.
*
* @return void
*/
function testSchemaReadWithCrossDatabase() {
$config = new DATABASE_CONFIG();
$skip = $this->skipIf(
!isset($config->test) || !isset($config->test2),
'%s Primary and secondary test databases not configured, skipping cross-database '
.'join tests.'
.' To run these tests, you must define $test and $test2 in your database configuration.'
);
if ($skip) {
return;
}
$db2 =& ConnectionManager::getDataSource('test2');
$fixture = new SchemaCrossDatabaseFixture();
$fixture->create($db2);
$fixture->insert($db2);
$read = $this->Schema->read(array(
'connection' => 'test_suite',
'name' => 'TestApp',
'models' => array('SchemaCrossDatabase', 'SchemaPost')
));
$this->assertTrue(isset($read['tables']['posts']));
$this->assertFalse(isset($read['tables']['cross_database']), 'Cross database should not appear');
$this->assertFalse(isset($read['tables']['missing']['cross_database']), 'Cross database should not appear');
$read = $this->Schema->read(array(
'connection' => 'test2',
'name' => 'TestApp',
'models' => array('SchemaCrossDatabase', 'SchemaPost')
));
$this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear');
$this->assertFalse(isset($read['tables']['posts']), 'Posts should not appear');
$this->assertTrue(isset($read['tables']['cross_database']));
$fixture->drop($db2);
}
/**
* test that tables are generated correctly
*
* @return void
*/
function testGenerateTable() {
$fields = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false),
'body' => array('type' => 'text', 'null' => true, 'default' => null),
'published' => array('type' => 'string', 'null' => true, 'default' => 'N', 'length' => 1),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
$result = $this->Schema->generateTable('posts', $fields);
$this->assertPattern('/var \$posts/', $result);
eval(substr($result, 4));
$this->assertEqual($posts, $fields);
}
/**
* testSchemaWrite method
*
* @access public
* @return void
*/
function testSchemaWrite() {
$write = $this->Schema->write(array('name' => 'MyOtherApp', 'tables' => $this->Schema->tables, 'path' => TMP . 'tests'));
$file = file_get_contents(TMP . 'tests' . DS .'schema.php');
$this->assertEqual($write, $file);
require_once( TMP . 'tests' . DS .'schema.php');
$OtherSchema = new MyOtherAppSchema();
$this->assertEqual($this->Schema->tables, $OtherSchema->tables);
}
/**
* testSchemaComparison method
*
* @access public
* @return void
*/
function testSchemaComparison() {
$New = new MyAppSchema();
$compare = $New->compare($this->Schema);
$expected = array(
'comments' => array(
'add' => array(
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'title' => array('type' => 'string', 'null' => false, 'length' => 100),
),
'drop' => array(
'article_id' => array('type' => 'integer', 'null' => false),
'tableParameters' => array(),
),
'change' => array(
'comment' => array('type' => 'text', 'null' => false, 'default' => null),
)
),
'posts' => array(
'add' => array(
'summary' => array('type' => 'text', 'null' => 1),
),
'drop' => array(
'tableParameters' => array(),
),
'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')
)
),
);
$this->assertEqual($expected, $compare);
$tables = array(
'missing' => array(
'categories' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'name' => array('type' => 'string', 'null' => false, 'default' => NULL, 'length' => 100),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
)
),
'ratings' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => NULL),
'model' => array('type' => 'varchar', 'null' => false, 'default' => NULL),
'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
)
);
$compare = $New->compare($this->Schema, $tables);
$expected = array(
'ratings' => array(
'add' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'foreign_key' => array('type' => 'integer', 'null' => false, 'default' => NULL),
'model' => array('type' => 'varchar', 'null' => false, 'default' => NULL),
'value' => array('type' => 'float', 'null' => false, 'length' => '5,2', 'default' => NULL),
'created' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'modified' => array('type' => 'datetime', 'null' => false, 'default' => NULL),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => 1)),
'tableParameters' => array('charset' => 'latin1', 'collate' => 'latin1_swedish_ci', 'engine' => 'MyISAM')
)
)
);
$this->assertEqual($expected, $compare);
}
/**
* test comparing '' and null and making sure they are different.
*
* @return void
*/
function testCompareEmptyStringAndNull() {
$One =& new CakeSchema(array(
'posts' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => false, 'default' => '')
)
));
$Two =& new CakeSchema(array(
'posts' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => NULL, 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => false, 'default' => null)
)
));
$compare = $One->compare($Two);
$expected = array(
'posts' => array(
'change' => array(
'name' => array('type' => 'string', 'null' => false, 'default' => null)
)
)
);
$this->assertEqual($expected, $compare);
}
/**
* Test comparing tableParameters and indexes.
*
* @return void
*/
function testTableParametersAndIndexComparison() {
$old = array(
'posts' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => true)
),
'tableParameters' => array(
'charset' => 'latin1',
'collate' => 'latin1_general_ci'
)
),
'comments' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'comment' => array('type' => 'text'),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => true),
'post_id' => array('column' => 'post_id'),
),
'tableParameters' => array(
'engine' => 'InnoDB',
'charset' => 'latin1',
'collate' => 'latin1_general_ci'
)
)
);
$new = array(
'posts' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => false),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => true),
'author_id' => array('column' => 'author_id'),
),
'tableParameters' => array(
'charset' => 'utf8',
'collate' => 'utf8_general_ci',
'engine' => 'MyISAM'
)
),
'comments' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'post_id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'comment' => array('type' => 'text'),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => true),
),
'tableParameters' => array(
'charset' => 'utf8',
'collate' => 'utf8_general_ci'
)
)
);
$compare = $this->Schema->compare($old, $new);
$expected = array(
'posts' => array(
'add' => array(
'indexes' => array('author_id' => array('column' => 'author_id')),
),
'change' => array(
'tableParameters' => array(
'charset' => 'utf8',
'collate' => 'utf8_general_ci',
'engine' => 'MyISAM'
)
)
),
'comments' => array(
'drop' => array(
'indexes' => array('post_id' => array('column' => 'post_id')),
),
'change' => array(
'tableParameters' => array(
'charset' => 'utf8',
'collate' => 'utf8_general_ci',
)
)
)
);
$this->assertEqual($compare, $expected);
}
/**
* testSchemaLoading method
*
* @access public
* @return void
*/
function testSchemaLoading() {
$Other =& $this->Schema->load(array('name' => 'MyOtherApp', 'path' => TMP . 'tests'));
$this->assertEqual($Other->name, 'MyOtherApp');
$this->assertEqual($Other->tables, $this->Schema->tables);
}
/**
* test loading schema files inside of plugins.
*
* @return void
*/
function testSchemaLoadingFromPlugin() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$Other =& $this->Schema->load(array('name' => 'TestPluginApp', 'plugin' => 'TestPlugin'));
$this->assertEqual($Other->name, 'TestPluginApp');
$this->assertEqual(array_keys($Other->tables), array('acos'));
App::build();
}
/**
* testSchemaCreateTable method
*
* @access public
* @return void
*/
function testSchemaCreateTable() {
$db =& ConnectionManager::getDataSource('test_suite');
$db->cacheSources = false;
$Schema =& new CakeSchema(array(
'connection' => 'test_suite',
'testdescribes' => array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'int_null' => array('type' => 'integer', 'null' => true),
'int_not_null' => array('type' => 'integer', 'null' => false),
),
));
$sql = $db->createSchema($Schema);
$col = $Schema->tables['testdescribes']['int_null'];
$col['name'] = 'int_null';
$column = $this->db->buildColumn($col);
$this->assertPattern('/' . preg_quote($column, '/') . '/', $sql);
$col = $Schema->tables['testdescribes']['int_not_null'];
$col['name'] = 'int_not_null';
$column = $this->db->buildColumn($col);
$this->assertPattern('/' . preg_quote($column, '/') . '/', $sql);
}
}

View File

@@ -0,0 +1,340 @@
<?php
/**
* Connection Manager tests
*
*
* PHP versions 4 and 5
*
* 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.5550
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'ConnectionManager');
/**
* ConnectionManagerTest
*
* @package cake
* @subpackage cake.tests.cases.models
*/
class ConnectionManagerTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->ConnectionManager =& ConnectionManager::getInstance();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->ConnectionManager);
}
/**
* testInstantiation method
*
* @access public
* @return void
*/
function testInstantiation() {
$this->assertTrue(is_a($this->ConnectionManager, 'ConnectionManager'));
}
/**
* testEnumConnectionObjects method
*
* @access public
* @return void
*/
function testEnumConnectionObjects() {
$sources = ConnectionManager::enumConnectionObjects();
$this->assertTrue(count($sources) >= 1);
$connections = array('default', 'test', 'test_suite');
$this->assertTrue(count(array_intersect(array_keys($sources), $connections)) >= 1);
}
/**
* testGetDataSource method
*
* @access public
* @return void
*/
function testGetDataSource() {
$connections = ConnectionManager::enumConnectionObjects();
$this->assertTrue(count(array_keys($connections) >= 1));
$source = ConnectionManager::getDataSource(key($connections));
$this->assertTrue(is_object($source));
$this->expectError(new PatternExpectation('/Non-existent data source/i'));
$source = ConnectionManager::getDataSource('non_existent_source');
$this->assertEqual($source, null);
}
/**
* testGetPluginDataSource method
*
* @access public
* @return void
*/
function testGetPluginDataSource() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$name = 'test_source';
$config = array('datasource' => 'TestPlugin.TestSource');
$connection = ConnectionManager::create($name, $config);
$this->assertTrue(class_exists('TestSource'));
$this->assertEqual($connection->configKeyName, $name);
$this->assertEqual($connection->config, $config);
App::build();
}
/**
* testGetPluginDataSourceAndPluginDriver method
*
* @access public
* @return void
*/
function testGetPluginDataSourceAndPluginDriver() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$name = 'test_plugin_source_and_driver';
$config = array('datasource' => 'TestPlugin.TestSource', 'driver' => 'TestPlugin.TestDriver');
$connection = ConnectionManager::create($name, $config);
$this->assertTrue(class_exists('TestSource'));
$this->assertTrue(class_exists('TestDriver'));
$this->assertEqual($connection->configKeyName, $name);
$this->assertEqual($connection->config, $config);
App::build();
}
/**
* testGetLocalDataSourceAndPluginDriver method
*
* @access public
* @return void
*/
function testGetLocalDataSourceAndPluginDriver() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS)
));
$name = 'test_local_source_and_plugin_driver';
$config = array('datasource' => 'dbo', 'driver' => 'TestPlugin.DboDummy');
$connection = ConnectionManager::create($name, $config);
$this->assertTrue(class_exists('DboSource'));
$this->assertTrue(class_exists('DboDummy'));
$this->assertEqual($connection->configKeyName, $name);
App::build();
}
/**
* testGetPluginDataSourceAndLocalDriver method
*
* @access public
* @return void
*/
function testGetPluginDataSourceAndLocalDriver() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'datasources' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS . 'datasources' . DS)
));
$name = 'test_plugin_source_and_local_driver';
$config = array('datasource' => 'TestPlugin.TestSource', 'driver' => 'local_driver');
$connection = ConnectionManager::create($name, $config);
$this->assertTrue(class_exists('TestSource'));
$this->assertTrue(class_exists('TestLocalDriver'));
$this->assertEqual($connection->configKeyName, $name);
$this->assertEqual($connection->config, $config);
App::build();
}
/**
* testSourceList method
*
* @access public
* @return void
*/
function testSourceList() {
$sources = ConnectionManager::sourceList();
$this->assertTrue(count($sources) >= 1);
$connections = array('default', 'test', 'test_suite');
$this->assertTrue(count(array_intersect($sources, $connections)) >= 1);
}
/**
* testGetSourceName method
*
* @access public
* @return void
*/
function testGetSourceName() {
$connections = ConnectionManager::enumConnectionObjects();
$name = key($connections);
$source = ConnectionManager::getDataSource($name);
$result = ConnectionManager::getSourceName($source);
$this->assertEqual($result, $name);
$source =& new StdClass();
$result = ConnectionManager::getSourceName($source);
$this->assertEqual($result, null);
}
/**
* testLoadDataSource method
*
* @access public
* @return void
*/
function testLoadDataSource() {
$connections = array(
array('classname' => 'DboMysql', 'filename' => 'dbo' . DS . 'dbo_mysql'),
array('classname' => 'DboMysqli', 'filename' => 'dbo' . DS . 'dbo_mysqli'),
array('classname' => 'DboMssql', 'filename' => 'dbo' . DS . 'dbo_mssql'),
array('classname' => 'DboOracle', 'filename' => 'dbo' . DS . 'dbo_oracle'),
);
foreach ($connections as $connection) {
$exists = class_exists($connection['classname']);
$loaded = ConnectionManager::loadDataSource($connection);
$this->assertEqual($loaded, !$exists, "%s Failed loading the {$connection['classname']} datasource");
}
$connection = array('classname' => 'NonExistentDataSource', 'filename' => 'non_existent');
$this->expectError(new PatternExpectation('/Unable to import DataSource class/i'));
$loaded = ConnectionManager::loadDataSource($connection);
$this->assertEqual($loaded, null);
}
/**
* testCreateDataSource method
*
* @access public
* @return void
*/
function testCreateDataSourceWithIntegrationTests() {
$name = 'test_created_connection';
$connections = ConnectionManager::enumConnectionObjects();
$this->assertTrue(count(array_keys($connections) >= 1));
$source = ConnectionManager::getDataSource(key($connections));
$this->assertTrue(is_object($source));
$config = $source->config;
$connection = ConnectionManager::create($name, $config);
$this->assertTrue(is_object($connection));
$this->assertEqual($name, $connection->configKeyName);
$this->assertEqual($name, ConnectionManager::getSourceName($connection));
$source = ConnectionManager::create(null, array());
$this->assertEqual($source, null);
$source = ConnectionManager::create('another_test', array());
$this->assertEqual($source, null);
$config = array('classname' => 'DboMysql', 'filename' => 'dbo' . DS . 'dbo_mysql');
$source = ConnectionManager::create(null, $config);
$this->assertEqual($source, null);
}
/**
* testConnectionData method
*
* @access public
* @return void
*/
function testConnectionData() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'datasources' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS . 'datasources' . DS)
));
$expected = array(
'filename' => 'test2_source',
'classname' => 'Test2Source',
'parent' => '',
'plugin' => ''
);
ConnectionManager::create('connection1', array('datasource' => 'Test2'));
$connections = ConnectionManager::enumConnectionObjects();
$this->assertEqual($expected, $connections['connection1']);
ConnectionManager::create('connection2', array('datasource' => 'Test2Source'));
$connections = ConnectionManager::enumConnectionObjects();
$this->assertEqual($expected, $connections['connection2']);
ConnectionManager::create('connection3', array('datasource' => 'TestPlugin.Test'));
$connections = ConnectionManager::enumConnectionObjects();
$expected['filename'] = 'test_source';
$expected['classname'] = 'TestSource';
$expected['plugin'] = 'TestPlugin';
$this->assertEqual($expected, $connections['connection3']);
ConnectionManager::create('connection4', array('datasource' => 'TestPlugin.TestSource'));
$connections = ConnectionManager::enumConnectionObjects();
$this->assertEqual($expected, $connections['connection4']);
ConnectionManager::create('connection5', array('datasource' => 'Test2Other'));
$connections = ConnectionManager::enumConnectionObjects();
$expected['filename'] = 'test2_other_source';
$expected['classname'] = 'Test2OtherSource';
$expected['plugin'] = '';
$this->assertEqual($expected, $connections['connection5']);
ConnectionManager::create('connection6', array('datasource' => 'Test2OtherSource'));
$connections = ConnectionManager::enumConnectionObjects();
$this->assertEqual($expected, $connections['connection6']);
ConnectionManager::create('connection7', array('datasource' => 'TestPlugin.TestOther'));
$connections = ConnectionManager::enumConnectionObjects();
$expected['filename'] = 'test_other_source';
$expected['classname'] = 'TestOtherSource';
$expected['plugin'] = 'TestPlugin';
$this->assertEqual($expected, $connections['connection7']);
ConnectionManager::create('connection8', array('datasource' => 'TestPlugin.TestOtherSource'));
$connections = ConnectionManager::enumConnectionObjects();
$this->assertEqual($expected, $connections['connection8']);
}
}

View File

@@ -0,0 +1,677 @@
<?php
/**
* DboMssqlTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
require_once LIBS.'model'.DS.'model.php';
require_once LIBS.'model'.DS.'datasources'.DS.'datasource.php';
require_once LIBS.'model'.DS.'datasources'.DS.'dbo_source.php';
require_once LIBS.'model'.DS.'datasources'.DS.'dbo'.DS.'dbo_mssql.php';
/**
* DboMssqlTestDb class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboMssqlTestDb extends DboMssql {
/**
* simulated property
*
* @var array
* @access public
*/
var $simulated = array();
/**
* simalate property
*
* @var array
* @access public
*/
var $simulate = true;
/**
* fetchAllResultsStack
*
* @var array
* @access public
*/
var $fetchAllResultsStack = array();
/**
* execute method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _execute($sql) {
if ($this->simulate) {
$this->simulated[] = $sql;
return null;
} else {
return parent::_execute($sql);
}
}
/**
* fetchAll method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _matchRecords(&$model, $conditions = null) {
return $this->conditions(array('id' => array(1, 2)));
}
/**
* fetchAll method
*
* @param mixed $sql
* @access protected
* @return void
*/
function fetchAll($sql, $cache = true, $modelName = null) {
$result = parent::fetchAll($sql, $cache, $modelName);
if (!empty($this->fetchAllResultsStack)) {
return array_pop($this->fetchAllResultsStack);
}
return $result;
}
/**
* getLastQuery method
*
* @access public
* @return void
*/
function getLastQuery() {
return $this->simulated[count($this->simulated) - 1];
}
/**
* getPrimaryKey method
*
* @param mixed $model
* @access public
* @return void
*/
function getPrimaryKey($model) {
return parent::_getPrimaryKey($model);
}
/**
* clearFieldMappings method
*
* @access public
* @return void
*/
function clearFieldMappings() {
$this->__fieldMappings = array();
}
}
/**
* MssqlTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class MssqlTestModel extends Model {
/**
* name property
*
* @var string 'MssqlTestModel'
* @access public
*/
var $name = 'MssqlTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* _schema property
*
* @var array
* @access protected
*/
var $_schema = array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
'last_login'=> array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'MssqlClientTestModel' => array(
'foreignKey' => 'client_id'
)
);
/**
* find method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function find($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* findAll method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* setSchema method
*
* @param array $schema
* @access public
* @return void
*/
function setSchema($schema) {
$this->_schema = $schema;
}
}
/**
* MssqlClientTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class MssqlClientTestModel extends Model {
/**
* name property
*
* @var string 'MssqlAssociatedTestModel'
* @access public
*/
var $name = 'MssqlClientTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* _schema property
*
* @var array
* @access protected
*/
var $_schema = array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
/**
* DboMssqlTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboMssqlTest extends CakeTestCase {
/**
* The Dbo instance to be tested
*
* @var DboSource
* @access public
*/
var $db = null;
/**
* autoFixtures property
*
* @var bool false
* @access public
*/
var $autoFixtures = false;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.category');
/**
* Skip if cannot connect to mssql
*
* @access public
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mssql', '%s SQL Server connection not available');
}
/**
* Make sure all fixtures tables are being created
*
* @access public
*/
function start() {
$this->db->simulate = false;
parent::start();
$this->db->simulate = true;
}
/**
* Make sure all fixtures tables are being dropped
*
* @access public
*/
function end() {
$this->db->simulate = false;
parent::end();
$this->db->simulate = true;
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function setUp() {
$db = ConnectionManager::getDataSource('test_suite');
$this->db = new DboMssqlTestDb($db->config);
$this->model = new MssqlTestModel();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->model);
}
/**
* testQuoting method
*
* @access public
* @return void
*/
function testQuoting() {
$expected = "1.2";
$result = $this->db->value(1.2, 'float');
$this->assertIdentical($expected, $result);
$expected = "'1,2'";
$result = $this->db->value('1,2', 'float');
$this->assertIdentical($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'integer');
$this->assertIdentical($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'float');
$this->assertIdentical($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'binary');
$this->assertIdentical($expected, $result);
}
/**
* testFields method
*
* @access public
* @return void
*/
function testFields() {
$fields = array(
'[MssqlTestModel].[id] AS [MssqlTestModel__0]',
'[MssqlTestModel].[client_id] AS [MssqlTestModel__1]',
'[MssqlTestModel].[name] AS [MssqlTestModel__2]',
'[MssqlTestModel].[login] AS [MssqlTestModel__3]',
'[MssqlTestModel].[passwd] AS [MssqlTestModel__4]',
'[MssqlTestModel].[addr_1] AS [MssqlTestModel__5]',
'[MssqlTestModel].[addr_2] AS [MssqlTestModel__6]',
'[MssqlTestModel].[zip_code] AS [MssqlTestModel__7]',
'[MssqlTestModel].[city] AS [MssqlTestModel__8]',
'[MssqlTestModel].[country] AS [MssqlTestModel__9]',
'[MssqlTestModel].[phone] AS [MssqlTestModel__10]',
'[MssqlTestModel].[fax] AS [MssqlTestModel__11]',
'[MssqlTestModel].[url] AS [MssqlTestModel__12]',
'[MssqlTestModel].[email] AS [MssqlTestModel__13]',
'[MssqlTestModel].[comments] AS [MssqlTestModel__14]',
'CONVERT(VARCHAR(20), [MssqlTestModel].[last_login], 20) AS [MssqlTestModel__15]',
'[MssqlTestModel].[created] AS [MssqlTestModel__16]',
'CONVERT(VARCHAR(20), [MssqlTestModel].[updated], 20) AS [MssqlTestModel__17]'
);
$result = $this->db->fields($this->model);
$expected = $fields;
$this->assertEqual($result, $expected);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, 'MssqlTestModel.*');
$expected = $fields;
$this->assertEqual($result, $expected);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, array('*', 'AnotherModel.id', 'AnotherModel.name'));
$expected = array_merge($fields, array(
'[AnotherModel].[id] AS [AnotherModel__18]',
'[AnotherModel].[name] AS [AnotherModel__19]'));
$this->assertEqual($result, $expected);
$this->db->clearFieldMappings();
$result = $this->db->fields($this->model, null, array('*', 'MssqlClientTestModel.*'));
$expected = array_merge($fields, array(
'[MssqlClientTestModel].[id] AS [MssqlClientTestModel__18]',
'[MssqlClientTestModel].[name] AS [MssqlClientTestModel__19]',
'[MssqlClientTestModel].[email] AS [MssqlClientTestModel__20]',
'CONVERT(VARCHAR(20), [MssqlClientTestModel].[created], 20) AS [MssqlClientTestModel__21]',
'CONVERT(VARCHAR(20), [MssqlClientTestModel].[updated], 20) AS [MssqlClientTestModel__22]'));
$this->assertEqual($result, $expected);
}
/**
* testDistinctFields method
*
* @access public
* @return void
*/
function testDistinctFields() {
$result = $this->db->fields($this->model, null, array('DISTINCT Car.country_code'));
$expected = array('DISTINCT [Car].[country_code] AS [Car__0]');
$this->assertEqual($result, $expected);
$result = $this->db->fields($this->model, null, 'DISTINCT Car.country_code');
$expected = array('DISTINCT [Car].[country_code] AS [Car__1]');
$this->assertEqual($result, $expected);
}
/**
* testDistinctWithLimit method
*
* @access public
* @return void
*/
function testDistinctWithLimit() {
$this->db->read($this->model, array(
'fields' => array('DISTINCT MssqlTestModel.city', 'MssqlTestModel.country'),
'limit' => 5
));
$result = $this->db->getLastQuery();
$this->assertPattern('/^SELECT DISTINCT TOP 5/', $result);
}
/**
* testDescribe method
*
* @access public
* @return void
*/
function testDescribe() {
$MssqlTableDescription = array(
0 => array(
0 => array(
'Default' => '((0))',
'Field' => 'count',
'Key' => 0,
'Length' => '4',
'Null' => 'NO',
'Type' => 'integer',
)
)
);
$this->db->fetchAllResultsStack = array($MssqlTableDescription);
$dummyModel = $this->model;
$result = $this->db->describe($dummyModel);
$expected = array(
'count' => array(
'type' => 'integer',
'null' => false,
'default' => '0',
'length' => 4
)
);
$this->assertEqual($result, $expected);
}
/**
* testBuildColumn
*
* @return unknown_type
* @access public
*/
function testBuildColumn() {
$column = array('name' => 'id', 'type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary');
$result = $this->db->buildColumn($column);
$expected = '[id] int IDENTITY (1, 1) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'client_id', 'type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11');
$result = $this->db->buildColumn($column);
$expected = '[client_id] int DEFAULT 0 NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'client_id', 'type' => 'integer', 'null' => true);
$result = $this->db->buildColumn($column);
$expected = '[client_id] int NULL';
$this->assertEqual($result, $expected);
// 'name' => 'type' format for columns
$column = array('type' => 'integer', 'name' => 'client_id');
$result = $this->db->buildColumn($column);
$expected = '[client_id] int NULL';
$this->assertEqual($result, $expected);
$column = array('type' => 'string', 'name' => 'name');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => '', 'default' => '', 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) DEFAULT \'\' NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => false, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => false, 'default' => null, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NOT NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => null, 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) NULL';
$this->assertEqual($result, $expected);
$column = array('name' => 'name', 'type' => 'string', 'null' => true, 'default' => '', 'length' => '255');
$result = $this->db->buildColumn($column);
$expected = '[name] varchar(255) DEFAULT \'\'';
$this->assertEqual($result, $expected);
}
/**
* testBuildIndex method
*
* @return void
* @access public
*/
function testBuildIndex() {
$indexes = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'client_id' => array('column' => 'client_id', 'unique' => 1)
);
$result = $this->db->buildIndex($indexes, 'items');
$expected = array(
'PRIMARY KEY ([id])',
'ALTER TABLE items ADD CONSTRAINT client_id UNIQUE([client_id]);'
);
$this->assertEqual($result, $expected);
$indexes = array('client_id' => array('column' => 'client_id'));
$result = $this->db->buildIndex($indexes, 'items');
$this->assertEqual($result, array());
$indexes = array('client_id' => array('column' => array('client_id', 'period_id'), 'unique' => 1));
$result = $this->db->buildIndex($indexes, 'items');
$expected = array('ALTER TABLE items ADD CONSTRAINT client_id UNIQUE([client_id], [period_id]);');
$this->assertEqual($result, $expected);
}
/**
* testUpdateAllSyntax method
*
* @return void
* @access public
*/
function testUpdateAllSyntax() {
$fields = array('MssqlTestModel.client_id' => '[MssqlTestModel].[client_id] + 1');
$conditions = array('MssqlTestModel.updated <' => date('2009-01-01 00:00:00'));
$this->db->update($this->model, $fields, null, $conditions);
$result = $this->db->getLastQuery();
$this->assertNoPattern('/MssqlTestModel/', $result);
$this->assertPattern('/^UPDATE \[mssql_test_models\]/', $result);
$this->assertPattern('/SET \[client_id\] = \[client_id\] \+ 1/', $result);
}
/**
* testGetPrimaryKey method
*
* @return void
* @access public
*/
function testGetPrimaryKey() {
// When param is a model
$result = $this->db->getPrimaryKey($this->model);
$this->assertEqual($result, 'id');
$schema = $this->model->schema();
unset($schema['id']['key']);
$this->model->setSchema($schema);
$result = $this->db->getPrimaryKey($this->model);
$this->assertNull($result);
// When param is a table name
$this->db->simulate = false;
$this->loadFixtures('Category');
$result = $this->db->getPrimaryKey('categories');
$this->assertEqual($result, 'id');
}
/**
* testInsertMulti
*
* @return void
* @access public
*/
function testInsertMulti() {
$fields = array('id', 'name', 'login');
$values = array('(1, \'Larry\', \'PhpNut\')', '(2, \'Renan\', \'renan.saddam\')');
$this->db->simulated = array();
$this->db->insertMulti($this->model, $fields, $values);
$result = $this->db->simulated;
$expected = array(
'SET IDENTITY_INSERT [mssql_test_models] ON',
'INSERT INTO [mssql_test_models] ([id], [name], [login]) VALUES (1, \'Larry\', \'PhpNut\')',
'INSERT INTO [mssql_test_models] ([id], [name], [login]) VALUES (2, \'Renan\', \'renan.saddam\')',
'SET IDENTITY_INSERT [mssql_test_models] OFF'
);
$this->assertEqual($result, $expected);
$fields = array('name', 'login');
$values = array('(\'Larry\', \'PhpNut\')', '(\'Renan\', \'renan.saddam\')');
$this->db->simulated = array();
$this->db->insertMulti($this->model, $fields, $values);
$result = $this->db->simulated;
$expected = array(
'INSERT INTO [mssql_test_models] ([name], [login]) VALUES (\'Larry\', \'PhpNut\')',
'INSERT INTO [mssql_test_models] ([name], [login]) VALUES (\'Renan\', \'renan.saddam\')'
);
$this->assertEqual($result, $expected);
}
/**
* testLastError
*
* @return void
* @access public
*/
function testLastError() {
$debug = Configure::read('debug');
Configure::write('debug', 0);
$this->db->simulate = false;
$query = 'SELECT [name] FROM [categories]';
$this->assertTrue($this->db->execute($query) !== false);
$this->assertNull($this->db->lastError());
$query = 'SELECT [inexistent_field] FROM [categories]';
$this->assertFalse($this->db->execute($query));
$this->assertNotNull($this->db->lastError());
$query = 'SELECT [name] FROM [categories]';
$this->assertTrue($this->db->execute($query) !== false);
$this->assertNull($this->db->lastError());
Configure::write('debug', $debug);
}
}

View File

@@ -0,0 +1,866 @@
<?php
/**
* DboMysqlTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Model', 'DataSource', 'DboSource', 'DboMysql'));
Mock::generatePartial('DboMysql', 'QueryMockDboMysql', array('query'));
/**
* DboMysqlTestDb class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class DboMysqlTestDb extends DboMysql {
/**
* simulated property
*
* @var array
* @access public
*/
var $simulated = array();
/**
* testing property
*
* @var bool true
* @access public
*/
var $testing = true;
/**
* execute method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _execute($sql) {
if ($this->testing) {
$this->simulated[] = $sql;
return null;
}
return parent::_execute($sql);
}
/**
* getLastQuery method
*
* @access public
* @return void
*/
function getLastQuery() {
return $this->simulated[count($this->simulated) - 1];
}
}
/**
* MysqlTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class MysqlTestModel extends Model {
/**
* name property
*
* @var string 'MysqlTestModel'
* @access public
*/
var $name = 'MysqlTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* find method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function find($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* findAll method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
return array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
'last_login'=> array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
}
/**
* DboMysqlTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboMysqlTest extends CakeTestCase {
var $fixtures = array('core.binary_test');
/**
* The Dbo instance to be tested
*
* @var DboSource
* @access public
*/
var $Db = null;
/**
* Skip if cannot connect to mysql
*
* @access public
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mysql', '%s MySQL connection not available');
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function startTest() {
$db = ConnectionManager::getDataSource('test_suite');
$this->model = new MysqlTestModel();
}
/**
* Sets up a Dbo class instance for testing
*
* @access 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);
}
/**
* Test Dbo value method
*
* @access public
*/
function testQuoting() {
$result = $this->db->fields($this->model);
$expected = array(
'`MysqlTestModel`.`id`',
'`MysqlTestModel`.`client_id`',
'`MysqlTestModel`.`name`',
'`MysqlTestModel`.`login`',
'`MysqlTestModel`.`passwd`',
'`MysqlTestModel`.`addr_1`',
'`MysqlTestModel`.`addr_2`',
'`MysqlTestModel`.`zip_code`',
'`MysqlTestModel`.`city`',
'`MysqlTestModel`.`country`',
'`MysqlTestModel`.`phone`',
'`MysqlTestModel`.`fax`',
'`MysqlTestModel`.`url`',
'`MysqlTestModel`.`email`',
'`MysqlTestModel`.`comments`',
'`MysqlTestModel`.`last_login`',
'`MysqlTestModel`.`created`',
'`MysqlTestModel`.`updated`'
);
$this->assertEqual($result, $expected);
$expected = 1.2;
$result = $this->db->value(1.2, 'float');
$this->assertEqual($expected, $result);
$expected = "'1,2'";
$result = $this->db->value('1,2', 'float');
$this->assertEqual($expected, $result);
$expected = "'4713e29446'";
$result = $this->db->value('4713e29446');
$this->assertEqual($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'integer');
$this->assertEqual($expected, $result);
$expected = 'NULL';
$result = $this->db->value('', 'boolean');
$this->assertEqual($expected, $result);
$expected = 10010001;
$result = $this->db->value(10010001);
$this->assertEqual($expected, $result);
$expected = "'00010010001'";
$result = $this->db->value('00010010001');
$this->assertEqual($expected, $result);
}
/**
* test that localized floats don't cause trouble.
*
* @return void
*/
function testLocalizedFloats() {
$restore = setlocale(LC_ALL, null);
setlocale(LC_ALL, 'de_DE');
$result = $this->db->value(3.141593, 'float');
$this->assertEqual((string)$result, '3.141593');
$result = $this->db->value(3.141593);
$this->assertEqual((string)$result, '3.141593');
setlocale(LC_ALL, $restore);
}
/**
* testTinyintCasting method
*
* @access public
* @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->model = new CakeTestModel(array(
'name' => 'Tinyint', 'table' => 'tinyint', '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)));
$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)));
$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)));
$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'));
}
/**
* testIndexDetection method
*
* @return void
* @access public
*/
function testIndexDetection() {
$this->db->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));');
$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
$result = $this->db->index('simple', false);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
);
$result = $this->db->index('with_a_key', false);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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),
'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
);
$result = $this->db->index('with_multiple_compound_keys', false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
}
/**
* testBuildColumn method
*
* @access public
* @return void
*/
function testBuildColumn() {
$restore = $this->db->columns;
$this->db->columns = array('varchar(255)' => 1);
$data = array(
'name' => 'testName',
'type' => 'varchar(255)',
'default',
'null' => true,
'key',
'comment' => 'test'
);
$result = $this->db->buildColumn($data);
$expected = '`testName` DEFAULT NULL COMMENT \'test\'';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'testName',
'type' => 'varchar(255)',
'default',
'null' => true,
'key',
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci'
);
$result = $this->db->buildColumn($data);
$expected = '`testName` CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL';
$this->assertEqual($result, $expected);
$this->db->columns = $restore;
}
/**
* MySQL 4.x returns index data in a different format,
* Using a mock ensure that MySQL 4.x output is properly parsed.
*
* @return void
*/
function testIndexOnMySQL4Output() {
$name = $this->db->fullTableName('simple');
$mockDbo =& new QueryMockDboMysql($this);
$columnData = array(
array('0' => array(
'Table' => 'with_compound_keys',
'Non_unique' => '0',
'Key_name' => 'PRIMARY',
'Seq_in_index' => '1',
'Column_name' => 'id',
'Collation' => 'A',
'Cardinality' => '0',
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => '',
'Index_type' => 'BTREE',
'Comment' => ''
)),
array('0' => array(
'Table' => 'with_compound_keys',
'Non_unique' => '1',
'Key_name' => 'pointless_bool',
'Seq_in_index' => '1',
'Column_name' => 'bool',
'Collation' => 'A',
'Cardinality' => NULL,
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => 'YES',
'Index_type' => 'BTREE',
'Comment' => ''
)),
array('0' => array(
'Table' => 'with_compound_keys',
'Non_unique' => '1',
'Key_name' => 'pointless_small_int',
'Seq_in_index' => '1',
'Column_name' => 'small_int',
'Collation' => 'A',
'Cardinality' => NULL,
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => 'YES',
'Index_type' => 'BTREE',
'Comment' => ''
)),
array('0' => array(
'Table' => 'with_compound_keys',
'Non_unique' => '1',
'Key_name' => 'one_way',
'Seq_in_index' => '1',
'Column_name' => 'bool',
'Collation' => 'A',
'Cardinality' => NULL,
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => 'YES',
'Index_type' => 'BTREE',
'Comment' => ''
)),
array('0' => array(
'Table' => 'with_compound_keys',
'Non_unique' => '1',
'Key_name' => 'one_way',
'Seq_in_index' => '2',
'Column_name' => 'small_int',
'Collation' => 'A',
'Cardinality' => NULL,
'Sub_part' => NULL,
'Packed' => NULL,
'Null' => 'YES',
'Index_type' => 'BTREE',
'Comment' => ''
))
);
$mockDbo->setReturnValue('query', $columnData, array('SHOW INDEX FROM ' . $name));
$result = $mockDbo->index($name, false);
$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),
);
$this->assertEqual($result, $expected);
}
/**
* testColumn method
*
* @return void
* @access public
*/
function testColumn() {
$result = $this->db->column('varchar(50)');
$expected = 'string';
$this->assertEqual($result, $expected);
$result = $this->db->column('text');
$expected = 'text';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11)');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11) unsigned');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('tinyint(1)');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('boolean');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('float');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('float unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('double unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('decimal(14,7) unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
}
/**
* testAlterSchemaIndexes method
*
* @access public
* @return void
*/
function testAlterSchemaIndexes() {
App::import('Model', 'CakeSchema');
$this->db->cacheSources = $this->db->testing = false;
$schema1 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'group1' => array('type' => 'integer', 'null' => true),
'group2' => array('type' => 'integer', 'null' => true)
)));
$this->db->query($this->db->createSchema($schema1));
$schema2 =& new CakeSchema(array(
'name' => 'AlterTest2',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'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))
)));
$this->db->query($this->db->alterSchema($schema2->compare($schema1)));
$indexes = $this->db->index('altertest');
$this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
// Change three indexes, delete one and add another one
$schema3 =& new CakeSchema(array(
'name' => 'AlterTest3',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'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),
'id_name_idx' => array('column' => array('id', 'name'), 'unique' => 0))
)));
$this->db->query($this->db->alterSchema($schema3->compare($schema2)));
$indexes = $this->db->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)));
$indexes = $this->db->index('altertest');
$this->assertEqual(array(), $indexes);
$this->db->query($this->db->dropSchema($schema1));
}
/**
* test saving and retrieval of blobs
*
* @return void
*/
function testBlobSaving() {
$this->db->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->save(compact('data'));
$result = $model->find('first');
$this->assertEqual($result['BinaryTest']['data'], $data);
}
/**
* test altering the table settings with schema.
*
* @return void
*/
function testAlteringTableParameters() {
App::import('Model', 'CakeSchema');
$this->db->cacheSources = $this->db->testing = false;
$schema1 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'tableParameters' => array(
'charset' => 'latin1',
'collate' => 'latin1_general_ci',
'engine' => 'MyISAM'
)
)
));
$this->db->query($this->db->createSchema($schema1));
$schema2 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'tableParameters' => array(
'charset' => 'utf8',
'collate' => 'utf8_general_ci',
'engine' => 'InnoDB'
)
)
));
$result = $this->db->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->assertEqual($result['Collation'], 'utf8_general_ci');
$this->assertEqual($result['Engine'], 'InnoDB');
$this->assertEqual($result['charset'], 'utf8');
$this->db->query($this->db->dropSchema($schema1));
}
/**
* test alterSchema on two tables.
*
* @return void
*/
function testAlteringTwoTables() {
$schema1 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
),
'other_table' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
)
));
$schema2 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
),
'other_table' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
)
));
$result = $this->db->alterSchema($schema2->compare($schema1));
$this->assertEqual(2, substr_count($result, 'field_two'), 'Too many fields');
}
/**
* testReadTableParameters method
*
* @access public
* @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');
$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');
$expected = array(
'charset' => 'cp1250',
'collate' => 'cp1250_general_ci',
'engine' => 'MyISAM');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
}
/**
* testBuildTableParameters method
*
* @access public
* @return void
*/
function testBuildTableParameters() {
$this->db->cacheSources = $this->db->testing = false;
$data = array(
'charset' => 'utf8',
'collate' => 'utf8_unicode_ci',
'engine' => 'InnoDB');
$result = $this->db->buildTableParameters($data);
$expected = array(
'DEFAULT CHARSET=utf8',
'COLLATE=utf8_unicode_ci',
'ENGINE=InnoDB');
$this->assertEqual($result, $expected);
}
/**
* testBuildTableParameters method
*
* @access public
* @return void
*/
function testGetCharsetName() {
$this->db->cacheSources = $this->db->testing = false;
$result = $this->db->getCharsetName('utf8_unicode_ci');
$this->assertEqual($result, 'utf8');
$result = $this->db->getCharsetName('cp1250_general_ci');
$this->assertEqual($result, 'cp1250');
}
/**
* test that changing the virtualFieldSeparator allows for __ fields.
*
* @return void
*/
function testVirtualFieldSeparators() {
$model =& new CakeTestModel(array('table' => 'binary_tests', 'ds' => 'test_suite', 'name' => 'BinaryTest'));
$model->virtualFields = array(
'other__field' => 'SUM(id)'
);
$this->db->virtualFieldSeparator = '_$_';
$result = $this->db->fields($model, null, array('data', 'other__field'));
$expected = array('`BinaryTest`.`data`', '(SUM(id)) AS `BinaryTest_$_other__field`');
$this->assertEqual($result, $expected);
}
/**
* test that a describe() gets additional fieldParameters
*
* @return void
*/
function testDescribeGettingFieldParameters() {
$schema =& new CakeSchema(array(
'connection' => 'test_suite',
'testdescribes' => array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'stringy' => array(
'type' => 'string',
'null' => true,
'charset' => 'cp1250',
'collate' => 'cp1250_general_ci',
),
'other_col' => array(
'type' => 'string',
'null' => false,
'charset' => 'latin1',
'comment' => 'Test Comment'
)
)
));
$this->db->execute($this->db->createSchema($schema));
$model =& new CakeTestModel(array('table' => 'testdescribes', 'name' => 'Testdescribes'));
$result = $this->db->describe($model);
$this->assertEqual($result['stringy']['collate'], 'cp1250_general_ci');
$this->assertEqual($result['stringy']['charset'], 'cp1250');
$this->assertEqual($result['other_col']['comment'], 'Test Comment');
$this->db->execute($this->db->dropSchema($schema));
}
}

View File

@@ -0,0 +1,339 @@
<?php
/**
* DboMysqliTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Core', array('Model', 'DataSource', 'DboSource', 'DboMysqli'));
/**
* DboMysqliTestDb class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class DboMysqliTestDb extends DboMysqli {
/**
* simulated property
*
* @var array
* @access public
*/
var $simulated = array();
/**
* testing property
*
* @var bool true
* @access public
*/
var $testing = true;
/**
* execute method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _execute($sql) {
if ($this->testing) {
$this->simulated[] = $sql;
return null;
}
return parent::_execute($sql);
}
/**
* getLastQuery method
*
* @access public
* @return void
*/
function getLastQuery() {
return $this->simulated[count($this->simulated) - 1];
}
}
/**
* MysqliTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class MysqliTestModel extends Model {
/**
* name property
*
* @var string 'MysqlTestModel'
* @access public
*/
var $name = 'MysqliTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
return array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
'last_login'=> array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
}
/**
* DboMysqliTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboMysqliTest extends CakeTestCase {
var $fixtures = array('core.datatype');
/**
* The Dbo instance to be tested
*
* @var DboSource
* @access public
*/
var $Db = null;
/**
* Skip if cannot connect to mysqli
*
* @access public
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'mysqli', '%s MySQLi connection not available');
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function setUp() {
$this->model = new MysqliTestModel();
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function tearDown() {
unset($this->model);
ClassRegistry::flush();
}
/**
* testIndexDetection method
*
* @return void
* @access public
*/
function testIndexDetection() {
$this->db->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));');
$expected = array('PRIMARY' => array('column' => 'id', 'unique' => 1));
$result = $this->db->index($name, false);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'pointless_bool' => array('column' => 'bool', 'unique' => 0),
);
$result = $this->db->index($name, false);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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);
$this->assertEqual($expected, $result);
$this->db->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` ));');
$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),
'other_way' => array('column' => array('small_int', 'bool'), 'unique' => 0),
);
$result = $this->db->index($name, false);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
}
/**
* testColumn method
*
* @return void
* @access public
*/
function testColumn() {
$result = $this->db->column('varchar(50)');
$expected = 'string';
$this->assertEqual($result, $expected);
$result = $this->db->column('text');
$expected = 'text';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11)');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('int(11) unsigned');
$expected = 'integer';
$this->assertEqual($result, $expected);
$result = $this->db->column('tinyint(1)');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('boolean');
$expected = 'boolean';
$this->assertEqual($result, $expected);
$result = $this->db->column('float');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('float unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('double unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
$result = $this->db->column('decimal(14,7) unsigned');
$expected = 'float';
$this->assertEqual($result, $expected);
}
/**
* test transaction commands.
*
* @return void
* @access public
*/
function testTransactions() {
$this->db->testing = false;
$result = $this->db->begin($this->model);
$this->assertTrue($result);
$beginSqlCalls = Set::extract('/.[query=START TRANSACTION]', $this->db->_queriesLog);
$this->assertEqual(1, count($beginSqlCalls));
$result = $this->db->commit($this->model);
$this->assertTrue($result);
}
/**
* test that float values are correctly identified
*
* @return void
*/
function testFloatParsing() {
$model =& new Model(array('ds' => 'test_suite', 'table' => 'datatypes', 'name' => 'Datatype'));
$result = $this->db->describe($model);
$this->assertEqual((string)$result['float_field']['length'], '5,2');
}
/**
* test that tableParameters like collation, charset and engine are functioning.
*
* @access public
* @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');
$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');
$expected = array(
'charset' => 'cp1250',
'collate' => 'cp1250_general_ci',
'engine' => 'MyISAM');
$this->assertEqual($result, $expected);
$this->db->query('DROP TABLE ' . $this->db->fullTableName('tinyint'));
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* DboOracleTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
require_once LIBS . 'model' . DS . 'datasources' . DS . 'dbo_source.php';
require_once LIBS . 'model' . DS . 'datasources' . DS . 'dbo' . DS . 'dbo_oracle.php';
/**
* DboOracleTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboOracleTest extends CakeTestCase {
/**
* fixtures property
*/
var $fixtures = array('core.oracle_user');
/**
* setup method
*
* @access public
* @return void
*/
function setUp() {
$this->_initDb();
}
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'oracle', '%s Oracle connection not available');
}
/**
* testLastErrorStatement method
*
* @access public
* @return void
*/
function testLastErrorStatement() {
if ($this->skip('testLastErrorStatement')) {
return;
}
$this->expectError();
$this->db->execute("SELECT ' FROM dual");
$e = $this->db->lastError();
$r = 'ORA-01756: quoted string not properly terminated';
$this->assertEqual($e, $r);
}
/**
* testLastErrorConnect method
*
* @access public
* @return void
*/
function testLastErrorConnect() {
if ($this->skip('testLastErrorConnect')) {
return;
}
$config = $this->db->config;
$old_pw = $this->db->config['password'];
$this->db->config['password'] = 'keepmeout';
$this->db->connect();
$e = $this->db->lastError();
$r = 'ORA-01017: invalid username/password; logon denied';
$this->assertEqual($e, $r);
$this->db->config['password'] = $old_pw;
$this->db->connect();
}
/**
* testName method
*
* @access public
* @return void
*/
function testName() {
$Db = $this->db;
#$Db =& new DboOracle($config = null, $autoConnect = false);
$r = $Db->name($Db->name($Db->name('foo.last_update_date')));
$e = 'foo.last_update_date';
$this->assertEqual($e, $r);
$r = $Db->name($Db->name($Db->name('foo._update')));
$e = 'foo."_update"';
$this->assertEqual($e, $r);
$r = $Db->name($Db->name($Db->name('foo.last_update_date')));
$e = 'foo.last_update_date';
$this->assertEqual($e, $r);
$r = $Db->name($Db->name($Db->name('last_update_date')));
$e = 'last_update_date';
$this->assertEqual($e, $r);
$r = $Db->name($Db->name($Db->name('_update')));
$e = '"_update"';
$this->assertEqual($e, $r);
}
}

View File

@@ -0,0 +1,880 @@
<?php
/**
* DboPostgresTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Model', 'DataSource', 'DboSource', 'DboPostgres'));
App::import('Model', 'App');
require_once dirname(dirname(dirname(__FILE__))) . DS . 'models.php';
/**
* DboPostgresTestDb class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class DboPostgresTestDb extends DboPostgres {
/**
* simulated property
*
* @var array
* @access public
*/
var $simulated = array();
/**
* execute method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _execute($sql) {
$this->simulated[] = $sql;
return null;
}
/**
* getLastQuery method
*
* @access public
* @return void
*/
function getLastQuery() {
return $this->simulated[count($this->simulated) - 1];
}
}
/**
* PostgresTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class PostgresTestModel extends Model {
/**
* name property
*
* @var string 'PostgresTestModel'
* @access public
*/
var $name = 'PostgresTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array(
'PostgresClientTestModel' => array(
'foreignKey' => 'client_id'
)
);
/**
* find method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function find($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* findAll method
*
* @param mixed $conditions
* @param mixed $fields
* @param mixed $order
* @param mixed $recursive
* @access public
* @return void
*/
function findAll($conditions = null, $fields = null, $order = null, $recursive = null) {
return $conditions;
}
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
return array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
'client_id' => array('type' => 'integer', 'null' => '', 'default' => '0', 'length' => '11'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'login' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'passwd' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_1' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'addr_2' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '25'),
'zip_code' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'city' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'country' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'phone' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'fax' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'url' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'comments' => array('type' => 'text', 'null' => '1', 'default' => '', 'length' => ''),
'last_login'=> array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
}
/**
* PostgresClientTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class PostgresClientTestModel extends Model {
/**
* name property
*
* @var string 'PostgresClientTestModel'
* @access public
*/
var $name = 'PostgresClientTestModel';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
return array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8', 'key' => 'primary'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'email' => array('type' => 'string', 'null' => '1', 'default' => '', 'length' => '155'),
'created' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
}
/**
* DboPostgresTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboPostgresTest extends CakeTestCase {
/**
* Do not automatically load fixtures for each test, they will be loaded manually
* using CakeTestCase::loadFixtures
*
* @var boolean
* @access public
*/
var $autoFixtures = false;
/**
* Fixtures
*
* @var object
* @access public
*/
var $fixtures = array('core.user', 'core.binary_test', 'core.comment', 'core.article',
'core.tag', 'core.articles_tag', 'core.attachment', 'core.person', 'core.post', 'core.author',
);
/**
* Actual DB connection used in testing
*
* @var DboSource
* @access public
*/
var $db = null;
/**
* Simulated DB connection used in testing
*
* @var DboSource
* @access public
*/
var $db2 = null;
/**
* Skip if cannot connect to postgres
*
* @access public
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'postgres', '%s PostgreSQL connection not available');
}
/**
* Set up test suite database connection
*
* @access public
*/
function startTest() {
$this->_initDb();
}
/**
* Sets up a Dbo class instance for testing
*
* @access 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->model = new PostgresTestModel();
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function tearDown() {
Configure::write('Cache.disable', false);
unset($this->db2);
}
/**
* Test field quoting method
*
* @access public
*/
function testFieldQuoting() {
$fields = array(
'"PostgresTestModel"."id" AS "PostgresTestModel__id"',
'"PostgresTestModel"."client_id" AS "PostgresTestModel__client_id"',
'"PostgresTestModel"."name" AS "PostgresTestModel__name"',
'"PostgresTestModel"."login" AS "PostgresTestModel__login"',
'"PostgresTestModel"."passwd" AS "PostgresTestModel__passwd"',
'"PostgresTestModel"."addr_1" AS "PostgresTestModel__addr_1"',
'"PostgresTestModel"."addr_2" AS "PostgresTestModel__addr_2"',
'"PostgresTestModel"."zip_code" AS "PostgresTestModel__zip_code"',
'"PostgresTestModel"."city" AS "PostgresTestModel__city"',
'"PostgresTestModel"."country" AS "PostgresTestModel__country"',
'"PostgresTestModel"."phone" AS "PostgresTestModel__phone"',
'"PostgresTestModel"."fax" AS "PostgresTestModel__fax"',
'"PostgresTestModel"."url" AS "PostgresTestModel__url"',
'"PostgresTestModel"."email" AS "PostgresTestModel__email"',
'"PostgresTestModel"."comments" AS "PostgresTestModel__comments"',
'"PostgresTestModel"."last_login" AS "PostgresTestModel__last_login"',
'"PostgresTestModel"."created" AS "PostgresTestModel__created"',
'"PostgresTestModel"."updated" AS "PostgresTestModel__updated"'
);
$result = $this->db->fields($this->model);
$expected = $fields;
$this->assertEqual($result, $expected);
$result = $this->db->fields($this->model, null, 'PostgresTestModel.*');
$expected = $fields;
$this->assertEqual($result, $expected);
$result = $this->db->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.*'));
$expected = array_merge($fields, array(
'"PostgresClientTestModel"."id" AS "PostgresClientTestModel__id"',
'"PostgresClientTestModel"."name" AS "PostgresClientTestModel__name"',
'"PostgresClientTestModel"."email" AS "PostgresClientTestModel__email"',
'"PostgresClientTestModel"."created" AS "PostgresClientTestModel__created"',
'"PostgresClientTestModel"."updated" AS "PostgresClientTestModel__updated"'));
$this->assertEqual($result, $expected);
}
/**
* testColumnParsing method
*
* @access public
* @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');
}
/**
* testValueQuoting method
*
* @access public
* @return void
*/
function testValueQuoting() {
$this->assertIdentical($this->db2->value(1.2, 'float'), "'1.200000'");
$this->assertEqual($this->db2->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->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");
}
/**
* test that localized floats don't cause trouble.
*
* @return void
*/
function testLocalizedFloats() {
$restore = setlocale(LC_ALL, null);
setlocale(LC_ALL, 'de_DE');
$result = $this->db->value(3.141593, 'float');
$this->assertEqual((string)$result, "'3.141593'");
$result = $this->db->value(3.14);
$this->assertEqual((string)$result, "'3.140000'");
setlocale(LC_ALL, $restore);
}
/**
* test that date and time columns do not generate errors with null and nullish values.
*
* @return void
*/
function testDateAndTimeAsNull() {
$this->assertEqual($this->db2->value(null, 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'date'), 'NULL');
$this->assertEqual($this->db2->value('', 'datetime'), 'NULL');
$this->assertEqual($this->db2->value(null, 'datetime'), 'NULL');
$this->assertEqual($this->db2->value('', 'timestamp'), 'NULL');
$this->assertEqual($this->db2->value(null, 'timestamp'), 'NULL');
$this->assertEqual($this->db2->value('', 'time'), 'NULL');
$this->assertEqual($this->db2->value(null, 'time'), 'NULL');
}
/**
* Tests that different Postgres boolean 'flavors' are properly returned as native PHP booleans
*
* @access public
* @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->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(''));
}
/**
* testLastInsertIdMultipleInsert method
*
* @access public
* @return void
*/
function testLastInsertIdMultipleInsert() {
$db1 = ConnectionManager::getDataSource('test_suite');
if (PHP5) {
$db2 = clone $db1;
} else {
$db2 = $db1;
}
$db2->connect();
$this->assertNotEqual($db1->connection, $db2->connection);
$table = $db1->fullTableName('users', false);
$password = '5f4dcc3b5aa765d61d8327deb882cf99';
$db1->execute(
"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);
}
/**
* Tests that table lists and descriptions are scoped to the proper Postgres schema
*
* @access public
* @return void
*/
function testSchemaScoping() {
$db1 =& ConnectionManager::getDataSource('test_suite');
$db1->cacheSources = false;
$db1->reconnect(array('persistent' => false));
$db1->query('CREATE SCHEMA _scope_test');
$db2 =& ConnectionManager::create(
'test_suite_2',
array_merge($db1->config, array('driver' => 'postgres', 'schema' => '_scope_test'))
);
$db2->cacheSources = false;
$db2->query('DROP SCHEMA _scope_test');
}
/**
* Tests that column types without default lengths in $columns do not have length values
* applied when generating schemas.
*
* @access public
* @return void
*/
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);
$result = array('name' => 'foo', 'type' => 'text', 'length' => 100, 'default' => 'FOO');
$expected = '"foo" text DEFAULT \'FOO\'';
$this->assertEqual($this->db->buildColumn($result), $expected);
}
/**
* Tests that binary data is escaped/unescaped properly on reads and writes
*
* @access public
* @return void
*/
function testBinaryDataIntegrity() {
$data = '%PDF-1.3
%ƒÂÚÂÎßÛ†–ƒ∆
4 0 obj
<< /Length 5 0 R /Filter /FlateDecode >>
stream
xµYMì€∆Ω„WÃ%)nï0¯îâ-«é]Q"πXµáÿ•Ip - P V,]Ú#c˚ˇ‰ut¥†∏Ti9 Ü=”Ø_˜4>à∑Épcé¢Pxæ®2q\'
1UªbU ᡒ+ö«√[ıµão"R∑"HiGæä€(å≠≈^Ãøsm?YlƒÃõªfiâEÚB&Î◊7bÒ^¸m°÷˛?2±Øs“fiu#®U√ˇú÷g¥C;ä")n})JºIÔ3ËSnÑÎ¥≤ıD∆¢∂Msx1üèG˚±Œ™>¶ySïufØ ˝¸?UπÃã√6flÌÚC=øK?˝…s
˛§¯ˇ:-˜ò7€ÓFæ∂∑Õ˛∆“V>ılflëÅd«ÜQdI ÎB%W¿ΩıÉn~h vêCS>«é˛(ØôK!€¡zB!√
[œÜ"ûß ·iH¸€ºæ∑¯¡L,ÀÚAlS∫ˆ=∫Œ≤cÄr&ˆÈ:√ÿ£˚È«4fl•À]vcbÅôÿî=siXe4/¡p]ã]ôÆIœ™ Ωflà_ƒG7 ùÿ ı¯K4ïIpV◊÷·\'éµóªÚæ>î
;!2fl¬F•/f∑j£
dw"IÊÜπ<ôÿˆ%IG1ytÛDflXg|Éòa§˜}C˛¿ÿe°G´Ú±jÍm~¿/∂hã<#-¥•ıùe87€t˜õ6w}´
mê ∆¡ 6\
rAÀBùZ3aËr$G·$ó0Ñ üâUY4È™¡%C∑Ÿ2rc<Iõ-cï.
[ŒöâFA†É‡+QglMÉîÉÄúÌ|¸»#x7¥«MgVÎ-GGÚ• I?Á”Lzw∞pHů◊nefqCî.nÕeè∆ÿÛy¡˙fb≤üŒHÜAëÕNq=´@ cQdÖúAÉIqñŸ˘+2&∏ Àù.gŃœ3EPƒOi—‰:>ÍCäı
=Õec=ëR˝”eñ=<V$ì˙+x+¢ïÒÕ<àeWå»–˚∫Õ d§&£àf ]fPA´âtënöå∏◊ó Ë@∆≠K´÷˘}a_CI˚©yòHg,ôSSVìBƒl4 L.ÈY…á,2∂íäÙ.$ó¸CäŸ*€óy
π?G,_√·ÆÎç=^Vkvo±ó{§ƒ2»±¨Ïüo»ëD-ãé fió¥cVÙ\'™G~\'p¢%* ã˚÷
ªºnh˚ºO^∏…®[Ó“ÅfıÌ≥∫F!Eœ(π∑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ëµ±ÿGû1coÔuñæz®. õ∑7ÉÏÜÆ,°H†ÍÉÌ∂7e º® íˆ◊øNWK”ÂYµñé;µ¶gV-fl>µ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->save(compact('data'));
$result = $model->find('first');
$this->assertEqual($result['BinaryTest']['data'], $data);
}
/**
* Tests the syntax of generated schema indexes
*
* @access public
* @return void
*/
function testSchemaIndexSyntax() {
$schema = new CakeSchema();
$schema->tables = array('i18n' => array(
'id' => array(
'type' => 'integer', 'null' => false, 'default' => null,
'length' => 10, 'key' => 'primary'
),
'locale' => array('type'=>'string', 'null' => false, 'length' => 6, 'key' => 'index'),
'model' => array('type'=>'string', 'null' => false, 'key' => 'index'),
'foreign_key' => array(
'type'=>'integer', 'null' => false, 'length' => 10, 'key' => 'index'
),
'field' => array('type'=>'string', 'null' => false, 'key' => 'index'),
'content' => array('type'=>'text', 'null' => true, 'default' => null),
'indexes' => array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'locale' => array('column' => 'locale', 'unique' => 0),
'model' => array('column' => 'model', 'unique' => 0),
'row_id' => array('column' => 'foreign_key', 'unique' => 0),
'field' => array('column' => 'field', 'unique' => 0)
)
));
$result = $this->db->createSchema($schema);
$this->assertNoPattern('/^CREATE INDEX(.+);,$/', $result);
}
/**
* testCakeSchema method
*
* Test that schema generated postgresql queries are valid. ref #5696
* Check that the create statement for a schema generated table is the same as the original sql
*
* @return void
* @access public
*/
function testCakeSchema() {
$db1 =& ConnectionManager::getDataSource('test_suite');
$db1->cacheSources = false;
$db1->reconnect(array('persistent' => false));
$db1->query('CREATE TABLE ' . $db1->fullTableName('datatypes') . ' (
id serial NOT NULL,
"varchar" character varying(40) NOT NULL,
"full_length" character varying NOT NULL,
"timestamp" timestamp without time zone,
date date,
CONSTRAINT test_suite_data_types_pkey PRIMARY KEY (id)
)');
$model = new Model(array('name' => 'Datatype', 'ds' => 'test_suite'));
$schema = new CakeSchema(array('connection' => 'test_suite'));
$result = $schema->read(array(
'connection' => 'test_suite',
'models' => array('Datatype')
));
$schema->tables = array('datatypes' => $result['tables']['datatypes']);
$result = $db1->createSchema($schema, 'datatypes');
$this->assertNoPattern('/timestamp DEFAULT/', $result);
$this->assertPattern('/\"full_length\"\s*text\s.*,/', $result);
$this->assertPattern('/timestamp\s*,/', $result);
$db1->query('DROP TABLE ' . $db1->fullTableName('datatypes'));
$db1->query($result);
$result2 = $schema->read(array(
'connection' => 'test_suite',
'models' => array('Datatype')
));
$schema->tables = array('datatypes' => $result2['tables']['datatypes']);
$result2 = $db1->createSchema($schema, 'datatypes');
$this->assertEqual($result, $result2);
$db1->query('DROP TABLE ' . $db1->fullTableName('datatypes'));
}
/**
* Test index generation from table info.
*
* @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")');
$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);
$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")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => 1),
);
$result = $this->db->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
}
/**
* Test the alterSchema capabilities of postgres
*
* @access public
* @return void
*/
function testAlterSchema() {
$Old =& new CakeSchema(array(
'connection' => 'test_suite',
'name' => 'AlterPosts',
'alter_posts' => array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => false),
'title' => array('type' => 'string', 'null' => true),
'body' => array('type' => 'text'),
'published' => array('type' => 'string', 'length' => 1, 'default' => 'N'),
'created' => array('type' => 'datetime'),
'updated' => array('type' => 'datetime'),
)
));
$this->db->query($this->db->createSchema($Old));
$New =& new CakeSchema(array(
'connection' => 'test_suite',
'name' => 'AlterPosts',
'alter_posts' => array(
'id' => array('type' => 'integer', 'key' => 'primary'),
'author_id' => array('type' => 'integer', 'null' => true),
'title' => array('type' => 'string', 'null' => false, 'default' => 'my title'),
'body' => array('type' => 'string', 'length' => 500),
'status' => array('type' => 'integer', 'length' => 3, 'default' => 1),
'created' => array('type' => 'datetime'),
'updated' => array('type' => 'datetime'),
)
));
$this->db->query($this->db->alterSchema($New->compare($Old), 'alter_posts'));
$model = new CakeTestModel(array('table' => 'alter_posts', 'ds' => 'test_suite'));
$result = $model->schema();
$this->assertTrue(isset($result['status']));
$this->assertFalse(isset($result['published']));
$this->assertEqual($result['body']['type'], 'string');
$this->assertEqual($result['status']['default'], 1);
$this->assertEqual($result['author_id']['null'], true);
$this->assertEqual($result['title']['null'], false);
$this->db->query($this->db->dropSchema($New));
}
/**
* Test the alter index capabilities of postgres
*
* @access public
* @return void
*/
function testAlterIndexes() {
$this->db->cacheSources = false;
$schema1 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'group1' => array('type' => 'integer', 'null' => true),
'group2' => array('type' => 'integer', 'null' => true)
)
));
$this->db->query($this->db->createSchema($schema1));
$schema2 =& new CakeSchema(array(
'name' => 'AlterTest2',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'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)
)
)
));
$this->db->query($this->db->alterSchema($schema2->compare($schema1)));
$indexes = $this->db->index('altertest');
$this->assertEqual($schema2->tables['altertest']['indexes'], $indexes);
// Change three indexes, delete one and add another one
$schema3 =& new CakeSchema(array(
'name' => 'AlterTest3',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
'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))
)));
$this->db->query($this->db->alterSchema($schema3->compare($schema2)));
$indexes = $this->db->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)));
$indexes = $this->db->index('altertest');
$this->assertEqual(array(), $indexes);
$this->db->query($this->db->dropSchema($schema1));
}
/*
* Test it is possible to use virtual field with postgresql
*
* @access public
* @return void
*/
function testVirtualFields() {
$this->loadFixtures('Article', 'Comment');
$Article = new Article;
$Article->virtualFields = array(
'next_id' => 'Article.id + 1',
'complex' => 'Article.title || Article.body',
'functional' => 'COALESCE(User.user, Article.title)',
'subquery' => 'SELECT count(*) FROM ' . $Article->Comment->table
);
$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']['subquery'], 6);
}
/**
* Tests additional order options for postgres
*
* @access public
* @return void
*/
function testOrderAdditionalParams() {
$result = $this->db->order(array('title' => 'DESC NULLS FIRST', 'body' => 'DESC'));
$expected = ' ORDER BY "title" DESC NULLS FIRST, "body" DESC';
$this->assertEqual($result, $expected);
}
/**
* Test it is possible to do a SELECT COUNT(DISTINCT Model.field) query in postgres and it gets correctly quoted
*/
function testQuoteDistinctInFunction() {
$this->loadFixtures('Article');
$Article = new Article;
$result = $this->db->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)'));
$expected = array('COUNT(DISTINCT "id")');
$this->assertEqual($result, $expected);
$result = $this->db->fields($Article, null, array('COUNT(DISTINCT FUNC(id))'));
$expected = array('COUNT(DISTINCT FUNC("id"))');
$this->assertEqual($result, $expected);
}
/**
* test that saveAll works even with conditions that lack a model name.
*
* @return void
*/
function testUpdateAllWithNonQualifiedConditions() {
$this->loadFixtures('Article');
$Article =& new Article();
$result = $Article->updateAll(array('title' => "'Awesome'"), array('title' => 'Third Article'));
$this->assertTrue($result);
$result = $Article->find('count', array(
'conditions' => array('Article.title' => 'Awesome')
));
$this->assertEqual($result, 1, 'Article count is wrong or fixture has changed.');
}
/**
* test alterSchema on two tables.
*
* @return void
*/
function testAlteringTwoTables() {
$schema1 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
),
'other_table' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'name' => array('type' => 'string', 'null' => false, 'length' => 50),
)
));
$schema2 =& new CakeSchema(array(
'name' => 'AlterTest1',
'connection' => 'test_suite',
'altertest' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
),
'other_table' => array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0),
'field_two' => array('type' => 'string', 'null' => false, 'length' => 50),
)
));
$result = $this->db->alterSchema($schema2->compare($schema1));
$this->assertEqual(2, substr_count($result, 'field_two'), 'Too many fields');
$this->assertFalse(strpos(';ALTER', $result), 'Too many semi colons');
}
}

View File

@@ -0,0 +1,355 @@
<?php
/**
* DboSqliteTest file
*
* PHP versions 4 and 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.cake.libs
* @since CakePHP(tm) v 1.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', array('Model', 'DataSource', 'DboSource', 'DboSqlite'));
/**
* DboSqliteTestDb class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources
*/
class DboSqliteTestDb extends DboSqlite {
/**
* simulated property
*
* @var array
* @access public
*/
var $simulated = array();
/**
* execute method
*
* @param mixed $sql
* @access protected
* @return void
*/
function _execute($sql) {
$this->simulated[] = $sql;
return null;
}
/**
* getLastQuery method
*
* @access public
* @return void
*/
function getLastQuery() {
return $this->simulated[count($this->simulated) - 1];
}
}
/**
* DboSqliteTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.model.datasources.dbo
*/
class DboSqliteTest extends CakeTestCase {
/**
* Do not automatically load fixtures for each test, they will be loaded manually using CakeTestCase::loadFixtures
*
* @var boolean
* @access public
*/
var $autoFixtures = false;
/**
* Fixtures
*
* @var object
* @access public
*/
var $fixtures = array('core.user');
/**
* Actual DB connection used in testing
*
* @var DboSource
* @access public
*/
var $db = null;
/**
* Simulated DB connection used in testing
*
* @var DboSource
* @access public
*/
var $db2 = null;
/**
* Skip if cannot connect to SQLite
*
* @access public
*/
function skip() {
$this->_initDb();
$this->skipUnless($this->db->config['driver'] == 'sqlite', '%s SQLite connection not available');
}
/**
* Set up test suite database connection
*
* @access public
*/
function startTest() {
$this->_initDb();
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function setUp() {
Configure::write('Cache.disable', true);
$this->startTest();
$this->db =& ConnectionManager::getDataSource('test_suite');
$this->db2 = new DboSqliteTestDb($this->db->config, false);
}
/**
* Sets up a Dbo class instance for testing
*
* @access public
*/
function tearDown() {
Configure::write('Cache.disable', false);
unset($this->db2);
}
/**
* Tests that SELECT queries from DboSqlite::listSources() are not cached
*
* @access public
*/
function testTableListCacheDisabling() {
$this->assertFalse(in_array('foo_test', $this->db->listSources()));
$this->db->query('CREATE TABLE foo_test (test VARCHAR(255));');
$this->assertTrue(in_array('foo_test', $this->db->listSources()));
$this->db->query('DROP TABLE foo_test;');
$this->assertFalse(in_array('foo_test', $this->db->listSources()));
}
/**
* test Index introspection.
*
* @access public
* @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")');
$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);
$this->assertEqual($expected, $result);
$this->db->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")');
$expected = array(
'PRIMARY' => array('column' => 'id', 'unique' => 1),
'multi_col' => array('column' => array('small_char', 'bool'), 'unique' => 1),
);
$result = $this->db->index($name);
$this->assertEqual($expected, $result);
$this->db->query('DROP TABLE ' . $name);
}
/**
* Tests that cached table descriptions are saved under the sanitized key name
*
* @access public
*/
function testCacheKeyName() {
Configure::write('Cache.disable', false);
$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)));
$this->assertTrue(file_exists(TMP . $dbName));
$db->execute("CREATE TABLE test_list (id VARCHAR(255));");
$db->cacheSources = true;
$this->assertEqual($db->listSources(), array('test_list'));
$db->cacheSources = false;
$fileName = '_' . preg_replace('/[^A-Za-z0-9_\-+]/', '_', TMP . $dbName) . '_list';
$result = Cache::read($fileName, '_cake_model_');
$this->assertEqual($result, array('test_list'));
Cache::delete($fileName, '_cake_model_');
Configure::write('Cache.disable', true);
}
/**
* test building columns with SQLite
*
* @return void
*/
function testBuildColumn() {
$data = array(
'name' => 'int_field',
'type' => 'integer',
'null' => false,
);
$result = $this->db->buildColumn($data);
$expected = '"int_field" integer(11) NOT NULL';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'name',
'type' => 'string',
'length' => 20,
'null' => false,
);
$result = $this->db->buildColumn($data);
$expected = '"name" varchar(20) NOT NULL';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'testName',
'type' => 'string',
'length' => 20,
'default' => null,
'null' => true,
'collate' => 'NOCASE'
);
$result = $this->db->buildColumn($data);
$expected = '"testName" varchar(20) DEFAULT NULL COLLATE NOCASE';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'testName',
'type' => 'string',
'length' => 20,
'default' => 'test-value',
'null' => false,
);
$result = $this->db->buildColumn($data);
$expected = '"testName" varchar(20) DEFAULT \'test-value\' NOT NULL';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'testName',
'type' => 'integer',
'length' => 10,
'default' => 10,
'null' => false,
);
$result = $this->db->buildColumn($data);
$expected = '"testName" integer(10) DEFAULT \'10\' NOT NULL';
$this->assertEqual($result, $expected);
$data = array(
'name' => 'testName',
'type' => 'integer',
'length' => 10,
'default' => 10,
'null' => false,
'collate' => 'BADVALUE'
);
$result = $this->db->buildColumn($data);
$expected = '"testName" integer(10) DEFAULT \'10\' NOT NULL';
$this->assertEqual($result, $expected);
}
/**
* test describe() and normal results.
*
* @return void
*/
function testDescribe() {
$Model =& new Model(array('name' => 'User', 'ds' => 'test_suite', 'table' => 'users'));
$result = $this->db->describe($Model);
$expected = array(
'id' => array(
'type' => 'integer',
'key' => 'primary',
'null' => false,
'default' => null,
'length' => 11
),
'user' => array(
'type' => 'string',
'length' => 255,
'null' => false,
'default' => null
),
'password' => array(
'type' => 'string',
'length' => 255,
'null' => false,
'default' => null
),
'created' => array(
'type' => 'datetime',
'null' => true,
'default' => null,
'length' => null,
),
'updated' => array(
'type' => 'datetime',
'null' => true,
'default' => null,
'length' => null,
)
);
$this->assertEqual($result, $expected);
}
/**
* test that describe does not corrupt UUID primary keys
*
* @return void
*/
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);
$expected = array(
'type' => 'string',
'length' => 36,
'null' => false,
'default' => null,
'key' => 'primary',
);
$this->assertEqual($result['id'], $expected);
$this->db->query('DROP TABLE ' . $tableName);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,396 @@
<?php
/**
* DbAclTest 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.controller.components.dbacl.models
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Component', 'Acl');
App::import('Core', 'db_acl');
/**
* DB ACL wrapper test class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAclNodeTestBase extends AclNode {
/**
* useDbConfig property
*
* @var string 'test_suite'
* @access public
*/
var $useDbConfig = 'test_suite';
/**
* cacheSources property
*
* @var bool false
* @access public
*/
var $cacheSources = false;
}
/**
* Aro Test Wrapper
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAroTest extends DbAclNodeTestBase {
/**
* name property
*
* @var string 'DbAroTest'
* @access public
*/
var $name = 'DbAroTest';
/**
* useTable property
*
* @var string 'aros'
* @access public
*/
var $useTable = 'aros';
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('DbAcoTest' => array('with' => 'DbPermissionTest'));
}
/**
* Aco Test Wrapper
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAcoTest extends DbAclNodeTestBase {
/**
* name property
*
* @var string 'DbAcoTest'
* @access public
*/
var $name = 'DbAcoTest';
/**
* useTable property
*
* @var string 'acos'
* @access public
*/
var $useTable = 'acos';
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('DbAroTest' => array('with' => 'DbPermissionTest'));
}
/**
* Permission Test Wrapper
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbPermissionTest extends CakeTestModel {
/**
* name property
*
* @var string 'DbPermissionTest'
* @access public
*/
var $name = 'DbPermissionTest';
/**
* useTable property
*
* @var string 'aros_acos'
* @access public
*/
var $useTable = 'aros_acos';
/**
* cacheQueries property
*
* @var bool false
* @access public
*/
var $cacheQueries = false;
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array('DbAroTest' => array('foreignKey' => 'aro_id'), 'DbAcoTest' => array('foreignKey' => 'aco_id'));
}
/**
* DboActionTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAcoActionTest extends CakeTestModel {
/**
* name property
*
* @var string 'DbAcoActionTest'
* @access public
*/
var $name = 'DbAcoActionTest';
/**
* useTable property
*
* @var string 'aco_actions'
* @access public
*/
var $useTable = 'aco_actions';
/**
* belongsTo property
*
* @var array
* @access public
*/
var $belongsTo = array('DbAcoTest' => array('foreignKey' => 'aco_id'));
}
/**
* DbAroUserTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAroUserTest extends CakeTestModel {
/**
* name property
*
* @var string 'AuthUser'
* @access public
*/
var $name = 'AuthUser';
/**
* useTable property
*
* @var string 'auth_users'
* @access public
*/
var $useTable = 'auth_users';
/**
* bindNode method
*
* @param mixed $ref
* @access public
* @return void
*/
function bindNode($ref = null) {
if (Configure::read('DbAclbindMode') == 'string') {
return 'ROOT/admins/Gandalf';
} elseif (Configure::read('DbAclbindMode') == 'array') {
return array('DbAroTest' => array('DbAroTest.model' => 'AuthUser', 'DbAroTest.foreign_key' => 2));
}
}
}
/**
* DbAclTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components
*/
class DbAclTest extends DbAcl {
/**
* construct method
*
* @access private
* @return void
*/
function __construct() {
$this->Aro =& new DbAroTest();
$this->Aro->Permission =& new DbPermissionTest();
$this->Aco =& new DbAcoTest();
$this->Aro->Permission =& new DbPermissionTest();
}
}
/**
* AclNodeTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.controller.components.dbacl.models
*/
class AclNodeTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.aro', 'core.aco', 'core.aros_aco', 'core.aco_action', 'core.auth_user');
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
Configure::write('Acl.classname', 'DbAclTest');
Configure::write('Acl.database', 'test_suite');
}
/**
* testNode method
*
* @access public
* @return void
*/
function testNode() {
$Aco =& new DbAcoTest();
$result = Set::extract($Aco->node('Controller1'), '{n}.DbAcoTest.id');
$expected = array(2, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller1/action1'), '{n}.DbAcoTest.id');
$expected = array(3, 2, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller2/action1'), '{n}.DbAcoTest.id');
$expected = array(7, 6, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller1/action2'), '{n}.DbAcoTest.id');
$expected = array(5, 2, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller1/action1/record1'), '{n}.DbAcoTest.id');
$expected = array(4, 3, 2, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller2/action1/record1'), '{n}.DbAcoTest.id');
$expected = array(8, 7, 6, 1);
$this->assertEqual($result, $expected);
$result = Set::extract($Aco->node('Controller2/action3'), '{n}.DbAcoTest.id');
$this->assertFalse($result);
$result = Set::extract($Aco->node('Controller2/action3/record5'), '{n}.DbAcoTest.id');
$this->assertFalse($result);
$result = $Aco->node('');
$this->assertEqual($result, null);
}
/**
* test that node() doesn't dig deeper than it should.
*
* @return void
*/
function testNodeWithDuplicatePathSegments() {
$Aco =& new DbAcoTest();
$nodes = $Aco->node('ROOT/Users');
$this->assertEqual($nodes[0]['DbAcoTest']['parent_id'], 1, 'Parent id does not point at ROOT. %s');
}
/**
* testNodeArrayFind method
*
* @access public
* @return void
*/
function testNodeArrayFind() {
$Aro = new DbAroTest();
Configure::write('DbAclbindMode', 'string');
$result = Set::extract($Aro->node(array('DbAroUserTest' => array('id' => '1', 'foreign_key' => '1'))), '{n}.DbAroTest.id');
$expected = array(3, 2, 1);
$this->assertEqual($result, $expected);
Configure::write('DbAclbindMode', 'array');
$result = Set::extract($Aro->node(array('DbAroUserTest' => array('id' => 4, 'foreign_key' => 2))), '{n}.DbAroTest.id');
$expected = array(4);
$this->assertEqual($result, $expected);
}
/**
* testNodeObjectFind method
*
* @access public
* @return void
*/
function testNodeObjectFind() {
$Aro = new DbAroTest();
$Model = new DbAroUserTest();
$Model->id = 1;
$result = Set::extract($Aro->node($Model), '{n}.DbAroTest.id');
$expected = array(3, 2, 1);
$this->assertEqual($result, $expected);
$Model->id = 2;
$result = Set::extract($Aro->node($Model), '{n}.DbAroTest.id');
$expected = array(4, 2, 1);
$this->assertEqual($result, $expected);
}
/**
* testNodeAliasParenting method
*
* @access public
* @return void
*/
function testNodeAliasParenting() {
$Aco = new DbAcoTest();
$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();
$Aco->create(array('model' => null, 'foreign_key' => null, 'parent_id' => $Aco->id, 'alias' => 'Pages'));
$Aco->save();
$result = $Aco->find('all');
$expected = array(
array('DbAcoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'Application', 'lft' => '1', 'rght' => '4'), 'DbAroTest' => array()),
array('DbAcoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'Pages', 'lft' => '2', 'rght' => '3', ), 'DbAroTest' => array())
);
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,103 @@
<?php
/**
* ModelTest 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.model
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('AppModel', 'Model'));
require_once dirname(__FILE__) . DS . 'models.php';
SimpleTest::ignore('BaseModelTest');
/**
* ModelBaseTest
*
* @package cake
* @subpackage cake.tests.cases.libs.model
*/
class BaseModelTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
* @access public
*/
var $autoFixtures = false;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array(
'core.category', 'core.category_thread', 'core.user', 'core.my_category', 'core.my_product',
'core.my_user', 'core.my_categories_my_users', 'core.my_categories_my_products',
'core.article', 'core.featured', 'core.article_featureds_tags', 'core.article_featured',
'core.articles', 'core.numeric_article', 'core.tag', 'core.articles_tag', 'core.comment',
'core.attachment', 'core.apple', 'core.sample', 'core.another_article', 'core.item',
'core.advertisement', 'core.home', 'core.post', 'core.author', 'core.bid', 'core.portfolio',
'core.product', 'core.project', 'core.thread', 'core.message', 'core.items_portfolio',
'core.syfile', 'core.image', 'core.device_type', 'core.device_type_category',
'core.feature_set', 'core.exterior_type_category', 'core.document', 'core.device',
'core.document_directory', 'core.primary_model', 'core.secondary_model', 'core.something',
'core.something_else', 'core.join_thing', 'core.join_a', 'core.join_b', 'core.join_c',
'core.join_a_b', 'core.join_a_c', 'core.uuid', 'core.data_test', 'core.posts_tag',
'core.the_paper_monkies', 'core.person', 'core.underscore_field', 'core.node',
'core.dependency', 'core.story', 'core.stories_tag', 'core.cd', 'core.book', 'core.basket',
'core.overall_favorite', 'core.account', 'core.content', 'core.content_account',
'core.film_file', 'core.test_plugin_article', 'core.test_plugin_comment', 'core.uuiditem',
'core.counter_cache_user', 'core.counter_cache_post',
'core.counter_cache_user_nonstandard_primary_key',
'core.counter_cache_post_nonstandard_primary_key', 'core.uuidportfolio',
'core.uuiditems_uuidportfolio', 'core.uuiditems_uuidportfolio_numericid', 'core.fruit',
'core.fruits_uuid_tag', 'core.uuid_tag', 'core.product_update_all', 'core.group_update_all'
);
/**
* start method
*
* @access public
* @return void
*/
function start() {
parent::start();
$this->debug = Configure::read('debug');
Configure::write('debug', 2);
}
/**
* end method
*
* @access public
* @return void
*/
function end() {
parent::end();
Configure::write('debug', $this->debug);
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
ClassRegistry::flush();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,754 @@
<?php
/**
* ModelDeleteTest 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.model
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once dirname(__FILE__) . DS . 'model.test.php';
/**
* ModelDeleteTest
*
* @package cake
* @subpackage cake.tests.cases.libs.model.operations
*/
class ModelDeleteTest extends BaseModelTest {
/**
* testDeleteHabtmReferenceWithConditions method
*
* @access public
* @return void
*/
function testDeleteHabtmReferenceWithConditions() {
$this->loadFixtures('Portfolio', 'Item', 'ItemsPortfolio');
$Portfolio =& new Portfolio();
$Portfolio->hasAndBelongsToMany['Item']['conditions'] = array('ItemsPortfolio.item_id >' => 1);
$result = $Portfolio->find('first', array(
'conditions' => array('Portfolio.id' => 1)
));
$expected = array(
array(
'id' => 3,
'syfile_id' => 3,
'published' => 0,
'name' => 'Item 3',
'ItemsPortfolio' => array(
'id' => 3,
'item_id' => 3,
'portfolio_id' => 1
)),
array(
'id' => 4,
'syfile_id' => 4,
'published' => 0,
'name' => 'Item 4',
'ItemsPortfolio' => array(
'id' => 4,
'item_id' => 4,
'portfolio_id' => 1
)),
array(
'id' => 5,
'syfile_id' => 5,
'published' => 0,
'name' => 'Item 5',
'ItemsPortfolio' => array(
'id' => 5,
'item_id' => 5,
'portfolio_id' => 1
)));
$this->assertEqual($result['Item'], $expected);
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$expected = array(
array(
'ItemsPortfolio' => array(
'id' => 1,
'item_id' => 1,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 3,
'item_id' => 3,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 4,
'item_id' => 4,
'portfolio_id' => 1
)),
array(
'ItemsPortfolio' => array(
'id' => 5,
'item_id' => 5,
'portfolio_id' => 1
)));
$this->assertEqual($result, $expected);
$Portfolio->delete(1);
$result = $Portfolio->find('first', array(
'conditions' => array('Portfolio.id' => 1)
));
$this->assertFalse($result);
$result = $Portfolio->ItemsPortfolio->find('all', array(
'conditions' => array('ItemsPortfolio.portfolio_id' => 1)
));
$this->assertFalse($result);
}
/**
* testDeleteArticleBLinks method
*
* @access public
* @return void
*/
function testDeleteArticleBLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new ArticleB();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '1', 'tag_id' => '2')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3'))
);
$this->assertEqual($result, $expected);
$TestModel->delete(1);
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '1')),
array('ArticlesTag' => array('article_id' => '2', 'tag_id' => '3'))
);
$this->assertEqual($result, $expected);
}
/**
* testDeleteDependentWithConditions method
*
* @access public
* @return void
*/
function testDeleteDependentWithConditions() {
$this->loadFixtures('Cd','Book','OverallFavorite');
$Cd =& new Cd();
$Book =& new Book();
$OverallFavorite =& new OverallFavorite();
$Cd->delete(1);
$result = $OverallFavorite->find('all', array(
'fields' => array('model_type', 'model_id', 'priority')
));
$expected = array(
array(
'OverallFavorite' => array(
'model_type' => 'Book',
'model_id' => 1,
'priority' => 2
)));
$this->assertTrue(is_array($result));
$this->assertEqual($result, $expected);
$Book->delete(1);
$result = $OverallFavorite->find('all', array(
'fields' => array('model_type', 'model_id', 'priority')
));
$expected = array();
$this->assertTrue(is_array($result));
$this->assertEqual($result, $expected);
}
/**
* testDel method
*
* @access public
* @return void
*/
function testDelete() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$result = $TestModel->delete(2);
$this->assertTrue($result);
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'title')
));
$expected = array(
array('Article' => array(
'id' => 1,
'title' => 'First Article'
)),
array('Article' => array(
'id' => 3,
'title' => 'Third Article'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->delete(3);
$this->assertTrue($result);
$result = $TestModel->read(null, 3);
$this->assertFalse($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'title')
));
$expected = array(
array('Article' => array(
'id' => 1,
'title' => 'First Article'
)));
$this->assertEqual($result, $expected);
// make sure deleting a non-existent record doesn't break save()
// ticket #6293
$this->loadFixtures('Uuid');
$Uuid =& new Uuid();
$data = array(
'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3',
'52C8865C-10EE-4302-AE6C-6E7D8E12E2C8',
'8208C7FE-E89C-47C5-B378-DED6C271F9B8');
foreach ($data as $id) {
$Uuid->save(array('id' => $id));
}
$Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8');
$Uuid->delete('52C8865C-10EE-4302-AE6C-6E7D8E12E2C8');
foreach ($data as $id) {
$Uuid->save(array('id' => $id));
}
$result = $Uuid->find('all', array(
'conditions' => array('id' => $data),
'fields' => array('id'),
'order' => 'id'));
$expected = array(
array('Uuid' => array(
'id' => '52C8865C-10EE-4302-AE6C-6E7D8E12E2C8')),
array('Uuid' => array(
'id' => '8208C7FE-E89C-47C5-B378-DED6C271F9B8')),
array('Uuid' => array(
'id' => 'B607DAB9-88A2-46CF-B57C-842CA9E3B3B3')));
$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->Post->delete(3);
$result = $User->read(null, 301);
$this->assertEqual($result['User']['post_count'], 0);
$result = $User->read(null, 66);
$this->assertEqual($result['User']['post_count'], 2);
}
/**
* testDeleteAll method
*
* @access public
* @return void
*/
function testDeleteAll() {
$this->loadFixtures('Article');
$TestModel =& new Article();
$data = array('Article' => array(
'user_id' => 2,
'id' => 4,
'title' => 'Fourth Article',
'published' => 'N'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$data = array('Article' => array(
'user_id' => 2,
'id' => 5,
'title' => 'Fifth Article',
'published' => 'Y'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$data = array('Article' => array(
'user_id' => 1,
'id' => 6,
'title' => 'Sixth Article',
'published' => 'N'
));
$result = $TestModel->set($data) && $TestModel->save();
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 2,
'user_id' => 3,
'title' => 'Second Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y')),
array('Article' => array(
'id' => 4,
'user_id' => 2,
'title' => 'Fourth Article',
'published' => 'N'
)),
array('Article' => array(
'id' => 5,
'user_id' => 2,
'title' => 'Fifth Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 6,
'user_id' => 1,
'title' => 'Sixth Article',
'published' => 'N'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.published' => 'N'));
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 2,
'user_id' => 3,
'title' => 'Second Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 5,
'user_id' => 2,
'title' => 'Fifth Article',
'published' => 'Y'
)));
$this->assertEqual($result, $expected);
$data = array('Article.user_id' => array(2, 3));
$result = $TestModel->deleteAll($data, true, true);
$this->assertTrue($result);
$TestModel->recursive = -1;
$result = $TestModel->find('all', array(
'fields' => array('id', 'user_id', 'title', 'published')
));
$expected = array(
array('Article' => array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'published' => 'Y'
)),
array('Article' => array(
'id' => 3,
'user_id' => 1,
'title' => 'Third Article',
'published' => 'Y'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.user_id' => 999));
$this->assertTrue($result, 'deleteAll returned false when all no records matched conditions. %s');
$this->expectError();
ob_start();
$result = $TestModel->deleteAll(array('Article.non_existent_field' => 999));
ob_get_clean();
$this->assertFalse($result, 'deleteAll returned true when find query generated sql error. %s');
}
/**
* testRecursiveDel method
*
* @access public
* @return void
*/
function testRecursiveDel() {
$this->loadFixtures('Article', 'Comment', 'Attachment');
$TestModel =& new Article();
$result = $TestModel->delete(2);
$this->assertTrue($result);
$TestModel->recursive = 2;
$result = $TestModel->read(null, 2);
$this->assertFalse($result);
$result = $TestModel->Comment->read(null, 5);
$this->assertFalse($result);
$result = $TestModel->Comment->read(null, 6);
$this->assertFalse($result);
$result = $TestModel->Comment->Attachment->read(null, 1);
$this->assertFalse($result);
$result = $TestModel->find('count');
$this->assertEqual($result, 2);
$result = $TestModel->Comment->find('count');
$this->assertEqual($result, 4);
$result = $TestModel->Comment->Attachment->find('count');
$this->assertEqual($result, 0);
}
/**
* testDependentExclusiveDelete method
*
* @access public
* @return void
*/
function testDependentExclusiveDelete() {
$this->loadFixtures('Article', 'Comment');
$TestModel =& new Article10();
$result = $TestModel->find('all');
$this->assertEqual(count($result[0]['Comment']), 4);
$this->assertEqual(count($result[1]['Comment']), 2);
$this->assertEqual($TestModel->Comment->find('count'), 6);
$TestModel->delete(1);
$this->assertEqual($TestModel->Comment->find('count'), 2);
}
/**
* testDeleteLinks method
*
* @access public
* @return void
*/
function testDeleteLinks() {
$this->loadFixtures('Article', 'ArticlesTag', 'Tag');
$TestModel =& new Article();
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array(
'article_id' => '1',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '1',
'tag_id' => '2'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '3'
)));
$this->assertEqual($result, $expected);
$TestModel->delete(1);
$result = $TestModel->ArticlesTag->find('all');
$expected = array(
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '1'
)),
array('ArticlesTag' => array(
'article_id' => '2',
'tag_id' => '3'
)));
$this->assertEqual($result, $expected);
$result = $TestModel->deleteAll(array('Article.user_id' => 999));
$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();
//create two new join records to expose the issue.
$JoinA->JoinAsJoinC->create(array(
'join_a_id' => 1,
'join_c_id' => 2,
));
$JoinA->JoinAsJoinC->save();
$JoinA->JoinAsJoinB->create(array(
'join_a_id' => 1,
'join_b_id' => 2,
));
$JoinA->JoinAsJoinB->save();
$result = $JoinA->delete(1);
$this->assertTrue($result, 'Delete failed %s');
$joinedBs = $JoinA->JoinAsJoinB->find('count', array(
'conditions' => array('JoinAsJoinB.join_a_id' => 1)
));
$this->assertEqual($joinedBs, 0, 'JoinA/JoinB link records left over. %s');
$joinedBs = $JoinA->JoinAsJoinC->find('count', array(
'conditions' => array('JoinAsJoinC.join_a_id' => 1)
));
$this->assertEqual($joinedBs, 0, 'JoinA/JoinC link records left over. %s');
}
/**
* testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable method
*
* @access public
* @return void
*/
function testHabtmDeleteLinksWhenNoPrimaryKeyInJoinTable() {
$this->loadFixtures('Apple', 'Device', 'ThePaperMonkies');
$ThePaper =& new ThePaper();
$ThePaper->id = 1;
$ThePaper->save(array('Monkey' => array(2, 3)));
$result = $ThePaper->findById(1);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
$ThePaper =& new ThePaper();
$ThePaper->id = 2;
$ThePaper->save(array('Monkey' => array(2, 3)));
$result = $ThePaper->findById(2);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
$ThePaper->delete(1);
$result = $ThePaper->findById(2);
$expected = array(
array(
'id' => '2',
'device_type_id' => '1',
'name' => 'Device 2',
'typ' => '1'
),
array(
'id' => '3',
'device_type_id' => '1',
'name' => 'Device 3',
'typ' => '2'
));
$this->assertEqual($result['Monkey'], $expected);
}
/**
* test that beforeDelete returning false can abort deletion.
*
* @return void
*/
function testBeforeDeleteDeleteAbortion() {
$this->loadFixtures('Post');
$Model =& new CallbackPostTestModel();
$Model->beforeDeleteReturn = false;
$result = $Model->delete(1);
$this->assertFalse($result);
$exists = $Model->findById(1);
$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.
*
* @return void
*/
function testDeleteHabtmPostgresFailure() {
$this->loadFixtures('Article', 'Tag', 'ArticlesTag');
$Article =& ClassRegistry::init('Article');
$Article->hasAndBelongsToMany['Tag']['unique'] = true;
$Tag =& ClassRegistry::init('Tag');
$Tag->bindModel(array('hasAndBelongsToMany' => array(
'Article' => array(
'className' => 'Article',
'unique' => true
)
)), true);
// Article 1 should have Tag.1 and Tag.2
$before = $Article->find("all", array(
"conditions" => array("Article.id" => 1),
));
$this->assertEqual(count($before[0]['Tag']), 2, 'Tag count for Article.id = 1 is incorrect, should be 2 %s');
// From now on, Tag #1 is only associated with Post #1
$submitted_data = array(
"Tag" => array("id" => 1, 'tag' => 'tag1'),
"Article" => array(
"Article" => array(1)
)
);
$Tag->save($submitted_data);
// One more submission (The other way around) to make sure the reverse save looks good.
$submitted_data = array(
"Article" => array("id" => 2, 'title' => 'second article'),
"Tag" => array(
"Tag" => array(2, 3)
)
);
// ERROR:
// Postgresql: DELETE FROM "articles_tags" WHERE tag_id IN ('1', '3')
// MySQL: DELETE `ArticlesTag` FROM `articles_tags` AS `ArticlesTag` WHERE `ArticlesTag`.`article_id` = 2 AND `ArticlesTag`.`tag_id` IN (1, 3)
$Article->save($submitted_data);
// Want to make sure Article #1 has Tag #1 and Tag #2 still.
$after = $Article->find("all", array(
"conditions" => array("Article.id" => 1),
));
// Removing Article #2 from Tag #1 is all that should have happened.
$this->assertEqual(count($before[0]["Tag"]), count($after[0]["Tag"]));
}
/**
* test that deleting records inside the beforeDelete doesn't truncate the table.
*
* @return void
*/
function testBeforeDeleteWipingTable() {
$this->loadFixtures('Comment');
$Comment =& new BeforeDeleteComment();
// Delete 3 records.
$Comment->delete(4);
$result = $Comment->find('count');
$this->assertTrue($result > 1, 'Comments are all gone.');
$Comment->create(array(
'article_id' => 1,
'user_id' => 2,
'comment' => 'new record',
'published' => 'Y'
));
$Comment->save();
$Comment->delete(5);
$result = $Comment->find('count');
$this->assertTrue($result > 1, 'Comments are all gone.');
}
/**
* test that deleting the same record from the beforeDelete and the delete doesn't truncate the table.
*
* @return void
*/
function testBeforeDeleteWipingTableWithDuplicateDelete() {
$this->loadFixtures('Comment');
$Comment =& new BeforeDeleteComment();
$Comment->delete(1);
$result = $Comment->find('count');
$this->assertTrue($result > 1, 'Comments are all gone.');
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,672 @@
<?php
/* SVN FILE: $Id: model.test.php 8225 2009-07-08 03:25:30Z mark_story $ */
/**
* ModelValidationTest 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.model
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
require_once dirname(__FILE__) . DS . 'model.test.php';
/**
* ModelValidationTest
*
* @package cake
* @subpackage cake.tests.cases.libs.model.operations
*/
class ModelValidationTest extends BaseModelTest {
/**
* Tests validation parameter order in custom validation methods
*
* @access public
* @return void
*/
function testValidationParams() {
$TestModel =& new ValidationTest1();
$TestModel->validate['title'] = array(
'rule' => 'customValidatorWithParams',
'required' => true
);
$TestModel->create(array('title' => 'foo'));
$TestModel->invalidFields();
$expected = array(
'data' => array(
'title' => 'foo'
),
'validator' => array(
'rule' => 'customValidatorWithParams',
'on' => null,
'last' => false,
'allowEmpty' => false,
'required' => true
),
'or' => true,
'ignore_on_same' => 'id'
);
$this->assertEqual($TestModel->validatorParams, $expected);
$TestModel->validate['title'] = array(
'rule' => 'customValidatorWithMessage',
'required' => true
);
$expected = array(
'title' => 'This field will *never* validate! Muhahaha!'
);
$this->assertEqual($TestModel->invalidFields(), $expected);
$TestModel->validate['title'] = array(
'rule' => array('customValidatorWithSixParams', 'one', 'two', null, 'four'),
'required' => true
);
$TestModel->create(array('title' => 'foo'));
$TestModel->invalidFields();
$expected = array(
'data' => array(
'title' => 'foo'
),
'one' => 'one',
'two' => 'two',
'three' => null,
'four' => 'four',
'five' => array(
'rule' => array(1 => 'one', 2 => 'two', 3 => null, 4 => 'four'),
'on' => null,
'last' => false,
'allowEmpty' => false,
'required' => true
),
'six' => 6
);
$this->assertEqual($TestModel->validatorParams, $expected);
$TestModel->validate['title'] = array(
'rule' => array('customValidatorWithSixParams', 'one', array('two'), null, 'four', array('five' => 5)),
'required' => true
);
$TestModel->create(array('title' => 'foo'));
$TestModel->invalidFields();
$expected = array(
'data' => array(
'title' => 'foo'
),
'one' => 'one',
'two' => array('two'),
'three' => null,
'four' => 'four',
'five' => array('five' => 5),
'six' => array(
'rule' => array(1 => 'one', 2 => array('two'), 3 => null, 4 => 'four', 5 => array('five' => 5)),
'on' => null,
'last' => false,
'allowEmpty' => false,
'required' => true
)
);
$this->assertEqual($TestModel->validatorParams, $expected);
}
/**
* Tests validation parameter fieldList in invalidFields
*
* @access public
* @return void
*/
function testInvalidFieldsWithFieldListParams() {
$TestModel =& new ValidationTest1();
$TestModel->validate = $validate = array(
'title' => array(
'rule' => 'customValidator',
'required' => true
),
'name' => array(
'rule' => 'allowEmpty',
'required' => true
));
$TestModel->invalidFields(array('fieldList' => array('title')));
$expected = array(
'title' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->invalidFields(array('fieldList' => array('name')));
$expected = array(
'name' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->invalidFields(array('fieldList' => array('name', 'title')));
$expected = array(
'name' => 'This field cannot be left blank',
'title' => 'This field cannot be left blank'
);
$this->assertEqual($TestModel->validationErrors, $expected);
$TestModel->validationErrors = array();
$TestModel->whitelist = array('name');
$TestModel->invalidFields();
$expected = array('name' => 'This field cannot be left blank');
$this->assertEqual($TestModel->validationErrors, $expected);
$this->assertEqual($TestModel->validate, $validate);
}
/**
* Test that invalidFields() integrates well with save(). And that fieldList can be an empty type.
*
* @return void
*/
function testInvalidFieldsWhitelist() {
$TestModel =& new ValidationTest1();
$TestModel->validate = $validate = array(
'title' => array(
'rule' => 'customValidator',
'required' => true
),
'name' => array(
'rule' => 'alphaNumeric',
'required' => true
));
$TestModel->whitelist = array('name');
$TestModel->save(array('name' => '#$$#'));
$expected = array('name' => 'This field cannot be left blank');
$this->assertEqual($TestModel->validationErrors, $expected);
}
/**
* testValidates method
*
* @access public
* @return void
*/
function testValidates() {
$TestModel =& new TestValidate();
$TestModel->validate = array(
'user_id' => 'numeric',
'title' => array('allowEmpty' => false, 'rule' => 'notEmpty'),
'body' => 'notEmpty'
);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => '',
'body' => 'body'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 'title',
'body' => 'body'
));
$result = $TestModel->create($data) && $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => '0',
'body' => 'body'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate['modified'] = array('allowEmpty' => true, 'rule' => 'date');
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'modified' => ''
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'modified' => '2007-05-01'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'modified' => 'invalid-date-here'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'modified' => 0
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'modified' => '0'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$TestModel->validate['modified'] = array('allowEmpty' => false, 'rule' => 'date');
$data = array('TestValidate' => array('modified' => null));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array('modified' => false));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array('modified' => ''));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'modified' => '2007-05-01'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate['slug'] = array('allowEmpty' => false, 'rule' => array('maxLength', 45));
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'slug' => ''
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'slug' => 'slug-right-here'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'user_id' => '1',
'title' => 0,
'body' => 'body',
'slug' => 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$TestModel->validate = array(
'number' => array(
'rule' => 'validateNumber',
'min' => 3,
'max' => 5
),
'title' => array(
'allowEmpty' => false,
'rule' => 'notEmpty'
));
$data = array('TestValidate' => array(
'title' => 'title',
'number' => '0'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'title' => 'title',
'number' => 0
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'title' => 'title',
'number' => '3'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$data = array('TestValidate' => array(
'title' => 'title',
'number' => 3
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate = array(
'number' => array(
'rule' => 'validateNumber',
'min' => 5,
'max' => 10
),
'title' => array(
'allowEmpty' => false,
'rule' => 'notEmpty'
));
$data = array('TestValidate' => array(
'title' => 'title',
'number' => '3'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'title' => 'title',
'number' => 3
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$TestModel->validate = array(
'title' => array(
'allowEmpty' => false,
'rule' => 'validateTitle'
));
$data = array('TestValidate' => array('title' => ''));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array('title' => 'new title'));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array('title' => 'title-new'));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate = array('title' => array(
'allowEmpty' => true,
'rule' => 'validateTitle'
));
$data = array('TestValidate' => array('title' => ''));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate = array(
'title' => array(
'length' => array(
'allowEmpty' => true,
'rule' => array('maxLength', 10)
)));
$data = array('TestValidate' => array('title' => ''));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate = array(
'title' => array(
'rule' => array('userDefined', 'Article', 'titleDuplicate')
));
$data = array('TestValidate' => array('title' => 'My Article Title'));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertFalse($result);
$data = array('TestValidate' => array(
'title' => 'My Article With a Different Title'
));
$result = $TestModel->create($data);
$this->assertTrue($result);
$result = $TestModel->validates();
$this->assertTrue($result);
$TestModel->validate = array(
'title' => array(
'tooShort' => array('rule' => array('minLength', 50)),
'onlyLetters' => array('rule' => '/^[a-z]+$/i')
),
);
$data = array('TestValidate' => array(
'title' => 'I am a short string'
));
$TestModel->create($data);
$result = $TestModel->validates();
$this->assertFalse($result);
$result = $TestModel->validationErrors;
$expected = array(
'title' => 'onlyLetters'
);
$this->assertEqual($result, $expected);
$TestModel->validate = array(
'title' => array(
'tooShort' => array(
'rule' => array('minLength', 50),
'last' => true
),
'onlyLetters' => array('rule' => '/^[a-z]+$/i')
),
);
$data = array('TestValidate' => array(
'title' => 'I am a short string'
));
$TestModel->create($data);
$result = $TestModel->validates();
$this->assertFalse($result);
$result = $TestModel->validationErrors;
$expected = array(
'title' => 'tooShort'
);
$this->assertEqual($result, $expected);
}
/**
* test that validates() checks all the 'with' associations as well for validation
* as this can cause partial/wrong data insertion.
*
* @return void
*/
function testValidatesWithAssociations() {
$data = array(
'Something' => array(
'id' => 5,
'title' => 'Extra Fields',
'body' => 'Extra Fields Body',
'published' => '1'
),
'SomethingElse' => array(
array('something_else_id' => 1, 'doomed' => '')
)
);
$Something =& new Something();
$JoinThing =& $Something->JoinThing;
$JoinThing->validate = array('doomed' => array('rule' => 'notEmpty'));
$expectedError = array('doomed' => 'This field cannot be left blank');
$Something->create();
$result = $Something->save($data);
$this->assertFalse($result, 'Save occured even when with models failed. %s');
$this->assertEqual($JoinThing->validationErrors, $expectedError);
$count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id'])));
$this->assertIdentical($count, 0);
$data = array(
'Something' => array(
'id' => 5,
'title' => 'Extra Fields',
'body' => 'Extra Fields Body',
'published' => '1'
),
'SomethingElse' => array(
array('something_else_id' => 1, 'doomed' => 1),
array('something_else_id' => 1, 'doomed' => '')
)
);
$Something->create();
$result = $Something->save($data);
$this->assertFalse($result, 'Save occured even when with models failed. %s');
$joinRecords = $JoinThing->find('count', array(
'conditions' => array('JoinThing.something_id' => $data['Something']['id'])
));
$this->assertEqual($joinRecords, 0, 'Records were saved on the join table. %s');
}
/**
* test that saveAll and with models with validation interact well
*
* @return void
*/
function testValidatesWithModelsAndSaveAll() {
$data = array(
'Something' => array(
'id' => 5,
'title' => 'Extra Fields',
'body' => 'Extra Fields Body',
'published' => '1'
),
'SomethingElse' => array(
array('something_else_id' => 1, 'doomed' => '')
)
);
$Something =& new Something();
$JoinThing =& $Something->JoinThing;
$JoinThing->validate = array('doomed' => array('rule' => 'notEmpty'));
$expectedError = array('doomed' => 'This field cannot be left blank');
$Something->create();
$result = $Something->saveAll($data, array('validate' => 'only'));
$this->assertFalse($result);
$this->assertEqual($JoinThing->validationErrors, $expectedError);
$Something->create();
$result = $Something->saveAll($data, array('validate' => 'first'));
$this->assertFalse($result);
$this->assertEqual($JoinThing->validationErrors, $expectedError);
$count = $Something->find('count', array('conditions' => array('Something.id' => $data['Something']['id'])));
$this->assertIdentical($count, 0);
$joinRecords = $JoinThing->find('count', array(
'conditions' => array('JoinThing.something_id' => $data['Something']['id'])
));
$this->assertEqual($joinRecords, 0, 'Records were saved on the join table. %s');
}
/**
* Test that missing validation methods trigger errors in development mode.
* Helps to make developement easier.
*
* @return void
*/
function testMissingValidationErrorTriggering() {
$restore = Configure::read('debug');
Configure::write('debug', 2);
$TestModel =& new ValidationTest1();
$TestModel->create(array('title' => 'foo'));
$TestModel->validate = array(
'title' => array(
'rule' => array('thisOneBringsThePain'),
'required' => true
)
);
$this->expectError(new PatternExpectation('/thisOneBringsThePain for title/i'));
$TestModel->invalidFields(array('fieldList' => array('title')));
Configure::write('debug', 0);
$this->assertNoErrors();
$TestModel->invalidFields(array('fieldList' => array('title')));
Configure::write('debug', $restore);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,866 @@
<?php
/**
* ObjectTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('Object', 'Controller', 'Model'));
/**
* RequestActionPost class
*
* @package cake
* @subpackage cake.tests.cases.libs.object
*/
class RequestActionPost extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerPost'
* @access public
*/
var $name = 'RequestActionPost';
/**
* useTable property
*
* @var string 'posts'
* @access public
*/
var $useTable = 'posts';
}
/**
* RequestActionController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RequestActionController extends Controller {
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array('RequestActionPost');
/**
* test_request_action method
*
* @access public
* @return void
*/
function test_request_action() {
return 'This is a test';
}
/**
* another_ra_test method
*
* @param mixed $id
* @param mixed $other
* @access public
* @return void
*/
function another_ra_test($id, $other) {
return $id + $other;
}
/**
* normal_request_action method
*
* @access public
* @return void
*/
function normal_request_action() {
return 'Hello World';
}
/**
* returns $this->here
*
* @return void
*/
function return_here() {
return $this->here;
}
/**
* paginate_request_action method
*
* @access public
* @return void
*/
function paginate_request_action() {
$data = $this->paginate();
return true;
}
/**
* post pass, testing post passing
*
* @return array
*/
function post_pass() {
return $this->data;
}
/**
* test param passing and parsing.
*
* @return array
*/
function params_pass() {
return $this->params;
}
}
/**
* RequestActionPersistentController class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class RequestActionPersistentController extends Controller {
/**
* uses property
*
* @var array
* @access public
*/
var $uses = array('PersisterOne');
/**
* persistModel property
*
* @var array
* @access public
*/
var $persistModel = true;
/**
* post pass, testing post passing
*
* @return array
*/
function index() {
return 'This is a test';
}
}
/**
* TestObject class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class TestObject extends Object {
/**
* firstName property
*
* @var string 'Joel'
* @access public
*/
var $firstName = 'Joel';
/**
* lastName property
*
* @var string 'Moss'
* @access public
*/
var $lastName = 'Moss';
/**
* methodCalls property
*
* @var array
* @access public
*/
var $methodCalls = array();
/**
* emptyMethod method
*
* @access public
* @return void
*/
function emptyMethod() {
$this->methodCalls[] = 'emptyMethod';
}
/**
* oneParamMethod method
*
* @param mixed $param
* @access public
* @return void
*/
function oneParamMethod($param) {
$this->methodCalls[] = array('oneParamMethod' => array($param));
}
/**
* twoParamMethod method
*
* @param mixed $param
* @param mixed $param2
* @access public
* @return void
*/
function twoParamMethod($param, $param2) {
$this->methodCalls[] = array('twoParamMethod' => array($param, $param2));
}
/**
* threeParamMethod method
*
* @param mixed $param
* @param mixed $param2
* @param mixed $param3
* @access public
* @return void
*/
function threeParamMethod($param, $param2, $param3) {
$this->methodCalls[] = array('threeParamMethod' => array($param, $param2, $param3));
}
/**
* fourParamMethod method
*
* @param mixed $param
* @param mixed $param2
* @param mixed $param3
* @param mixed $param4
* @access public
* @return void
*/
function fourParamMethod($param, $param2, $param3, $param4) {
$this->methodCalls[] = array('fourParamMethod' => array($param, $param2, $param3, $param4));
}
/**
* fiveParamMethod method
*
* @param mixed $param
* @param mixed $param2
* @param mixed $param3
* @param mixed $param4
* @param mixed $param5
* @access public
* @return void
*/
function fiveParamMethod($param, $param2, $param3, $param4, $param5) {
$this->methodCalls[] = array('fiveParamMethod' => array($param, $param2, $param3, $param4, $param5));
}
/**
* crazyMethod method
*
* @param mixed $param
* @param mixed $param2
* @param mixed $param3
* @param mixed $param4
* @param mixed $param5
* @param mixed $param6
* @param mixed $param7
* @access public
* @return void
*/
function crazyMethod($param, $param2, $param3, $param4, $param5, $param6, $param7 = null) {
$this->methodCalls[] = array('crazyMethod' => array($param, $param2, $param3, $param4, $param5, $param6, $param7));
}
/**
* methodWithOptionalParam method
*
* @param mixed $param
* @access public
* @return void
*/
function methodWithOptionalParam($param = null) {
$this->methodCalls[] = array('methodWithOptionalParam' => array($param));
}
/**
* testPersist
*
* @return void
*/
function testPersist($name, $return = null, &$object, $type = null) {
return $this->_persist($name, $return, $object, $type);
}
}
/**
* ObjectTestModel class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ObjectTestModel extends CakeTestModel {
var $useTable = false;
var $name = 'ObjectTestModel';
}
/**
* Object Test class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class ObjectTest extends CakeTestCase {
/**
* fixtures
*
* @var string
*/
var $fixtures = array('core.post', 'core.test_plugin_comment', 'core.comment');
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->object = new TestObject();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->object);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* testLog method
*
* @access public
* @return void
*/
function testLog() {
@unlink(LOGS . 'error.log');
$this->assertTrue($this->object->log('Test warning 1'));
$this->assertTrue($this->object->log(array('Test' => 'warning 2')));
$result = file(LOGS . 'error.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Test warning 1$/', $result[0]);
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Error: Array$/', $result[1]);
$this->assertPattern('/^\($/', $result[2]);
$this->assertPattern('/\[Test\] => warning 2$/', $result[3]);
$this->assertPattern('/^\)$/', $result[4]);
unlink(LOGS . 'error.log');
@unlink(LOGS . 'error.log');
$this->assertTrue($this->object->log('Test warning 1', LOG_WARNING));
$this->assertTrue($this->object->log(array('Test' => 'warning 2'), LOG_WARNING));
$result = file(LOGS . 'error.log');
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Test warning 1$/', $result[0]);
$this->assertPattern('/^2[0-9]{3}-[0-9]+-[0-9]+ [0-9]+:[0-9]+:[0-9]+ Warning: Array$/', $result[1]);
$this->assertPattern('/^\($/', $result[2]);
$this->assertPattern('/\[Test\] => warning 2$/', $result[3]);
$this->assertPattern('/^\)$/', $result[4]);
unlink(LOGS . 'error.log');
}
/**
* testSet method
*
* @access public
* @return void
*/
function testSet() {
$this->object->_set('a string');
$this->assertEqual($this->object->firstName, 'Joel');
$this->object->_set(array('firstName'));
$this->assertEqual($this->object->firstName, 'Joel');
$this->object->_set(array('firstName' => 'Ashley'));
$this->assertEqual($this->object->firstName, 'Ashley');
$this->object->_set(array('firstName' => 'Joel', 'lastName' => 'Moose'));
$this->assertEqual($this->object->firstName, 'Joel');
$this->assertEqual($this->object->lastName, 'Moose');
}
/**
* testPersist method
*
* @access public
* @return void
*/
function testPersist() {
ClassRegistry::flush();
$cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
@unlink(CACHE . 'persistent' . DS . 'testmodel.php');
$test = new stdClass;
$this->assertFalse($this->object->testPersist('TestModel', null, $test));
$this->assertFalse($this->object->testPersist('TestModel', true, $test));
$this->assertTrue($this->object->testPersist('TestModel', null, $test));
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'testmodel.php'));
$this->assertTrue($this->object->testPersist('TestModel', true, $test));
$this->assertEqual($this->object->TestModel, $test);
@unlink(CACHE . 'persistent' . DS . 'testmodel.php');
$model =& new ObjectTestModel();
$expected = ClassRegistry::keys();
ClassRegistry::flush();
$data = array('object_test_model' => $model);
$this->assertFalse($this->object->testPersist('ObjectTestModel', true, $data));
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'objecttestmodel.php'));
$this->object->testPersist('ObjectTestModel', true, $model, 'registry');
$result = ClassRegistry::keys();
$this->assertEqual($result, $expected);
$newModel = ClassRegistry::getObject('object_test_model');
$this->assertEqual('ObjectTestModel', $newModel->name);
@unlink(CACHE . 'persistent' . DS . 'objecttestmodel.php');
Configure::write('Cache.disable', $cacheDisable);
}
/**
* testPersistWithRequestAction method
*
* @access public
* @return void
*/
function testPersistWithBehavior() {
ClassRegistry::flush();
$cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
App::build(array(
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins'. DS),
'behaviors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models'. DS . 'behaviors' . DS),
), true);
$this->assertFalse(class_exists('PersisterOneBehaviorBehavior'));
$this->assertFalse(class_exists('PersisterTwoBehaviorBehavior'));
$this->assertFalse(class_exists('TestPluginPersisterBehavior'));
$this->assertFalse(class_exists('TestPluginAuthors'));
$Controller = new RequestActionPersistentController();
$Controller->persistModel = true;
$Controller->constructClasses();
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'persisterone.php'));
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'persisteroneregistry.php'));
$contents = file_get_contents(CACHE . 'persistent' . DS . 'persisteroneregistry.php');
$contents = str_replace('"PersisterOne"', '"PersisterTwo"', $contents);
$contents = str_replace('persister_one', 'persister_two', $contents);
$contents = str_replace('test_plugin_comment', 'test_plugin_authors', $contents);
$result = file_put_contents(CACHE . 'persistent' . DS . 'persisteroneregistry.php', $contents);
$this->assertTrue(class_exists('PersisterOneBehaviorBehavior'));
$this->assertTrue(class_exists('TestPluginPersisterOneBehavior'));
$this->assertTrue(class_exists('TestPluginComment'));
$this->assertFalse(class_exists('PersisterTwoBehaviorBehavior'));
$this->assertFalse(class_exists('TestPluginPersisterTwoBehavior'));
$this->assertFalse(class_exists('TestPluginAuthors'));
$Controller = new RequestActionPersistentController();
$Controller->persistModel = true;
$Controller->constructClasses();
$this->assertTrue(class_exists('PersisterOneBehaviorBehavior'));
$this->assertTrue(class_exists('PersisterTwoBehaviorBehavior'));
$this->assertTrue(class_exists('TestPluginPersisterTwoBehavior'));
$this->assertTrue(class_exists('TestPluginAuthors'));
@unlink(CACHE . 'persistent' . DS . 'persisterone.php');
@unlink(CACHE . 'persistent' . DS . 'persisteroneregistry.php');
}
/**
* testPersistWithBehaviorAndRequestAction method
*
* @see testPersistWithBehavior
* @access public
* @return void
*/
function testPersistWithBehaviorAndRequestAction() {
ClassRegistry::flush();
$cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
$this->assertFalse(class_exists('ContainableBehavior'));
App::build(array(
'models' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models' . DS),
'behaviors' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'models'. DS . 'behaviors' . DS),
), true);
$this->assertFalse(class_exists('PersistOneBehaviorBehavior'));
$this->assertFalse(class_exists('PersistTwoBehaviorBehavior'));
$Controller = new RequestActionPersistentController();
$Controller->persistModel = true;
$Controller->constructClasses();
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'persisterone.php'));
$this->assertTrue(file_exists(CACHE . 'persistent' . DS . 'persisteroneregistry.php'));
$keys = ClassRegistry::keys();
$this->assertEqual($keys, array(
'persister_one',
'comment',
'test_plugin_comment',
'test_plugin.test_plugin_comment',
'persister_one_behavior_behavior',
'test_plugin_persister_one_behavior',
'test_plugin.test_plugin_persister_one_behavior'
));
ob_start();
$Controller->set('content_for_layout', 'cool');
$Controller->render('index', 'ajax', '/layouts/ajax');
$result = ob_get_clean();
$keys = ClassRegistry::keys();
$this->assertEqual($keys, array(
'persister_one',
'comment',
'test_plugin_comment',
'test_plugin.test_plugin_comment',
'persister_one_behavior_behavior',
'test_plugin_persister_one_behavior',
'test_plugin.test_plugin_persister_one_behavior',
'view'
));
$result = $this->object->requestAction('/request_action_persistent/index');
$expected = 'This is a test';
$this->assertEqual($result, $expected);
@unlink(CACHE . 'persistent' . DS . 'persisterone.php');
@unlink(CACHE . 'persistent' . DS . 'persisteroneregistry.php');
$Controller = new RequestActionPersistentController();
$Controller->persistModel = true;
$Controller->constructClasses();
@unlink(CACHE . 'persistent' . DS . 'persisterone.php');
@unlink(CACHE . 'persistent' . DS . 'persisteroneregistry.php');
Configure::write('Cache.disable', $cacheDisable);
}
/**
* testToString method
*
* @access public
* @return void
*/
function testToString() {
$result = strtolower($this->object->toString());
$this->assertEqual($result, 'testobject');
}
/**
* testMethodDispatching method
*
* @access public
* @return void
*/
function testMethodDispatching() {
$this->object->emptyMethod();
$expected = array('emptyMethod');
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->oneParamMethod('Hello');
$expected[] = array('oneParamMethod' => array('Hello'));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->twoParamMethod(true, false);
$expected[] = array('twoParamMethod' => array(true, false));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->threeParamMethod(true, false, null);
$expected[] = array('threeParamMethod' => array(true, false, null));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->crazyMethod(1, 2, 3, 4, 5, 6, 7);
$expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object = new TestObject();
$this->assertIdentical($this->object->methodCalls, array());
$this->object->dispatchMethod('emptyMethod');
$expected = array('emptyMethod');
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('oneParamMethod', array('Hello'));
$expected[] = array('oneParamMethod' => array('Hello'));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('twoParamMethod', array(true, false));
$expected[] = array('twoParamMethod' => array(true, false));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('threeParamMethod', array(true, false, null));
$expected[] = array('threeParamMethod' => array(true, false, null));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('fourParamMethod', array(1, 2, 3, 4));
$expected[] = array('fourParamMethod' => array(1, 2, 3, 4));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('fiveParamMethod', array(1, 2, 3, 4, 5));
$expected[] = array('fiveParamMethod' => array(1, 2, 3, 4, 5));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('crazyMethod', array(1, 2, 3, 4, 5, 6, 7));
$expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('methodWithOptionalParam', array('Hello'));
$expected[] = array('methodWithOptionalParam' => array("Hello"));
$this->assertIdentical($this->object->methodCalls, $expected);
$this->object->dispatchMethod('methodWithOptionalParam');
$expected[] = array('methodWithOptionalParam' => array(null));
$this->assertIdentical($this->object->methodCalls, $expected);
}
/**
* testRequestAction method
*
* @access public
* @return void
*/
function testRequestAction() {
App::build(array(
'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)
));
$result = $this->object->requestAction('');
$this->assertFalse($result);
$result = $this->object->requestAction('/request_action/test_request_action');
$expected = 'This is a test';
$this->assertEqual($result, $expected);;
$result = $this->object->requestAction('/request_action/another_ra_test/2/5');
$expected = 7;
$this->assertEqual($result, $expected);
$result = $this->object->requestAction('/tests_apps/index', array('return'));
$expected = 'This is the TestsAppsController index view';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction('/tests_apps/some_method');
$expected = 5;
$this->assertEqual($result, $expected);
$result = $this->object->requestAction('/request_action/paginate_request_action');
$this->assertTrue($result);
$result = $this->object->requestAction('/request_action/normal_request_action');
$expected = 'Hello World';
$this->assertEqual($result, $expected);
App::build();
}
/**
* test requestAction() and plugins.
*
* @return void
*/
function testRequestActionPlugins() {
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
));
App::objects('plugin', null, false);
Router::reload();
$result = $this->object->requestAction('/test_plugin/tests/index', array('return'));
$expected = 'test plugin index';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction('/test_plugin/tests/index/some_param', array('return'));
$expected = 'test plugin index';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'tests', 'action' => 'index', 'plugin' => 'test_plugin'), array('return')
);
$expected = 'test plugin index';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction('/test_plugin/tests/some_method');
$expected = 25;
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'tests', 'action' => 'some_method', 'plugin' => 'test_plugin')
);
$expected = 25;
$this->assertEqual($result, $expected);
App::build();
App::objects('plugin', null, false);
}
/**
* test requestAction() with arrays.
*
* @return void
*/
function testRequestActionArray() {
App::build(array(
'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)
));
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'test_request_action')
);
$expected = 'This is a test';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'another_ra_test'),
array('pass' => array('5', '7'))
);
$expected = 12;
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'tests_apps', 'action' => 'index'), array('return')
);
$expected = 'This is the TestsAppsController index view';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(array('controller' => 'tests_apps', 'action' => 'some_method'));
$expected = 5;
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'normal_request_action')
);
$expected = 'Hello World';
$this->assertEqual($result, $expected);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'paginate_request_action')
);
$this->assertTrue($result);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'paginate_request_action'),
array('pass' => array(5), 'named' => array('param' => 'value'))
);
$this->assertTrue($result);
App::build();
}
/**
* Test that requestAction() is populating $this->params properly
*
* @access public
* @return void
*/
function testRequestActionParamParseAndPass() {
$result = $this->object->requestAction('/request_action/params_pass');
$this->assertTrue(isset($result['url']['url']));
$this->assertEqual($result['url']['url'], '/request_action/params_pass');
$this->assertEqual($result['controller'], 'request_action');
$this->assertEqual($result['action'], 'params_pass');
$this->assertEqual($result['form'], array());
$this->assertEqual($result['plugin'], null);
$result = $this->object->requestAction('/request_action/params_pass/sort:desc/limit:5');
$expected = array('sort' => 'desc', 'limit' => 5,);
$this->assertEqual($result['named'], $expected);
$result = $this->object->requestAction(
array('controller' => 'request_action', 'action' => 'params_pass'),
array('named' => array('sort' => 'desc', 'limit' => 5))
);
$this->assertEqual($result['named'], $expected);
}
/**
* test requestAction and POST parameter passing, and not passing when url is an array.
*
* @access public
* @return void
*/
function testRequestActionPostPassing() {
$_tmp = $_POST;
$_POST = array('data' => array(
'item' => 'value'
));
$result = $this->object->requestAction(array('controller' => 'request_action', 'action' => 'post_pass'));
$expected = array();
$this->assertEqual($expected, $result);
$result = $this->object->requestAction(array('controller' => 'request_action', 'action' => 'post_pass'), array('data' => $_POST['data']));
$expected = $_POST['data'];
$this->assertEqual($expected, $result);
$result = $this->object->requestAction('/request_action/post_pass');
$expected = $_POST['data'];
$this->assertEqual($expected, $result);
$_POST = $_tmp;
}
/**
* testCakeError
*
* @return void
*/
function testCakeError() {
}
}

View File

@@ -0,0 +1,39 @@
<?php
/**
* OverloadableTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Overloadable');
/**
* OverloadableTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class OverloadableTest extends CakeTestCase {
/**
* skip method
*
* @access public
* @return void
*/
function skip() {
$this->skipIf(true, ' %s OverloadableTest not implemented');
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,523 @@
<?php
/**
* SanitizeTest 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.5428
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Sanitize');
/**
* DataTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SanitizeDataTest extends CakeTestModel {
/**
* name property
*
* @var string 'SanitizeDataTest'
* @access public
*/
var $name = 'SanitizeDataTest';
/**
* useTable property
*
* @var string 'data_tests'
* @access public
*/
var $useTable = 'data_tests';
}
/**
* Article class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SanitizeArticle extends CakeTestModel {
/**
* name property
*
* @var string 'Article'
* @access public
*/
var $name = 'SanitizeArticle';
/**
* useTable property
*
* @var string 'articles'
* @access public
*/
var $useTable = 'articles';
}
/**
* SanitizeTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SanitizeTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
* @access public
*/
var $autoFixtures = false;
/**
* fixtures property
*
* @var array
* @access public
*/
var $fixtures = array('core.data_test', 'core.article');
/**
* startTest method
*
* @param mixed $method
* @access public
* @return void
*/
function startTest($method) {
parent::startTest($method);
$this->_initDb();
}
/**
* testEscapeAlphaNumeric method
*
* @access public
* @return void
*/
function testEscapeAlphaNumeric() {
$resultAlpha = Sanitize::escape('abc', 'test_suite');
$this->assertEqual($resultAlpha, 'abc');
$resultNumeric = Sanitize::escape('123', 'test_suite');
$this->assertEqual($resultNumeric, '123');
$resultNumeric = Sanitize::escape(1234, 'test_suite');
$this->assertEqual($resultNumeric, 1234);
$resultNumeric = Sanitize::escape(1234.23, 'test_suite');
$this->assertEqual($resultNumeric, 1234.23);
$resultNumeric = Sanitize::escape('#1234.23', 'test_suite');
$this->assertEqual($resultNumeric, '#1234.23');
$resultNull = Sanitize::escape(null, 'test_suite');
$this->assertEqual($resultNull, null);
$resultNull = Sanitize::escape(false, 'test_suite');
$this->assertEqual($resultNull, false);
$resultNull = Sanitize::escape(true, 'test_suite');
$this->assertEqual($resultNull, true);
}
/**
* testClean method
*
* @access public
* @return void
*/
function testClean() {
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test &amp; &quot;quote&quot; &#039;other&#039; ;.$ symbol.another line';
$result = Sanitize::clean($string, array('connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test & ' . Sanitize::escape('"quote"', 'test_suite') . ' ' . Sanitize::escape('\'other\'', 'test_suite') . ' ;.$ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ $ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ \\$ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'dollar' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'carriage' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$array = array(array('test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'));
$expected = array(array('test &amp; &quot;quote&quot; &#039;other&#039; ;.$ symbol.another line'));
$result = Sanitize::clean($array, array('connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$array = array(array('test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line'));
$expected = array(array('test & "quote" \'other\' ;.$ $ symbol.another line'));
$result = Sanitize::clean($array, array('encode' => false, 'escape' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$array = array(array('test odd Ä spacesé'));
$expected = array(array('test odd &Auml; spaces&eacute;'));
$result = Sanitize::clean($array, array('odd_spaces' => false, 'escape' => false, 'connection' => 'test_suite'));
$this->assertEqual($result, $expected);
$array = array(array('\\$', array('key' => 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line')));
$expected = array(array('$', array('key' => 'test & "quote" \'other\' ;.$ $ symbol.another line')));
$result = Sanitize::clean($array, array('encode' => false, 'escape' => false));
$this->assertEqual($result, $expected);
$string = '';
$expected = '';
$result = Sanitize::clean($string);
$this->assertEqual($string, $expected);
$data = array(
'Grant' => array(
'title' => '2 o clock grant',
'grant_peer_review_id' => 3,
'institution_id' => 5,
'created_by' => 1,
'modified_by' => 1,
'created' => '2010-07-15 14:11:00',
'modified' => '2010-07-19 10:45:41'
),
'GrantsMember' => array(
0 => array(
'id' => 68,
'grant_id' => 120,
'member_id' => 16,
'program_id' => 29,
'pi_percent_commitment' => 1
)
)
);
$result = Sanitize::clean($data);
$this->assertEqual($result, $data);
}
/**
* testHtml method
*
* @access public
* @return void
*/
function testHtml() {
$string = '<p>This is a <em>test string</em> & so is this</p>';
$expected = 'This is a test string &amp; so is this';
$result = Sanitize::html($string, array('remove' => true));
$this->assertEqual($result, $expected);
$string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true';
$expected = 'The &quot;lazy&quot; dog &#039;jumped&#039; &amp; flew over the moon. If (1+1) = 2 &lt;em&gt;is&lt;/em&gt; true, (2-1) = 1 is also true';
$result = Sanitize::html($string);
$this->assertEqual($result, $expected);
$string = 'The "lazy" dog \'jumped\'';
$expected = 'The &quot;lazy&quot; dog \'jumped\'';
$result = Sanitize::html($string, array('quotes' => ENT_COMPAT));
$this->assertEqual($result, $expected);
$string = 'The "lazy" dog \'jumped\'';
$result = Sanitize::html($string, array('quotes' => ENT_NOQUOTES));
$this->assertEqual($result, $string);
$string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true';
$expected = 'The &quot;lazy&quot; dog &#039;jumped&#039; &amp; flew over the moon. If (1+1) = 2 &lt;em&gt;is&lt;/em&gt; true, (2-1) = 1 is also true';
$result = Sanitize::html($string);
$this->assertEqual($result, $expected);
}
/**
* testStripWhitespace method
*
* @access public
* @return void
*/
function testStripWhitespace() {
$string = "This sentence \t\t\t has lots of \n\n white\nspace \rthat \r\n needs to be \t \n trimmed.";
$expected = "This sentence has lots of whitespace that needs to be trimmed.";
$result = Sanitize::stripWhitespace($string);
$this->assertEqual($result, $expected);
}
/**
* testParanoid method
*
* @access public
* @return void
*/
function testParanoid() {
$string = 'I would like to !%@#% & dance & sing ^$&*()-+';
$expected = 'Iwouldliketodancesing';
$result = Sanitize::paranoid($string);
$this->assertEqual($result, $expected);
$string = array('This |s th% s0ng that never ends it g*es',
'on and on my friends, b^ca#use it is the',
'so&g th===t never ends.');
$expected = array('This s th% s0ng that never ends it g*es',
'on and on my friends bcause it is the',
'sog tht never ends.');
$result = Sanitize::paranoid($string, array('%', '*', '.', ' '));
$this->assertEqual($result, $expected);
$string = "anything' OR 1 = 1";
$expected = 'anythingOR11';
$result = Sanitize::paranoid($string);
$this->assertEqual($result, $expected);
$string = "x' AND email IS NULL; --";
$expected = 'xANDemailISNULL';
$result = Sanitize::paranoid($string);
$this->assertEqual($result, $expected);
$string = "x' AND 1=(SELECT COUNT(*) FROM users); --";
$expected = "xAND1SELECTCOUNTFROMusers";
$result = Sanitize::paranoid($string);
$this->assertEqual($result, $expected);
$string = "x'; DROP TABLE members; --";
$expected = "xDROPTABLEmembers";
$result = Sanitize::paranoid($string);
$this->assertEqual($result, $expected);
}
/**
* testStripImages method
*
* @access public
* @return void
*/
function testStripImages() {
$string = '<img src="/img/test.jpg" alt="my image" />';
$expected = 'my image<br />';
$result = Sanitize::stripImages($string);
$this->assertEqual($result, $expected);
$string = '<img src="javascript:alert(\'XSS\');" />';
$expected = '';
$result = Sanitize::stripImages($string);
$this->assertEqual($result, $expected);
$string = '<a href="http://www.badsite.com/phising"><img src="/img/test.jpg" alt="test image alt" title="test image title" id="myImage" class="image-left"/></a>';
$expected = '<a href="http://www.badsite.com/phising">test image alt</a><br />';
$result = Sanitize::stripImages($string);
$this->assertEqual($result, $expected);
$string = '<a onclick="medium()" href="http://example.com"><img src="foobar.png" onclick="evilFunction(); return false;"/></a>';
$expected = '<a onclick="medium()" href="http://example.com"></a>';
$result = Sanitize::stripImages($string);
$this->assertEqual($result, $expected);
}
/**
* testStripScripts method
*
* @access public
* @return void
*/
function testStripScripts() {
$string = '<link href="/css/styles.css" media="screen" rel="stylesheet" />';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = '<link href="/css/styles.css" media="screen" rel="stylesheet" />' . "\n" . '<link rel="icon" href="/favicon.ico" type="image/x-icon" />' . "\n" . '<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />' . "\n" . '<link rel="alternate" href="/feed.xml" title="RSS Feed" type="application/rss+xml" />';
$expected = "\n" . '<link rel="icon" href="/favicon.ico" type="image/x-icon" />' . "\n" . '<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />'."\n".'<link rel="alternate" href="/feed.xml" title="RSS Feed" type="application/rss+xml" />';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = '<script type="text/javascript"> alert("hacked!");</script>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = '<script> alert("hacked!");</script>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = '<style>#content { display:none; }</style>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = '<style type="text/css"><!-- #content { display:none; } --></style>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = <<<HTML
text
<style type="text/css">
<!--
#content { display:none; }
-->
</style>
text
HTML;
$expected = "text\n\ntext";
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
$string = <<<HTML
text
<script type="text/javascript">
<!--
alert('wooo');
-->
</script>
text
HTML;
$expected = "text\n\ntext";
$result = Sanitize::stripScripts($string);
$this->assertEqual($result, $expected);
}
/**
* testStripAll method
*
* @access public
* @return void
*/
function testStripAll() {
$string = '<img """><script>alert("xss")</script>"/>';
$expected ='"/>';
$result = Sanitize::stripAll($string);
$this->assertEqual($result, $expected);
$string = '<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>';
$expected = '';
$result = Sanitize::stripAll($string);
$this->assertEqual($result, $expected);
$string = '<<script>alert("XSS");//<</script>';
$expected = '<';
$result = Sanitize::stripAll($string);
$this->assertEqual($result, $expected);
$string = '<img src="http://google.com/images/logo.gif" onload="window.location=\'http://sam.com/\'" />'."\n".
"<p>This is ok \t\n text</p>\n".
'<link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="my sheet" charset="utf-8">'."\n".
'<script src="xss.js" type="text/javascript" charset="utf-8"></script>';
$expected = '<p>This is ok text</p>';
$result = Sanitize::stripAll($string);
$this->assertEqual($result, $expected);
}
/**
* testStripTags method
*
* @access public
* @return void
*/
function testStripTags() {
$string = '<h2>Headline</h2><p><a href="http://example.com">My Link</a> could go to a bad site</p>';
$expected = 'Headline<p>My Link could go to a bad site</p>';
$result = Sanitize::stripTags($string, 'h2', 'a');
$this->assertEqual($result, $expected);
$string = '<script type="text/javascript" src="http://evildomain.com"> </script>';
$expected = ' ';
$result = Sanitize::stripTags($string, 'script');
$this->assertEqual($result, $expected);
$string = '<h2>Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here <img src="/img/test.png" />. Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a');
$this->assertEqual($result, $expected);
$string = '<h2>Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here . Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a', 'img');
$this->assertEqual($result, $expected);
$string = '<b>Important message!</b><br>This message will self destruct!';
$expected = 'Important message!<br>This message will self destruct!';
$result = Sanitize::stripTags($string, 'b');
$this->assertEqual($result, $expected);
$string = '<b>Important message!</b><br />This message will self destruct!';
$expected = 'Important message!<br />This message will self destruct!';
$result = Sanitize::stripTags($string, 'b');
$this->assertEqual($result, $expected);
$string = '<h2 onclick="alert(\'evil\'); onmouseover="badness()">Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here . Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a', 'img');
$this->assertEqual($result, $expected);
}
/**
* testFormatColumns method
*
* @access public
* @return void
*/
function testFormatColumns() {
$this->loadFixtures('DataTest', 'Article');
$this->DataTest =& new SanitizeDataTest(array('alias' => 'DataTest'));
$data = array('DataTest' => array(
'id' => 'z',
'count' => '12a',
'float' => '2.31456',
'updated' => '2008-01-01'
)
);
$this->DataTest->set($data);
$expected = array('DataTest' => array(
'id' => '0',
'count' => '12',
'float' => 2.31456,
'updated' => '2008-01-01 00:00:00',
));
Sanitize::formatColumns($this->DataTest);
$result = $this->DataTest->data;
$this->assertEqual($result, $expected);
$this->Article =& new SanitizeArticle(array('alias' => 'Article'));
$data = array('Article' => array(
'id' => 'ZB',
'user_id' => '12',
'title' => 'title of article',
'body' => 'body text',
'published' => 'QQQQQQQ',
));
$this->Article->set($data);
$expected = array('Article' => array(
'id' => '0',
'user_id' => '12',
'title' => 'title of article',
'body' => 'body text',
'published' => 'QQQQQQQ',
));
Sanitize::formatColumns($this->Article);
$result = $this->Article->data;
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,173 @@
<?php
/**
* SecurityTest 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.5432
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', 'Security');
/**
* SecurityTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class SecurityTest extends CakeTestCase {
/**
* sut property
*
* @var mixed null
* @access public
*/
var $sut = null;
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->sut =& Security::getInstance();
}
/**
* testInactiveMins method
*
* @access public
* @return void
*/
function testInactiveMins() {
Configure::write('Security.level', 'high');
$this->assertEqual(10, Security::inactiveMins());
Configure::write('Security.level', 'medium');
$this->assertEqual(100, Security::inactiveMins());
Configure::write('Security.level', 'low');
$this->assertEqual(300, Security::inactiveMins());
}
/**
* testGenerateAuthkey method
*
* @access public
* @return void
*/
function testGenerateAuthkey() {
$this->assertEqual(strlen(Security::generateAuthKey()), 40);
}
/**
* testValidateAuthKey method
*
* @access public
* @return void
*/
function testValidateAuthKey() {
$authKey = Security::generateAuthKey();
$this->assertTrue(Security::validateAuthKey($authKey));
}
/**
* testHash method
*
* @access public
* @return void
*/
function testHash() {
$Security =& Security::getInstance();
$_hashType = $Security->hashType;
$key = 'someKey';
$hash = 'someHash';
$this->assertIdentical(strlen(Security::hash($key, null, false)), 40);
$this->assertIdentical(strlen(Security::hash($key, 'sha1', false)), 40);
$this->assertIdentical(strlen(Security::hash($key, null, true)), 40);
$this->assertIdentical(strlen(Security::hash($key, 'sha1', true)), 40);
$result = Security::hash($key, null, $hash);
$this->assertIdentical($result, 'e38fcb877dccb6a94729a81523851c931a46efb1');
$result = Security::hash($key, 'sha1', $hash);
$this->assertIdentical($result, 'e38fcb877dccb6a94729a81523851c931a46efb1');
$hashType = 'sha1';
Security::setHash($hashType);
$this->assertIdentical($this->sut->hashType, $hashType);
$this->assertIdentical(strlen(Security::hash($key, null, true)), 40);
$this->assertIdentical(strlen(Security::hash($key, null, false)), 40);
$this->assertIdentical(strlen(Security::hash($key, 'md5', false)), 32);
$this->assertIdentical(strlen(Security::hash($key, 'md5', true)), 32);
$hashType = 'md5';
Security::setHash($hashType);
$this->assertIdentical($this->sut->hashType, $hashType);
$this->assertIdentical(strlen(Security::hash($key, null, false)), 32);
$this->assertIdentical(strlen(Security::hash($key, null, true)), 32);
if (!function_exists('hash') && !function_exists('mhash')) {
$this->assertIdentical(strlen(Security::hash($key, 'sha256', false)), 32);
$this->assertIdentical(strlen(Security::hash($key, 'sha256', true)), 32);
} else {
$this->assertIdentical(strlen(Security::hash($key, 'sha256', false)), 64);
$this->assertIdentical(strlen(Security::hash($key, 'sha256', true)), 64);
}
Security::setHash($_hashType);
}
/**
* testCipher method
*
* @access public
* @return void
*/
function testCipher() {
$length = 10;
$txt = '';
for ($i = 0; $i < $length; $i++) {
$txt .= mt_rand(0, 255);
}
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEqual(Security::cipher($result, $key), $txt);
$txt = '';
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEqual(Security::cipher($result, $key), $txt);
$txt = 'some_text';
$key = '';
$result = Security::cipher($txt, $key);
$this->assertError();
$this->assertIdentical($result, '');
$txt = 123456;
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEqual(Security::cipher($result, $key), $txt);
$txt = '123456';
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEqual(Security::cipher($result, $key), $txt);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,310 @@
<?php
/**
* StringTest file
*
* PHP versions 4 and 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://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Core', 'String');
/**
* StringTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class StringTest extends CakeTestCase {
/**
* testUuidGeneration method
*
* @access public
* @return void
*/
function testUuidGeneration() {
$result = String::uuid();
$pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
$match = preg_match($pattern, $result);
$this->assertTrue($match);
}
/**
* testMultipleUuidGeneration method
*
* @access public
* @return void
*/
function testMultipleUuidGeneration() {
$check = array();
$count = mt_rand(10, 1000);
$pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
for($i = 0; $i < $count; $i++) {
$result = String::uuid();
$match = preg_match($pattern, $result);
$this->assertTrue($match);
$this->assertFalse(in_array($result, $check));
$check[] = $result;
}
}
/**
* testInsert method
*
* @access public
* @return void
*/
function testInsert() {
$string = 'some string';
$expected = 'some string';
$result = String::insert($string, array());
$this->assertEqual($result, $expected);
$string = '2 + 2 = :sum. Cake is :adjective.';
$expected = '2 + 2 = 4. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = %sum. Cake is %adjective.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = 2sum2. Cake is 9adjective9.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])%s\\1/'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = 12sum21. Cake is 23adjective45.';
$expected = '2 + 2 = 4. Cake is 23adjective45.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])([\d])%s\\2\\1/'));
$this->assertEqual($result, $expected);
$string = ':web :web_site';
$expected = 'www http';
$result = String::insert($string, array('web' => 'www', 'web_site' => 'http'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = <sum. Cake is <adjective>.';
$expected = '2 + 2 = <sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '<', 'after' => '>'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = \:sum. Cake is :adjective.';
$expected = '2 + 2 = :sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = !:sum. Cake is :adjective.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('escape' => '!'));
$this->assertEqual($result, $expected);
$string = '2 + 2 = \%sum. Cake is %adjective.';
$expected = '2 + 2 = %sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%'));
$this->assertEqual($result, $expected);
$string = ':a :b \:a :a';
$expected = '1 2 :a 1';
$result = String::insert($string, array('a' => 1, 'b' => 2));
$this->assertEqual($result, $expected);
$string = ':a :b :c';
$expected = '2 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEqual($result, $expected);
$string = ':a :b :c';
$expected = '1 3';
$result = String::insert($string, array('a' => 1, 'c' => 3), array('clean' => true));
$this->assertEqual($result, $expected);
$string = ':a :b :c';
$expected = '2 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEqual($result, $expected);
$string = ':a, :b and :c';
$expected = '2 and 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEqual($result, $expected);
$string = '":a, :b and :c"';
$expected = '"1, 2"';
$result = String::insert($string, array('a' => 1, 'b' => 2), array('clean' => true));
$this->assertEqual($result, $expected);
$string = '"${a}, ${b} and ${c}"';
$expected = '"1, 2"';
$result = String::insert($string, array('a' => 1, 'b' => 2), array('before' => '${', 'after' => '}', 'clean' => true));
$this->assertEqual($result, $expected);
$string = '<img src=":src" alt=":alt" class="foo :extra bar"/>';
$expected = '<img src="foo" class="foo bar"/>';
$result = String::insert($string, array('src' => 'foo'), array('clean' => 'html'));
$this->assertEqual($result, $expected);
$string = '<img src=":src" class=":no :extra"/>';
$expected = '<img src="foo"/>';
$result = String::insert($string, array('src' => 'foo'), array('clean' => 'html'));
$this->assertEqual($result, $expected);
$string = '<img src=":src" class=":no :extra"/>';
$expected = '<img src="foo" class="bar"/>';
$result = String::insert($string, array('src' => 'foo', 'extra' => 'bar'), array('clean' => 'html'));
$this->assertEqual($result, $expected);
$result = String::insert("this is a ? string", "test");
$expected = "this is a test string";
$this->assertEqual($result, $expected);
$result = String::insert("this is a ? string with a ? ? ?", array('long', 'few?', 'params', 'you know'));
$expected = "this is a long string with a few? params you know";
$this->assertEqual($result, $expected);
$result = String::insert('update saved_urls set url = :url where id = :id', array('url' => 'http://www.testurl.com/param1:url/param2:id','id' => 1));
$expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
$this->assertEqual($result, $expected);
$result = String::insert('update saved_urls set url = :url where id = :id', array('id' => 1, 'url' => 'http://www.testurl.com/param1:url/param2:id'));
$expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
$this->assertEqual($result, $expected);
$result = String::insert(':me cake. :subject :verb fantastic.', array('me' => 'I :verb', 'subject' => 'cake', 'verb' => 'is'));
$expected = "I :verb cake. cake is fantastic.";
$this->assertEqual($result, $expected);
$result = String::insert(':I.am: :not.yet: passing.', array('I.am' => 'We are'), array('before' => ':', 'after' => ':', 'clean' => array('replacement' => ' of course', 'method' => 'text')));
$expected = "We are of course passing.";
$this->assertEqual($result, $expected);
$result = String::insert(
':I.am: :not.yet: passing.',
array('I.am' => 'We are'),
array('before' => ':', 'after' => ':', 'clean' => true)
);
$expected = "We are passing.";
$this->assertEqual($result, $expected);
$result = String::insert('?-pended result', array('Pre'));
$expected = "Pre-pended result";
$this->assertEqual($result, $expected);
$string = 'switching :timeout / :timeout_count';
$expected = 'switching 5 / 10';
$result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10));
$this->assertEqual($result, $expected);
$string = 'switching :timeout / :timeout_count';
$expected = 'switching 5 / 10';
$result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5));
$this->assertEqual($result, $expected);
$string = 'switching :timeout_count by :timeout';
$expected = 'switching 10 by 5';
$result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10));
$this->assertEqual($result, $expected);
$string = 'switching :timeout_count by :timeout';
$expected = 'switching 10 by 5';
$result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5));
$this->assertEqual($result, $expected);
}
/**
* test Clean Insert
*
* @return void
*/
function testCleanInsert() {
$result = String::cleanInsert(':incomplete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEqual($result, '');
$result = String::cleanInsert(':incomplete', array(
'clean' => array('method' => 'text', 'replacement' => 'complete'),
'before' => ':', 'after' => '')
);
$this->assertEqual($result, 'complete');
$result = String::cleanInsert(':in.complete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEqual($result, '');
$result = String::cleanInsert(':in.complete and', array(
'clean' => true, 'before' => ':', 'after' => '')
);
$this->assertEqual($result, '');
$result = String::cleanInsert(':in.complete or stuff', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEqual($result, 'stuff');
$result = String::cleanInsert(
'<p class=":missing" id=":missing">Text here</p>',
array('clean' => 'html', 'before' => ':', 'after' => '')
);
$this->assertEqual($result, '<p>Text here</p>');
}
/**
* Tests that non-insertable variables (i.e. arrays) are skipped when used as values in
* String::insert().
*
* @return void
*/
function testAutoIgnoreBadInsertData() {
$data = array('foo' => 'alpha', 'bar' => 'beta', 'fale' => array());
$result = String::insert('(:foo > :bar || :fale!)', $data, array('clean' => 'text'));
$this->assertEqual($result, '(alpha > beta || !)');
}
/**
* testTokenize method
*
* @access public
* @return void
*/
function testTokenize() {
$result = String::tokenize('A,(short,boring test)');
$expected = array('A', '(short,boring test)');
$this->assertEqual($result, $expected);
$result = String::tokenize('A,(short,more interesting( test)');
$expected = array('A', '(short,more interesting( test)');
$this->assertEqual($result, $expected);
$result = String::tokenize('A,(short,very interesting( test))');
$expected = array('A', '(short,very interesting( test))');
$this->assertEqual($result, $expected);
$result = String::tokenize('"single tag"', ' ', '"', '"');
$expected = array('"single tag"');
$this->assertEqual($expected, $result);
$result = String::tokenize('tagA "single tag" tagB', ' ', '"', '"');
$expected = array('tagA', '"single tag"', 'tagB');
$this->assertEqual($expected, $result);
}
function testReplaceWithQuestionMarkInString() {
$string = ':a, :b and :c?';
$expected = '2 and 3?';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEqual($expected, $result);
}
}

View File

@@ -0,0 +1,120 @@
<?php
/**
* TestManagerTest file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2010, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* 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
*/
/**
* TestManagerTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class TestManagerTest extends CakeTestCase {
/**
* setUp method
*
* @return void
* @access public
*/
function setUp() {
$this->TestManager =& new TestManager();
$this->Reporter =& new CakeHtmlReporter();
}
/**
* testRunAllTests method
*
* @return void
* @access public
*/
function testRunAllTests() {
$folder =& new Folder($this->TestManager->_getTestsPath());
$extension = str_replace('.', '\.', $this->TestManager->getExtension('test'));
$out = $folder->findRecursive('.*' . $extension);
$reporter =& new CakeHtmlReporter();
$list = $this->TestManager->runAllTests($reporter, true);
$this->assertEqual(count($out), count($list));
}
/**
* testRunTestCase method
*
* @return void
* @access public
*/
function testRunTestCase() {
$file = md5(time());
$result = $this->TestManager->runTestCase($file, $this->Reporter);
$this->assertError('Test case ' . $file . ' cannot be found');
$this->assertFalse($result);
$file = str_replace(CORE_TEST_CASES, '', __FILE__);
$result = $this->TestManager->runTestCase($file, $this->Reporter, true);
$this->assertTrue($result);
}
/**
* testRunGroupTest method
*
* @return void
* @access public
*/
function testRunGroupTest() {
}
/**
* testAddTestCasesFromDirectory method
*
* @return void
* @access public
*/
function testAddTestCasesFromDirectory() {
}
/**
* testAddTestFile method
*
* @return void
* @access public
*/
function testAddTestFile() {
}
/**
* testGetTestCaseList method
*
* @return void
* @access public
*/
function testGetTestCaseList() {
}
/**
* testGetGroupTestList method
*
* @return void
* @access public
*/
function testGetGroupTestList() {
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,804 @@
<?php
/**
* HelperTest 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
*/
App::import('Core', array('View', 'Helper'));
/**
* HelperTestPost class
*
* @package cake
* @subpackage cake.tests.cases.libs.view
*/
class HelperTestPost extends Model {
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'body' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => ''),
'number' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'date' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
/**
* hasAndBelongsToMany property
*
* @var array
* @access public
*/
var $hasAndBelongsToMany = array('HelperTestTag'=> array('with' => 'HelperTestPostsTag'));
}
/**
* HelperTestComment class
*
* @package cake
* @subpackage cake.tests.cases.libs.view
*/
class HelperTestComment extends Model {
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'author_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'body' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
}
/**
* HelperTestTag class
*
* @package cake
* @subpackage cake.tests.cases.libs.view
*/
class HelperTestTag extends Model {
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
}
/**
* HelperTestPostsTag class
*
* @package cake
* @subpackage cake.tests.cases.libs.view
*/
class HelperTestPostsTag extends Model {
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
$this->_schema = array(
'helper_test_post_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'helper_test_tag_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
);
return $this->_schema;
}
}
class TestHelper extends Helper {
/**
* expose a method as public
*
* @param string $options
* @param string $exclude
* @param string $insertBefore
* @param string $insertAfter
* @return void
*/
function parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
return $this->_parseAttributes($options, $exclude, $insertBefore, $insertAfter);
}
}
/**
* HelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs
*/
class HelperTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
ClassRegistry::flush();
Router::reload();
$null = null;
$this->View = new View($null);
$this->Helper = new Helper();
ClassRegistry::addObject('HelperTestPost', new HelperTestPost());
ClassRegistry::addObject('HelperTestComment', new HelperTestComment());
ClassRegistry::addObject('HelperTestTag', new HelperTestTag());
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Helper, $this->View);
ClassRegistry::flush();
}
/**
* testFormFieldNameParsing method
*
* @access public
* @return void
*/
function testSetEntity() {
// PHP4 reference hack
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $this->View);
$this->Helper->setEntity('HelperTestPost.id');
$this->assertFalse($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->Helper->setEntity('HelperTestComment.body');
$this->assertFalse($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestComment');
$this->assertEqual($this->View->field, 'body');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('HelperTestPost', true);
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, null);
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('_Token.fields');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'fields');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, '_Token');
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('id');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('HelperTestComment.body');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'body');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, 'HelperTestComment');
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('body');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'body');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('Something.else');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'else');
$this->assertEqual($this->View->modelId, false);
$this->assertEqual($this->View->association, 'Something');
$this->assertEqual($this->View->fieldSuffix, '');
$this->Helper->setEntity('5.id');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, '5');
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->assertEqual($this->View->entity(), array('HelperTestPost', 5, 'id'));
$this->Helper->setEntity('0.id');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, '0');
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->assertEqual($this->View->entity(), array('HelperTestPost', 0, 'id'));
$this->Helper->setEntity('5.created.month');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'created');
$this->assertEqual($this->View->modelId, '5');
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, 'month');
$this->Helper->setEntity('HelperTestComment.5.id');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, '5');
$this->assertEqual($this->View->association, 'HelperTestComment');
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('HelperTestComment.id.time');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, 'HelperTestComment');
$this->assertEqual($this->View->fieldSuffix, 'time');
$this->Helper->setEntity('HelperTestTag');
$this->assertTrue($this->View->modelScope);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'HelperTestTag');
$this->assertEqual($this->View->modelId, '');
$this->assertEqual($this->View->association, 'HelperTestTag');
$this->assertEqual($this->View->fieldSuffix, '');
$this->Helper->setEntity(null);
$this->Helper->setEntity('ModelThatDoesntExist.field_that_doesnt_exist');
$this->assertFalse($this->View->modelScope);
$this->assertEqual($this->View->model, 'ModelThatDoesntExist');
$this->assertEqual($this->View->field, 'field_that_doesnt_exist');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
}
/**
* test that 'view' doesn't break things.
*
* @return void
*/
function testSetEntityWithView() {
$this->assertNull($this->Helper->setEntity('Allow.view.group_id'));
$this->assertNull($this->Helper->setEntity('Allow.view'));
$this->assertNull($this->Helper->setEntity('View.view'));
}
/**
* test getting values from Helper
*
* @return void
*/
function testValue() {
$this->Helper->data = array('fullname' => 'This is me');
$this->Helper->setEntity('fullname');
$result = $this->Helper->value('fullname');
$this->assertEqual($result, 'This is me');
$this->Helper->data = array('Post' => array('name' => 'First Post'));
$this->Helper->setEntity('Post.name');
$result = $this->Helper->value('Post.name');
$this->assertEqual($result, 'First Post');
$this->Helper->data = array('Post' => array(2 => array('name' => 'First Post')));
$this->Helper->setEntity('Post.2.name');
$result = $this->Helper->value('Post.2.name');
$this->assertEqual($result, 'First Post');
$this->Helper->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->setEntity('Post.2.created');
$result = $this->Helper->value('Post.2.created');
$this->assertEqual($result, array('year' => '2008'));
$this->Helper->data = array('Post' => array(2 => array('created' => array('year' => '2008'))));
$this->Helper->setEntity('Post.2.created.year');
$result = $this->Helper->value('Post.2.created.year');
$this->assertEqual($result, '2008');
$this->Helper->data = array('HelperTestTag' => array('HelperTestTag' => ''));
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, '');
$this->Helper->data = array('HelperTestTag' => array('HelperTestTag' => array(2, 3, 4)));
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, array(2, 3, 4));
$this->Helper->data = array(
'HelperTestTag' => array(
array('id' => 3),
array('id' => 5)
)
);
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEqual($result, array(3 => 3, 5 => 5));
$this->Helper->data = array('zero' => 0);
$this->Helper->setEntity('zero');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEqual($result, array('value' => 0));
$this->Helper->data = array('zero' => '0');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEqual($result, array('value' => '0'));
$this->Helper->setEntity('inexistent');
$result = $this->Helper->value(array('default' => 'something'), 'inexistent');
$this->assertEqual($result, array('value' => 'something'));
}
/**
* Ensure HTML escaping of url params. So link addresses are valid and not exploited
*
* @return void
*/
function testUrlConversion() {
$result = $this->Helper->url('/controller/action/1');
$this->assertEqual($result, '/controller/action/1');
$result = $this->Helper->url('/controller/action/1?one=1&two=2');
$this->assertEqual($result, '/controller/action/1?one=1&amp;two=2');
$result = $this->Helper->url(array('controller' => 'posts', 'action' => 'index', 'page' => '1" onclick="alert(\'XSS\');"'));
$this->assertEqual($result, "/posts/index/page:1&quot; onclick=&quot;alert(&#039;XSS&#039;);&quot;");
$result = $this->Helper->url('/controller/action/1/param:this+one+more');
$this->assertEqual($result, '/controller/action/1/param:this+one+more');
$result = $this->Helper->url('/controller/action/1/param:this%20one%20more');
$this->assertEqual($result, '/controller/action/1/param:this%20one%20more');
$result = $this->Helper->url('/controller/action/1/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24');
$this->assertEqual($result, '/controller/action/1/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24');
$result = $this->Helper->url(array(
'controller' => 'posts', 'action' => 'index', 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24'
));
$this->assertEqual($result, "/posts/index/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24");
$result = $this->Helper->url(array(
'controller' => 'posts', 'action' => 'index', 'page' => '1',
'?' => array('one' => 'value', 'two' => 'value', 'three' => 'purple')
));
$this->assertEqual($result, "/posts/index/page:1?one=value&amp;two=value&amp;three=purple");
}
/**
* test assetTimestamp application
*
* @return void
*/
function testAssetTimestamp() {
$_timestamp = Configure::read('Asset.timestamp');
$_debug = Configure::read('debug');
Configure::write('Asset.timestamp', false);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertEqual($result, CSS_URL . 'cake.generic.css');
Configure::write('Asset.timestamp', true);
Configure::write('debug', 0);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertEqual($result, CSS_URL . 'cake.generic.css');
Configure::write('Asset.timestamp', true);
Configure::write('debug', 2);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertPattern('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
Configure::write('Asset.timestamp', 'force');
Configure::write('debug', 0);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertPattern('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css?someparam');
$this->assertEqual($result, CSS_URL . 'cake.generic.css?someparam');
$this->Helper->webroot = '/some/dir/';
$result = $this->Helper->assetTimestamp('/some/dir/' . CSS_URL . 'cake.generic.css');
$this->assertPattern('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
Configure::write('debug', $_debug);
Configure::write('Asset.timestamp', $_timestamp);
}
/**
* test assetTimestamp with plugins and themes
*
* @return void
*/
function testAssetTimestampPluginsAndThemes() {
$_timestamp = Configure::read('Asset.timestamp');
Configure::write('Asset.timestamp', 'force');
App::build(array(
'plugins' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'plugins' . DS),
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views' . DS),
));
$result = $this->Helper->assetTimestamp('/test_plugin/css/test_plugin_asset.css');
$this->assertPattern('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin');
$result = $this->Helper->assetTimestamp('/test_plugin/css/i_dont_exist.css');
$this->assertPattern('#/test_plugin/css/i_dont_exist.css\?$#', $result, 'No error on missing file');
$result = $this->Helper->assetTimestamp('/theme/test_theme/js/theme.js');
$this->assertPattern('#/theme/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme');
$result = $this->Helper->assetTimestamp('/theme/test_theme/js/non_existant.js');
$this->assertPattern('#/theme/test_theme/js/non_existant.js\?$#', $result, 'No error on missing file');
App::build();
Configure::write('Asset.timestamp', $_timestamp);
}
/**
* testFieldsWithSameName method
*
* @access public
* @return void
*/
function testFieldsWithSameName() {
// PHP4 reference hack
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $this->View);
$this->Helper->setEntity('HelperTestTag', true);
$this->Helper->setEntity('HelperTestTag.id');
$this->assertEqual($this->View->model, 'HelperTestTag');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('My.id');
$this->assertEqual($this->View->model, 'HelperTestTag');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, 'My');
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('MyOther.id');
$this->assertEqual($this->View->model, 'HelperTestTag');
$this->assertEqual($this->View->field, 'id');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, 'MyOther');
$this->assertEqual($this->View->fieldSuffix, null);
}
/**
* testFieldSameAsModel method
*
* @access public
* @return void
*/
function testFieldSameAsModel() {
// PHP4 reference hack
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $this->View);
$this->Helper->setEntity('HelperTestTag', true);
$this->Helper->setEntity('helper_test_post');
$this->assertEqual($this->View->model, 'HelperTestTag');
$this->assertEqual($this->View->field, 'helper_test_post');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('HelperTestTag');
$this->assertEqual($this->View->model, 'HelperTestTag');
$this->assertEqual($this->View->field, 'HelperTestTag');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->assertEqual($this->View->entityPath, 'HelperTestTag');
}
/**
* testFieldSuffixForDate method
*
* @access public
* @return void
*/
function testFieldSuffixForDate() {
// PHP4 reference hack
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $this->View);
$this->Helper->setEntity('HelperTestPost', true);
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, null);
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, null);
$this->Helper->setEntity('date.month');
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->field, 'date');
$this->assertEqual($this->View->modelId, null);
$this->assertEqual($this->View->association, null);
$this->assertEqual($this->View->fieldSuffix, 'month');
}
/**
* testMulitDimensionValue method
*
* @access public
* @return void
*/
function testMulitDimensionValue() {
$this->Helper->data = array();
for ($i = 0; $i < 2; $i++) {
$this->Helper->data['Model'][$i] = 'what';
$result[] = $this->Helper->value("Model.{$i}");
$this->Helper->data['Model'][$i] = array();
for ($j = 0; $j < 2; $j++) {
$this->Helper->data['Model'][$i][$j] = 'how';
$result[] = $this->Helper->value("Model.{$i}.{$j}");
}
}
$expected = array('what', 'how', 'how', 'what', 'how', 'how');
$this->assertEqual($result, $expected);
$this->Helper->data['HelperTestComment']['5']['id'] = 'ok';
$result = $this->Helper->value('HelperTestComment.5.id');
$this->assertEqual($result, 'ok');
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->data['HelperTestPost']['5']['created']['month'] = '10';
$result = $this->Helper->value('5.created.month');
$this->assertEqual($result, 10);
$this->Helper->data['HelperTestPost']['0']['id'] = 100;
$result = $this->Helper->value('0.id');
$this->assertEqual($result, 100);
}
/**
* testClean method
*
* @access public
* @return void
*/
function testClean() {
$result = $this->Helper->clean(array());
$this->assertEqual($result, null);
$result = $this->Helper->clean(array('<script>with something</script>', '<applet>something else</applet>'));
$this->assertEqual($result, array('with something', 'something else'));
$result = $this->Helper->clean('<script>with something</script>');
$this->assertEqual($result, 'with something');
$result = $this->Helper->clean('<script type="text/javascript">alert("ruined");</script>');
$this->assertNoPattern('#</*script#', $result);
$result = $this->Helper->clean("<script \ntype=\"text/javascript\">\n\talert('ruined');\n\n\t\t</script>");
$this->assertNoPattern('#</*script#', $result);
$result = $this->Helper->clean('<body/onload=do(/something/)>');
$this->assertEqual($result, '<body/>');
$result = $this->Helper->clean('&lt;script&gt;alert(document.cookie)&lt;/script&gt;');
$this->assertEqual($result, '&amp;lt;script&amp;gt;alert(document.cookie)&amp;lt;/script&amp;gt;');
}
/**
* testMultiDimensionalField method
*
* @access public
* @return void
*/
function testMultiDimensionalField() {
// PHP4 reference hack
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $this->View);
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->setEntity('HelperTestPost.2.HelperTestComment.1.title');
$this->assertEqual($this->View->model, 'HelperTestPost');
$this->assertEqual($this->View->association, 'HelperTestComment');
$this->assertEqual($this->View->modelId,2);
$this->assertEqual($this->View->field, 'title');
$this->Helper->setEntity('HelperTestPost.1.HelperTestComment.1.HelperTestTag.1.created');
$this->assertEqual($this->View->field,'created');
$this->assertEqual($this->View->association,'HelperTestTag');
$this->assertEqual($this->View->modelId,1);
$this->Helper->setEntity('HelperTestPost.0.HelperTestComment.1.HelperTestTag.1.fake');
$this->assertEqual($this->View->model,'HelperTestPost');
$this->assertEqual($this->View->association,'HelperTestTag');
$this->assertEqual($this->View->field,null);
$this->Helper->setEntity('1.HelperTestComment.1.HelperTestTag.created.year');
$this->assertEqual($this->View->model,'HelperTestPost');
$this->assertEqual($this->View->association,'HelperTestTag');
$this->assertEqual($this->View->field,'created');
$this->assertEqual($this->View->modelId,1);
$this->assertEqual($this->View->fieldSuffix,'year');
$this->Helper->data['HelperTestPost'][2]['HelperTestComment'][1]['title'] = 'My Title';
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.title');
$this->assertEqual($result,'My Title');
$this->Helper->data['HelperTestPost'][2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEqual($result,2008);
$this->Helper->data[2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEqual($result,2008);
$this->Helper->data['HelperTestPost']['title'] = 'My Title';
$result = $this->Helper->value('title');
$this->assertEqual($result,'My Title');
$this->Helper->data['My']['title'] = 'My Title';
$result = $this->Helper->value('My.title');
$this->assertEqual($result,'My Title');
}
function testWebrootPaths() {
$this->Helper->webroot = '/';
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/img/cake.power.gif';
$this->assertEqual($result, $expected);
$this->Helper->theme = 'test_theme';
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/theme/test_theme/img/cake.power.gif';
$this->assertEqual($result, $expected);
$result = $this->Helper->webroot('/img/test.jpg');
$expected = '/theme/test_theme/img/test.jpg';
$this->assertEqual($result, $expected);
$webRoot = Configure::read('App.www_root');
Configure::write('App.www_root', TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'webroot' . DS);
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/theme/test_theme/img/cake.power.gif';
$this->assertEqual($result, $expected);
$result = $this->Helper->webroot('/img/test.jpg');
$expected = '/theme/test_theme/img/test.jpg';
$this->assertEqual($result, $expected);
$result = $this->Helper->webroot('/img/cake.icon.gif');
$expected = '/img/cake.icon.gif';
$this->assertEqual($result, $expected);
$result = $this->Helper->webroot('/img/cake.icon.gif?some=param');
$expected = '/img/cake.icon.gif?some=param';
$this->assertEqual($result, $expected);
Configure::write('App.www_root', $webRoot);
}
/**
* test parsing attributes.
*
* @return void
*/
function testParseAttributeCompact() {
$helper =& new TestHelper();
$compact = array('compact', 'checked', 'declare', 'readonly', 'disabled',
'selected', 'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize');
foreach ($compact as $attribute) {
foreach (array('true', true, 1, '1', $attribute) as $value) {
$attrs = array($attribute => $value);
$expected = ' ' . $attribute . '="' . $attribute . '"';
$this->assertEqual($helper->parseAttributes($attrs), $expected, '%s Failed on ' . $value);
}
}
}
}

View File

@@ -0,0 +1,910 @@
<?php
/**
* AjaxHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Helper', array('Html', 'Form', 'Javascript', 'Ajax'));
/**
* AjaxTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class AjaxTestController extends Controller {
/**
* name property
*
* @var string 'AjaxTest'
* @access public
*/
var $name = 'AjaxTest';
/**
* uses property
*
* @var mixed null
* @access public
*/
var $uses = null;
}
/**
* PostAjaxTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class PostAjaxTest extends Model {
/**
* primaryKey property
*
* @var string 'id'
* @access public
*/
var $primaryKey = 'id';
/**
* useTable property
*
* @var bool false
* @access public
*/
var $useTable = false;
/**
* schema method
*
* @access public
* @return void
*/
function schema() {
return array(
'id' => array('type' => 'integer', 'null' => '', 'default' => '', 'length' => '8'),
'name' => array('type' => 'string', 'null' => '', 'default' => '', 'length' => '255'),
'created' => array('type' => 'date', 'null' => '1', 'default' => '', 'length' => ''),
'updated' => array('type' => 'datetime', 'null' => '1', 'default' => '', 'length' => null)
);
}
}
/**
* TestAjaxHelper class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TestAjaxHelper extends AjaxHelper {
/**
* stop method
*
* @access public
* @return void
*/
function _stop() {
}
}
/**
* TestJavascriptHelper class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TestJavascriptHelper extends JavascriptHelper {
/**
* codeBlocks property
*
* @var mixed
* @access public
*/
var $codeBlocks;
/**
* codeBlock method
*
* @param mixed $parameter
* @access public
* @return void
*/
function codeBlock($parameter) {
if (empty($this->codeBlocks)) {
$this->codeBlocks = array();
}
$this->codeBlocks[] = $parameter;
}
}
/**
* AjaxTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class AjaxHelperTest extends CakeTestCase {
/**
* Regexp for CDATA start block
*
* @var string
*/
var $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/';
/**
* Regexp for CDATA end block
*
* @var string
*/
var $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
Router::reload();
$this->Ajax =& new TestAjaxHelper();
$this->Ajax->Html =& new HtmlHelper();
$this->Ajax->Form =& new FormHelper();
$this->Ajax->Javascript =& new JavascriptHelper();
$this->Ajax->Form->Html =& $this->Ajax->Html;
$view =& new View(new AjaxTestController());
ClassRegistry::addObject('view', $view);
ClassRegistry::addObject('PostAjaxTest', new PostAjaxTest());
$this->Ajax->Form->params = array(
'plugin' => null,
'action' => 'view',
'controller' => 'users'
);
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Ajax);
ClassRegistry::flush();
}
/**
* testEvalScripts method
*
* @access public
* @return void
*/
function testEvalScripts() {
$result = $this->Ajax->link('Test Link', 'http://www.cakephp.org', array('id' => 'link1', 'update' => 'content', 'evalScripts' => false));
$expected = array(
'a' => array('id' => 'link1', 'onclick' => ' event.returnValue = false; return false;', 'href' => 'http://www.cakephp.org'),
'Test Link',
'/a',
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Event.observe('link1', 'click', function(event) { new Ajax.Updater('content','http://www.cakephp.org', {asynchronous:true, evalScripts:false, requestHeaders:['X-Update', 'content']}) }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->link('Test Link', 'http://www.cakephp.org', array('id' => 'link1', 'update' => 'content'));
$expected = array(
'a' => array('id' => 'link1', 'onclick' => ' event.returnValue = false; return false;', 'href' => 'http://www.cakephp.org'),
'Test Link',
'/a',
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Event.observe('link1', 'click', function(event) { new Ajax.Updater('content','http://www.cakephp.org', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'content']}) }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* testAutoComplete method
*
* @access public
* @return void
*/
function testAutoComplete() {
$result = $this->Ajax->autoComplete('PostAjaxTest.title' , '/posts', array('minChars' => 2));
$this->assertPattern('/^<input[^<>]+name="data\[PostAjaxTest\]\[title\]"[^<>]+autocomplete="off"[^<>]+\/>/', $result);
$this->assertPattern('/<div[^<>]+id="PostAjaxTestTitle_autoComplete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<div[^<>]+class="auto_complete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<\/div>\s+<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\',')) . '/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\', {minChars:2});')) . '/', $result);
$this->assertPattern('/<\/script>$/', $result);
$result = $this->Ajax->autoComplete('PostAjaxTest.title' , '/posts', array('paramName' => 'parameter'));
$this->assertPattern('/^<input[^<>]+name="data\[PostAjaxTest\]\[title\]"[^<>]+autocomplete="off"[^<>]+\/>/', $result);
$this->assertPattern('/<div[^<>]+id="PostAjaxTestTitle_autoComplete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<div[^<>]+class="auto_complete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<\/div>\s+<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\',')) . '/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\', {paramName:\'parameter\'});')) . '/', $result);
$this->assertPattern('/<\/script>$/', $result);
$result = $this->Ajax->autoComplete('PostAjaxTest.title' , '/posts', array('paramName' => 'parameter', 'updateElement' => 'elementUpdated', 'afterUpdateElement' => 'function (input, element) { alert("updated"); }'));
$this->assertPattern('/^<input[^<>]+name="data\[PostAjaxTest\]\[title\]"[^<>]+autocomplete="off"[^<>]+\/>/', $result);
$this->assertPattern('/<div[^<>]+id="PostAjaxTestTitle_autoComplete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<div[^<>]+class="auto_complete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<\/div>\s+<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\',')) . '/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\', {paramName:\'parameter\', updateElement:elementUpdated, afterUpdateElement:function (input, element) { alert("updated"); }});')) . '/', $result);
$this->assertPattern('/<\/script>$/', $result);
$result = $this->Ajax->autoComplete('PostAjaxTest.title' , '/posts', array('callback' => 'function (input, queryString) { alert("requesting"); }'));
$this->assertPattern('/^<input[^<>]+name="data\[PostAjaxTest\]\[title\]"[^<>]+autocomplete="off"[^<>]+\/>/', $result);
$this->assertPattern('/<div[^<>]+id="PostAjaxTestTitle_autoComplete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<div[^<>]+class="auto_complete"[^<>]*><\/div>/', $result);
$this->assertPattern('/<\/div>\s+<script type="text\/javascript">\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\',')) . '/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Autocompleter(\'PostAjaxTestTitle\', \'PostAjaxTestTitle_autoComplete\', \'/posts\', {callback:function (input, queryString) { alert("requesting"); }});')) . '/', $result);
$this->assertPattern('/<\/script>$/', $result);
$result = $this->Ajax->autoComplete("PostAjaxText.title", "/post", array("parameters" => "'key=value&key2=value2'"));
$this->assertPattern('/{parameters:\'key=value&key2=value2\'}/', $result);
$result = $this->Ajax->autoComplete("PostAjaxText.title", "/post", array("with" => "'key=value&key2=value2'"));
$this->assertPattern('/{parameters:\'key=value&key2=value2\'}/', $result);
}
/**
* testAsynchronous method
*
* @access public
* @return void
*/
function testAsynchronous() {
$result = $this->Ajax->link('Test Link', '/', array('id' => 'link1', 'update' => 'content', 'type' => 'synchronous'));
$expected = array(
'a' => array('id' => 'link1', 'onclick' => ' event.returnValue = false; return false;', 'href' => '/'),
'Test Link',
'/a',
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Event.observe('link1', 'click', function(event) { new Ajax.Updater('content','/', {asynchronous:false, evalScripts:true, requestHeaders:['X-Update', 'content']}) }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* testDraggable method
*
* @access public
* @return void
*/
function testDraggable() {
$result = $this->Ajax->drag('id', array('handle' => 'other_id'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Draggable('id', {handle:'other_id'});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->drag('id', array('onDrag' => 'doDrag', 'onEnd' => 'doEnd'));
$this->assertPattern('/onDrag:doDrag/', $result);
$this->assertPattern('/onEnd:doEnd/', $result);
}
/**
* testDroppable method
*
* @access public
* @return void
*/
function testDroppable() {
$result = $this->Ajax->drop('droppable', array('accept' => 'crap'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Droppables.add('droppable', {accept:'crap'});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->dropRemote('droppable', array('accept' => 'crap'), array('url' => '/posts'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Droppables.add('droppable', {accept:'crap', onDrop:function(element, droppable, event) {new Ajax.Request('/posts', {asynchronous:true, evalScripts:true})}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->dropRemote('droppable', array('accept' => array('crap1', 'crap2')), array('url' => '/posts'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Droppables.add('droppable', {accept:[\"crap1\",\"crap2\"], onDrop:function(element, droppable, event) {new Ajax.Request('/posts', {asynchronous:true, evalScripts:true})}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->dropRemote('droppable', array('accept' => 'crap'), array('url' => '/posts', 'with' => '{drag_id:element.id,drop_id:dropon.id,event:event.whatever_you_want}'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Droppables.add('droppable', {accept:'crap', onDrop:function(element, droppable, event) {new Ajax.Request('/posts', {asynchronous:true, evalScripts:true, parameters:{drag_id:element.id,drop_id:dropon.id,event:event.whatever_you_want}})}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* testForm method
*
* @access public
* @return void
*/
function testForm() {
$result = $this->Ajax->form('showForm', 'post', array('model' => 'Form', 'url' => array('action' => 'showForm', 'controller' => 'forms'), 'update' => 'form_box'));
$this->assertNoPattern('/model=/', $result);
$result = $this->Ajax->form('showForm', 'post', array('name'=> 'SomeFormName', 'id' => 'MyFormID', 'url' => array('action' => 'showForm', 'controller' => 'forms'), 'update' => 'form_box'));
$this->assertPattern('/id="MyFormID"/', $result);
$this->assertPattern('/name="SomeFormName"/', $result);
}
/**
* testSortable method
*
* @access public
* @return void
*/
function testSortable() {
$result = $this->Ajax->sortable('ull', array('constraint' => false, 'ghosting' => true));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Sortable.create('ull', {constraint:false, ghosting:true});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->sortable('ull', array('constraint' => 'false', 'ghosting' => 'true'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Sortable.create('ull', {constraint:false, ghosting:true});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->sortable('ull', array('constraint'=>'false', 'ghosting'=>'true', 'update' => 'myId'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Sortable.create('ull', {constraint:false, ghosting:true, update:'myId'});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->sortable('faqs', array('url'=>'http://www.cakephp.org',
'update' => 'faqs',
'tag' => 'tbody',
'handle' => 'grip',
'before' => "Element.hide('message')",
'complete' => "Element.show('message');"
));
$expected = 'Sortable.create(\'faqs\', {update:\'faqs\', tag:\'tbody\', handle:\'grip\', onUpdate:function(sortable) {Element.hide(\'message\'); new Ajax.Updater(\'faqs\',\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, onComplete:function(request, json) {Element.show(\'message\');}, parameters:Sortable.serialize(\'faqs\'), requestHeaders:[\'X-Update\', \'faqs\']})}});';
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*' . str_replace('/', '\\/', preg_quote($expected)) . '\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$result = $this->Ajax->sortable('div', array('overlap' => 'foo'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"Sortable.create('div', {overlap:'foo'});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->sortable('div', array('block' => false));
$expected = "Sortable.create('div', {});";
$this->assertEqual($result, $expected);
$result = $this->Ajax->sortable('div', array('block' => false, 'scroll' => 'someID'));
$expected = "Sortable.create('div', {scroll:'someID'});";
$this->assertEqual($result, $expected);
$result = $this->Ajax->sortable('div', array('block' => false, 'scroll' => 'window'));
$expected = "Sortable.create('div', {scroll:window});";
$this->assertEqual($result, $expected);
$result = $this->Ajax->sortable('div', array('block' => false, 'scroll' => "$('someElement')"));
$expected = "Sortable.create('div', {scroll:$('someElement')});";
$this->assertEqual($result, $expected);
}
/**
* testSubmitWithIndicator method
*
* @access public
* @return void
*/
function testSubmitWithIndicator() {
$result = $this->Ajax->submit('Add', array('div' => false, 'url' => "http://www.cakephp.org", 'indicator' => 'loading', 'loading' => "doSomething()", 'complete' => 'doSomethingElse() '));
$this->assertPattern('/onLoading:function\(request\) {doSomething\(\);\s+Element.show\(\'loading\'\);}/', $result);
$this->assertPattern('/onComplete:function\(request, json\) {doSomethingElse\(\) ;\s+Element.hide\(\'loading\'\);}/', $result);
}
/**
* testLink method
*
* @access public
* @return void
*/
function testLink() {
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads');
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="link\d+"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'link\d+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Request\(\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('confirm' => 'Are you sure & positive?'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="link\d+"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'link\d+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*if \(confirm\(\'Are you sure & positive\?\'\)\) {\s*new Ajax\.Request\(\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true}\);\s*}\s*else\s*{\s*event.returnValue = false;\s*return false;\s*}\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="link\d+"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'link\d+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'id' => 'myLink'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="myLink"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'myLink\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'id' => 'myLink', 'complete' => 'myComplete();'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="myLink"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'myLink\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, onComplete:function\(request, json\) {myComplete\(\);}, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'id' => 'myLink', 'loading' => 'myLoading();', 'complete' => 'myComplete();'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+id="myLink"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'myLink\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, onComplete:function\(request, json\) {myComplete\(\);}, onLoading:function\(request\) {myLoading\(\);}, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'encoding' => 'utf-8'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'\w+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, encoding:\'utf-8\', requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'success' => 'success();'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'\w+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, onSuccess:function\(request\) {success\(\);}, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', 'http://www.cakephp.org/downloads', array('update' => 'myDiv', 'failure' => 'failure();'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/^<a[^<>]+href="http:\/\/www.cakephp.org\/downloads"[^<>]*>/', $result);
$this->assertPattern('/^<a[^<>]+onclick="\s*event.returnValue = false;\s*return false;"[^<>]*>/', $result);
$this->assertPattern('/<script[^<>]+type="text\/javascript"[^<>]*>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/Event.observe\(\'\w+\',\s*\'click\',\s*function\(event\)\s*{.+},\s*false\);\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/function\(event\)\s*{\s*new Ajax\.Updater\(\'myDiv\',\s*\'http:\/\/www.cakephp.org\/downloads\',\s*{asynchronous:true, evalScripts:true, onFailure:function\(request\) {failure\(\);}, requestHeaders:\[\'X-Update\', \'myDiv\'\]}\)\s*},\s*false\);/', $result);
$result = $this->Ajax->link('Ajax Link', '/test', array('complete' => 'test'));
$this->assertPattern('/^<a[^<>]+>Ajax Link<\/a><script [^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*[^<>]+\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern("/Event.observe\('link[0-9]+', [\w\d,'\(\)\s{}]+Ajax\.Request\([\w\d\s,'\(\){}:\/]+onComplete:function\(request, json\) {test}/", $result);
$this->assertNoPattern('/^<a[^<>]+complete="test"[^<>]*>Ajax Link<\/a>/', $result);
$this->assertNoPattern('/^<a\s+[^<>]*url="[^"]*"[^<>]*>/', $result);
$result = $this->Ajax->link(
'Ajax Link',
array('controller' => 'posts', 'action' => 'index', '?' => array('one' => '1', 'two' => '2')),
array('update' => 'myDiv', 'id' => 'myLink')
);
$this->assertPattern('#/posts\?one\=1\&two\=2#', $result);
}
/**
* testRemoteTimer method
*
* @access public
* @return void
*/
function testRemoteTimer() {
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'frequency' => 25));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 25\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'complete' => 'complete();'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, onComplete:function(request, json) {complete();}})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'complete' => 'complete();', 'create' => 'create();'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, onComplete:function(request, json) {complete();}, onCreate:function(request, xhr) {create();}})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'exception' => 'alert(exception);'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, onException:function(request, exception) {alert(exception);}})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'contentType' => 'application/x-www-form-urlencoded'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, contentType:\'application/x-www-form-urlencoded\'})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'method' => 'get', 'encoding' => 'utf-8'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, method:\'get\', encoding:\'utf-8\'})')) . '/', $result);
$result = $this->Ajax->remoteTimer(array('url' => 'http://www.cakephp.org', 'postBody' => 'var1=value1'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new PeriodicalExecuter\(function\(\) {.+}, 10\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, postBody:\'var1=value1\'})')) . '/', $result);
}
/**
* testObserveField method
*
* @access public
* @return void
*/
function testObserveField() {
$result = $this->Ajax->observeField('field', array('url' => 'http://www.cakephp.org'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new Form.Element.EventObserver\(\'field\', function\(element, value\) {.+}\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(\'field\')})')) . '/', $result);
$result = $this->Ajax->observeField('field', array('url' => 'http://www.cakephp.org', 'frequency' => 15));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new Form.Element.Observer\(\'field\', 15, function\(element, value\) {.+}\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Request(\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(\'field\')})')) . '/', $result);
$result = $this->Ajax->observeField('field', array('url' => 'http://www.cakephp.org', 'update' => 'divId'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new Form.Element.EventObserver\(\'field\', function\(element, value\) {.+}\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Updater(\'divId\',\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(\'field\'), requestHeaders:[\'X-Update\', \'divId\']})')) . '/', $result);
$result = $this->Ajax->observeField('field', array('url' => 'http://www.cakephp.org', 'update' => 'divId', 'with' => 'Form.Element.serialize(\'otherField\')'));
$this->assertPattern('/^<script[^<>]+type="text\/javascript"[^<>]*>.+<\/script>$/s', $result);
$this->assertNoPattern('/<script[^<>]+[^type]=[^<>]*>/', $result);
$this->assertPattern('/^<script[^<>]+>\s*' . str_replace('/', '\\/', preg_quote('//<![CDATA[')) . '\s*new Form.Element.EventObserver\(\'field\', function\(element, value\) {.+}\)\s*' . str_replace('/', '\\/', preg_quote('//]]>')) . '\s*<\/script>$/', $result);
$this->assertPattern('/' . str_replace('/', '\\/', preg_quote('new Ajax.Updater(\'divId\',\'http://www.cakephp.org\', {asynchronous:true, evalScripts:true, parameters:Form.Element.serialize(\'otherField\'), requestHeaders:[\'X-Update\', \'divId\']})')) . '/', $result);
}
/**
* testObserveForm method
*
* @access public
* @return void
*/
function testObserveForm() {
$result = $this->Ajax->observeForm('form', array('url' => 'http://www.cakephp.org'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Form.EventObserver('form', function(element, value) {new Ajax.Request('http://www.cakephp.org', {asynchronous:true, evalScripts:true, parameters:Form.serialize('form')})})",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->observeForm('form', array('url' => 'http://www.cakephp.org', 'frequency' => 15));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Form.Observer('form', 15, function(element, value) {new Ajax.Request('http://www.cakephp.org', {asynchronous:true, evalScripts:true, parameters:Form.serialize('form')})})",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->observeForm('form', array('url' => 'http://www.cakephp.org', 'update' => 'divId'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Form.EventObserver('form', function(element, value) {new Ajax.Updater('divId','http://www.cakephp.org', {asynchronous:true, evalScripts:true, parameters:Form.serialize('form'), requestHeaders:['X-Update', 'divId']})}",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->observeForm('form', array('url' => 'http://www.cakephp.org', 'update' => 'divId', 'with' => "Form.serialize('otherForm')"));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Form.EventObserver('form', function(element, value) {new Ajax.Updater('divId','http://www.cakephp.org', {asynchronous:true, evalScripts:true, parameters:Form.serialize('otherForm'), requestHeaders:['X-Update', 'divId']})}",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* testSlider method
*
* @access public
* @return void
*/
function testSlider() {
$result = $this->Ajax->slider('sliderId', 'trackId');
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('axis' => 'vertical'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {axis:'vertical'});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('axis' => 'vertical', 'minimum' => 60, 'maximum' => 288, 'alignX' => -28, 'alignY' => -5, 'disabled' => true));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {axis:'vertical', minimum:60, maximum:288, alignX:-28, alignY:-5, disabled:true});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('change' => "alert('changed');"));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {onChange:function(value) {alert('changed');}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('change' => "alert('changed');", 'slide' => "alert('sliding');"));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {onChange:function(value) {alert('changed');}, onSlide:function(value) {alert('sliding');}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('values' => array(10, 20, 30)));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {values:[10,20,30]});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->slider('sliderId', 'trackId', array('range' => '$R(10, 30)'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var sliderId = new Control.Slider('sliderId', 'trackId', {range:\$R(10, 30)});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* testRemoteFunction method
*
* @access public
* @return void
*/
function testRemoteFunction() {
$result = $this->Ajax->remoteFunction(array('complete' => 'testComplete();'));
$expected = "new Ajax.Request('/', {asynchronous:true, evalScripts:true, onComplete:function(request, json) {testComplete();}})";
$this->assertEqual($result, $expected);
$result = $this->Ajax->remoteFunction(array('update' => 'myDiv'));
$expected = "new Ajax.Updater('myDiv','/', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'myDiv']})";
$this->assertEqual($result, $expected);
$result = $this->Ajax->remoteFunction(array('update' => array('div1', 'div2')));
$expected = "new Ajax.Updater(document.createElement('div'),'/', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'div1 div2']})";
$this->assertEqual($result, $expected);
$result = $this->Ajax->remoteFunction(array('update' => 'myDiv', 'confirm' => 'Are you sure?'));
$expected = "if (confirm('Are you sure?')) { new Ajax.Updater('myDiv','/', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'myDiv']}); } else { event.returnValue = false; return false; }";
$this->assertEqual($result, $expected);
}
/**
* testDiv method
*
* @access public
* @return void
*/
function testDiv() {
ob_start();
$oldXUpdate = env('HTTP_X_UPDATE');
$result = $this->Ajax->div('myDiv');
$this->assertTags($result, array('div' => array('id' => 'myDiv')));
$_SERVER['HTTP_X_UPDATE'] = null;
$result = $this->Ajax->divEnd('myDiv');
$this->assertTags($result, '/div');
$_SERVER['HTTP_X_UPDATE'] = 'secondDiv';
$result = $this->Ajax->div('myDiv');
$this->assertTags($result, array('div' => array('id' => 'myDiv')));
$result = $this->Ajax->divEnd('myDiv');
$this->assertTags($result, '/div');
$_SERVER['HTTP_X_UPDATE'] = 'secondDiv myDiv anotherDiv';
$result = $this->Ajax->div('myDiv');
$this->assertTrue(empty($result));
$result = $this->Ajax->divEnd('myDiv');
$this->assertTrue(empty($result));
$_SERVER['HTTP_X_UPDATE'] = $oldXUpdate;
}
/**
* testAfterRender method
*
* @access public
* @return void
*/
function testAfterRender() {
ob_start();
$oldXUpdate = env('HTTP_X_UPDATE');
$this->Ajax->Javascript =& new TestJavascriptHelper();
$_SERVER['HTTP_X_UPDATE'] = 'secondDiv myDiv anotherDiv';
$result = $this->Ajax->div('myDiv');
$this->assertTrue(empty($result));
echo 'Contents of myDiv';
$result = $this->Ajax->divEnd('myDiv');
$this->assertTrue(empty($result));
ob_start();
$this->Ajax->afterRender();
$result = array_shift($this->Ajax->Javascript->codeBlocks);
$this->assertPattern('/^\s*' . str_replace('/', '\\/', preg_quote('var __ajaxUpdater__ = {myDiv:"Contents%20of%20myDiv"};')) . '\s*' . str_replace('/', '\\/', preg_quote('for (n in __ajaxUpdater__) { if (typeof __ajaxUpdater__[n] == "string" && $(n)) Element.update($(n), unescape(decodeURIComponent(__ajaxUpdater__[n]))); }')) . '\s*$/s', $result);
$_SERVER['HTTP_X_UPDATE'] = $oldXUpdate;
}
/**
* testEditor method
*
* @access public
* @return void
*/
function testEditor() {
$result = $this->Ajax->editor('myDiv', '/');
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Ajax.InPlaceEditor('myDiv', '/', {ajaxOptions:{asynchronous:true, evalScripts:true}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->editor('myDiv', '/', array('complete' => 'testComplete();'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Ajax.InPlaceEditor('myDiv', '/', {ajaxOptions:{asynchronous:true, evalScripts:true, onComplete:function(request, json) {testComplete();}}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->editor('myDiv', '/', array('callback' => 'callback();'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Ajax.InPlaceEditor('myDiv', '/', {callback:function(form, value) {callback();}, ajaxOptions:{asynchronous:true, evalScripts:true}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->editor('myDiv', '/', array('collection' => array(1 => 'first', 2 => 'second')));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"new Ajax.InPlaceCollectionEditor('myDiv', '/', {collection:{\"1\":\"first\",\"2\":\"second\"}, ajaxOptions:{asynchronous:true, evalScripts:true}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Ajax->editor('myDiv', '/', array('var' => 'myVar'));
$expected = array(
array('script' => array('type' => 'text/javascript')),
$this->cDataStart,
"var myVar = new Ajax.InPlaceEditor('myDiv', '/', {ajaxOptions:{asynchronous:true, evalScripts:true}});",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
}

View File

@@ -0,0 +1,536 @@
<?php
/**
* CacheHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('Controller', 'Model', 'View'));
App::import('Helper', 'Cache');
/**
* CacheTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class CacheTestController extends Controller {
/**
* helpers property
*
* @var array
* @access public
*/
var $helpers = array('Html', 'Cache');
/**
* cache_parsing method
*
* @access public
* @return void
*/
function cache_parsing() {
$this->viewPath = 'posts';
$this->layout = 'cache_layout';
$this->set('variable', 'variableValue');
$this->set('superman', 'clark kent');
$this->set('batman', 'bruce wayne');
$this->set('spiderman', 'peter parker');
}
}
/**
* CacheHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class CacheHelperTest extends CakeTestCase {
/**
* Checks if TMP/views is writable, and skips the case if it is not.
*
* @return void
*/
function skip() {
$this->skipUnless(is_writable(TMP . 'cache' . DS . 'views' . DS), 'TMP/views is not writable %s');
}
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Controller = new CacheTestController();
$this->Cache = new CacheHelper();
$this->_cacheSettings = Configure::read('Cache');
Configure::write('Cache.check', true);
Configure::write('Cache.disable', false);
}
/**
* Start Case - switch view paths
*
* @access public
* @return void
*/
function startCase() {
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
), true);
}
/**
* End Case - restore view Paths
*
* @access public
* @return void
*/
function endCase() {
App::build();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
clearCache();
unset($this->Cache);
Configure::write('Cache', $this->_cacheSettings);
}
/**
* test cache parsing with no cake:nocache tags in view file.
*
* @access public
* @return void
*/
function testLayoutCacheParsingNoTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertPattern('/php echo \$variable/', $contents);
$this->assertPattern('/php echo microtime()/', $contents);
$this->assertPattern('/clark kent/', $result);
@unlink($filename);
}
/**
* test cache parsing with non-latin characters in current route
*
* @access public
* @return void
*/
function testCacheNonLatinCharactersInRoute() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array('風街ろまん'),
'named' => array()
);
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/posts/view/風街ろまん';
$this->Controller->action = 'view';
$View = new View($this->Controller);
$result = $View->render('index');
$filename = CACHE . 'views' . DS . 'posts_view_風街ろまん.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
}
/**
* Test cache parsing with cake:nocache tags in view file.
*
* @access public
* @return void
*/
function testLayoutCacheParsingWithTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('test_nocache_tags');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertPattern('/if \(is_writable\(TMP\)\)\:/', $contents);
$this->assertPattern('/php echo \$variable/', $contents);
$this->assertPattern('/php echo microtime()/', $contents);
$this->assertNoPattern('/cake:nocache/', $contents);
@unlink($filename);
}
/**
* test that multiple <cake:nocache> tags function with multiple nocache tags in the layout.
*
* @return void
*/
function testMultipleNoCacheTagsInViewfile() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = 21600;
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('multiple_nocache');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertNoPattern('/cake:nocache/', $contents);
@unlink($filename);
}
/**
* testComplexNoCache method
*
* @return void
* @access public
*/
function testComplexNoCache () {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_complex',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = array('cache_complex' => 21600);
$this->Controller->here = '/cacheTest/cache_complex';
$this->Controller->action = 'cache_complex';
$this->Controller->layout = 'multi_cache';
$this->Controller->viewPath = 'posts';
$View = new View($this->Controller);
$result = $View->render('sequencial_nocache');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$this->assertPattern('/A\. Layout Before Content/', $result);
$this->assertPattern('/B\. In Plain Element/', $result);
$this->assertPattern('/C\. Layout After Test Element/', $result);
$this->assertPattern('/D\. In View File/', $result);
$this->assertPattern('/E\. Layout After Content/', $result);
//$this->assertPattern('/F\. In Element With No Cache Tags/', $result);
$this->assertPattern('/G\. Layout After Content And After Element With No Cache Tags/', $result);
$this->assertNoPattern('/1\. layout before content/', $result);
$this->assertNoPattern('/2\. in plain element/', $result);
$this->assertNoPattern('/3\. layout after test element/', $result);
$this->assertNoPattern('/4\. in view file/', $result);
$this->assertNoPattern('/5\. layout after content/', $result);
//$this->assertNoPattern('/6\. in element with no cache tags/', $result);
$this->assertNoPattern('/7\. layout after content and after element with no cache tags/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_complex.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
@unlink($filename);
$this->assertPattern('/A\. Layout Before Content/', $contents);
$this->assertNoPattern('/B\. In Plain Element/', $contents);
$this->assertPattern('/C\. Layout After Test Element/', $contents);
$this->assertPattern('/D\. In View File/', $contents);
$this->assertPattern('/E\. Layout After Content/', $contents);
//$this->assertPattern('/F\. In Element With No Cache Tags/', $contents);
$this->assertPattern('/G\. Layout After Content And After Element With No Cache Tags/', $contents);
$this->assertPattern('/1\. layout before content/', $contents);
$this->assertNoPattern('/2\. in plain element/', $contents);
$this->assertPattern('/3\. layout after test element/', $contents);
$this->assertPattern('/4\. in view file/', $contents);
$this->assertPattern('/5\. layout after content/', $contents);
//$this->assertPattern('/6\. in element with no cache tags/', $contents);
$this->assertPattern('/7\. layout after content and after element with no cache tags/', $contents);
}
/**
* test cacheAction set to a boolean
*
* @return void
*/
function testCacheActionArray() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/cache_test/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_test_cache_parsing.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
$this->Controller->cache_parsing();
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = array(
'some_other_action' => 21600
);
$this->Controller->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertFalse(file_exists($filename));
}
/**
* test with named and pass args.
*
* @return void
*/
function testCacheWithNamedAndPassedArgs() {
Router::reload();
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(1, 2),
'named' => array(
'name' => 'mark',
'ice' => 'cream'
)
);
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/cache_test/cache_parsing/1/2/name:mark/ice:cream';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_test_cache_parsing_1_2_name_mark_ice_cream.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
}
/**
* test that custom routes are respected when generating cache files.
*
* @return void
*/
function testCacheWithCustomRoutes() {
Router::reload();
Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
$this->Controller->cache_parsing();
$this->Controller->params = array(
'lang' => 'en',
'controller' => 'cache_test',
'action' => 'cache_parsing',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->here = '/en/cache_test/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'en_cache_test_cache_parsing.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
}
/**
* test ControllerName contains AppName
*
* This test verifys view cache is created correctly when the app name is contained in part of the controller name.
* (webapp Name) base name is 'cache' controller is 'cacheTest' action is 'cache_name'
* apps url would look somehing like http://localhost/cache/cacheTest/cache_name
*
* @return void
**/
function testCacheBaseNameControllerName() {
$this->Controller->cache_parsing();
$this->Controller->cacheAction = array(
'cache_name' => 21600
);
$this->Controller->params = array(
'controller' => 'cacheTest',
'action' => 'cache_name',
'url' => array(),
'pass' => array(),
'named' => array()
);
$this->Controller->here = '/cache/cacheTest/cache_name';
$this->Controller->action = 'cache_name';
$this->Controller->base = '/cache';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_cachetest_cache_name.php';
$this->assertTrue(file_exists($filename));
@unlink($filename);
}
/**
* testCacheEmptySections method
*
* This test must be uncommented/fixed in next release (1.2+)
*
* @return void
* @access public
*
function testCacheEmptySections () {
$this->Controller->cache_parsing();
$this->Controller->cacheAction = array('cacheTest' => 21600);
$this->Controller->here = '/cacheTest/cache_empty_sections';
$this->Controller->action = 'cache_empty_sections';
$this->Controller->layout = 'cache_empty_sections';
$this->Controller->viewPath = 'posts';
$View = new View($this->Controller);
$result = $View->render('cache_empty_sections');
$this->assertNoPattern('/cake:nocache/', $result);
$this->assertNoPattern('/php echo/', $result);
$this->assertPattern(
'@</title>\s*</head>\s*' .
'<body>\s*' .
'View Content\s*' .
'cached count is: 3\s*' .
'</body>@', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_empty_sections.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertNoPattern('/cake:nocache/', $contents);
$this->assertPattern(
'@<head>\s*<title>Posts</title>\s*' .
"<\?php \$x = 1; \?>\s*" .
'</head>\s*' .
'<body>\s*' .
"<\?php \$x\+\+; \?>\s*" .
"<\?php \$x\+\+; \?>\s*" .
'View Content\s*' .
"<\?php \$y = 1; \?>\s*" .
"<\?php echo 'cached count is:' . \$x; \?>\s*" .
'@', $contents);
@unlink($filename);
}
*/
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,911 @@
<?php
/**
* JavascriptHelperTest file
*
* PHP versions 4 and 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2006-2010, Cake Software Foundation, Inc.
*
* Licensed under The Open Group Test Suite License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Core', array('Controller', 'View', 'ClassRegistry', 'View'));
App::import('Helper', array('Javascript', 'Html', 'Form'));
/**
* TheJsTestController class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TheJsTestController extends Controller {
/**
* name property
*
* @var string 'TheTest'
* @access public
*/
var $name = 'TheTest';
/**
* uses property
*
* @var mixed null
* @access public
*/
var $uses = null;
}
/**
* TheView class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TheView extends View {
/**
* scripts method
*
* @access public
* @return void
*/
function scripts() {
return $this->__scripts;
}
}
/**
* TestJavascriptObject class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TestJavascriptObject {
/**
* property1 property
*
* @var string 'value1'
* @access public
*/
var $property1 = 'value1';
/**
* property2 property
*
* @var int 2
* @access public
*/
var $property2 = 2;
}
/**
* JavascriptTest class
*
* @package test_suite
* @subpackage test_suite.cases.libs
* @since CakePHP Test Suite v 1.0.0.0
*/
class JavascriptTest extends CakeTestCase {
/**
* Regexp for CDATA start block
*
* @var string
*/
var $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/';
/**
* Regexp for CDATA end block
*
* @var string
*/
var $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
/**
* setUp method
*
* @access public
* @return void
*/
function startTest() {
$this->Javascript =& new JavascriptHelper();
$this->Javascript->Html =& new HtmlHelper();
$this->Javascript->Form =& new FormHelper();
$this->View =& new TheView(new TheJsTestController());
ClassRegistry::addObject('view', $this->View);
}
/**
* tearDown method
*
* @access public
* @return void
*/
function endTest() {
unset($this->Javascript->Html);
unset($this->Javascript->Form);
unset($this->Javascript);
ClassRegistry::removeObject('view');
unset($this->View);
}
/**
* testConstruct method
*
* @access public
* @return void
*/
function testConstruct() {
$Javascript =& new JavascriptHelper(array('safe'));
$this->assertTrue($Javascript->safe);
$Javascript =& new JavascriptHelper(array('safe' => false));
$this->assertFalse($Javascript->safe);
}
/**
* testLink method
*
* @access public
* @return void
*/
function testLink() {
Configure::write('Asset.timestamp', false);
$result = $this->Javascript->link('script.js');
$expected = '<script type="text/javascript" src="js/script.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('script');
$expected = '<script type="text/javascript" src="js/script.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('scriptaculous.js?load=effects');
$expected = '<script type="text/javascript" src="js/scriptaculous.js?load=effects"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('some.json.libary');
$expected = '<script type="text/javascript" src="js/some.json.libary.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('jquery-1.1.2');
$expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('jquery-1.1.2');
$expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('/plugin/js/jquery-1.1.2');
$expected = '<script type="text/javascript" src="/plugin/js/jquery-1.1.2.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('/some_other_path/myfile.1.2.2.min.js');
$expected = '<script type="text/javascript" src="/some_other_path/myfile.1.2.2.min.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('some_other_path/myfile.1.2.2.min.js');
$expected = '<script type="text/javascript" src="js/some_other_path/myfile.1.2.2.min.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('some_other_path/myfile.1.2.2.min');
$expected = '<script type="text/javascript" src="js/some_other_path/myfile.1.2.2.min.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('http://example.com/jquery.js');
$expected = '<script type="text/javascript" src="http://example.com/jquery.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link(array('prototype.js', 'scriptaculous.js'));
$this->assertPattern('/^\s*<script\s+type="text\/javascript"\s+src=".*js\/prototype\.js"[^<>]*><\/script>/', $result);
$this->assertPattern('/<\/script>\s*<script[^<>]+>/', $result);
$this->assertPattern('/<script\s+type="text\/javascript"\s+src=".*js\/scriptaculous\.js"[^<>]*><\/script>\s*$/', $result);
$result = $this->Javascript->link('jquery-1.1.2', false);
$resultScripts = $this->View->scripts();
reset($resultScripts);
$expected = '<script type="text/javascript" src="js/jquery-1.1.2.js"></script>';
$this->assertNull($result);
$this->assertEqual(count($resultScripts), 1);
$this->assertEqual(current($resultScripts), $expected);
}
/**
* testFilteringAndTimestamping method
*
* @access public
* @return void
*/
function testFilteringAndTimestamping() {
if ($this->skipIf(!is_writable(JS), 'JavaScript directory not writable, skipping JS asset timestamp tests. %s')) {
return;
}
cache(str_replace(WWW_ROOT, '', JS) . '__cake_js_test.js', 'alert("test")', '+999 days', 'public');
$timestamp = substr(strtotime('now'), 0, 8);
Configure::write('Asset.timestamp', true);
$result = $this->Javascript->link('__cake_js_test');
$this->assertPattern('/^<script[^<>]+src=".*js\/__cake_js_test\.js\?' . $timestamp . '[0-9]{2}"[^<>]*>/', $result);
$debug = Configure::read('debug');
Configure::write('debug', 0);
$result = $this->Javascript->link('__cake_js_test');
$expected = '<script type="text/javascript" src="js/__cake_js_test.js"></script>';
$this->assertEqual($result, $expected);
Configure::write('Asset.timestamp', 'force');
$result = $this->Javascript->link('__cake_js_test');
$this->assertPattern('/^<script[^<>]+src=".*js\/__cake_js_test.js\?' . $timestamp . '[0-9]{2}"[^<>]*>/', $result);
Configure::write('debug', $debug);
Configure::write('Asset.timestamp', false);
$old = Configure::read('Asset.filter.js');
Configure::write('Asset.filter.js', 'js.php');
$result = $this->Javascript->link('__cake_js_test');
$this->assertPattern('/^<script[^<>]+src=".*cjs\/__cake_js_test\.js"[^<>]*>/', $result);
Configure::write('Asset.filter.js', true);
$result = $this->Javascript->link('jquery-1.1.2');
$expected = '<script type="text/javascript" src="cjs/jquery-1.1.2.js"></script>';
$this->assertEqual($result, $expected);
$result = $this->Javascript->link('folderjs/jquery-1.1.2');
$expected = '<script type="text/javascript" src="cjs/folderjs/jquery-1.1.2.js"></script>';
$this->assertEqual($result, $expected);
if ($old === null) {
Configure::delete('Asset.filter.js');
}
$debug = Configure::read('debug');
$webroot = $this->Javascript->webroot;
Configure::write('debug', 0);
Configure::write('Asset.timestamp', 'force');
$this->Javascript->webroot = '/testing/';
$result = $this->Javascript->link('__cake_js_test');
$this->assertPattern('/^<script[^<>]+src="\/testing\/js\/__cake_js_test\.js\?\d+"[^<>]*>/', $result);
$this->Javascript->webroot = '/testing/longer/';
$result = $this->Javascript->link('__cake_js_test');
$this->assertPattern('/^<script[^<>]+src="\/testing\/longer\/js\/__cake_js_test\.js\?\d+"[^<>]*>/', $result);
$this->Javascript->webroot = $webroot;
Configure::write('debug', $debug);
unlink(JS . '__cake_js_test.js');
}
/**
* testValue method
*
* @access public
* @return void
*/
function testValue() {
$result = $this->Javascript->value(array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8)));
$expected = '{"title":"New thing","indexes":[5,6,7,8]}';
$this->assertEqual($result, $expected);
$result = $this->Javascript->value(null);
$this->assertEqual($result, 'null');
$result = $this->Javascript->value(true);
$this->assertEqual($result, 'true');
$result = $this->Javascript->value(false);
$this->assertEqual($result, 'false');
$result = $this->Javascript->value(5);
$this->assertEqual($result, '5');
$result = $this->Javascript->value(floatval(5.3));
$this->assertPattern('/^5.3[0]+$/', $result);
$result = $this->Javascript->value('');
$expected = '""';
$this->assertEqual($result, $expected);
$result = $this->Javascript->value('CakePHP' . "\n" . 'Rapid Development Framework');
$expected = '"CakePHP\\nRapid Development Framework"';
$this->assertEqual($result, $expected);
$result = $this->Javascript->value('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP');
$expected = '"CakePHP\\nRapid Development Framework\\nFor PHP"';
$this->assertEqual($result, $expected);
$result = $this->Javascript->value('CakePHP: "Rapid Development Framework"');
$expected = '"CakePHP: \\"Rapid Development Framework\\""';
$this->assertEqual($result, $expected);
$result = $this->Javascript->value('CakePHP: \'Rapid Development Framework\'');
$expected = '"CakePHP: \\\'Rapid Development Framework\\\'"';
$this->assertEqual($result, $expected);
}
/**
* testObjectGeneration method
*
* @access public
* @return void
*/
function testObjectGeneration() {
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
$result = $this->Javascript->object($object);
$expected = '{"title":"New thing","indexes":[5,6,7,8]}';
$this->assertEqual($result, $expected);
$result = $this->Javascript->object(array('default' => 0));
$expected = '{"default":0}';
$this->assertEqual($result, $expected);
$result = $this->Javascript->object(array(
'2007' => array(
'Spring' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')),
'Fall' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky'))
), '2006' => array(
'Spring' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')),
'Fall' => array('1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
))
));
$expected = '{"2007":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}},"2006":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}}}';
$this->assertEqual($result, $expected);
if (ini_get('precision') >= 12) {
$number = 3.141592653589;
if (!$this->Javascript->useNative) {
$number = sprintf("%.11f", $number);
}
$result = $this->Javascript->object(array('Object' => array(true, false, 1, '02101', 0, -1, 3.141592653589, "1")));
$expected = '{"Object":[true,false,1,"02101",0,-1,' . $number . ',"1"]}';
$this->assertEqual($result, $expected);
$result = $this->Javascript->object(array('Object' => array(true => true, false, -3.141592653589, -10)));
$expected = '{"Object":{"1":true,"2":false,"3":' . (-1 * $number) . ',"4":-10}}';
$this->assertEqual($result, $expected);
}
$result = $this->Javascript->object(new TestJavascriptObject());
$expected = '{"property1":"value1","property2":2}';
$this->assertEqual($result, $expected);
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
$result = $this->Javascript->object($object, array('block' => true));
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'{"title":"New thing","indexes":[5,6,7,8]}',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1)));
$result = $this->Javascript->object($object);
$expected = '{"title":"New thing","indexes":[5,6,7,8],"object":{"inner":{"value":1}}}';
$this->assertEqual($result, $expected);
foreach (array('true' => true, 'false' => false, 'null' => null) as $expected => $data) {
$result = $this->Javascript->object($data);
$this->assertEqual($result, $expected);
}
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1)));
$result = $this->Javascript->object($object, array('prefix' => 'PREFIX', 'postfix' => 'POSTFIX'));
$this->assertPattern('/^PREFIX/', $result);
$this->assertPattern('/POSTFIX$/', $result);
$this->assertNoPattern('/.PREFIX./', $result);
$this->assertNoPattern('/.POSTFIX./', $result);
if ($this->Javascript->useNative) {
$this->Javascript->useNative = false;
$this->testObjectGeneration();
$this->Javascript->useNative = true;
}
}
/**
* testObjectNonNative method
*
* @access public
* @return void
*/
function testObjectNonNative() {
$oldNative = $this->Javascript->useNative;
$this->Javascript->useNative = false;
$object = array(
'Object' => array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3'
)
);
$expected = '{"Object":{"key1":val1,"key2":"val2","key3":val3}}';
$result = $this->Javascript->object($object, array('quoteKeys' => false, 'stringKeys' => array('key1', 'key3')));
$this->assertEqual($result, $expected);
$expected = '{?Object?:{?key1?:"val1",?key2?:"val2",?key3?:"val3"}}';
$result = $this->Javascript->object($object, array('q' => '?'));
$this->assertEqual($result, $expected);
$expected = '{?Object?:{?key1?:"val1",?key2?:val2,?key3?:"val3"}}';
$result = $this->Javascript->object($object, array(
'q' => '?', 'stringKeys' => array('key3', 'key1')
));
$this->assertEqual($result, $expected);
$expected = '{?Object?:{?key1?:val1,?key2?:"val2",?key3?:val3}}';
$result = $this->Javascript->object($object, array(
'q' => '?', 'stringKeys' => array('key3', 'key1'), 'quoteKeys' => false
));
$this->assertEqual($result, $expected);
$this->Javascript->useNative = $oldNative;
}
/**
* testScriptBlock method
*
* @access public
* @return void
*/
function testScriptBlock() {
$result = $this->Javascript->codeBlock('something');
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('allowCache' => true, 'safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
'something',
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('allowCache' => false, 'safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
'something',
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', true);
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', false);
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
'something',
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock('something', array('safe' => true));
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'something',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock(null, array('safe' => true, 'allowCache' => false));
$this->assertNull($result);
echo 'this is some javascript';
$result = $this->Javascript->blockEnd();
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'this is some javascript',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->codeBlock();
$this->assertNull($result);
echo "alert('hey');";
$result = $this->Javascript->blockEnd();
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"alert('hey');",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$this->Javascript->cacheEvents(false, true);
$this->assertFalse($this->Javascript->inBlock);
$result = $this->Javascript->codeBlock();
$this->assertIdentical($result, null);
$this->assertTrue($this->Javascript->inBlock);
echo 'alert("this is a buffered script");';
$result = $this->Javascript->blockEnd();
$this->assertIdentical($result, null);
$this->assertFalse($this->Javascript->inBlock);
$result = $this->Javascript->getCache();
$this->assertEqual('alert("this is a buffered script");', $result);
}
/**
* testOutOfLineScriptWriting method
*
* @access public
* @return void
*/
function testOutOfLineScriptWriting() {
echo $this->Javascript->codeBlock('$(document).ready(function() { });', array('inline' => false));
$this->Javascript->codeBlock(null, array('inline' => false));
echo '$(function(){ });';
$this->Javascript->blockEnd();
$script = $this->View->scripts();
$this->assertEqual(count($script), 2);
$this->assertPattern('/' . preg_quote('$(document).ready(function() { });', '/') . '/', $script[0]);
$this->assertPattern('/' . preg_quote('$(function(){ });', '/') . '/', $script[1]);
}
/**
* testEvent method
*
* @access public
* @return void
*/
function testEvent() {
$result = $this->Javascript->event('myId', 'click', 'something();');
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', array('safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click');
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', false);
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('myId', 'click', 'something();', array('useCapture' => true));
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, true);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('document', 'load');
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe(document, 'load', function(event) { }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('$(\'myId\')', 'click', 'something();', array('safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->event('\'document\'', 'load', 'something();', array('safe' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
"Event.observe('document', 'load', function(event) { something(); }, false);",
'/script'
);
$this->assertTags($result, $expected);
$this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertNull($result);
$result = $this->Javascript->getCache();
$this->assertPattern('/^' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '$/s', $result);
$result = $this->Javascript->event('#myId', 'alert(event);');
$this->assertNull($result);
$result = $this->Javascript->getCache();
$this->assertPattern('/^\s*var Rules = {\s*\'#myId\': function\(element, event\)\s*{\s*alert\(event\);\s*}\s*}\s*EventSelectors\.start\(Rules\);\s*$/s', $result);
}
/**
* testWriteEvents method
*
* @access public
* @return void
*/
function testWriteEvents() {
$this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertNull($result);
$result = $this->Javascript->writeEvents();
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache();
$this->assertTrue(empty($result));
$this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertNull($result);
$result = $this->Javascript->writeEvents(false);
$resultScripts = $this->View->scripts();
reset($resultScripts);
$this->assertNull($result);
$this->assertEqual(count($resultScripts), 1);
$result = current($resultScripts);
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache();
$this->assertTrue(empty($result));
}
/**
* testEscapeScript method
*
* @access public
* @return void
*/
function testEscapeScript() {
$result = $this->Javascript->escapeScript('');
$expected = '';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeScript('CakePHP' . "\n" . 'Rapid Development Framework');
$expected = 'CakePHP\\nRapid Development Framework';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeScript('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP');
$expected = 'CakePHP\\nRapid Development Framework\\nFor PHP';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeScript('CakePHP: "Rapid Development Framework"');
$expected = 'CakePHP: \\"Rapid Development Framework\\"';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeScript('CakePHP: \'Rapid Development Framework\'');
$expected = 'CakePHP: \\\'Rapid Development Framework\\\'';
$this->assertEqual($result, $expected);
}
/**
* testEscapeString method
*
* @access public
* @return void
*/
function testEscapeString() {
$result = $this->Javascript->escapeString('');
$expected = '';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('CakePHP' . "\n" . 'Rapid Development Framework');
$expected = 'CakePHP\\nRapid Development Framework';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP');
$expected = 'CakePHP\\nRapid Development Framework\\nFor PHP';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('CakePHP: "Rapid Development Framework"');
$expected = 'CakePHP: \\"Rapid Development Framework\\"';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('CakePHP: \'Rapid Development Framework\'');
$expected = "CakePHP: \\'Rapid Development Framework\\'";
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('my \\"string\\"');
$expected = 'my \\\\\\"string\\\\\\"';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('my string\nanother line');
$expected = 'my string\\\nanother line';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('String with \n string that looks like newline');
$expected = 'String with \\\n string that looks like newline';
$this->assertEqual($result, $expected);
$result = $this->Javascript->escapeString('String with \n string that looks like newline');
$expected = 'String with \\\n string that looks like newline';
$this->assertEqual($result, $expected);
}
/**
* test string escaping and compare to json_encode()
*
* @return void
*/
function testStringJsonEncodeCompliance() {
if (!function_exists('json_encode')) {
return;
}
$this->Javascript->useNative = false;
$data = array();
$data['mystring'] = "simple string";
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = "strïng with spécial chârs";
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = "a two lines\nstring";
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = "a \t tabbed \t string";
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = "a \"double-quoted\" string";
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
$data['mystring'] = 'a \\"double-quoted\\" string';
$this->assertEqual(json_encode($data), $this->Javascript->object($data));
}
/**
* test that text encoded with Javascript::object decodes properly
*
* @return void
*/
function testObjectDecodeCompatibility() {
if (!function_exists('json_decode')) {
return;
}
$this->Javascript->useNative = false;
$data = array("simple string");
$result = $this->Javascript->object($data);
$this->assertEqual(json_decode($result), $data);
$data = array('my \"string\"');
$result = $this->Javascript->object($data);
$this->assertEqual(json_decode($result), $data);
$data = array('my \\"string\\"');
$result = $this->Javascript->object($data);
$this->assertEqual(json_decode($result), $data);
}
/**
* testAfterRender method
*
* @access public
* @return void
*/
function testAfterRender() {
$this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertNull($result);
ob_start();
$this->Javascript->afterRender();
$result = ob_get_clean();
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"Event.observe($('myId'), 'click', function(event) { something(); }, false);",
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$result = $this->Javascript->getCache();
$this->assertTrue(empty($result));
$old = $this->Javascript->enabled;
$this->Javascript->enabled = false;
$this->Javascript->cacheEvents();
$result = $this->Javascript->event('myId', 'click', 'something();');
$this->assertNull($result);
ob_start();
$this->Javascript->afterRender();
$result = ob_get_clean();
$this->assertTrue(empty($result));
$result = $this->Javascript->getCache();
$this->assertPattern('/^' . str_replace('/', '\\/', preg_quote('Event.observe($(\'myId\'), \'click\', function(event) { something(); }, false);')) . '$/s', $result);
$this->Javascript->enabled = $old;
}
}

View File

@@ -0,0 +1,367 @@
<?php
/**
* JqueryEngineTestCase
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright 2006-2010, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake.tests
* @subpackage cake.tests.cases.views.helpers
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Helper', array('Html', 'Js', 'JqueryEngine'));
class JqueryEngineHelperTestCase extends CakeTestCase {
/**
* startTest
*
* @return void
*/
function startTest() {
$this->Jquery =& new JqueryEngineHelper();
}
/**
* end test
*
* @return void
*/
function endTest() {
unset($this->Jquery);
}
/**
* test selector method
*
* @return void
*/
function testSelector() {
$result = $this->Jquery->get('#content');
$this->assertEqual($result, $this->Jquery);
$this->assertEqual($this->Jquery->selection, '$("#content")');
$result = $this->Jquery->get('document');
$this->assertEqual($result, $this->Jquery);
$this->assertEqual($this->Jquery->selection, '$(document)');
$result = $this->Jquery->get('window');
$this->assertEqual($result, $this->Jquery);
$this->assertEqual($this->Jquery->selection, '$(window)');
$result = $this->Jquery->get('ul');
$this->assertEqual($result, $this->Jquery);
$this->assertEqual($this->Jquery->selection, '$("ul")');
}
/**
* test event binding
*
* @return void
*/
function testEvent() {
$this->Jquery->get('#myLink');
$result = $this->Jquery->event('click', 'doClick', array('wrap' => false));
$expected = '$("#myLink").bind("click", doClick);';
$this->assertEqual($result, $expected);
$result = $this->Jquery->event('click', '$(this).show();', array('stop' => false));
$expected = '$("#myLink").bind("click", function (event) {$(this).show();});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->event('click', '$(this).hide();');
$expected = '$("#myLink").bind("click", function (event) {$(this).hide();'."\n".'return false;});';
$this->assertEqual($result, $expected);
}
/**
* test dom ready event creation
*
* @return void
*/
function testDomReady() {
$result = $this->Jquery->domReady('foo.name = "bar";');
$expected = '$(document).ready(function () {foo.name = "bar";});';
$this->assertEqual($result, $expected);
}
/**
* test Each method
*
* @return void
*/
function testEach() {
$this->Jquery->get('#foo');
$result = $this->Jquery->each('$(this).hide();');
$expected = '$("#foo").each(function () {$(this).hide();});';
$this->assertEqual($result, $expected);
}
/**
* test Effect generation
*
* @return void
*/
function testEffect() {
$this->Jquery->get('#foo');
$result = $this->Jquery->effect('show');
$expected = '$("#foo").show();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('hide');
$expected = '$("#foo").hide();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('hide', array('speed' => 'fast'));
$expected = '$("#foo").hide("fast");';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('fadeIn');
$expected = '$("#foo").fadeIn();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('fadeOut');
$expected = '$("#foo").fadeOut();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('slideIn');
$expected = '$("#foo").slideDown();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('slideOut');
$expected = '$("#foo").slideUp();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('slideDown');
$expected = '$("#foo").slideDown();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->effect('slideUp');
$expected = '$("#foo").slideUp();';
$this->assertEqual($result, $expected);
}
/**
* Test Request Generation
*
* @return void
*/
function testRequest() {
$result = $this->Jquery->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = '$.ajax({url:"\\/posts\\/view\\/1"});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->request(array('controller' => 'posts', 'action' => 'view', 1), array(
'update' => '#content'
));
$expected = '$.ajax({dataType:"html", success:function (data, textStatus) {$("#content").html(data);}, url:"\/posts\/view\/1"});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = '$.ajax({beforeSend:doBefore, complete:doComplete, data:"name=jim&height=185cm", dataType:"json", error:handleError, success:doSuccess, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'wrapCallbacks' => false
));
$expected = '$.ajax({dataType:"html", success:function (data, textStatus) {doFoo$("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'dataExpression' => true,
'data' => '$("#someId").serialize()',
'wrapCallbacks' => false
));
$expected = '$.ajax({data:$("#someId").serialize(), dataType:"html", success:function (data, textStatus) {doFoo$("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->request('/people/edit/1', array(
'success' => 'doFoo',
'before' => 'doBefore',
'method' => 'post',
'dataExpression' => true,
'data' => '$("#someId").serialize()',
));
$expected = '$.ajax({beforeSend:function (XMLHttpRequest) {doBefore}, data:$("#someId").serialize(), success:function (data, textStatus) {doFoo}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
}
/**
* test that alternate jQuery object values work for request()
*
* @return void
*/
function testRequestWithAlternateJqueryObject() {
$this->Jquery->jQueryObject = '$j';
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'dataExpression' => true,
'data' => '$j("#someId").serialize()',
'wrapCallbacks' => false
));
$expected = '$j.ajax({data:$j("#someId").serialize(), dataType:"html", success:function (data, textStatus) {doFoo$j("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEqual($result, $expected);
}
/**
* test sortable list generation
*
* @return void
*/
function testSortable() {
$this->Jquery->get('#myList');
$result = $this->Jquery->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = '$("#myList").sortable({containment:"parent", distance:5, sort:onSort, start:onStart, stop:onStop});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
));
$expected = '$("#myList").sortable({containment:"parent", distance:5, sort:function (event, ui) {onSort}, start:function (event, ui) {onStart}, stop:function (event, ui) {onStop}});';
$this->assertEqual($result, $expected);
}
/**
* test drag() method
*
* @return void
*/
function testDrag() {
$this->Jquery->get('#element');
$result = $this->Jquery->drag(array(
'container' => '#content',
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = '$("#element").draggable({containment:"#content", drag:onDrag, grid:[10,10], start:onStart, stop:onStop});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->drag(array(
'container' => '#content',
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
));
$expected = '$("#element").draggable({containment:"#content", drag:function (event, ui) {onDrag}, grid:[10,10], start:function (event, ui) {onStart}, stop:function (event, ui) {onStop}});';
$this->assertEqual($result, $expected);
}
/**
* test drop() method
*
* @return void
*/
function testDrop() {
$this->Jquery->get('#element');
$result = $this->Jquery->drop(array(
'accept' => '.items',
'hover' => 'onHover',
'leave' => 'onExit',
'drop' => 'onDrop',
'wrapCallbacks' => false
));
$expected = '$("#element").droppable({accept:".items", drop:onDrop, out:onExit, over:onHover});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->drop(array(
'accept' => '.items',
'hover' => 'onHover',
'leave' => 'onExit',
'drop' => 'onDrop',
));
$expected = '$("#element").droppable({accept:".items", drop:function (event, ui) {onDrop}, out:function (event, ui) {onExit}, over:function (event, ui) {onHover}});';
$this->assertEqual($result, $expected);
}
/**
* test slider generation
*
* @return void
*/
function testSlider() {
$this->Jquery->get('#element');
$result = $this->Jquery->slider(array(
'complete' => 'onComplete',
'change' => 'onChange',
'min' => 0,
'max' => 10,
'value' => 2,
'direction' => 'vertical',
'wrapCallbacks' => false
));
$expected = '$("#element").slider({change:onChange, max:10, min:0, orientation:"vertical", stop:onComplete, value:2});';
$this->assertEqual($result, $expected);
$result = $this->Jquery->slider(array(
'complete' => 'onComplete',
'change' => 'onChange',
'min' => 0,
'max' => 10,
'value' => 2,
'direction' => 'vertical',
));
$expected = '$("#element").slider({change:function (event, ui) {onChange}, max:10, min:0, orientation:"vertical", stop:function (event, ui) {onComplete}, value:2});';
$this->assertEqual($result, $expected);
}
/**
* test the serializeForm method
*
* @return void
*/
function testSerializeForm() {
$this->Jquery->get('#element');
$result = $this->Jquery->serializeForm(array('isForm' => false));
$expected = '$("#element").closest("form").serialize();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->serializeForm(array('isForm' => true));
$expected = '$("#element").serialize();';
$this->assertEqual($result, $expected);
$result = $this->Jquery->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$("#element").closest("form").serialize()';
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,833 @@
<?php
/**
* JsHelper Test Case
*
* TestCase for the JsHelper
*
* 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.view.helpers
* @since CakePHP(tm) v 1.3
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Helper', array('Js', 'Html', 'Form'));
App::import('Core', array('View', 'ClassRegistry'));
Mock::generate('JsBaseEngineHelper', 'TestJsEngineHelper', array('methodOne'));
Mock::generate('View', 'JsHelperMockView');
class OptionEngineHelper extends JsBaseEngineHelper {
var $_optionMap = array(
'request' => array(
'complete' => 'success',
'request' => 'beforeSend',
'type' => 'dataType'
)
);
/**
* test method for testing option mapping
*
* @return array
*/
function testMap($options = array()) {
return $this->_mapOptions('request', $options);
}
/**
* test method for option parsing
*
* @return void
*/
function testParseOptions($options, $safe = array()) {
return $this->_parseOptions($options, $safe);
}
}
/**
* JsHelper TestCase.
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class JsHelperTestCase extends CakeTestCase {
/**
* Regexp for CDATA start block
*
* @var string
*/
var $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/';
/**
* Regexp for CDATA end block
*
* @var string
*/
var $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->_asset = Configure::read('Asset.timestamp');
Configure::write('Asset.timestamp', false);
$this->Js =& new JsHelper('JsBase');
$this->Js->Html =& new HtmlHelper();
$this->Js->Form =& new FormHelper();
$this->Js->Form->Html =& new HtmlHelper();
$this->Js->JsBaseEngine =& new JsBaseEngineHelper();
$view =& new JsHelperMockView();
ClassRegistry::addObject('view', $view);
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
Configure::write('Asset.timestamp', $this->_asset);
ClassRegistry::removeObject('view');
unset($this->Js);
}
/**
* Switches $this->Js to a mocked engine.
*
* @return void
*/
function _useMock() {
$this->Js =& new JsHelper(array('TestJs'));
$this->Js->TestJsEngine =& new TestJsEngineHelper($this);
$this->Js->Html =& new HtmlHelper();
$this->Js->Form =& new FormHelper();
$this->Js->Form->Html =& new HtmlHelper();
}
/**
* test object construction
*
* @return void
*/
function testConstruction() {
$js =& new JsHelper();
$this->assertEqual($js->helpers, array('Html', 'Form', 'JqueryEngine'));
$js =& new JsHelper(array('mootools'));
$this->assertEqual($js->helpers, array('Html', 'Form', 'mootoolsEngine'));
$js =& new JsHelper('prototype');
$this->assertEqual($js->helpers, array('Html', 'Form', 'prototypeEngine'));
$js =& new JsHelper('MyPlugin.Dojo');
$this->assertEqual($js->helpers, array('Html', 'Form', 'MyPlugin.DojoEngine'));
}
/**
* test that methods dispatch internally and to the engine class
*
* @return void
*/
function testMethodDispatching() {
$this->_useMock();
$this->Js->TestJsEngine->expectOnce('dispatchMethod', array(new PatternExpectation('/methodOne/i'), array()));
$this->Js->methodOne();
$this->Js->TestEngine =& new StdClass();
$this->expectError();
$this->Js->someMethodThatSurelyDoesntExist();
}
/**
* Test that method dispatching respects buffer parameters and bufferedMethods Lists.
*
* @return void
*/
function testMethodDispatchWithBuffering() {
$this->_useMock();
$this->Js->TestJsEngine->bufferedMethods = array('event', 'sortables');
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'This is an event call', array('event', '*'));
$this->Js->event('click', 'foo');
$result = $this->Js->getBuffer();
$this->assertEqual(count($result), 1);
$this->assertEqual($result[0], 'This is an event call');
$result = $this->Js->event('click', 'foo', array('buffer' => false));
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEqual($result, 'This is an event call');
$result = $this->Js->event('click', 'foo', false);
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEqual($result, 'This is an event call');
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'I am not buffered.', array('effect', '*'));
$result = $this->Js->effect('slideIn');
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEqual($result, 'I am not buffered.');
$result = $this->Js->effect('slideIn', true);
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEqual(count($buffer), 1);
$this->assertEqual($buffer[0], 'I am not buffered.');
$result = $this->Js->effect('slideIn', array('speed' => 'slow'), true);
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEqual(count($buffer), 1);
$this->assertEqual($buffer[0], 'I am not buffered.');
$result = $this->Js->effect('slideIn', array('speed' => 'slow', 'buffer' => true));
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEqual(count($buffer), 1);
$this->assertEqual($buffer[0], 'I am not buffered.');
}
/**
* test that writeScripts generates scripts inline.
*
* @return void
*/
function testWriteScriptsNoFile() {
$this->_useMock();
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'cache' => false, 'clear' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"one = 1;\ntwo = 2;",
$this->cDataEnd,
'/script',
);
$this->assertTags($result, $expected, true);
$this->Js->TestJsEngine->expectAtLeastOnce('domReady');
$result = $this->Js->writeBuffer(array('onDomReady' => true, 'cache' => false, 'clear' => false));
ClassRegistry::removeObject('view');
$view =& new JsHelperMockView();
ClassRegistry::addObject('view', $view);
$view->expectCallCount('addScript', 1);
$view->expectAt(0, 'addScript', array(new PatternExpectation('/one\s\=\s1;\ntwo\s\=\s2;/')));
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'cache' => false));
}
/**
* test that writing the buffer with inline = false includes a script tag.
*
* @return void
*/
function testWriteBufferNotInline() {
$this->Js->set('foo', 1);
$view =& new JsHelperMockView();
ClassRegistry::removeObject('view');
ClassRegistry::addObject('view', $view);
$view->expectCallCount('addScript', 1);
$pattern = new PatternExpectation('#<script type="text\/javascript">window.app \= \{"foo"\:1\}\;<\/script>#');
$view->expectAt(0, 'addScript', array($pattern));
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'safe' => false));
}
/**
* test that writeBuffer() sets domReady = false when the request is done by XHR.
* Including a domReady() when in XHR can cause issues as events aren't triggered by some libraries
*
* @return void
*/
function testWriteBufferAndXhr() {
$this->_useMock();
$this->Js->params['isAjax'] = true;
$this->Js->buffer('alert("test");');
$this->Js->TestJsEngine->expectCallCount('dispatchMethod', 0);
$result = $this->Js->writeBuffer();
}
/**
* test that writeScripts makes files, and puts the events into them.
*
* @return void
*/
function testWriteScriptsInFile() {
if ($this->skipIf(!is_writable(JS), 'webroot/js is not Writable, script caching test has been skipped')) {
return;
}
$this->Js->JsBaseEngine = new TestJsEngineHelper();
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'cache' => true));
$expected = array(
'script' => array('type' => 'text/javascript', 'src' => 'preg:/(.)*\.js/'),
);
$this->assertTags($result, $expected);
preg_match('/src="(.*\.js)"/', $result, $filename);
$this->assertTrue(file_exists(WWW_ROOT . $filename[1]));
$contents = file_get_contents(WWW_ROOT . $filename[1]);
$this->assertPattern('/one\s=\s1;\ntwo\s=\s2;/', $contents);
@unlink(WWW_ROOT . $filename[1]);
}
/**
* test link()
*
* @return void
*/
function testLinkWithMock() {
$this->_useMock();
$options = array('update' => '#content');
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'ajax code', array('request', '*'));
$this->Js->TestJsEngine->expectAt(0, 'dispatchMethod', array('get', new AnythingExpectation()));
$this->Js->TestJsEngine->expectAt(1, 'dispatchMethod', array(
'request', array('/posts/view/1', $options)
));
$this->Js->TestJsEngine->expectAt(2, 'dispatchMethod', array(
'event', array('click', 'ajax code', $options + array('buffer' => null))
));
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a'
);
$this->assertTags($result, $expected);
$options = array(
'confirm' => 'Are you sure?',
'update' => '#content',
'class' => 'my-class',
'id' => 'custom-id',
'escape' => false
);
$this->Js->TestJsEngine->expectAt(0, 'confirm', array($options['confirm']));
$this->Js->TestJsEngine->expectAt(1, 'request', array('/posts/view/1', '*'));
$code = <<<CODE
var _confirm = confirm("Are you sure?");
if (!_confirm) {
return false;
}
CODE;
$this->Js->TestJsEngine->expectAt(1, 'event', array('click', $code));
$result = $this->Js->link('test link »', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => $options['id'], 'class' => $options['class'], 'href' => '/posts/view/1'),
'test link »',
'/a'
);
$this->assertTags($result, $expected);
$options = array('id' => 'something', 'htmlAttributes' => array('arbitrary' => 'value', 'batman' => 'robin'));
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => $options['id'], 'href' => '/posts/view/1', 'arbitrary' => 'value',
'batman' => 'robin'),
'test link',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* test that link() and no buffering returns an <a> and <script> tags.
*
* @return void
*/
function testLinkWithNoBuffering() {
$this->_useMock();
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'ajax code', array(
'request', array('/posts/view/1', array('update' => '#content'))
));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', '-event handler-', array('event', '*'));
$options = array('update' => '#content', 'buffer' => false);
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a',
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'-event handler-',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
$options = array('update' => '#content', 'buffer' => false, 'safe' => false);
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a',
'script' => array('type' => 'text/javascript'),
'-event handler-',
'/script'
);
$this->assertTags($result, $expected);
}
/**
* test submit() with a Mock to check Engine method calls
*
* @return void
*/
function testSubmitWithMock() {
$this->_useMock();
$options = array('update' => '#content', 'id' => 'test-submit');
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'serialize-code', array('serializeform', '*'));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'serialize-code', array('serializeForm', '*'));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'ajax-code', array('request', '*'));
$this->Js->TestJsEngine->expectAt(0, 'dispatchMethod', array('get', '*'));
$this->Js->TestJsEngine->expectAt(1, 'dispatchMethod', array(new PatternExpectation('/serializeForm/i'), '*'));
$this->Js->TestJsEngine->expectAt(2, 'dispatchMethod', array('request', '*'));
$params = array(
'update' => $options['update'], 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => null
);
$this->Js->TestJsEngine->expectAt(3, 'dispatchMethod', array(
'event', array('click', "ajax-code", $params)
));
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save'),
'/div'
);
$this->assertTags($result, $expected);
$this->Js->TestJsEngine->expectAt(4, 'dispatchMethod', array('get', '*'));
$this->Js->TestJsEngine->expectAt(5, 'dispatchMethod', array(new PatternExpectation('/serializeForm/i'), '*'));
$requestParams = array(
'/custom/url', array(
'update' => '#content',
'data' => 'serialize-code',
'method' => 'post',
'dataExpression' => true
)
);
$this->Js->TestJsEngine->expectAt(6, 'dispatchMethod', array('request', $requestParams));
$params = array(
'update' => '#content', 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => null
);
$this->Js->TestJsEngine->expectAt(7, 'dispatchMethod', array(
'event', array('click', "ajax-code", $params)
));
$options = array('update' => '#content', 'id' => 'test-submit', 'url' => '/custom/url');
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save'),
'/div'
);
$this->assertTags($result, $expected);
}
/**
* test that no buffer works with submit() and that parameters are leaking into the script tag.
*
* @return void
*/
function testSubmitWithNoBuffer() {
$this->_useMock();
$options = array('update' => '#content', 'id' => 'test-submit', 'buffer' => false, 'safe' => false);
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'serialize-code', array('serializeform', '*'));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'serialize-code', array('serializeForm', '*'));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'ajax-code', array('request', '*'));
$this->Js->TestJsEngine->setReturnValue('dispatchMethod', 'event-handler', array('event', '*'));
$this->Js->TestJsEngine->expectAt(0, 'dispatchMethod', array('get', '*'));
$this->Js->TestJsEngine->expectAt(1, 'dispatchMethod', array(new PatternExpectation('/serializeForm/i'), '*'));
$this->Js->TestJsEngine->expectAt(2, 'dispatchMethod', array('request', array(
'', array('update' => $options['update'], 'data' => 'serialize-code', 'method' => 'post', 'dataExpression' => true)
)));
$params = array(
'update' => $options['update'], 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => false
);
$this->Js->TestJsEngine->expectAt(3, 'dispatchMethod', array(
'event', array('click', "ajax-code", $params)
));
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save'),
'/div',
'script' => array('type' => 'text/javascript'),
'event-handler',
'/script'
);
$this->assertTags($result, $expected);
}
/**
* Test that Object::Object() is not breaking json output in JsHelper
*
* @return void
*/
function testObjectPassThrough() {
$result = $this->Js->object(array('one' => 'first', 'two' => 'second'));
$expected = '{"one":"first","two":"second"}';
$this->assertEqual($result, $expected);
}
/**
* Test that inherited Helper::value() is overwritten in JsHelper::value()
* and calls JsBaseEngineHelper::value().
*
* @return void
*/
function testValuePassThrough() {
$result = $this->Js->value('string "quote"', true);
$expected = '"string \"quote\""';
$this->assertEqual($result, $expected);
}
/**
* test set()'ing variables to the Javascript buffer and controlling the output var name.
*
* @return void
*/
function testSet() {
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$result = $this->Js->getBuffer();
$expected = 'window.app = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEqual($result[0], $expected);
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->setVariable = 'WICKED';
$result = $this->Js->getBuffer();
$expected = 'window.WICKED = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEqual($result[0], $expected);
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->setVariable = 'Application.variables';
$result = $this->Js->getBuffer();
$expected = 'Application.variables = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEqual($result[0], $expected);
}
/**
* test that vars set with Js->set() go to the top of the buffered scripts list.
*
* @return void
*/
function testSetVarsAtTopOfBufferedScripts() {
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->alert('hey you!', array('buffer' => true));
$this->Js->confirm('Are you sure?', array('buffer' => true));
$result = $this->Js->getBuffer(false);
$expected = 'window.app = {"height":"tall","color":"purple"};';
$this->assertEqual($result[0], $expected);
$this->assertEqual($result[1], 'alert("hey you!");');
$this->assertEqual($result[2], 'confirm("Are you sure?");');
}
}
/**
* JsBaseEngine Class Test case
*
* @package cake.tests.view.helpers
*/
class JsBaseEngineTestCase extends CakeTestCase {
/**
* startTest method
*
* @access public
* @return void
*/
function startTest() {
$this->JsEngine = new JsBaseEngineHelper();
}
/**
* endTest method
*
* @access public
* @return void
*/
function endTest() {
ClassRegistry::removeObject('view');
unset($this->JsEngine);
}
/**
* test escape string skills
*
* @return void
*/
function testEscaping() {
$result = $this->JsEngine->escape('');
$expected = '';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->escape('CakePHP' . "\n" . 'Rapid Development Framework');
$expected = 'CakePHP\\nRapid Development Framework';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->escape('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP');
$expected = 'CakePHP\\r\\nRapid Development Framework\\rFor PHP';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->escape('CakePHP: "Rapid Development Framework"');
$expected = 'CakePHP: \\"Rapid Development Framework\\"';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->escape("CakePHP: 'Rapid Development Framework'");
$expected = "CakePHP: 'Rapid Development Framework'";
$this->assertEqual($result, $expected);
$result = $this->JsEngine->escape('my \\"string\\"');
$expected = 'my \\\\\\"string\\\\\\"';
$this->assertEqual($result, $expected);
}
/**
* test prompt() creation
*
* @return void
*/
function testPrompt() {
$result = $this->JsEngine->prompt('Hey, hey you', 'hi!');
$expected = 'prompt("Hey, hey you", "hi!");';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->prompt('"Hey"', '"hi"');
$expected = 'prompt("\"Hey\"", "\"hi\"");';
$this->assertEqual($result, $expected);
}
/**
* test alert generation
*
* @return void
*/
function testAlert() {
$result = $this->JsEngine->alert('Hey there');
$expected = 'alert("Hey there");';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->alert('"Hey"');
$expected = 'alert("\"Hey\"");';
$this->assertEqual($result, $expected);
}
/**
* test confirm generation
*
* @return void
*/
function testConfirm() {
$result = $this->JsEngine->confirm('Are you sure?');
$expected = 'confirm("Are you sure?");';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->confirm('"Are you sure?"');
$expected = 'confirm("\"Are you sure?\"");';
$this->assertEqual($result, $expected);
}
/**
* test Redirect
*
* @return void
*/
function testRedirect() {
$result = $this->JsEngine->redirect(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'window.location = "/posts/view/1";';
$this->assertEqual($result, $expected);
}
/**
* testObject encoding with non-native methods.
*
* @return void
*/
function testObject() {
$this->JsEngine->useNative = false;
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
$result = $this->JsEngine->object($object);
$expected = '{"title":"New thing","indexes":[5,6,7,8]}';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->object(array('default' => 0));
$expected = '{"default":0}';
$this->assertEqual($result, $expected);
$result = $this->JsEngine->object(array(
'2007' => array(
'Spring' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
),
'Fall' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
)
),
'2006' => array(
'Spring' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
),
'Fall' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
)
)
));
$expected = '{"2007":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}},"2006":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}}}';
$this->assertEqual($result, $expected);
foreach (array('true' => true, 'false' => false, 'null' => null) as $expected => $data) {
$result = $this->JsEngine->object($data);
$this->assertEqual($result, $expected);
}
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1)));
$result = $this->JsEngine->object($object, array('prefix' => 'PREFIX', 'postfix' => 'POSTFIX'));
$this->assertPattern('/^PREFIX/', $result);
$this->assertPattern('/POSTFIX$/', $result);
$this->assertNoPattern('/.PREFIX./', $result);
$this->assertNoPattern('/.POSTFIX./', $result);
}
/**
* test compatibility of JsBaseEngineHelper::object() vs. json_encode()
*
* @return void
*/
function testObjectAgainstJsonEncode() {
$skip = $this->skipIf(!function_exists('json_encode'), 'json_encode() not found, comparison tests skipped. %s');
if ($skip) {
return;
}
$this->JsEngine->useNative = false;
$data = array();
$data['mystring'] = "simple string";
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
$data['mystring'] = "strïng with spécial chârs";
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
$data['mystring'] = "a two lines\nstring";
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
$data['mystring'] = "a \t tabbed \t string";
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
$data['mystring'] = "a \"double-quoted\" string";
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
$data['mystring'] = 'a \\"double-quoted\\" string';
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
unset($data['mystring']);
$data[3] = array(1, 2, 3);
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
unset($data[3]);
$data = array('mystring' => null, 'bool' => false, 'array' => array(1, 44, 66));
$this->assertEqual(json_encode($data), $this->JsEngine->object($data));
}
/**
* test that JSON made with JsBaseEngineHelper::object() against json_decode()
*
* @return void
*/
function testObjectAgainstJsonDecode() {
$skip = $this->skipIf(!function_exists('json_encode'), 'json_encode() not found, comparison tests skipped. %s');
if ($skip) {
return;
}
$this->JsEngine->useNative = false;
$data = array("simple string");
$result = $this->JsEngine->object($data);
$this->assertEqual(json_decode($result), $data);
$data = array('my "string"');
$result = $this->JsEngine->object($data);
$this->assertEqual(json_decode($result), $data);
$data = array('my \\"string\\"');
$result = $this->JsEngine->object($data);
$this->assertEqual(json_decode($result), $data);
}
/**
* test Mapping of options.
*
* @return void
*/
function testOptionMapping() {
$JsEngine = new OptionEngineHelper();
$result = $JsEngine->testMap();
$this->assertEqual($result, array());
$result = $JsEngine->testMap(array('foo' => 'bar', 'baz' => 'sho'));
$this->assertEqual($result, array('foo' => 'bar', 'baz' => 'sho'));
$result = $JsEngine->testMap(array('complete' => 'myFunc', 'type' => 'json', 'update' => '#element'));
$this->assertEqual($result, array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'));
$result = $JsEngine->testMap(array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'));
$this->assertEqual($result, array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'));
}
/**
* test that option parsing escapes strings and saves what is supposed to be saved.
*
* @return void
*/
function testOptionParsing() {
$JsEngine = new OptionEngineHelper();
$result = $JsEngine->testParseOptions(array('url' => '/posts/view/1', 'key' => 1));
$expected = 'key:1, url:"\\/posts\\/view\\/1"';
$this->assertEqual($result, $expected);
$result = $JsEngine->testParseOptions(array('url' => '/posts/view/1', 'success' => 'doSuccess'), array('success'));
$expected = 'success:doSuccess, url:"\\/posts\\/view\\/1"';
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,354 @@
<?php
/**
* MooEngineTestCase
*
*
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright 2006-2010, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake.tests
* @subpackage cake.tests.cases.views.helpers
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Helper', array('Html', 'Js', 'MootoolsEngine'));
class MooEngineHelperTestCase extends CakeTestCase {
/**
* startTest
*
* @return void
*/
function startTest() {
$this->Moo =& new MootoolsEngineHelper();
}
/**
* end test
*
* @return void
*/
function endTest() {
unset($this->Moo);
}
/**
* test selector method
*
* @return void
*/
function testSelector() {
$result = $this->Moo->get('#content');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, '$("content")');
$result = $this->Moo->get('a .remove');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, '$$("a .remove")');
$result = $this->Moo->get('document');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, "$(document)");
$result = $this->Moo->get('window');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, "$(window)");
$result = $this->Moo->get('ul');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, '$$("ul")');
$result = $this->Moo->get('#some_long-id.class');
$this->assertEqual($result, $this->Moo);
$this->assertEqual($this->Moo->selection, '$$("#some_long-id.class")');
}
/**
* test event binding
*
* @return void
*/
function testEvent() {
$this->Moo->get('#myLink');
$result = $this->Moo->event('click', 'doClick', array('wrap' => false));
$expected = '$("myLink").addEvent("click", doClick);';
$this->assertEqual($result, $expected);
$result = $this->Moo->event('click', 'this.setStyle("display", "");', array('stop' => false));
$expected = '$("myLink").addEvent("click", function (event) {this.setStyle("display", "");});';
$this->assertEqual($result, $expected);
$result = $this->Moo->event('click', 'this.setStyle("display", "none");');
$expected = "\$(\"myLink\").addEvent(\"click\", function (event) {event.stop();\nthis.setStyle(\"display\", \"none\");});";
$this->assertEqual($result, $expected);
}
/**
* test dom ready event creation
*
* @return void
*/
function testDomReady() {
$result = $this->Moo->domReady('foo.name = "bar";');
$expected = 'window.addEvent("domready", function (event) {foo.name = "bar";});';
$this->assertEqual($result, $expected);
}
/**
* test Each method
*
* @return void
*/
function testEach() {
$this->Moo->get('#foo');
$result = $this->Moo->each('item.setStyle("display", "none");');
$expected = '$("foo").each(function (item, index) {item.setStyle("display", "none");});';
$this->assertEqual($result, $expected);
}
/**
* test Effect generation
*
* @return void
*/
function testEffect() {
$this->Moo->get('#foo');
$result = $this->Moo->effect('show');
$expected = '$("foo").setStyle("display", "");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('hide');
$expected = '$("foo").setStyle("display", "none");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('fadeIn');
$expected = '$("foo").fade("in");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('fadeOut');
$expected = '$("foo").fade("out");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('slideIn');
$expected = '$("foo").slide("in");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('slideOut');
$expected = '$("foo").slide("out");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('slideOut', array('speed' => 'fast'));
$expected = '$("foo").set("slide", {duration:"short"}).slide("out");';
$this->assertEqual($result, $expected);
$result = $this->Moo->effect('slideOut', array('speed' => 'slow'));
$expected = '$("foo").set("slide", {duration:"long"}).slide("out");';
$this->assertEqual($result, $expected);
}
/**
* Test Request Generation
*
* @return void
*/
function testRequest() {
$result = $this->Moo->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'var jsRequest = new Request({url:"\\/posts\\/view\\/1"}).send();';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/posts/view/1', array('update' => 'content'));
$expected = 'var jsRequest = new Request.HTML({update:"content", url:"\\/posts\\/view\\/1"}).send();';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.JSON({method:"post", onComplete:doSuccess, onFailure:handleError, url:"\\/people\\/edit\\/1"}).send({"name":"jim","height":"185cm"});';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'update' => '#update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'doFailure',
'before' => 'doBefore',
'update' => 'update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doComplete, onFailure:doFailure, onRequest:doBefore, onSuccess:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'doFailure',
'before' => 'doBefore',
'update' => 'update-zone',
'dataExpression' => true,
'data' => '$("foo").toQueryString()',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doComplete, onFailure:doFailure, onRequest:doBefore, onSuccess:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send($("foo").toQueryString());';
$this->assertEqual($result, $expected);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore',
'success' => 'doSuccess',
'complete' => 'doComplete',
'update' => '#update-zone',
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:function () {doComplete}, onRequest:function () {doBefore}, onSuccess:function (responseText, responseXML) {doSuccess}, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEqual($result, $expected);
}
/**
* test sortable list generation
*
* @return void
*/
function testSortable() {
$this->Moo->get('#myList');
$result = $this->Moo->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = 'var jsSortable = new Sortables($("myList"), {constrain:"parent", onComplete:onStop, onSort:onSort, onStart:onStart, snap:5});';
$this->assertEqual($result, $expected);
}
/**
* test drag() method
*
* @return void
*/
function testDrag() {
$this->Moo->get('#drag-me');
$result = $this->Moo->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10,10),
'wrapCallbacks' => false
));
$expected = '$("drag-me").makeDraggable({onComplete:onStop, onDrag:onDrag, onStart:onStart, snap:[10,10]});';
$this->assertEqual($result, $expected);
}
/**
* test drop() method
*
* @return void
*/
function testDrop() {
$this->expectError();
$this->Moo->get('#drop-me');
$this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
));
$result = $this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
'drag' => '#my-drag',
'wrapCallbacks' => false
));
$expected = '$("my-drag").makeDraggable({droppables:$("drop-me"), onDrop:onDrop, onEnter:onHover, onLeave:onLeave});';
$this->assertEqual($result, $expected);
$this->assertEqual($this->Moo->selection, '$("drop-me")');
$result = $this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
'drag' => '#my-drag',
));
$expected = '$("my-drag").makeDraggable({droppables:$("drop-me"), onDrop:function (element, droppable, event) {onDrop}, onEnter:function (element, droppable) {onHover}, onLeave:function (element, droppable) {onLeave}});';
$this->assertEqual($result, $expected);
}
/**
* test slider generation
*
* @return void
*/
function testSlider() {
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'onComplete',
'change' => 'onChange',
'direction' => 'horizontal',
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:onChange, onComplete:onComplete});';
$this->assertEqual($result, $expected);
$this->assertEqual($this->Moo->selection, '$("slider")');
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'onComplete',
'change' => 'onChange',
'direction' => 'horizontal',
'min' => 10,
'max' => 40,
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:onChange, onComplete:onComplete, range:[10,40]});';
$this->assertEqual($result, $expected);
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'complete;',
'change' => 'change;',
'direction' => 'horizontal',
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:function (step) {change;}, onComplete:function (event) {complete;}});';
$this->assertEqual($result, $expected);
}
/**
* test the serializeForm implementation.
*
* @return void
*/
function testSerializeForm() {
$this->Moo->get('#element');
$result = $this->Moo->serializeForm(array('isForm' => true));
$expected = '$("element").toQueryString();';
$this->assertEqual($result, $expected);
$result = $this->Moo->serializeForm(array('isForm' => true, 'inline' => true));
$expected = '$("element").toQueryString()';
$this->assertEqual($result, $expected);
$result = $this->Moo->serializeForm(array('isForm' => false));
$expected = '$($("element").form).toQueryString();';
$this->assertEqual($result, $expected);
$result = $this->Moo->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$($("element").form).toQueryString()';
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,432 @@
<?php
/**
* NumberHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Helper', 'Number');
/**
* NumberHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class NumberHelperTest extends CakeTestCase {
/**
* helper property
*
* @var mixed null
* @access public
*/
var $helper = null;
/**
* setUp method
*
* @access public
* @return void
*/
function startTest() {
$this->Number =& new NumberHelper();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function endTest() {
unset($this->Number);
}
/**
* testFormatAndCurrency method
*
* @access public
* @return void
*/
function testFormat() {
$value = '100100100';
$result = $this->Number->format($value, '#');
$expected = '#100,100,100';
$this->assertEqual($expected, $result);
$result = $this->Number->format($value, 3);
$expected = '100,100,100.000';
$this->assertEqual($expected, $result);
$result = $this->Number->format($value);
$expected = '100,100,100';
$this->assertEqual($expected, $result);
$result = $this->Number->format($value, '-');
$expected = '100-100-100';
$this->assertEqual($expected, $result);
}
/**
* Test currency method.
*
* @access public
* @return void
*/
function testCurrency() {
$value = '100100100';
$result = $this->Number->currency($value);
$expected = '$100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, '#');
$expected = '#100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, false);
$expected = '100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'USD');
$expected = '$100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, '', array('thousands' =>' ', 'after' => '€', 'decimals' => ',', 'zero' => 'Gratuit'));
$expected = '100 100 100,00€';
$this->assertEqual($expected, $result);
$result = $this->Number->currency(1000.45, NULL, array('after'=>'øre','before'=>'Kr. ','decimals'=>',','thousands'=>'.'));
$expected = 'Kr. 1.000,45';
$this->assertEqual($expected,$result);
$result = $this->Number->currency(0.5, 'USD');
$expected = '50c';
$this->assertEqual($expected,$result);
$result = $this->Number->currency(0.5, NULL, array('after'=>'øre'));
$expected = '50øre';
$this->assertEqual($expected,$result);
}
/**
* Test adding currency format options to the number helper
*
* @access public
* @return void
*/
function testCurrencyAddFormat() {
$this->Number->addFormat('NOK', array('before' => 'Kr. '));
$result = $this->Number->currency(1000, 'NOK');
$expected = 'Kr. 1,000.00';
$this->assertEqual($expected,$result);
$this->Number->addFormat('Other', array('before' => '$$ ', 'after' => 'c!'));
$result = $this->Number->currency(0.22, 'Other');
$expected = '22c!';
$this->assertEqual($expected,$result);
$result = $this->Number->currency(-10, 'Other');
$expected = '($$ 10.00)';
$this->assertEqual($expected,$result);
}
/**
* testCurrencyPositive method
*
* @access public
* @return void
*/
function testCurrencyPositive() {
$value = '100100100';
$result = $this->Number->currency($value);
$expected = '$100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'USD', array('before'=> '#'));
$expected = '#100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, false);
$expected = '100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'USD');
$expected = '$100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$this->assertEqual($expected, $result);
}
/**
* testCurrencyNegative method
*
* @access public
* @return void
*/
function testCurrencyNegative() {
$value = '-100100100';
$result = $this->Number->currency($value);
$expected = '($100,100,100.00)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;100.100.100,00)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(&#163;100,100,100.00)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'USD', array('negative'=>'-'));
$expected = '-$100,100,100.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative'=>'-'));
$expected = '-&#8364;100.100.100,00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative'=>'-'));
$expected = '-&#163;100,100,100.00';
$this->assertEqual($expected, $result);
}
/**
* testCurrencyCentsPositive method
*
* @access public
* @return void
*/
function testCurrencyCentsPositive() {
$value = '0.99';
$result = $this->Number->currency($value, 'USD');
$expected = '99c';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,99';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '99p';
$this->assertEqual($expected, $result);
}
/**
* testCurrencyCentsNegative method
*
* @access public
* @return void
*/
function testCurrencyCentsNegative() {
$value = '-0.99';
$result = $this->Number->currency($value, 'USD');
$expected = '(99c)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;0,99)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(99p)';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'USD', array('negative'=>'-'));
$expected = '-99c';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative'=>'-'));
$expected = '-&#8364;0,99';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative'=>'-'));
$expected = '-99p';
$this->assertEqual($expected, $result);
}
/**
* testCurrencyZero method
*
* @access public
* @return void
*/
function testCurrencyZero() {
$value = '0';
$result = $this->Number->currency($value, 'USD');
$expected = '$0.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;0.00';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('zero' => 'FREE!'));
$expected = 'FREE!';
$this->assertEqual($expected, $result);
}
/**
* testCurrencyOptions method
*
* @access public
* @return void
*/
function testCurrencyOptions() {
$value = '1234567.89';
$result = $this->Number->currency($value, null, array('before' => 'GBP'));
$expected = 'GBP1,234,567.89';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('places' => 0));
$expected = '&#163;1,234,568';
$this->assertEqual($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('escape' => true));
$expected = '&amp;#163;1,234,567.89';
$this->assertEqual($expected, $result);
$result = $this->Number->currency('0.35', 'USD', array('after' => false));
$expected = '$0.35';
$this->assertEqual($expected, $result);
$result = $this->Number->currency('0.35', 'GBP', array('after' => false));
$expected = '&#163;0.35';
$this->assertEqual($expected, $result);
$result = $this->Number->currency('0.35', 'GBP');
$expected = '35p';
$this->assertEqual($expected, $result);
$result = $this->Number->currency('0.35', 'EUR');
$expected = '&#8364;0,35';
$this->assertEqual($expected, $result);
}
/**
* testToReadableSize method
*
* @access public
* @return void
*/
function testToReadableSize() {
$result = $this->Number->toReadableSize(0);
$expected = '0 Bytes';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1);
$expected = '1 Byte';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(45);
$expected = '45 Bytes';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1023);
$expected = '1023 Bytes';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024);
$expected = '1 KB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*512);
$expected = '512 KB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024-1);
$expected = '1.00 MB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*512);
$expected = '512.00 MB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024-1);
$expected = '1.00 GB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024*512);
$expected = '512.00 GB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024*1024-1);
$expected = '1.00 TB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024*1024*512);
$expected = '512.00 TB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024*1024*1024-1);
$expected = '1024.00 TB';
$this->assertEqual($expected, $result);
$result = $this->Number->toReadableSize(1024*1024*1024*1024*1024*1024);
$expected = (1024 * 1024) . '.00 TB';
$this->assertEqual($expected, $result);
}
/**
* testToPercentage method
*
* @access public
* @return void
*/
function testToPercentage() {
$result = $this->Number->toPercentage(45, 0);
$expected = '45%';
$this->assertEqual($result, $expected);
$result = $this->Number->toPercentage(45, 2);
$expected = '45.00%';
$this->assertEqual($result, $expected);
$result = $this->Number->toPercentage(0, 0);
$expected = '0%';
$this->assertEqual($result, $expected);
$result = $this->Number->toPercentage(0, 4);
$expected = '0.0000%';
$this->assertEqual($result, $expected);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,380 @@
<?php
/**
* PrototypeEngine TestCase
*
* PHP versions 4 and 5
*
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
* Copyright 2006-2010, Cake Software Foundation, Inc.
* 1785 E. Sahara Avenue, Suite 490-204
* Las Vegas, Nevada 89104
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2006-2010, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package cake.tests
* @subpackage cake.tests.cases.views.helpers
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::import('Helper', array('Html', 'Js', 'PrototypeEngine'));
class PrototypeEngineHelperTestCase extends CakeTestCase {
/**
* startTest
*
* @return void
*/
function startTest() {
$this->Proto =& new PrototypeEngineHelper();
}
/**
* end test
*
* @return void
*/
function endTest() {
unset($this->Proto);
}
/**
* test selector method
*
* @return void
*/
function testSelector() {
$result = $this->Proto->get('#content');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, '$("content")');
$result = $this->Proto->get('a .remove');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, '$$("a .remove")');
$result = $this->Proto->get('document');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, "$(document)");
$result = $this->Proto->get('window');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, "$(window)");
$result = $this->Proto->get('ul');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, '$$("ul")');
$result = $this->Proto->get('#some_long-id.class');
$this->assertEqual($result, $this->Proto);
$this->assertEqual($this->Proto->selection, '$$("#some_long-id.class")');
}
/**
* test event binding
*
* @return void
*/
function testEvent() {
$this->Proto->get('#myLink');
$result = $this->Proto->event('click', 'doClick', array('wrap' => false));
$expected = '$("myLink").observe("click", doClick);';
$this->assertEqual($result, $expected);
$result = $this->Proto->event('click', 'Element.hide(this);', array('stop' => false));
$expected = '$("myLink").observe("click", function (event) {Element.hide(this);});';
$this->assertEqual($result, $expected);
$result = $this->Proto->event('click', 'Element.hide(this);');
$expected = "\$(\"myLink\").observe(\"click\", function (event) {event.stop();\nElement.hide(this);});";
$this->assertEqual($result, $expected);
}
/**
* test dom ready event creation
*
* @return void
*/
function testDomReady() {
$result = $this->Proto->domReady('foo.name = "bar";');
$expected = 'document.observe("dom:loaded", function (event) {foo.name = "bar";});';
$this->assertEqual($result, $expected);
}
/**
* test Each method
*
* @return void
*/
function testEach() {
$this->Proto->get('#foo li');
$result = $this->Proto->each('item.hide();');
$expected = '$$("#foo li").each(function (item, index) {item.hide();});';
$this->assertEqual($result, $expected);
}
/**
* test Effect generation
*
* @return void
*/
function testEffect() {
$this->Proto->get('#foo');
$result = $this->Proto->effect('show');
$expected = '$("foo").show();';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('hide');
$expected = '$("foo").hide();';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeIn');
$expected = '$("foo").appear();';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeIn', array('speed' => 'fast'));
$expected = '$("foo").appear({duration:0.50000000000});';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeIn', array('speed' => 'slow'));
$expected = '$("foo").appear({duration:2});';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeOut');
$expected = '$("foo").fade();';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeOut', array('speed' => 'fast'));
$expected = '$("foo").fade({duration:0.50000000000});';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('fadeOut', array('speed' => 'slow'));
$expected = '$("foo").fade({duration:2});';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('slideIn');
$expected = 'Effect.slideDown($("foo"));';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('slideOut');
$expected = 'Effect.slideUp($("foo"));';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('slideOut', array('speed' => 'fast'));
$expected = 'Effect.slideUp($("foo"), {duration:0.50000000000});';
$this->assertEqual($result, $expected);
$result = $this->Proto->effect('slideOut', array('speed' => 'slow'));
$expected = 'Effect.slideUp($("foo"), {duration:2});';
$this->assertEqual($result, $expected);
}
/**
* Test Request Generation
*
* @return void
*/
function testRequest() {
$result = $this->Proto->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1");';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/posts/view/1', array(
'method' => 'post',
'complete' => 'doComplete',
'before' => 'doBefore',
'success' => 'doSuccess',
'error' => 'doError',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1", {method:"post", onComplete:doComplete, onCreate:doBefore, onFailure:doError, onSuccess:doSuccess, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/posts/view/1', array('update' => 'content'));
$expected = 'var jsRequest = new Ajax.Updater("content", "/posts/view/1");';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'update' => '#update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Updater("update-zone", "/people/edit/1", {method:"post", onComplete:doSuccess});';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => '$("element").serialize()',
'dataExpression' => true,
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:$("element").serialize()});';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEqual($result, $expected);
$result = $this->Proto->request('/people/edit/1', array(
'async' => false,
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {asynchronous:false, method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEqual($result, $expected);
$this->Proto->get('#submit');
$result = $this->Proto->request('/users/login', array(
'before' => 'login.create(event)',
'complete' => 'login.complete(event)',
'update' => 'auth',
'data' => $this->Proto->serializeForm(array('isForm' => false, 'inline' => true)),
'dataExpression' => true
));
$this->assertTrue(strpos($result, '$($("submit").form).serialize()') > 0);
$this->assertFalse(strpos($result, 'parameters:function () {$($("submit").form).serialize()}') > 0);
}
/**
* test sortable list generation
*
* @return void
*/
function testSortable() {
$this->Proto->get('#myList');
$result = $this->Proto->sortable(array(
'distance' => 5,
'start' => 'onStart',
'complete' => 'onComplete',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = 'var jsSortable = Sortable.create($("myList"), {onChange:onSort, onStart:onStart, onUpdate:onComplete, snap:5});';
$this->assertEqual($result, $expected);
}
/**
* test drag() method. Scriptaculous lacks the ability to take an Array of Elements
* in new Drag() when selection is a multiple type. Iterate over the array.
*
* @return void
*/
function testDrag() {
$this->Proto->get('#element');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = 'var jsDrag = new Draggable($("element"), {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});';
$this->assertEqual($result, $expected);
$this->Proto->get('div.dragger');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = '$$("div.dragger").each(function (item, index) {new Draggable(item, {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});});';
$this->assertEqual($result, $expected);
}
/**
* test drop() method
*
* @return void
*/
function testDrop() {
$this->Proto->get('#element');
$result = $this->Proto->drop(array(
'hover' => 'onHover',
'drop' => 'onDrop',
'accept' => '.drag-me',
'wrapCallbacks' => false
));
$expected = 'Droppables.add($("element"), {accept:".drag-me", onDrop:onDrop, onHover:onHover});';
$this->assertEqual($result, $expected);
}
/**
* ensure that slider() method behaves properly
*
* @return void
*/
function testSlider() {
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'direction' => 'horizontal',
'change' => 'onChange',
'complete' => 'onComplete',
'value' => 4,
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {axis:"horizontal", onChange:onComplete, onSlide:onChange, sliderValue:4});';
$this->assertEqual($result, $expected);
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'change' => 'change();',
'complete' => 'complete();',
'value' => 4
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {onChange:function (value) {complete();}, onSlide:function (value) {change();}, sliderValue:4});';
$this->assertEqual($result, $expected);
}
/**
* test the serializeForm implementation.
*
* @return void
*/
function testSerializeForm() {
$this->Proto->get('#element');
$result = $this->Proto->serializeForm(array('isForm' => true));
$expected = '$("element").serialize();';
$this->assertEqual($result, $expected);
$result = $this->Proto->serializeForm(array('isForm' => true, 'inline' => true));
$expected = '$("element").serialize()';
$this->assertEqual($result, $expected);
$result = $this->Proto->serializeForm(array('isForm' => false));
$expected = '$($("element").form).serialize();';
$this->assertEqual($result, $expected);
$result = $this->Proto->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$($("element").form).serialize()';
$this->assertEqual($result, $expected);
}
}

View File

@@ -0,0 +1,593 @@
<?php
/**
* RssHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Helper', array('Rss', 'Time'));
/**
* RssHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class RssHelperTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Rss =& new RssHelper();
$this->Rss->Time =& new TimeHelper();
$this->Rss->beforeRender();
$manager =& XmlManager::getInstance();
$manager->namespaces = array();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Rss);
}
/**
* testAddNamespace method
*
* @access public
* @return void
*/
function testAddNamespace() {
$this->Rss->addNs('custom', 'http://example.com/dtd.xml');
$manager =& XmlManager::getInstance();
$expected = array('custom' => 'http://example.com/dtd.xml');
$this->assertEqual($manager->namespaces, $expected);
$this->Rss->removeNs('custom');
$this->Rss->addNs('dummy', 'http://dummy.com/1.0/');
$result = $this->Rss->document();
$expected = array(
'rss' => array(
'xmlns:dummy' => 'http://dummy.com/1.0/',
'version' => '2.0'
)
);
$this->assertTags($result, $expected);
$this->Rss->removeNs('dummy');
}
/**
* testRemoveNamespace method
*
* @access public
* @return void
*/
function testRemoveNamespace() {
$this->Rss->addNs('custom', 'http://example.com/dtd.xml');
$this->Rss->addNs('custom2', 'http://example.com/dtd2.xml');
$manager =& XmlManager::getInstance();
$expected = array('custom' => 'http://example.com/dtd.xml', 'custom2' => 'http://example.com/dtd2.xml');
$this->assertEqual($manager->namespaces, $expected);
$this->Rss->removeNs('custom');
$expected = array('custom2' => 'http://example.com/dtd2.xml');
$this->assertEqual($manager->namespaces, $expected);
}
/**
* testDocument method
*
* @access public
* @return void
*/
function testDocument() {
$result = $this->Rss->document();
$expected = array(
'rss' => array(
'version' => '2.0'
)
);
$this->assertTags($result, $expected);
$result = $this->Rss->document(array('contrived' => 'parameter'));
$expected = array(
'rss' => array(
'version' => '2.0'
),
'<parameter'
);
$this->assertTags($result, $expected);
$result = $this->Rss->document(null, 'content');
$expected = array(
'rss' => array(
'version' => '2.0'
),
'content'
);
$this->assertTags($result, $expected);
$result = $this->Rss->document(array('contrived' => 'parameter'), 'content');
$expected = array(
'rss' => array(
'contrived' => 'parameter',
'version' => '2.0'
),
'content'
);
$this->assertTags($result, $expected);
}
/**
* testChannel method
*
* @access public
* @return void
*/
function testChannel() {
$attrib = array('a' => '1', 'b' => '2');
$elements = array('title' => 'title');
$content = 'content';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'channel' => array(
'a' => '1',
'b' => '2'
),
'<title',
'title',
'/title',
'<link',
RssHelper::url('/', true),
'/link',
'<description',
'content',
'/channel'
);
$this->assertTags($result, $expected);
}
/**
* test correct creation of channel sub elements.
*
* @access public
* @return void
*/
function testChannelElements() {
$attrib = array();
$elements = array(
'title' => 'Title of RSS Feed',
'link' => 'http://example.com',
'description' => 'Description of RSS Feed',
'image' => array(
'title' => 'Title of image',
'url' => 'http://example.com/example.png',
'link' => 'http://example.com'
),
'cloud' => array(
'domain' => "rpc.sys.com",
'port' => "80",
'path' =>"/RPC2",
'registerProcedure' => "myCloud.rssPleaseNotify",
'protocol' => "xml-rpc"
)
);
$content = 'content-here';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'<channel',
'<title', 'Title of RSS Feed', '/title',
'<link', 'http://example.com', '/link',
'<description', 'Description of RSS Feed', '/description',
'<image',
'<title', 'Title of image', '/title',
'<url', 'http://example.com/example.png', '/url',
'<link', 'http://example.com', '/link',
'/image',
'cloud' => array(
'domain' => "rpc.sys.com",
'port' => "80",
'path' =>"/RPC2",
'registerProcedure' => "myCloud.rssPleaseNotify",
'protocol' => "xml-rpc"
),
'content-here',
'/channel',
);
$this->assertTags($result, $expected);
}
function testChannelElementAttributes() {
$attrib = array();
$elements = array(
'title' => 'Title of RSS Feed',
'link' => 'http://example.com',
'description' => 'Description of RSS Feed',
'image' => array(
'title' => 'Title of image',
'url' => 'http://example.com/example.png',
'link' => 'http://example.com'
),
'atom:link' => array(
'attrib' => array(
'href' => 'http://www.example.com/rss.xml',
'rel' => 'self',
'type' => 'application/rss+xml')
)
);
$content = 'content-here';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'<channel',
'<title', 'Title of RSS Feed', '/title',
'<link', 'http://example.com', '/link',
'<description', 'Description of RSS Feed', '/description',
'<image',
'<title', 'Title of image', '/title',
'<url', 'http://example.com/example.png', '/url',
'<link', 'http://example.com', '/link',
'/image',
'atom:link' => array(
'href' => "http://www.example.com/rss.xml",
'rel' => "self",
'type' =>"application/rss+xml"
),
'content-here',
'/channel',
);
$this->assertTags($result, $expected);
}
/**
* testItems method
*
* @access public
* @return void
*/
function testItems() {
$items = array(
array('title' => 'title1', 'guid' => 'http://www.example.com/guid1', 'link' => 'http://www.example.com/link1', 'description' => 'description1'),
array('title' => 'title2', 'guid' => 'http://www.example.com/guid2', 'link' => 'http://www.example.com/link2', 'description' => 'description2'),
array('title' => 'title3', 'guid' => 'http://www.example.com/guid3', 'link' => 'http://www.example.com/link3', 'description' => 'description3')
);
$result = $this->Rss->items($items);
$expected = array(
'<item',
'<title', 'title1', '/title',
'<guid', 'http://www.example.com/guid1', '/guid',
'<link', 'http://www.example.com/link1', '/link',
'<description', 'description1', '/description',
'/item',
'<item',
'<title', 'title2', '/title',
'<guid', 'http://www.example.com/guid2', '/guid',
'<link', 'http://www.example.com/link2', '/link',
'<description', 'description2', '/description',
'/item',
'<item',
'<title', 'title3', '/title',
'<guid', 'http://www.example.com/guid3', '/guid',
'<link', 'http://www.example.com/link3', '/link',
'<description', 'description3', '/description',
'/item'
);
$this->assertTags($result, $expected);
$result = $this->Rss->items(array());
$expected = '';
$this->assertEqual($result, $expected);
}
/**
* testItem method
*
* @access public
* @return void
*/
function testItem() {
$item = array(
'title' => 'My title',
'description' => 'My description',
'link' => 'http://www.google.com/'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My title',
'/title',
'<description',
'My description',
'/description',
'<link',
'http://www.google.com/',
'/link',
'<guid',
'http://www.google.com/',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title',
'cdata' => true,
),
'link' => 'http://www.example.com/1',
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'pubDate' => '2008-05-31 12:00:00',
'guid' => 'http://www.example.com/1'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title]]',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<guid',
'http://www.example.com/1',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'cdata' => true
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title &amp; more]]',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'convertEntities' => false
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My Title & more',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title & more',
'cdata' => true,
'convertEntities' => false,
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title & more]]',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'category' => array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'category' => array(
array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
),
array(
'value' => 'Bakery',
'cdata' => true
)
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'<category',
'<![CDATA[Bakery]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title',
'cdata' => true,
),
'link' => 'http://www.example.com/1',
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'enclosure' => array(
'url' => '/test.flv'
),
'pubDate' => '2008-05-31 12:00:00',
'guid' => 'http://www.example.com/1',
'category' => array(
array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
),
array(
'value' => 'Bakery',
'cdata' => true
)
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title]]',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'enclosure' => array('url' => RssHelper::url('/test.flv', true)),
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<guid',
'http://www.example.com/1',
'/guid',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'<category',
'<![CDATA[Bakery]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'Foo bar',
'link' => array(
'url' => 'http://example.com/foo?a=1&b=2',
'convertEntities' => false
),
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'pubDate' => '2008-05-31 12:00:00'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'Foo bar',
'/title',
'<link',
'http://example.com/foo?a=1&amp;b=2',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<guid',
'http://example.com/foo?a=1&amp;b=2',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
}
/**
* testTime method
*
* @access public
* @return void
*/
function testTime() {
}
/**
* testElementAttrNotInParent method
*
* @access public
* @return void
*/
function testElementAttrNotInParent() {
$attributes = array(
'title' => 'Some Title',
'link' => 'http://link.com',
'description' => 'description'
);
$elements = array('enclosure' => array('url' => 'http://test.com'));
$result = $this->Rss->item($attributes, $elements);
$expected = array(
'item' => array(
'title' => 'Some Title',
'link' => 'http://link.com',
'description' => 'description'
),
'enclosure' => array(
'url' => 'http://test.com'
),
'/item'
);
$this->assertTags($result, $expected);
}
}

View File

@@ -0,0 +1,236 @@
<?php
/**
* SessionHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
if (!defined('CAKEPHP_UNIT_TEST_EXECUTION')) {
define('CAKEPHP_UNIT_TEST_EXECUTION', 1);
}
App::import('Core', array('Helper', 'AppHelper', 'Controller', 'View'));
App::import('Helper', array('Session'));
/**
* SessionHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class SessionHelperTest extends CakeTestCase {
/**
* setUp method
*
* @access public
* @return void
*/
function startTest() {
$this->Session = new SessionHelper();
$_SESSION = array(
'test' => 'info',
'Message' => array(
'flash' => array(
'element' => 'default',
'params' => array(),
'message' => 'This is a calling'
),
'notification' => array(
'element' => 'session_helper',
'params' => array('title' => 'Notice!', 'name' => 'Alert!'),
'message' => 'This is a test of the emergency broadcasting system',
),
'classy' => array(
'element' => 'default',
'params' => array('class' => 'positive'),
'message' => 'Recorded'
),
'bare' => array(
'element' => null,
'message' => 'Bare message',
'params' => array(),
),
),
'Deeply' => array('nested' => array('key' => 'value')),
);
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
$_SESSION = array();
unset($this->Session);
}
/**
* endTest
*
* @access public
* @return void
*/
function endTest() {
App::build();
}
/**
* test construction and initial property settings
*
* @return void
*/
function testConstruct() {
$this->assertFalse(empty($this->Session->sessionTime));
$this->assertFalse(empty($this->Session->security));
}
/**
* testRead method
*
* @access public
* @return void
*/
function testRead() {
$result = $this->Session->read('Deeply.nested.key');
$this->assertEqual($result, 'value');
$result = $this->Session->read('test');
$this->assertEqual($result, 'info');
}
/**
* testCheck method
*
* @access public
* @return void
*/
function testCheck() {
$this->assertTrue($this->Session->check('test'));
$this->assertTrue($this->Session->check('Message.flash.element'));
$this->assertFalse($this->Session->check('Does.not.exist'));
$this->assertFalse($this->Session->check('Nope'));
}
/**
* testWrite method
*
* @access public
* @return void
*/
function testWrite() {
$this->expectError();
$this->Session->write('NoWay', 'AccessDenied');
}
/**
* testFlash method
*
* @access public
* @return void
*/
function testFlash() {
$result = $this->Session->flash('flash', true);
$expected = '<div id="flashMessage" class="message">This is a calling</div>';
$this->assertEqual($result, $expected);
$this->assertFalse($this->Session->check('Message.flash'));
$expected = '<div id="classyMessage" class="positive">Recorded</div>';
$result = $this->Session->flash('classy', true);
$this->assertEqual($result, $expected);
App::build(array(
'views' => array(TEST_CAKE_CORE_INCLUDE_PATH . 'tests' . DS . 'test_app' . DS . 'views'. DS)
));
$controller = new Controller();
$this->Session->view = new View($controller);
$result = $this->Session->flash('notification', true);
$result = str_replace("\r\n", "\n", $result);
$expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a test of the emergency broadcasting system</p>\n</div>";
$this->assertEqual($result, $expected);
$this->assertFalse($this->Session->check('Message.notification'));
$result = $this->Session->flash('bare');
$expected = 'Bare message';
$this->assertEqual($result, $expected);
$this->assertFalse($this->Session->check('Message.bare'));
}
/**
* testID method
*
* @access public
* @return void
*/
function testID() {
$id = session_id();
$result = $this->Session->id();
$this->assertEqual($id, $result);
}
/**
* testError method
*
* @access public
* @return void
*/
function testError() {
$result = $this->Session->error();
$this->assertFalse($result);
$this->Session->read('CauseError');
$result = $this->Session->error();
$expected = "CauseError doesn't exist";
$this->assertEqual($result, $expected);
}
/**
* testDisabling method
*
* @access public
* @return void
*/
function testDisabling() {
Configure::write('Session.start', false);
$this->Session = new SessionHelper();
$this->assertFalse($this->Session->check('test'));
$this->assertFalse($this->Session->read('test'));
$this->Session->read('CauseError');
$this->assertFalse($this->Session->error());
ob_start();
$this->assertFalse($this->Session->flash('bare'));
$result = ob_get_contents();
ob_clean();
$this->assertFalse($result);
}
/**
* testValid method
*
* @access public
* @return void
*/
function testValid() {
//wierd it always ends up false in the test suite
//$this->assertFalse($this->Session->valid());
}
}

View File

@@ -0,0 +1,414 @@
<?php
/**
* TextHelperTest 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.view.helpers
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/opengroup.php The Open Group Test Suite License
*/
App::import('Helper', 'Text');
/**
* TextHelperTest class
*
* @package cake
* @subpackage cake.tests.cases.libs.view.helpers
*/
class TextHelperTest extends CakeTestCase {
/**
* helper property
*
* @var mixed null
* @access public
*/
var $helper = null;
/**
* setUp method
*
* @access public
* @return void
*/
function setUp() {
$this->Text = new TextHelper();
}
/**
* tearDown method
*
* @access public
* @return void
*/
function tearDown() {
unset($this->Text);
}
/**
* testTruncate method
*
* @access public
* @return void
*/
function testTruncate() {
$text1 = 'The quick brown fox jumps over the lazy dog';
$text2 = 'Heiz&ouml;lr&uuml;cksto&szlig;abd&auml;mpfung';
$text3 = '<b>&copy; 2005-2007, Cake Software Foundation, Inc.</b><br />written by Alexander Wegener';
$text4 = '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Great, or?';
$text5 = '0<b>1<i>2<span class="myclass">3</span>4<u>5</u>6</i>7</b>8<b>9</b>0';
$text6 = '<p><strong>Extra dates have been announced for this year\'s tour.</strong></p><p>Tickets for the new shows in</p>';
$text7 = 'El moño está en el lugar correcto. Eso fue lo que dijo la niña, ¿habrá dicho la verdad?';
$text8 = 'Vive la R'.chr(195).chr(169).'publique de France';
$text9 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь';
$this->assertIdentical($this->Text->truncate($text1, 15), 'The quick br...');
$this->assertIdentical($this->Text->truncate($text1, 15, array('exact' => false)), 'The quick...');
$this->assertIdentical($this->Text->truncate($text1, 100), 'The quick brown fox jumps over the lazy dog');
$this->assertIdentical($this->Text->truncate($text2, 10), 'Heiz&ou...');
$this->assertIdentical($this->Text->truncate($text2, 10, array('exact' => false)), '...');
$this->assertIdentical($this->Text->truncate($text3, 20), '<b>&copy; 2005-20...');
$this->assertIdentical($this->Text->truncate($text4, 15), '<img src="my...');
$this->assertIdentical($this->Text->truncate($text5, 6, array('ending' => '')), '0<b>1<');
$this->assertIdentical($this->Text->truncate($text1, 15, array('html' => true)), 'The quick br...');
$this->assertIdentical($this->Text->truncate($text1, 15, array('exact' => false, 'html' => true)), 'The quick...');
$this->assertIdentical($this->Text->truncate($text2, 10, array('html' => true)), 'Heiz&ouml;lr...');
$this->assertIdentical($this->Text->truncate($text2, 10, array('exact' => false, 'html' => true)), '...');
$this->assertIdentical($this->Text->truncate($text3, 20, array('html' => true)), '<b>&copy; 2005-2007, Cake...</b>');
$this->assertIdentical($this->Text->truncate($text4, 15, array('html' => true)), '<img src="mypic.jpg"> This image ...');
$this->assertIdentical($this->Text->truncate($text4, 45, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But t...</b>');
$this->assertIdentical($this->Text->truncate($text4, 90, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Grea...');
$this->assertIdentical($this->Text->truncate($text5, 6, array('ending' => '', 'html' => true)), '0<b>1<i>2<span class="myclass">3</span>4<u>5</u></i></b>');
$this->assertIdentical($this->Text->truncate($text5, 20, array('ending' => '', 'html' => true)), $text5);
$this->assertIdentical($this->Text->truncate($text6, 57, array('exact' => false, 'html' => true)), "<p><strong>Extra dates have been announced for this year's...</strong></p>");
$this->assertIdentical($this->Text->truncate($text7, 255), $text7);
$this->assertIdentical($this->Text->truncate($text7, 15), 'El moño está...');
$this->assertIdentical($this->Text->truncate($text8, 15), 'Vive la R'.chr(195).chr(169).'pu...');
$this->assertIdentical($this->Text->truncate($text9, 10), 'НОПРСТУ...');
}
/**
* testHighlight method
*
* @access public
* @return void
*/
function testHighlight() {
$text = 'This is a test text';
$phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$expected = '<b>This</b> is a test <b>text</b>';
$this->assertEqual($expected, $result);
$text = 'This is a test text';
$phrases = null;
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEqual($result, $text);
$text = 'Ich saß in einem Café am Übergang';
$expected = 'Ich <b>saß</b> in einem <b>Café</b> am <b>Übergang</b>';
$phrases = array('saß', 'café', 'übergang');
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEqual($result, $expected);
}
/**
* testHighlightHtml method
*
* @access public
* @return void
*/
function testHighlightHtml() {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>';
$text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>';
$text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$text4 = 'What a strong mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$options = array('format' => '<b>\1</b>', 'html' => true);
$expected = '<p><b>strong</b>bow isn&rsquo;t real cider</p>';
$this->assertEqual($this->Text->highlight($text1, 'strong', $options), $expected);
$expected = '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>';
$this->assertEqual($this->Text->highlight($text2, 'strong', $options), $expected);
$this->assertEqual($this->Text->highlight($text3, 'strong', $options), $text3);
$this->assertEqual($this->Text->highlight($text3, array('strong', 'what'), $options), $text3);
$expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEqual($this->Text->highlight($text4, array('strong', 'what'), $options), $expected);
}
/**
* testHighlightMulti method
*
* @access public
* @return void
*/
function testHighlightMulti() {
$text = 'This is a test text';
$phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, array('format' => array('<b>\1</b>', '<em>\1</em>')));
$expected = '<b>This</b> is a test <em>text</em>';
$this->assertEqual($expected, $result);
}
/**
* testStripLinks method
*
* @access public
* @return void
*/
function testStripLinks() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->stripLinks($text);
$this->assertEqual($expected, $result);
$text = 'This is a <a href="#">test</a> text';
$expected = 'This is a test text';
$result = $this->Text->stripLinks($text);
$this->assertEqual($expected, $result);
$text = 'This <strong>is</strong> a <a href="#">test</a> <a href="#">text</a>';
$expected = 'This <strong>is</strong> a test text';
$result = $this->Text->stripLinks($text);
$this->assertEqual($expected, $result);
$text = 'This <strong>is</strong> a <a href="#">test</a> and <abbr>some</abbr> other <a href="#">text</a>';
$expected = 'This <strong>is</strong> a test and <abbr>some</abbr> other text';
$result = $this->Text->stripLinks($text);
$this->assertEqual($expected, $result);
}
/**
* testAutoLink method
*
* @access public
* @return void
*/
function testAutoLink() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLink($text);
$this->assertEqual($expected, $result);
$text = 'Text with a partial www.cakephp.org URL and test@cakephp.org email address';
$result = $this->Text->autoLink($text);
$expected = 'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL and <a href="mailto:test@cakephp\.org">test@cakephp\.org</a> email address';
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text);
$this->assertEqual($result, $expected);
$text = 'This is a test text with URL http://www.cakephp.org and some more text';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a> and some more text';
$result = $this->Text->autoLink($text);
$this->assertEqual($result, $expected);
$text = "This is a test text with URL http://www.cakephp.org\tand some more text";
$expected = "This is a test text with URL <a href=\"http://www.cakephp.org\">http://www.cakephp.org</a>\tand some more text";
$result = $this->Text->autoLink($text);
$this->assertEqual($result, $expected);
$text = 'This is a test text with URL http://www.cakephp.org(and some more text)';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>(and some more text)';
$result = $this->Text->autoLink($text);
$this->assertEqual($result, $expected);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org" class="link">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text, array('class'=>'link'));
$this->assertEqual($result, $expected);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org" class="link" id="MyLink">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text, array('class'=>'link', 'id'=>'MyLink'));
$this->assertEqual($result, $expected);
}
/**
* testAutoLinkUrls method
*
* @access public
* @return void
*/
function testAutoLinkUrls() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
$text = 'This is a test that includes (www.cakephp.org)';
$expected = 'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
$text = 'Text with a partial www.cakephp.org URL';
$expected = 'Text with a partial <a href="http://www.cakephp.org"\s*>www.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text);
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'Text with a partial www.cakephp.org URL';
$expected = 'Text with a partial <a href="http://www.cakephp.org" \s*class="link">www.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text, array('class' => 'link'));
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'Text with a partial WWW.cakephp.org URL';
$expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text);
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'Text with a partial WWW.cakephp.org &copy; URL';
$expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> &copy; URL';
$result = $this->Text->autoLinkUrls($text, array('escape' => false));
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'Text with a url www.cot.ag/cuIb2Q and more';
$expected = 'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
}
/**
* testAutoLinkEmails method
*
* @access public
* @return void
*/
function testAutoLinkEmails() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLinkUrls($text);
$this->assertEqual($expected, $result);
$text = 'Text with email@example.com address';
$expected = 'Text with <a href="mailto:email@example.com"\s*>email@example.com</a> address';
$result = $this->Text->autoLinkEmails($text);
$this->assertPattern('#^' . $expected . '$#', $result);
$text = 'Text with email@example.com address';
$expected = 'Text with <a href="mailto:email@example.com" \s*class="link">email@example.com</a> address';
$result = $this->Text->autoLinkEmails($text, array('class' => 'link'));
$this->assertPattern('#^' . $expected . '$#', $result);
}
/**
* testHighlightCaseInsensitivity method
*
* @access public
* @return void
*/
function testHighlightCaseInsensitivity() {
$text = 'This is a Test text';
$expected = 'This is a <b>Test</b> text';
$result = $this->Text->highlight($text, 'test', array('format' => '<b>\1</b>'));
$this->assertEqual($expected, $result);
$result = $this->Text->highlight($text, array('test'), array('format' => '<b>\1</b>'));
$this->assertEqual($expected, $result);
}
/**
* testExcerpt method
*
* @access public
* @return void
*/
function testExcerpt() {
$text = 'This is a phrase with test text to play with';
$expected = '...with test text...';
$result = $this->Text->excerpt($text, 'test', 9, '...');
$this->assertEqual($expected, $result);
$expected = 'This is a...';
$result = $this->Text->excerpt($text, 'not_found', 9, '...');
$this->assertEqual($expected, $result);
$expected = 'This is a phras...';
$result = $this->Text->excerpt($text, null, 9, '...');
$this->assertEqual($expected, $result);
$expected = $text;
$result = $this->Text->excerpt($text, null, 200, '...');
$this->assertEqual($expected, $result);
$expected = '...phrase...';
$result = $this->Text->excerpt($text, 'phrase', 2, '...');
$this->assertEqual($expected, $result);
$phrase = 'This is a phrase with test';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, strlen($phrase) + 3, '...');
$this->assertEqual($expected, $result);
$phrase = 'This is a phrase with text';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, 10, '...');
$this->assertEqual($expected, $result);
}
/**
* testExcerptCaseInsensitivity method
*
* @access public
* @return void
*/
function testExcerptCaseInsensitivity() {
$text = 'This is a phrase with test text to play with';
$expected = '...with test text...';
$result = $this->Text->excerpt($text, 'TEST', 9, '...');
$this->assertEqual($expected, $result);
$expected = 'This is a...';
$result = $this->Text->excerpt($text, 'NOT_FOUND', 9, '...');
$this->assertEqual($expected, $result);
}
/**
* testListGeneration method
*
* @access public
* @return void
*/
function testListGeneration() {
$result = $this->Text->toList(array());
$this->assertEqual($result, '');
$result = $this->Text->toList(array('One'));
$this->assertEqual($result, 'One');
$result = $this->Text->toList(array('Larry', 'Curly', 'Moe'));
$this->assertEqual($result, 'Larry, Curly and Moe');
$result = $this->Text->toList(array('Dusty', 'Lucky', 'Ned'), 'y');
$this->assertEqual($result, 'Dusty, Lucky y Ned');
$result = $this->Text->toList(array( 1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'y');
$this->assertEqual($result, 'Dusty, Lucky y Ned');
$result = $this->Text->toList(array( 1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'and', ' + ');
$this->assertEqual($result, 'Dusty + Lucky and Ned');
$result = $this->Text->toList(array( 'name1' => 'Dusty', 'name2' => 'Lucky'));
$this->assertEqual($result, 'Dusty and Lucky');
$result = $this->Text->toList(array( 'test_0' => 'banana', 'test_1' => 'apple', 'test_2' => 'lemon'));
$this->assertEqual($result, 'banana, apple and lemon');
}
}

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