Upgrade CakePHP from 2.2.5 to 2.9.5

This commit is contained in:
Brm Ko 2017-02-26 15:29:44 +01:00
parent 5a580df460
commit 235a541597
793 changed files with 60746 additions and 23753 deletions

View file

@ -2,20 +2,20 @@
/**
* AllBehaviorsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllBehaviorsTest class
*

View file

@ -2,19 +2,18 @@
/**
* AllCacheTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllComponentsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllConfigureTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllConsoleTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -41,4 +40,4 @@ class AllConsoleTest extends PHPUnit_Framework_TestSuite {
$suite->addTestFile($path . 'AllShellsTest.php');
return $suite;
}
}
}

View file

@ -2,19 +2,18 @@
/**
* AllControllersTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -41,4 +40,4 @@ class AllControllersTest extends PHPUnit_Framework_TestSuite {
$suite->addTestFile(CORE_TEST_CASES . DS . 'Controller' . DS . 'ControllerMergeVarsTest.php');
return $suite;
}
}
}

View file

@ -2,19 +2,18 @@
/**
* AllCoreTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -38,4 +37,3 @@ class AllCoreTest extends PHPUnit_Framework_TestSuite {
return $suite;
}
}

View file

@ -2,19 +2,18 @@
/**
* AllDatabaseTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -0,0 +1,49 @@
<?php
/**
* AllDbRelatedTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllDbRelatedTest class
*
* This test group will run db related tests.
*
* @package Cake.Test.Case
*/
class AllDbRelatedTest extends PHPUnit_Framework_TestSuite {
/**
* Suite define the tests for this suite
*
* @return void
*/
public static function suite() {
$suite = new PHPUnit_Framework_TestSuite('All Db Related Tests');
$path = CORE_TEST_CASES . DS;
$suite->addTestFile($path . 'AllBehaviorsTest.php');
$suite->addTestFile($path . 'Controller' . DS . 'Component' . DS . 'PaginatorComponentTest.php');
$suite->addTestFile($path . 'AllDatabaseTest.php');
$suite->addTestFile($path . 'Model' . DS . 'ModelTest.php');
$suite->addTestFile($path . 'View' . DS . 'ViewTest.php');
$suite->addTestFile($path . 'View' . DS . 'ScaffoldViewTest.php');
$suite->addTestFile($path . 'View' . DS . 'HelperTest.php');
$suite->addTestFile($path . 'View' . DS . 'Helper' . DS . 'FormHelperTest.php');
$suite->addTestFile($path . 'View' . DS . 'Helper' . DS . 'PaginatorHelperTest.php');
return $suite;
}
}

View file

@ -2,19 +2,18 @@
/**
* AllErrorTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllEventTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -37,4 +36,3 @@ class AllEventTest extends PHPUnit_Framework_TestSuite {
return $suite;
}
}

View file

@ -2,19 +2,18 @@
/**
* HelpersGroupTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllLocalizationTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllLogTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -38,4 +37,3 @@ class AllLogTest extends PHPUnit_Framework_TestSuite {
return $suite;
}
}

View file

@ -2,19 +2,18 @@
/**
* AllNetworkTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllRoutingTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllTestSuiteTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -37,4 +36,4 @@ class AllTestSuiteTest extends PHPUnit_Framework_TestSuite {
$suite->addTestDirectory(CORE_TEST_CASES . DS . 'TestSuite');
return $suite;
}
}
}

View file

@ -2,20 +2,20 @@
/**
* AllTests file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* AllTests class
*

View file

@ -2,19 +2,18 @@
/**
* AllUtilityTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllViewTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,24 +2,25 @@
/**
* BasicsTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
require_once CAKE . 'basics.php';
App::uses('Folder', 'Utility');
App::uses('CakeResponse', 'Network');
App::uses('Debugger', 'Utility');
/**
* BasicsTest class
@ -277,7 +278,7 @@ class BasicsTest extends CakeTestCase {
Configure::write('Cache.disable', false);
$result = cache('basics_test', 'simple cache write');
$this->assertTrue((boolean)$result);
$this->assertTrue((bool)$result);
$this->assertTrue(file_exists(CACHE . 'basics_test'));
$result = cache('basics_test');
@ -380,6 +381,14 @@ class BasicsTest extends CakeTestCase {
$expected = 'Some string with multiple arguments';
$this->assertEquals($expected, $result);
$result = __('Some string with %s and a null argument', null);
$expected = 'Some string with %s and a null argument';
$this->assertEquals($expected, $result);
$result = __('Some string with multiple %s%s, first being null', null, 'arguments');
$expected = 'Some string with multiple arguments, first being null';
$this->assertEquals($expected, $result);
$result = __('Some string with %s %s', array('multiple', 'arguments'));
$expected = 'Some string with multiple arguments';
$this->assertEquals($expected, $result);
@ -397,6 +406,181 @@ class BasicsTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* testTranslatePercent
*
* @return void
*/
public function testTranslatePercent() {
$result = __('%s are 100% real fruit', 'Apples');
$expected = 'Apples are 100% real fruit';
$this->assertEquals($expected, $result, 'Percent sign at end of word should be considered literal');
$result = __('%s are %d% real fruit', 'Apples', 100);
$expected = 'Apples are 100% real fruit';
$this->assertEquals($expected, $result, 'A digit marker should not be misinterpreted');
$result = __('%s are %s% real fruit', 'Apples', 100);
$expected = 'Apples are 100% real fruit';
$this->assertEquals($expected, $result, 'A string marker should not be misinterpreted');
$result = __('%nonsense %s', 'Apples');
$expected = '%nonsense Apples';
$this->assertEquals($expected, $result, 'A percent sign at the start of the string should be considered literal');
$result = __('%s are awesome%', 'Apples');
$expected = 'Apples are awesome%';
$this->assertEquals($expected, $result, 'A percent sign at the end of the string should be considered literal');
$result = __('%2$d %1$s entered the bowl', 'Apples', 2);
$expected = '2 Apples entered the bowl';
$this->assertEquals($expected, $result, 'Positional replacement markers should not be misinterpreted');
$result = __('%.2f% of all %s agree', 99.44444, 'Cats');
$expected = '99.44% of all Cats agree';
$this->assertEquals($expected, $result, 'significant-digit placeholder should not be misinterpreted');
}
/**
* testTranslateWithFormatSpecifiers
*
* @return void
*/
public function testTranslateWithFormatSpecifiers() {
$expected = 'Check, one, two, three';
$result = __('Check, %+10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, +1, two, three';
$result = __('Check, %+5d, two, three', 1);
$this->assertEquals($expected, $result);
$expected = 'Check, @@one, two, three';
$result = __('Check, %\'@+10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, one, two , three';
$result = __('Check, %-10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, one, two##, three';
$result = __('Check, %\'#-10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, one, two, three';
$result = __d('default', 'Check, %+10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, @@one, two, three';
$result = __d('default', 'Check, %\'@+10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, one, two , three';
$result = __d('default', 'Check, %-10s, three', 'one, two');
$this->assertEquals($expected, $result);
$expected = 'Check, one, two##, three';
$result = __d('default', 'Check, %\'#-10s, three', 'one, two');
$this->assertEquals($expected, $result);
}
/**
* testTranslateDomainPluralWithFormatSpecifiers
*
* @return void
*/
public function testTranslateDomainPluralWithFormatSpecifiers() {
$result = __dn('core', '%+5d item.', '%+5d items.', 1, 1);
$expected = ' +1 item.';
$this->assertEquals($expected, $result);
$result = __dn('core', '%-5d item.', '%-5d items.', 10, 10);
$expected = '10 items.';
$this->assertEquals($expected, $result);
$result = __dn('core', '%\'#+5d item.', '%\'*+5d items.', 1, 1);
$expected = '###+1 item.';
$this->assertEquals($expected, $result);
$result = __dn('core', '%\'#+5d item.', '%\'*+5d items.', 90, 90);
$expected = '**+90 items.';
$this->assertEquals($expected, $result);
$result = __dn('core', '%\'#+5d item.', '%\'*+5d items.', 9000, 9000);
$expected = '+9000 items.';
$this->assertEquals($expected, $result);
}
/**
* test testTranslatePluralWithFormatSpecifiers
*
* @return void
*/
public function testTranslatePluralWithFormatSpecifiers() {
Configure::write('Config.language', 'rule_1_po');
$result = __n('%-5d = 1', '%-5d = 0 or > 1', 10);
$expected = '%-5d = 0 or > 1 (translated)';
$this->assertEquals($expected, $result);
}
/**
* test testTranslateDomainCategoryWithFormatSpecifiers
*
* @return void
*/
public function testTranslateDomainCategoryWithFormatSpecifiers() {
Configure::write('Config.language', 'rule_1_po');
$result = __dc('default', '%+10s world', 6, 'hello');
$expected = ' hello world';
$this->assertEquals($expected, $result);
$result = __dc('default', '%-10s world', 6, 'hello');
$expected = 'hello world';
$this->assertEquals($expected, $result);
$result = __dc('default', '%\'@-10s world', 6, 'hello');
$expected = 'hello@@@@@ world';
$this->assertEquals($expected, $result);
}
/**
* test testTranslateDomainCategoryPluralWithFormatSpecifiers
*
* @return void
*/
public function testTranslateDomainCategoryPluralWithFormatSpecifiers() {
Configure::write('Config.language', 'rule_1_po');
$result = __dcn('default', '%-5d = 1', '%-5d = 0 or > 1', 0, 6);
$expected = '%-5d = 0 or > 1 (translated)';
$this->assertEquals($expected, $result);
$result = __dcn('default', '%-5d = 1', '%-5d = 0 or > 1', 1, 6);
$expected = '%-5d = 1 (translated)';
$this->assertEquals($expected, $result);
}
/**
* test testTranslateCategoryWithFormatSpecifiers
*
* @return void
*/
public function testTranslateCategoryWithFormatSpecifiers() {
$result = __c('Some string with %+10s', 6, 'arguments');
$expected = 'Some string with arguments';
$this->assertEquals($expected, $result);
$result = __c('Some string with %-10s: args', 6, 'arguments');
$expected = 'Some string with arguments : args';
$this->assertEquals($expected, $result);
$result = __c('Some string with %\'*-10s: args', 6, 'arguments');
$expected = 'Some string with arguments*: args';
$this->assertEquals($expected, $result);
}
/**
* test __n()
*
@ -702,8 +886,9 @@ class BasicsTest extends CakeTestCase {
########## DEBUG ##########
'this-is-a-test'
###########################
EXPECTED;
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8);
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9);
$this->assertEquals($expected, $result);
@ -765,11 +950,12 @@ EXPECTED;
########## DEBUG ##########
'<div>this-is-a-test</div>'
###########################
EXPECTED;
if (php_sapi_name() == 'cli') {
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 17);
if (PHP_SAPI === 'cli') {
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18);
} else {
$expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19);
$expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 20);
}
$this->assertEquals($expected, $result);
@ -789,9 +975,10 @@ EXPECTED;
########## DEBUG ##########
'<div>this-is-a-test</div>'
###########################
EXPECTED;
if (php_sapi_name() == 'cli') {
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 17);
if (PHP_SAPI === 'cli') {
$expected = sprintf($expectedText, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 18);
} else {
$expected = sprintf($expectedHtml, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 19);
}
@ -805,8 +992,9 @@ EXPECTED;
########## DEBUG ##########
'<div>this-is-a-test</div>'
###########################
EXPECTED;
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8);
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9);
$this->assertEquals($expected, $result);
ob_start();
@ -817,8 +1005,9 @@ EXPECTED;
########## DEBUG ##########
'<div>this-is-a-test</div>'
###########################
EXPECTED;
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8);
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9);
$this->assertEquals($expected, $result);
ob_start();
@ -829,8 +1018,22 @@ EXPECTED;
########## DEBUG ##########
'<div>this-is-a-test</div>'
###########################
EXPECTED;
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 8);
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9);
$this->assertEquals($expected, $result);
ob_start();
debug(false, false, false);
$result = ob_get_clean();
$expected = <<<EXPECTED
########## DEBUG ##########
false
###########################
EXPECTED;
$expected = sprintf($expected, str_replace(CAKE_CORE_INCLUDE_PATH, '', __FILE__), __LINE__ - 9);
$this->assertEquals($expected, $result);
}
@ -840,6 +1043,7 @@ EXPECTED;
* @return void
*/
public function testPr() {
$this->skipIf(PHP_SAPI === 'cli', 'Skipping web test in cli mode');
ob_start();
pr('this is a test');
$result = ob_get_clean();
@ -853,6 +1057,26 @@ EXPECTED;
$this->assertEquals($expected, $result);
}
/**
* test pr()
*
* @return void
*/
public function testPrCli() {
$this->skipIf(PHP_SAPI !== 'cli', 'Skipping cli test in web mode');
ob_start();
pr('this is a test');
$result = ob_get_clean();
$expected = "\nthis is a test\n";
$this->assertEquals($expected, $result);
ob_start();
pr(array('this' => 'is', 'a' => 'test'));
$result = ob_get_clean();
$expected = "\nArray\n(\n [this] => is\n [a] => test\n)\n\n";
$this->assertEquals($expected, $result);
}
/**
* test stripslashes_deep()
*
@ -925,6 +1149,24 @@ EXPECTED;
$this->assertEquals($expected, stripslashes_deep($nested));
}
/**
* Tests that the stackTrace() method is a shortcut for Debugger::trace()
*
* @return void
*/
public function testStackTrace() {
ob_start();
list(, $expected) = array(stackTrace(), Debugger::trace());
$result = ob_get_clean();
$this->assertEquals($expected, $result);
$opts = array('args' => true);
ob_start();
list(, $expected) = array(stackTrace($opts), Debugger::trace($opts));
$result = ob_get_clean();
$this->assertEquals($expected, $result);
}
/**
* test pluginSplit
*

View file

@ -2,19 +2,18 @@
/**
* CacheTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -26,6 +25,8 @@ App::uses('Cache', 'Cache');
*/
class CacheTest extends CakeTestCase {
protected $_count = 0;
/**
* setUp method
*
@ -47,6 +48,9 @@ class CacheTest extends CakeTestCase {
*/
public function tearDown() {
parent::tearDown();
Cache::drop('latest');
Cache::drop('page');
Cache::drop('archive');
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::config('default', $this->_defaultCacheConfig['settings']);
}
@ -64,6 +68,17 @@ class CacheTest extends CakeTestCase {
$this->assertTrue(isset($results['settings']));
}
/**
* testConfigInvalidEngine method
*
* @expectedException CacheException
* @return void
*/
public function testConfigInvalidEngine() {
$settings = array('engine' => 'Imaginary');
Cache::config('imaginary', $settings);
}
/**
* Check that no fatal errors are issued doing normal things when Cache.disable is true.
*
@ -117,6 +132,10 @@ class CacheTest extends CakeTestCase {
* @return void
*/
public function testInvalidConfig() {
// In debug mode it would auto create the folder.
$debug = Configure::read('debug');
Configure::write('debug', 0);
Cache::config('invalid', array(
'engine' => 'File',
'duration' => '+1 year',
@ -125,7 +144,9 @@ class CacheTest extends CakeTestCase {
'serialize' => true,
'random' => 'wii'
));
$read = Cache::read('Test', 'invalid');
Cache::read('Test', 'invalid');
Configure::write('debug', $debug);
}
/**
@ -216,7 +237,7 @@ class CacheTest extends CakeTestCase {
'duration' => 3600,
'probability' => 100,
'engine' => 'File',
'isWindows' => DIRECTORY_SEPARATOR == '\\',
'isWindows' => DIRECTORY_SEPARATOR === '\\',
'mask' => 0664,
'groups' => array()
);
@ -225,6 +246,71 @@ class CacheTest extends CakeTestCase {
Cache::config('sessions', $_cacheConfigSessions['settings']);
}
/**
* testGroupConfigs method
*
* @return void
*/
public function testGroupConfigs() {
Cache::config('latest', array(
'duration' => 300,
'engine' => 'File',
'groups' => array(
'posts', 'comments',
),
));
$expected = array(
'posts' => array('latest'),
'comments' => array('latest'),
);
$result = Cache::groupConfigs();
$this->assertEquals($expected, $result);
$result = Cache::groupConfigs('posts');
$this->assertEquals(array('posts' => array('latest')), $result);
Cache::config('page', array(
'duration' => 86400,
'engine' => 'File',
'groups' => array(
'posts', 'archive'
),
));
$result = Cache::groupConfigs();
$expected = array(
'posts' => array('latest', 'page'),
'comments' => array('latest'),
'archive' => array('page'),
);
$this->assertEquals($expected, $result);
$result = Cache::groupConfigs('archive');
$this->assertEquals(array('archive' => array('page')), $result);
Cache::config('archive', array(
'duration' => 86400 * 30,
'engine' => 'File',
'groups' => array(
'posts', 'archive', 'comments',
),
));
$result = Cache::groupConfigs('archive');
$this->assertEquals(array('archive' => array('archive', 'page')), $result);
}
/**
* testGroupConfigsThrowsException method
*
* @expectedException CacheException
* @return void
*/
public function testGroupConfigsThrowsException() {
Cache::groupConfigs('bogus');
}
/**
* test that configured returns an array of the currently configured cache
* settings
@ -290,13 +376,13 @@ class CacheTest extends CakeTestCase {
*/
public function testWriteEmptyValues() {
Cache::write('App.falseTest', false);
$this->assertSame(Cache::read('App.falseTest'), false);
$this->assertFalse(Cache::read('App.falseTest'));
Cache::write('App.trueTest', true);
$this->assertSame(Cache::read('App.trueTest'), true);
$this->assertTrue(Cache::read('App.trueTest'));
Cache::write('App.nullTest', null);
$this->assertSame(Cache::read('App.nullTest'), null);
$this->assertNull(Cache::read('App.nullTest'));
Cache::write('App.zeroTest', 0);
$this->assertSame(Cache::read('App.zeroTest'), 0);
@ -391,7 +477,7 @@ class CacheTest extends CakeTestCase {
Cache::delete('test_cache');
$global = Cache::settings();
Cache::settings();
Cache::set($_cacheSet);
}
@ -409,4 +495,108 @@ class CacheTest extends CakeTestCase {
$this->assertEquals('test_file_', $settings['prefix']);
$this->assertEquals(strtotime('+1 year') - time(), $settings['duration']);
}
/**
* test remember method.
*
* @return void
*/
public function testRemember() {
$expected = 'This is some data 0';
$result = Cache::remember('test_key', array($this, 'cacher'), 'default');
$this->assertEquals($expected, $result);
$this->_count = 1;
$result = Cache::remember('test_key', array($this, 'cacher'), 'default');
$this->assertEquals($expected, $result);
}
/**
* Method for testing Cache::remember()
*
* @return string
*/
public function cacher() {
return 'This is some data ' . $this->_count;
}
/**
* Test add method.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'default');
$result = Cache::add('test_add_key', 'test data', 'default');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'default');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'default');
$this->assertFalse($result);
}
/**
* Test engine method.
*
* Success, default engine.
*
* @return void
*/
public function testEngineSuccess() {
$actual = Cache::engine();
$this->assertInstanceOf('CacheEngine', $actual);
$actual = Cache::engine('default');
$this->assertInstanceOf('CacheEngine', $actual);
}
/**
* Test engine method.
*
* Success, memcached engine.
*
* @return void
*/
public function testEngineSuccessMemcached() {
$this->skipIf(!class_exists('Memcached'), 'Memcached is not installed or configured properly.');
// @codingStandardsIgnoreStart
$socket = @fsockopen('127.0.0.1', 11211, $errno, $errstr, 1);
// @codingStandardsIgnoreEnd
$this->skipIf(!$socket, 'Memcached is not running.');
fclose($socket);
Cache::config('memcached', array(
'engine' => 'Memcached',
'prefix' => 'cake_',
'duration' => 3600
));
$actual = Cache::engine('memcached');
$this->assertInstanceOf('MemcachedEngine', $actual);
$this->assertTrue($actual->add('test_add_key', 'test data', 10));
$this->assertFalse($actual->add('test_add_key', 'test data', 10));
$this->assertTrue($actual->delete('test_add_key'));
}
/**
* Test engine method.
*
* Failure.
*
* @return void
*/
public function testEngineFailure() {
$actual = Cache::engine('some_config_that_does_not_exist');
$this->assertNull($actual);
Configure::write('Cache.disable', true);
$actual = Cache::engine();
$this->assertNull($actual);
}
}

View file

@ -2,19 +2,18 @@
/**
* ApcEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 1.2.0.5434
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -26,6 +25,13 @@ App::uses('Cache', 'Cache');
*/
class ApcEngineTest extends CakeTestCase {
/**
* APC extension to be used
*
* @var string
*/
protected $_apcExtension = 'apc';
/**
* setUp method
*
@ -33,7 +39,16 @@ class ApcEngineTest extends CakeTestCase {
*/
public function setUp() {
parent::setUp();
$this->skipIf(!function_exists('apc_store'), 'Apc is not installed or configured properly.');
$hasApc = extension_loaded('apc') || extension_loaded('apcu');
$this->skipIf(!$hasApc, 'Apc is not installed or configured properly.');
if (PHP_SAPI === 'cli') {
$this->skipIf(!ini_get('apc.enable_cli'), 'APC is not enabled for the CLI.');
}
if (extension_loaded('apcu')) {
$this->_apcExtension = 'apcu';
}
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
@ -144,7 +159,8 @@ class ApcEngineTest extends CakeTestCase {
* @return void
*/
public function testDecrement() {
$this->skipIf(!function_exists('apc_dec'), 'No apc_dec() function, cannot test decrement().');
$hasSupport = function_exists('apc_dec') || function_exists('apcu_dec');
$this->skipIf(!$hasSupport, 'No apc_dec()/apcu_dec() function, cannot test decrement().');
$result = Cache::write('test_decrement', 5, 'apc');
$this->assertTrue($result);
@ -168,7 +184,8 @@ class ApcEngineTest extends CakeTestCase {
* @return void
*/
public function testIncrement() {
$this->skipIf(!function_exists('apc_inc'), 'No apc_inc() function, cannot test increment().');
$hasSupport = function_exists('apc_inc') || function_exists('apcu_inc');
$this->skipIf(!function_exists('apc_inc'), 'No apc_inc()/apcu_inc() function, cannot test increment().');
$result = Cache::write('test_increment', 5, 'apc');
$this->assertTrue($result);
@ -192,14 +209,18 @@ class ApcEngineTest extends CakeTestCase {
* @return void
*/
public function testClear() {
apc_store('not_cake', 'survive');
$storeFunc = $this->_apcExtension . '_store';
$fetchFunc = $this->_apcExtension . '_fetch';
$deleteFunc = $this->_apcExtension . '_delete';
$storeFunc('not_cake', 'survive');
Cache::write('some_value', 'value', 'apc');
$result = Cache::clear(false, 'apc');
$this->assertTrue($result);
$this->assertFalse(Cache::read('some_value', 'apc'));
$this->assertEquals('survive', apc_fetch('not_cake'));
apc_delete('not_cake');
$this->assertEquals('survive', $fetchFunc('not_cake'));
$deleteFunc('not_cake');
}
/**
@ -210,6 +231,7 @@ class ApcEngineTest extends CakeTestCase {
* @return void
*/
public function testGroupsReadWrite() {
$incFunc = $this->_apcExtension . '_inc';
Cache::config('apc_groups', array(
'engine' => 'Apc',
'duration' => 0,
@ -219,12 +241,12 @@ class ApcEngineTest extends CakeTestCase {
$this->assertTrue(Cache::write('test_groups', 'value', 'apc_groups'));
$this->assertEquals('value', Cache::read('test_groups', 'apc_groups'));
apc_inc('test_group_a');
$incFunc('test_group_a');
$this->assertFalse(Cache::read('test_groups', 'apc_groups'));
$this->assertTrue(Cache::write('test_groups', 'value2', 'apc_groups'));
$this->assertEquals('value2', Cache::read('test_groups', 'apc_groups'));
apc_inc('test_group_b');
$incFunc('test_group_b');
$this->assertFalse(Cache::read('test_groups', 'apc_groups'));
$this->assertTrue(Cache::write('test_groups', 'value3', 'apc_groups'));
$this->assertEquals('value3', Cache::read('test_groups', 'apc_groups'));
@ -253,7 +275,7 @@ class ApcEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('apc_groups', array(
'engine' => 'Apc',
@ -270,4 +292,23 @@ class ApcEngineTest extends CakeTestCase {
$this->assertTrue(Cache::clearGroup('group_b', 'apc_groups'));
$this->assertFalse(Cache::read('test_groups', 'apc_groups'));
}
/**
* Test add method.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'apc');
$result = Cache::add('test_add_key', 'test data', 'apc');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'apc');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'apc');
$this->assertFalse($result);
}
}

View file

@ -2,19 +2,18 @@
/**
* FileEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 1.2.0.5434
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -51,7 +50,7 @@ class FileEngineTest extends CakeTestCase {
*/
public function tearDown() {
parent::tearDown();
Cache::clear(false, 'file_test');
// Cache::clear(false, 'file_test');
Cache::drop('file_test');
Cache::drop('file_groups');
Cache::drop('file_groups2');
@ -181,7 +180,7 @@ class FileEngineTest extends CakeTestCase {
$newread = Cache::read('serialize_test', 'file_test');
$delete = Cache::delete('serialize_test', 'file_test');
Cache::delete('serialize_test', 'file_test');
$this->assertSame($read, serialize($data));
@ -197,9 +196,9 @@ class FileEngineTest extends CakeTestCase {
Cache::config('file_test', array('engine' => 'File', 'duration' => 1));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test1', $data, 'file_test');
$write = Cache::write('serialize_test2', $data, 'file_test');
$write = Cache::write('serialize_test3', $data, 'file_test');
Cache::write('serialize_test1', $data, 'file_test');
Cache::write('serialize_test2', $data, 'file_test');
Cache::write('serialize_test3', $data, 'file_test');
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test3'));
@ -211,9 +210,9 @@ class FileEngineTest extends CakeTestCase {
$this->assertFalse(file_exists(CACHE . 'cake_serialize_test3'));
$data = 'this is a test of the emergency broadcasting system';
$write = Cache::write('serialize_test1', $data, 'file_test');
$write = Cache::write('serialize_test2', $data, 'file_test');
$write = Cache::write('serialize_test3', $data, 'file_test');
Cache::write('serialize_test1', $data, 'file_test');
Cache::write('serialize_test2', $data, 'file_test');
Cache::write('serialize_test3', $data, 'file_test');
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test1'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test2'));
$this->assertTrue(file_exists(CACHE . 'cake_serialize_test3'));
@ -254,6 +253,41 @@ class FileEngineTest extends CakeTestCase {
$FileTwo->clear(false);
}
/**
* Test that clear() also removes files with group tags.
*
* @return void
*/
public function testClearWithGroups() {
$engine = new FileEngine();
$engine->init(array(
'prefix' => 'cake_test_',
'duration' => DAY,
'groups' => array('short', 'round')
));
$key = 'cake_test_test_key';
$engine->write($key, 'it works', DAY);
$engine->clear(false);
$this->assertFalse($engine->read($key), 'Key should have been removed');
}
/**
* Test that clear() also removes files with group tags.
*
* @return void
*/
public function testClearWithNoKeys() {
$engine = new FileEngine();
$engine->init(array(
'prefix' => 'cake_test_',
'duration' => DAY,
'groups' => array('one', 'two')
));
$key = 'cake_test_test_key';
$engine->clear(false);
$this->assertFalse($engine->read($key), 'No errors should be found');
}
/**
* testKeyPath method
*
@ -269,6 +303,14 @@ class FileEngineTest extends CakeTestCase {
$result = Cache::clear(false, 'file_test');
$this->assertTrue($result);
$result = Cache::write('domain.test.com:8080', 'here', 'file_test');
$this->assertTrue($result);
$this->assertTrue(file_exists(CACHE . 'cake_domain_test_com_8080'));
$result = Cache::write('command>dir|more', 'here', 'file_test');
$this->assertTrue($result);
$this->assertTrue(file_exists(CACHE . 'cake_command_dir_more'));
}
/**
@ -337,20 +379,19 @@ class FileEngineTest extends CakeTestCase {
}
/**
* check that FileEngine generates an error when a configured Path does not exist.
* check that FileEngine does not generate an error when a configured Path does not exist in debug mode.
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testErrorWhenPathDoesNotExist() {
$this->skipIf(is_dir(TMP . 'tests' . DS . 'file_failure'), 'Cannot run test directory exists.');
public function testPathDoesNotExist() {
$this->skipIf(is_dir(TMP . 'tests' . DS . 'autocreate'), 'Cannot run if test directory exists.');
Cache::config('failure', array(
Cache::config('autocreate', array(
'engine' => 'File',
'path' => TMP . 'tests' . DS . 'file_failure'
'path' => TMP . 'tests' . DS . 'autocreate'
));
Cache::drop('failure');
Cache::drop('autocreate');
}
/**
@ -365,31 +406,31 @@ class FileEngineTest extends CakeTestCase {
Cache::config('mask_test', array('engine' => 'File', 'path' => TMP . 'tests'));
$data = 'This is some test content';
$write = Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
$result = substr(sprintf('%o', fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
$expected = '0664';
$this->assertEquals($expected, $result);
Cache::delete('masking_test', 'mask_test');
Cache::drop('mask_test');
Cache::config('mask_test', array('engine' => 'File', 'mask' => 0666, 'path' => TMP . 'tests'));
$write = Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o', fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
$expected = '0666';
$this->assertEquals($expected, $result);
Cache::delete('masking_test', 'mask_test');
Cache::drop('mask_test');
Cache::config('mask_test', array('engine' => 'File', 'mask' => 0644, 'path' => TMP . 'tests'));
$write = Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o', fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
$expected = '0644';
$this->assertEquals($expected, $result);
Cache::delete('masking_test', 'mask_test');
Cache::drop('mask_test');
Cache::config('mask_test', array('engine' => 'File', 'mask' => 0640, 'path' => TMP . 'tests'));
$write = Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o',fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
Cache::write('masking_test', $data, 'mask_test');
$result = substr(sprintf('%o', fileperms(TMP . 'tests' . DS . 'cake_masking_test')), -4);
$expected = '0640';
$this->assertEquals($expected, $result);
Cache::delete('masking_test', 'mask_test');
@ -411,12 +452,44 @@ class FileEngineTest extends CakeTestCase {
}
/**
* Tests that deleteing from a groups-enabled config is possible
* Test that clearing with repeat writes works properly
*
* @return void
*/
public function testClearingWithRepeatWrites() {
Cache::config('repeat', array(
'engine' => 'File', 'groups' => array('users')
));
$this->assertTrue(Cache::write('user', 'rchavik', 'repeat'));
$this->assertEquals('rchavik', Cache::read('user', 'repeat'));
Cache::delete('user', 'repeat');
$this->assertEquals(false, Cache::read('user', 'repeat'));
$this->assertTrue(Cache::write('user', 'ADmad', 'repeat'));
$this->assertEquals('ADmad', Cache::read('user', 'repeat'));
Cache::clearGroup('users', 'repeat');
$this->assertEquals(false, Cache::read('user', 'repeat'));
$this->assertTrue(Cache::write('user', 'markstory', 'repeat'));
$this->assertEquals('markstory', Cache::read('user', 'repeat'));
Cache::drop('repeat');
}
/**
* Tests that deleting from a groups-enabled config is possible
*
* @return void
*/
public function testGroupDelete() {
Cache::config('file_groups', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a', 'group_b')));
Cache::config('file_groups', array(
'engine' => 'File',
'duration' => 3600,
'groups' => array('group_a', 'group_b')
));
$this->assertTrue(Cache::write('test_groups', 'value', 'file_groups'));
$this->assertEquals('value', Cache::read('test_groups', 'file_groups'));
$this->assertTrue(Cache::delete('test_groups', 'file_groups'));
@ -428,28 +501,71 @@ class FileEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('file_groups', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a', 'group_b')));
Cache::config('file_groups2', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_b')));
Cache::config('file_groups3', array('engine' => 'File', 'duration' => 3600, 'groups' => array('group_a')));
Cache::config('file_groups3', array(
'engine' => 'File',
'duration' => 3600,
'groups' => array('group_b'),
'prefix' => 'leading_',
));
$this->assertTrue(Cache::write('test_groups', 'value', 'file_groups'));
$this->assertTrue(Cache::write('test_groups2', 'value', 'file_groups2'));
$this->assertTrue(Cache::write('test_groups3', 'value', 'file_groups3'));
$this->assertTrue(Cache::write('test_groups2', 'value 2', 'file_groups2'));
$this->assertTrue(Cache::write('test_groups3', 'value 3', 'file_groups3'));
$this->assertTrue(Cache::clearGroup('group_a', 'file_groups'));
$this->assertTrue(Cache::clearGroup('group_b', 'file_groups'));
$this->assertFalse(Cache::read('test_groups', 'file_groups'));
$this->assertEquals('value', Cache::read('test_groups2', 'file_groups2'));
$this->assertFalse(Cache::read('test_groups3', 'file_groups3'));
$this->assertFalse(Cache::read('test_groups2', 'file_groups2'));
$this->assertEquals('value 3', Cache::read('test_groups3', 'file_groups3'));
$this->assertTrue(Cache::write('test_groups4', 'value', 'file_groups'));
$this->assertTrue(Cache::write('test_groups5', 'value', 'file_groups2'));
$this->assertTrue(Cache::write('test_groups6', 'value', 'file_groups3'));
$this->assertTrue(Cache::write('test_groups5', 'value 2', 'file_groups2'));
$this->assertTrue(Cache::write('test_groups6', 'value 3', 'file_groups3'));
$this->assertTrue(Cache::clearGroup('group_b', 'file_groups'));
$this->assertFalse(Cache::read('test_groups4', 'file_groups'));
$this->assertFalse(Cache::read('test_groups5', 'file_groups2'));
$this->assertEquals('value', Cache::read('test_groups6', 'file_groups3'));
$this->assertEquals('value 3', Cache::read('test_groups6', 'file_groups3'));
}
/**
* Test that clearGroup works with no prefix.
*
* @return void
*/
public function testGroupClearNoPrefix() {
Cache::config('file_groups', array(
'engine' => 'File',
'duration' => 3600,
'prefix' => '',
'groups' => array('group_a', 'group_b')
));
Cache::write('key_1', 'value', 'file_groups');
Cache::write('key_2', 'value', 'file_groups');
Cache::clearGroup('group_a', 'file_groups');
$this->assertFalse(Cache::read('key_1', 'file_groups'), 'Did not delete');
$this->assertFalse(Cache::read('key_2', 'file_groups'), 'Did not delete');
}
/**
* Test add method.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'file_test');
$result = Cache::add('test_add_key', 'test data', 'file_test');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'file_test');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'file_test');
$this->assertFalse($result);
}
}

View file

@ -2,24 +2,28 @@
/**
* MemcacheEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 1.2.0.5434
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
App::uses('MemcacheEngine', 'Cache/Engine');
/**
* TestMemcacheEngine
*
* @package Cake.Test.Case.Cache.Engine
*/
class TestMemcacheEngine extends MemcacheEngine {
/**
@ -93,7 +97,6 @@ class MemcacheEngineTest extends CakeTestCase {
'persistent' => true,
'compress' => false,
'engine' => 'Memcache',
'persistent' => true,
'groups' => array()
);
$this->assertEquals($expecting, $settings);
@ -158,6 +161,17 @@ class MemcacheEngineTest extends CakeTestCase {
$this->assertTrue($result);
}
/**
* test domain starts with u
*
* @return void
*/
public function testParseServerStringWithU() {
$Memcached = new TestMemcachedEngine();
$result = $Memcached->parseServerString('udomain.net:13211');
$this->assertEquals(array('udomain.net', '13211'), $result);
}
/**
* test non latin domains.
*
@ -460,7 +474,7 @@ class MemcacheEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('memcache_groups', array(
'engine' => 'Memcache',
@ -476,4 +490,23 @@ class MemcacheEngineTest extends CakeTestCase {
$this->assertTrue(Cache::clearGroup('group_b', 'memcache_groups'));
$this->assertFalse(Cache::read('test_groups', 'memcache_groups'));
}
/**
* Test that failed add write return false.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'memcache');
$result = Cache::add('test_add_key', 'test data', 'memcache');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'memcache');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'memcache');
$this->assertFalse($result);
}
}

View file

@ -0,0 +1,827 @@
<?php
/**
* MemcachedEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 2.5.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
App::uses('MemcachedEngine', 'Cache/Engine');
/**
* TestMemcachedEngine
*
* @package Cake.Test.Case.Cache.Engine
*/
class TestMemcachedEngine extends MemcachedEngine {
/**
* public accessor to _parseServerString
*
* @param string $server
* @return array
*/
public function parseServerString($server) {
return $this->_parseServerString($server);
}
public function setMemcached($memcached) {
$this->_Memcached = $memcached;
}
public function getMemcached() {
return $this->_Memcached;
}
}
/**
* MemcachedEngineTest class
*
* @package Cake.Test.Case.Cache.Engine
*/
class MemcachedEngineTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->skipIf(!class_exists('Memcached'), 'Memcached is not installed or configured properly.');
// @codingStandardsIgnoreStart
$socket = @fsockopen('127.0.0.1', 11211, $errno, $errstr, 1);
// @codingStandardsIgnoreEnd
$this->skipIf(!$socket, 'Memcached is not running.');
fclose($socket);
Cache::config('memcached', array(
'engine' => 'Memcached',
'prefix' => 'cake_',
'duration' => 3600
));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
Cache::drop('memcached');
Cache::drop('memcached_groups');
Cache::drop('memcached_helper');
Cache::config('default');
}
/**
* testSettings method
*
* @return void
*/
public function testSettings() {
$settings = Cache::settings('memcached');
unset($settings['path']);
$expecting = array(
'prefix' => 'cake_',
'duration' => 3600,
'probability' => 100,
'servers' => array('127.0.0.1'),
'persistent' => false,
'compress' => false,
'engine' => 'Memcached',
'login' => null,
'password' => null,
'groups' => array(),
'serialize' => 'php',
'options' => array()
);
$this->assertEquals($expecting, $settings);
}
/**
* testCompressionSetting method
*
* @return void
*/
public function testCompressionSetting() {
$Memcached = new TestMemcachedEngine();
$Memcached->init(array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'compress' => false
));
$this->assertFalse($Memcached->getMemcached()->getOption(Memcached::OPT_COMPRESSION));
$MemcachedCompressed = new TestMemcachedEngine();
$MemcachedCompressed->init(array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'compress' => true
));
$this->assertTrue($MemcachedCompressed->getMemcached()->getOption(Memcached::OPT_COMPRESSION));
}
/**
* test setting options
*
* @return void
*/
public function testOptionsSetting() {
$memcached = new TestMemcachedEngine();
$memcached->init(array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'options' => array(
Memcached::OPT_BINARY_PROTOCOL => true
)
));
$this->assertEquals(1, $memcached->getMemcached()->getOption(Memcached::OPT_BINARY_PROTOCOL));
}
/**
* test accepts only valid serializer engine
*
* @return void
*/
public function testInvalidSerializerSetting() {
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'invalid_serializer'
);
$this->setExpectedException(
'CacheException', 'invalid_serializer is not a valid serializer engine for Memcached'
);
$Memcached->init($settings);
}
/**
* testPhpSerializerSetting method
*
* @return void
*/
public function testPhpSerializerSetting() {
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'php'
);
$Memcached->init($settings);
$this->assertEquals(Memcached::SERIALIZER_PHP, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER));
}
/**
* testJsonSerializerSetting method
*
* @return void
*/
public function testJsonSerializerSetting() {
$this->skipIf(
!Memcached::HAVE_JSON,
'Memcached extension is not compiled with json support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'json'
);
$Memcached->init($settings);
$this->assertEquals(Memcached::SERIALIZER_JSON, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER));
}
/**
* testIgbinarySerializerSetting method
*
* @return void
*/
public function testIgbinarySerializerSetting() {
$this->skipIf(
!Memcached::HAVE_IGBINARY,
'Memcached extension is not compiled with igbinary support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'igbinary'
);
$Memcached->init($settings);
$this->assertEquals(Memcached::SERIALIZER_IGBINARY, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER));
}
/**
* testMsgpackSerializerSetting method
*
* @return void
*/
public function testMsgpackSerializerSetting() {
$this->skipIf(
!defined('Memcached::HAVE_MSGPACK') || !Memcached::HAVE_MSGPACK,
'Memcached extension is not compiled with msgpack support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'msgpack'
);
$Memcached->init($settings);
$this->assertEquals(Memcached::SERIALIZER_MSGPACK, $Memcached->getMemcached()->getOption(Memcached::OPT_SERIALIZER));
}
/**
* testJsonSerializerThrowException method
*
* @return void
*/
public function testJsonSerializerThrowException() {
$this->skipIf(
Memcached::HAVE_JSON,
'Memcached extension is compiled with json support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'json'
);
$this->setExpectedException(
'CacheException', 'Memcached extension is not compiled with json support'
);
$Memcached->init($settings);
}
/**
* testMsgpackSerializerThrowException method
*
* @return void
*/
public function testMsgpackSerializerThrowException() {
$this->skipIf(
defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK,
'Memcached extension is compiled with msgpack support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'msgpack'
);
$this->setExpectedException(
'CacheException', 'msgpack is not a valid serializer engine for Memcached'
);
$Memcached->init($settings);
}
/**
* testIgbinarySerializerThrowException method
*
* @return void
*/
public function testIgbinarySerializerThrowException() {
$this->skipIf(
Memcached::HAVE_IGBINARY,
'Memcached extension is compiled with igbinary support'
);
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'serialize' => 'igbinary'
);
$this->setExpectedException(
'CacheException', 'Memcached extension is not compiled with igbinary support'
);
$Memcached->init($settings);
}
/**
* test using authentication without memcached installed with SASL support
* throw an exception
*
* @return void
*/
public function testSaslAuthException() {
$this->skipIf(version_compare(PHP_VERSION, '7.0.0', '>='));
$Memcached = new TestMemcachedEngine();
$settings = array(
'engine' => 'Memcached',
'servers' => array('127.0.0.1:11211'),
'persistent' => false,
'login' => 'test',
'password' => 'password'
);
$this->setExpectedException('PHPUnit_Framework_Error_Warning');
$Memcached->init($settings);
}
/**
* testSettings method
*
* @return void
*/
public function testMultipleServers() {
$servers = array('127.0.0.1:11211', '127.0.0.1:11222');
$available = true;
$Memcached = new Memcached();
foreach ($servers as $server) {
list($host, $port) = explode(':', $server);
//@codingStandardsIgnoreStart
if (!$Memcached->addServer($host, $port)) {
$available = false;
}
//@codingStandardsIgnoreEnd
}
$this->skipIf(!$available, 'Need memcached servers at ' . implode(', ', $servers) . ' to run this test.');
$Memcached = new MemcachedEngine();
$Memcached->init(array('engine' => 'Memcached', 'servers' => $servers));
$settings = $Memcached->settings();
$this->assertEquals($settings['servers'], $servers);
Cache::drop('dual_server');
}
/**
* test connecting to an ipv6 server.
*
* @return void
*/
public function testConnectIpv6() {
$Memcached = new MemcachedEngine();
$result = $Memcached->init(array(
'prefix' => 'cake_',
'duration' => 200,
'engine' => 'Memcached',
'servers' => array(
'[::1]:11211'
)
));
$this->assertTrue($result);
}
/**
* test domain starts with u
*
* @return void
*/
public function testParseServerStringWithU() {
$Memcached = new TestMemcachedEngine();
$result = $Memcached->parseServerString('udomain.net:13211');
$this->assertEquals(array('udomain.net', '13211'), $result);
}
/**
* test non latin domains.
*
* @return void
*/
public function testParseServerStringNonLatin() {
$Memcached = new TestMemcachedEngine();
$result = $Memcached->parseServerString('schülervz.net:13211');
$this->assertEquals(array('schülervz.net', '13211'), $result);
$result = $Memcached->parseServerString('sülül:1111');
$this->assertEquals(array('sülül', '1111'), $result);
}
/**
* test unix sockets.
*
* @return void
*/
public function testParseServerStringUnix() {
$Memcached = new TestMemcachedEngine();
$result = $Memcached->parseServerString('unix:///path/to/memcachedd.sock');
$this->assertEquals(array('/path/to/memcachedd.sock', 0), $result);
}
/**
* testReadAndWriteCache method
*
* @return void
*/
public function testReadAndWriteCache() {
Cache::set(array('duration' => 1), null, 'memcached');
$result = Cache::read('test', 'memcached');
$expecting = '';
$this->assertEquals($expecting, $result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('test', $data, 'memcached');
$this->assertTrue($result);
$result = Cache::read('test', 'memcached');
$expecting = $data;
$this->assertEquals($expecting, $result);
Cache::delete('test', 'memcached');
}
/**
* testExpiry method
*
* @return void
*/
public function testExpiry() {
Cache::set(array('duration' => 1), 'memcached');
$result = Cache::read('test', 'memcached');
$this->assertFalse($result);
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data, 'memcached');
$this->assertTrue($result);
sleep(2);
$result = Cache::read('other_test', 'memcached');
$this->assertFalse($result);
Cache::set(array('duration' => "+1 second"), 'memcached');
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('other_test', $data, 'memcached');
$this->assertTrue($result);
sleep(3);
$result = Cache::read('other_test', 'memcached');
$this->assertFalse($result);
Cache::config('memcached', array('duration' => '+1 second'));
$result = Cache::read('other_test', 'memcached');
$this->assertFalse($result);
Cache::config('memcached', array('duration' => '+29 days'));
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('long_expiry_test', $data, 'memcached');
$this->assertTrue($result);
sleep(2);
$result = Cache::read('long_expiry_test', 'memcached');
$expecting = $data;
$this->assertEquals($expecting, $result);
Cache::config('memcached', array('duration' => 3600));
}
/**
* testDeleteCache method
*
* @return void
*/
public function testDeleteCache() {
$data = 'this is a test of the emergency broadcasting system';
$result = Cache::write('delete_test', $data, 'memcached');
$this->assertTrue($result);
$result = Cache::delete('delete_test', 'memcached');
$this->assertTrue($result);
}
/**
* testDecrement method
*
* @return void
*/
public function testDecrement() {
$result = Cache::write('test_decrement', 5, 'memcached');
$this->assertTrue($result);
$result = Cache::decrement('test_decrement', 1, 'memcached');
$this->assertEquals(4, $result);
$result = Cache::read('test_decrement', 'memcached');
$this->assertEquals(4, $result);
$result = Cache::decrement('test_decrement', 2, 'memcached');
$this->assertEquals(2, $result);
$result = Cache::read('test_decrement', 'memcached');
$this->assertEquals(2, $result);
Cache::delete('test_decrement', 'memcached');
}
/**
* test decrementing compressed keys
*
* @return void
*/
public function testDecrementCompressedKeys() {
Cache::config('compressed_memcached', array(
'engine' => 'Memcached',
'duration' => '+2 seconds',
'servers' => array('127.0.0.1:11211'),
'compress' => true
));
$result = Cache::write('test_decrement', 5, 'compressed_memcached');
$this->assertTrue($result);
$result = Cache::decrement('test_decrement', 1, 'compressed_memcached');
$this->assertEquals(4, $result);
$result = Cache::read('test_decrement', 'compressed_memcached');
$this->assertEquals(4, $result);
$result = Cache::decrement('test_decrement', 2, 'compressed_memcached');
$this->assertEquals(2, $result);
$result = Cache::read('test_decrement', 'compressed_memcached');
$this->assertEquals(2, $result);
Cache::delete('test_decrement', 'compressed_memcached');
}
/**
* testIncrement method
*
* @return void
*/
public function testIncrement() {
$result = Cache::write('test_increment', 5, 'memcached');
$this->assertTrue($result);
$result = Cache::increment('test_increment', 1, 'memcached');
$this->assertEquals(6, $result);
$result = Cache::read('test_increment', 'memcached');
$this->assertEquals(6, $result);
$result = Cache::increment('test_increment', 2, 'memcached');
$this->assertEquals(8, $result);
$result = Cache::read('test_increment', 'memcached');
$this->assertEquals(8, $result);
Cache::delete('test_increment', 'memcached');
}
/**
* test incrementing compressed keys
*
* @return void
*/
public function testIncrementCompressedKeys() {
Cache::config('compressed_memcached', array(
'engine' => 'Memcached',
'duration' => '+2 seconds',
'servers' => array('127.0.0.1:11211'),
'compress' => true
));
$result = Cache::write('test_increment', 5, 'compressed_memcached');
$this->assertTrue($result);
$result = Cache::increment('test_increment', 1, 'compressed_memcached');
$this->assertEquals(6, $result);
$result = Cache::read('test_increment', 'compressed_memcached');
$this->assertEquals(6, $result);
$result = Cache::increment('test_increment', 2, 'compressed_memcached');
$this->assertEquals(8, $result);
$result = Cache::read('test_increment', 'compressed_memcached');
$this->assertEquals(8, $result);
Cache::delete('test_increment', 'compressed_memcached');
}
/**
* test that configurations don't conflict, when a file engine is declared after a memcached one.
*
* @return void
*/
public function testConfigurationConflict() {
Cache::config('long_memcached', array(
'engine' => 'Memcached',
'duration' => '+2 seconds',
'servers' => array('127.0.0.1:11211'),
));
Cache::config('short_memcached', array(
'engine' => 'Memcached',
'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_memcached'));
$this->assertTrue(Cache::write('short_duration_test', 'boo', 'short_memcached'));
$this->assertEquals('yay', Cache::read('duration_test', 'long_memcached'), 'Value was not read %s');
$this->assertEquals('boo', Cache::read('short_duration_test', 'short_memcached'), 'Value was not read %s');
sleep(1);
$this->assertEquals('yay', Cache::read('duration_test', 'long_memcached'), 'Value was not read %s');
sleep(2);
$this->assertFalse(Cache::read('short_duration_test', 'short_memcached'), 'Cache was not invalidated %s');
$this->assertFalse(Cache::read('duration_test', 'long_memcached'), 'Value did not expire %s');
Cache::delete('duration_test', 'long_memcached');
Cache::delete('short_duration_test', 'short_memcached');
}
/**
* test clearing memcached.
*
* @return void
*/
public function testClear() {
Cache::config('memcached2', array(
'engine' => 'Memcached',
'prefix' => 'cake2_',
'duration' => 3600
));
Cache::write('some_value', 'cache1', 'memcached');
$result = Cache::clear(true, 'memcached');
$this->assertTrue($result);
$this->assertEquals('cache1', Cache::read('some_value', 'memcached'));
Cache::write('some_value', 'cache2', 'memcached2');
$result = Cache::clear(false, 'memcached');
$this->assertTrue($result);
$this->assertFalse(Cache::read('some_value', 'memcached'));
$this->assertEquals('cache2', Cache::read('some_value', 'memcached2'));
Cache::clear(false, 'memcached2');
}
/**
* test that a 0 duration can successfully write.
*
* @return void
*/
public function testZeroDuration() {
Cache::config('memcached', array('duration' => 0));
$result = Cache::write('test_key', 'written!', 'memcached');
$this->assertTrue($result);
$result = Cache::read('test_key', 'memcached');
$this->assertEquals('written!', $result);
}
/**
* test that durations greater than 30 days never expire
*
* @return void
*/
public function testLongDurationEqualToZero() {
$this->markTestSkipped('Cannot run as Memcached cannot be reflected');
$memcached = new TestMemcachedEngine();
$memcached->settings['compress'] = false;
$mock = $this->getMock('Memcached');
$memcached->setMemcached($mock);
$mock->expects($this->once())
->method('set')
->with('key', 'value', 0);
$value = 'value';
$memcached->write('key', $value, 50 * DAY);
}
/**
* Tests that configuring groups for stored keys return the correct values when read/written
* Shows that altering the group value is equivalent to deleting all keys under the same
* group
*
* @return void
*/
public function testGroupReadWrite() {
Cache::config('memcached_groups', array(
'engine' => 'Memcached',
'duration' => 3600,
'groups' => array('group_a', 'group_b'),
'prefix' => 'test_'
));
Cache::config('memcached_helper', array(
'engine' => 'Memcached',
'duration' => 3600,
'prefix' => 'test_'
));
$this->assertTrue(Cache::write('test_groups', 'value', 'memcached_groups'));
$this->assertEquals('value', Cache::read('test_groups', 'memcached_groups'));
Cache::increment('group_a', 1, 'memcached_helper');
$this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
$this->assertTrue(Cache::write('test_groups', 'value2', 'memcached_groups'));
$this->assertEquals('value2', Cache::read('test_groups', 'memcached_groups'));
Cache::increment('group_b', 1, 'memcached_helper');
$this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
$this->assertTrue(Cache::write('test_groups', 'value3', 'memcached_groups'));
$this->assertEquals('value3', Cache::read('test_groups', 'memcached_groups'));
}
/**
* Tests that deleteing from a groups-enabled config is possible
*
* @return void
*/
public function testGroupDelete() {
Cache::config('memcached_groups', array(
'engine' => 'Memcached',
'duration' => 3600,
'groups' => array('group_a', 'group_b')
));
$this->assertTrue(Cache::write('test_groups', 'value', 'memcached_groups'));
$this->assertEquals('value', Cache::read('test_groups', 'memcached_groups'));
$this->assertTrue(Cache::delete('test_groups', 'memcached_groups'));
$this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
}
/**
* Test clearing a cache group
*
* @return void
*/
public function testGroupClear() {
Cache::config('memcached_groups', array(
'engine' => 'Memcached',
'duration' => 3600,
'groups' => array('group_a', 'group_b')
));
$this->assertTrue(Cache::write('test_groups', 'value', 'memcached_groups'));
$this->assertTrue(Cache::clearGroup('group_a', 'memcached_groups'));
$this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
$this->assertTrue(Cache::write('test_groups', 'value2', 'memcached_groups'));
$this->assertTrue(Cache::clearGroup('group_b', 'memcached_groups'));
$this->assertFalse(Cache::read('test_groups', 'memcached_groups'));
}
/**
* Test add method.
*
* @return void
*/
public function testAdd() {
Cache::set(array('duration' => 1), null, 'memcached');
Cache::delete('test_add_key', 'default');
$result = Cache::add('test_add_key', 'test data', 'default');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'default');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'default');
$this->assertFalse($result);
}
}

View file

@ -2,19 +2,18 @@
/**
* RedisEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 2.2
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -25,7 +24,7 @@ App::uses('RedisEngine', 'Cache/Engine');
*
* @package Cake.Test.Case.Cache.Engine
*/
class RegisEngineTest extends CakeTestCase {
class RedisEngineTest extends CakeTestCase {
/**
* setUp method
@ -33,10 +32,18 @@ class RegisEngineTest extends CakeTestCase {
* @return void
*/
public function setUp() {
parent::setUp();
$this->skipIf(!class_exists('Redis'), 'Redis is not installed or configured properly.');
$this->_cacheDisable = Configure::read('Cache.disable');
Configure::write('Cache.disable', false);
// @codingStandardsIgnoreStart
$socket = @fsockopen('127.0.0.1', 6379, $errno, $errstr, 1);
// @codingStandardsIgnoreEnd
$this->skipIf(!$socket, 'Redis is not running.');
fclose($socket);
Cache::config('redis', array(
'engine' => 'Redis',
'prefix' => 'cake_',
@ -50,6 +57,7 @@ class RegisEngineTest extends CakeTestCase {
* @return void
*/
public function tearDown() {
parent::tearDown();
Configure::write('Cache.disable', $this->_cacheDisable);
Cache::drop('');
Cache::drop('redis_groups');
@ -73,7 +81,10 @@ class RegisEngineTest extends CakeTestCase {
'server' => '127.0.0.1',
'port' => 6379,
'timeout' => 0,
'persistent' => true
'persistent' => true,
'password' => false,
'database' => 0,
'unix_socket' => false,
);
$this->assertEquals($expecting, $settings);
}
@ -88,6 +99,67 @@ class RegisEngineTest extends CakeTestCase {
$this->assertTrue($Redis->init(Cache::settings('redis')));
}
/**
* testMultiDatabaseOperations method
*
* @return void
*/
public function testMultiDatabaseOperations() {
Cache::config('redisdb0', array(
'engine' => 'Redis',
'prefix' => 'cake2_',
'duration' => 3600,
'persistent' => false,
));
Cache::config('redisdb1', array(
'engine' => 'Redis',
'database' => 1,
'prefix' => 'cake2_',
'duration' => 3600,
'persistent' => false,
));
$result = Cache::write('save_in_0', true, 'redisdb0');
$exist = Cache::read('save_in_0', 'redisdb0');
$this->assertTrue($result);
$this->assertTrue($exist);
$result = Cache::write('save_in_1', true, 'redisdb1');
$this->assertTrue($result);
$exist = Cache::read('save_in_0', 'redisdb1');
$this->assertFalse($exist);
$exist = Cache::read('save_in_1', 'redisdb1');
$this->assertTrue($exist);
Cache::delete('save_in_0', 'redisdb0');
$exist = Cache::read('save_in_0', 'redisdb0');
$this->assertFalse($exist);
Cache::delete('save_in_1', 'redisdb1');
$exist = Cache::read('save_in_1', 'redisdb1');
$this->assertFalse($exist);
Cache::drop('redisdb0');
Cache::drop('redisdb1');
}
/**
* test write numbers method
*
* @return void
*/
public function testWriteNumbers() {
$result = Cache::write('test-counter', 1, 'redis');
$this->assertSame(1, Cache::read('test-counter', 'redis'));
$result = Cache::write('test-counter', 0, 'redis');
$this->assertSame(0, Cache::read('test-counter', 'redis'));
$result = Cache::write('test-counter', -1, 'redis');
$this->assertSame(-1, Cache::read('test-counter', 'redis'));
}
/**
* testReadAndWriteCache method
*
@ -315,7 +387,7 @@ class RegisEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('redis_groups', array(
'engine' => 'Redis',
@ -332,4 +404,22 @@ class RegisEngineTest extends CakeTestCase {
$this->assertFalse(Cache::read('test_groups', 'redis_groups'));
}
/**
* Test add method.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'redis');
$result = Cache::add('test_add_key', 'test data', 'redis');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'redis');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'redis');
$this->assertFalse($result);
}
}

View file

@ -2,19 +2,18 @@
/**
* WincacheEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 1.2.0.5434
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -243,7 +242,7 @@ class WincacheEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('wincache_groups', array(
'engine' => 'Wincache',
@ -260,4 +259,23 @@ class WincacheEngineTest extends CakeTestCase {
$this->assertTrue(Cache::clearGroup('group_b', 'wincache_groups'));
$this->assertFalse(Cache::read('test_groups', 'wincache_groups'));
}
/**
* Test that failed add write return false.
*
* @return void
*/
public function testAdd() {
Cache::delete('test_add_key', 'wincache');
$result = Cache::add('test_add_key', 'test data', 'wincache');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'wincache');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'wincache');
$this->assertFalse($result);
}
}

View file

@ -2,19 +2,18 @@
/**
* XcacheEngineTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Cache.Engine
* @since CakePHP(tm) v 1.2.0.5434
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Cache', 'Cache');
@ -252,7 +251,7 @@ class XcacheEngineTest extends CakeTestCase {
* Test clearing a cache group
*
* @return void
**/
*/
public function testGroupClear() {
Cache::config('xcache_groups', array(
'engine' => 'Xcache',
@ -269,4 +268,24 @@ class XcacheEngineTest extends CakeTestCase {
$this->assertTrue(Cache::clearGroup('group_b', 'xcache_groups'));
$this->assertFalse(Cache::read('test_groups', 'xcache_groups'));
}
/**
* Test that failed add write return false.
*
* @return void
*/
public function testAdd() {
Cache::set(array('duration' => 1), null);
Cache::delete('test_add_key', 'default');
$result = Cache::add('test_add_key', 'test data', 'default');
$this->assertTrue($result);
$expected = 'test data';
$result = Cache::read('test_add_key', 'default');
$this->assertEquals($expected, $result);
$result = Cache::add('test_add_key', 'test data 2', 'default');
$this->assertFalse($result);
}
}

View file

@ -2,22 +2,27 @@
/**
* IniReaderTest
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Configure
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('IniReader', 'Configure');
/**
* IniReaderTest
*
* @package Cake.Test.Case.Configure
*/
class IniReaderTest extends CakeTestCase {
/**
@ -261,6 +266,7 @@ three.four = value four
is_null = null
bool_false = false
bool_true = true
[Asset]
timestamp = force
INI;

View file

@ -2,22 +2,27 @@
/**
* PhpConfigReaderTest
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Configure
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('PhpReader', 'Configure');
/**
* PhpReaderTest
*
* @package Cake.Test.Case.Configure
*/
class PhpReaderTest extends CakeTestCase {
/**

View file

@ -2,19 +2,18 @@
/**
* AllConsoleLibsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -45,4 +44,4 @@ class AllConsoleLibsTest extends PHPUnit_Framework_TestSuite {
}
return $suite;
}
}
}

View file

@ -2,19 +2,18 @@
/**
* AllConsoleTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**

View file

@ -2,19 +2,18 @@
/**
* AllShellsTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -39,4 +38,4 @@ class AllShellsTest extends PHPUnit_Framework_TestSuite {
$suite->addTestDirectory($path);
return $suite;
}
}
}

View file

@ -2,19 +2,18 @@
/**
* AllTasksTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -39,4 +38,3 @@ class AllTasksTest extends PHPUnit_Framework_TestSuite {
return $suite;
}
}

View file

@ -2,19 +2,18 @@
/**
* AclShell Test file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
@ -115,6 +114,7 @@ class AclShellTest extends CakeTestCase {
public function testParsingModelAndForeignKey() {
$result = $this->Task->parseIdentifier('Model.foreignKey');
$expected = array('model' => 'Model', 'foreign_key' => 'foreignKey');
$this->assertEquals($expected, $result);
$result = $this->Task->parseIdentifier('mySuperUser');
$this->assertEquals('mySuperUser', $result);
@ -253,7 +253,7 @@ class AclShellTest extends CakeTestCase {
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'create');
$this->Task->check();
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', '*');
$this->Task->args = array('AuthUser.2', 'ROOT/Controller1', 'delete');
$this->Task->check();
}

View file

@ -2,19 +2,18 @@
/**
* ApiShellTest file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
@ -43,7 +42,7 @@ class ApiShellTest extends CakeTestCase {
$this->Shell = $this->getMock(
'ApiShell',
array('in', 'out', 'createFile', 'hr', '_stop'),
array( $out, $out, $in)
array($out, $out, $in)
);
}

View file

@ -2,20 +2,18 @@
/**
* BakeShell Test Case
*
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
@ -30,9 +28,6 @@ App::uses('Controller', 'Controller');
if (!class_exists('UsersController')) {
class UsersController extends Controller {
public $name = 'Users';
}
}

View file

@ -2,27 +2,31 @@
/**
* CommandListShellTest file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CommandListShell', 'Console/Command');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('CommandTask', 'Console/Command/Task');
/**
* TestStringOutput
*
* @package Cake.Test.Case.Console.Command
*/
class TestStringOutput extends ConsoleOutput {
public $output = '';
@ -33,6 +37,11 @@ class TestStringOutput extends ConsoleOutput {
}
/**
* CommandListShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class CommandListShellTest extends CakeTestCase {
/**
@ -60,6 +69,12 @@ class CommandListShellTest extends CakeTestCase {
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
$this->Shell->Command = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
@ -88,7 +103,7 @@ class CommandListShellTest extends CakeTestCase {
$expected = "/\[.*TestPluginTwo.*\] example, welcome/";
$this->assertRegExp($expected, $output);
$expected = "/\[.*CORE.*\] acl, api, bake, command_list, console, i18n, schema, test, testsuite, upgrade/";
$expected = "/\[.*CORE.*\] acl, api, bake, command_list, completion, console, i18n, schema, server, test, testsuite, upgrade/";
$this->assertRegExp($expected, $output);
$expected = "/\[.*app.*\] sample/";

View file

@ -0,0 +1,261 @@
<?php
/**
* CompletionShellTest file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.5
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CompletionShell', 'Console/Command');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
App::uses('Shell', 'Console');
App::uses('CommandTask', 'Console/Command/Task');
/**
* TestCompletionStringOutput
*
* @package Cake.Test.Case.Console.Command
*/
class TestCompletionStringOutput extends ConsoleOutput {
public $output = '';
protected function _write($message) {
$this->output .= $message;
}
}
/**
* CompletionShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class CompletionShellTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$out = new TestCompletionStringOutput();
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Shell = $this->getMock(
'CompletionShell',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
$this->Shell->Command = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Shell);
CakePlugin::unload();
}
/**
* test that the startup method supresses the shell header
*
* @return void
*/
public function testStartup() {
$this->Shell->runCommand('main', array());
$output = $this->Shell->stdout->output;
$needle = 'Welcome to CakePHP';
$this->assertTextNotContains($needle, $output);
}
/**
* test that main displays a warning
*
* @return void
*/
public function testMain() {
$this->Shell->runCommand('main', array());
$output = $this->Shell->stdout->output;
$expected = "/This command is not intended to be called manually/";
$this->assertRegExp($expected, $output);
}
/**
* test commands method that list all available commands
*
* @return void
*/
public function testCommands() {
$this->Shell->runCommand('commands', array());
$output = $this->Shell->stdout->output;
$expected = "TestPlugin.example TestPlugin.test_plugin TestPluginTwo.example TestPluginTwo.welcome acl api bake command_list completion console i18n schema server test testsuite upgrade sample\n";
$this->assertEquals($expected, $output);
}
/**
* test that options without argument returns the default options
*
* @return void
*/
public function testOptionsNoArguments() {
$this->Shell->runCommand('options', array());
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q\n";
$this->assertEquals($expected, $output);
}
/**
* test that options with a nonexisting command returns the default options
*
* @return void
*/
public function testOptionsNonExistingCommand() {
$this->Shell->runCommand('options', array('options', 'foo'));
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q\n";
$this->assertEquals($expected, $output);
}
/**
* test that options with a existing command returns the proper options
*
* @return void
*/
public function testOptions() {
$this->Shell->runCommand('options', array('options', 'bake'));
$output = $this->Shell->stdout->output;
$expected = "--help -h --verbose -v --quiet -q --connection -c --theme -t\n";
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing CORE command returns the proper sub commands
*
* @return void
*/
public function testSubCommandsCorePlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'CORE.bake'));
$output = $this->Shell->stdout->output;
$expected = "controller db_config fixture model plugin project test view\n";
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing APP command returns the proper sub commands (in this case none)
*
* @return void
*/
public function testSubCommandsAppPlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'app.sample'));
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subCommands with a existing plugin command returns the proper sub commands
*
* @return void
*/
public function testSubCommandsPlugin() {
$this->Shell->runCommand('subCommands', array('subCommands', 'TestPluginTwo.welcome'));
$output = $this->Shell->stdout->output;
$expected = "say_hello\n";
$this->assertEquals($expected, $output);
}
/**
* test that subcommands without arguments returns nothing
*
* @return void
*/
public function testSubCommandsNoArguments() {
$this->Shell->runCommand('subCommands', array());
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subcommands with a nonexisting command returns nothing
*
* @return void
*/
public function testSubCommandsNonExistingCommand() {
$this->Shell->runCommand('subCommands', array('subCommands', 'foo'));
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
/**
* test that subcommands returns the available subcommands for the given command
*
* @return void
*/
public function testSubCommands() {
$this->Shell->runCommand('subCommands', array('subCommands', 'bake'));
$output = $this->Shell->stdout->output;
$expected = "controller db_config fixture model plugin project test view\n";
$this->assertEquals($expected, $output);
}
/**
* test that fuzzy returns nothing
*
* @return void
*/
public function testFuzzy() {
$this->Shell->runCommand('fuzzy', array());
$output = $this->Shell->stdout->output;
$expected = '';
$this->assertEquals($expected, $output);
}
}

View file

@ -2,19 +2,18 @@
/**
* SchemaShellTest Test file
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -31,17 +30,10 @@ App::uses('SchemaShell', 'Console/Command');
*/
class SchemaShellTestSchema extends CakeSchema {
/**
* name property
*
* @var string 'MyApp'
*/
public $name = 'SchemaShellTest';
/**
* connection property
*
* @var string 'test'
* @var string
*/
public $connection = 'test';
@ -78,6 +70,14 @@ class SchemaShellTestSchema extends CakeSchema {
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
public $newone = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => 0, 'key' => 'primary'),
'testit' => array('type' => 'string', 'null' => false, 'default' => 'Title'),
'created' => array('type' => 'datetime', 'null' => true, 'default' => null),
'updated' => array('type' => 'datetime', 'null' => true, 'default' => null),
'indexes' => array('PRIMARY' => array('column' => 'id', 'unique' => true)),
);
}
/**
@ -92,8 +92,9 @@ class SchemaShellTest extends CakeTestCase {
*
* @var array
*/
public $fixtures = array('core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author',
'core.comment', 'core.test_plugin_comment'
public $fixtures = array(
'core.article', 'core.user', 'core.post', 'core.auth_user', 'core.author',
'core.comment', 'core.test_plugin_comment', 'core.aco', 'core.aro', 'core.aros_aco',
);
/**
@ -134,7 +135,7 @@ class SchemaShellTest extends CakeTestCase {
public function testStartup() {
$this->Shell->startup();
$this->assertTrue(isset($this->Shell->Schema));
$this->assertTrue(is_a($this->Shell->Schema, 'CakeSchema'));
$this->assertInstanceOf('CakeSchema', $this->Shell->Schema);
$this->assertEquals(Inflector::camelize(Inflector::slug(APP_DIR)), $this->Shell->Schema->name);
$this->assertEquals('schema.php', $this->Shell->Schema->file);
@ -294,7 +295,7 @@ class SchemaShellTest extends CakeTestCase {
$this->Shell->Schema->path = TMP;
$this->Shell->Schema->expects($this->never())->method('read');
$result = $this->Shell->generate();
$this->Shell->generate();
unlink(TMP . 'schema.php');
}
@ -362,6 +363,90 @@ class SchemaShellTest extends CakeTestCase {
CakePlugin::unload();
}
/**
* test generate with specific models
*
* @return void
*/
public function testGenerateModels() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$this->db->cacheSources = false;
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'models' => 'TestPluginComment',
'force' => false,
'overwrite' => true
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$this->file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $this->file->read();
$this->assertRegExp('/class TestPluginSchema/', $contents);
$this->assertRegExp('/public \$test_plugin_comments/', $contents);
$this->assertNotRegExp('/public \$authors/', $contents);
$this->assertNotRegExp('/public \$auth_users/', $contents);
$this->assertNotRegExp('/public \$posts/', $contents);
CakePlugin::unload();
}
/**
* test generate with excluded tables
*
* @return void
*/
public function testGenerateExclude() {
Configure::write('Acl.database', 'test');
$this->db->cacheSources = false;
$this->Shell->params = array(
'connection' => 'test',
'force' => false,
'models' => 'Aro, Aco, Permission',
'overwrite' => true,
'exclude' => 'acos, aros',
);
$this->Shell->startup();
$this->Shell->Schema->path = TMP . 'tests' . DS;
$this->Shell->generate();
$this->file = new File(TMP . 'tests' . DS . 'schema.php');
$contents = $this->file->read();
$this->assertNotContains('public $acos = array(', $contents);
$this->assertNotContains('public $aros = array(', $contents);
$this->assertContains('public $aros_acos = array(', $contents);
}
/**
* Test schema run create with --yes option
*
* @return void
*/
public function testCreateOptionYes() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'yes' => true,
);
$this->Shell->args = array('i18n');
$this->Shell->expects($this->never())->method('in');
$this->Shell->expects($this->exactly(2))->method('_run');
$this->Shell->startup();
$this->Shell->create();
}
/**
* Test schema run create with no table args.
*
@ -394,15 +479,15 @@ class SchemaShellTest extends CakeTestCase {
public function testCreateWithTableArgs() {
$db = ConnectionManager::getDataSource('test');
$sources = $db->listSources();
if (in_array('acos', $sources)) {
$this->markTestSkipped('acos table already exists, cannot try to create it again.');
if (in_array('i18n', $sources)) {
$this->markTestSkipped('i18n table already exists, cannot try to create it again.');
}
$this->Shell->params = array(
'connection' => 'test',
'name' => 'DbAcl',
'name' => 'I18n',
'path' => APP . 'Config' . DS . 'Schema'
);
$this->Shell->args = array('DbAcl', 'acos');
$this->Shell->args = array('I18n', 'i18n');
$this->Shell->startup();
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->create();
@ -410,12 +495,10 @@ class SchemaShellTest extends CakeTestCase {
$db = ConnectionManager::getDataSource('test');
$db->cacheSources = false;
$sources = $db->listSources();
$this->assertTrue(in_array($db->config['prefix'] . 'acos', $sources), 'acos should be present.');
$this->assertFalse(in_array($db->config['prefix'] . 'aros', $sources), 'aros should not be found.');
$this->assertFalse(in_array('aros_acos', $sources), 'aros_acos should not be found.');
$this->assertTrue(in_array($db->config['prefix'] . 'i18n', $sources), 'i18n should be present.');
$schema = new DbAclSchema();
$db->execute($db->dropSchema($schema, 'acos'));
$schema = new I18nSchema();
$db->execute($db->dropSchema($schema, 'i18n'));
}
/**
@ -436,8 +519,66 @@ class SchemaShellTest extends CakeTestCase {
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->expects($this->any())->method('in')->will($this->returnValue('y'));
$this->Shell->expects($this->once())->method('_run')
$this->Shell->expects($this->any())
->method('in')
->will($this->returnValue('y'));
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
}
/**
* test run update with a table arg. and checks that a CREATE statement is issued
* table creation
* @return void
*/
public function testUpdateWithTableCreate() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'force' => true
);
$this->Shell->args = array('SchemaShellTest', 'newone');
$this->Shell->startup();
$this->Shell->expects($this->any())
->method('in')
->will($this->returnValue('y'));
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('newone'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
}
/**
* test run update with --yes option
*
* @return void
*/
public function testUpdateWithOptionYes() {
$this->Shell = $this->getMock(
'SchemaShell',
array('in', 'out', 'hr', 'createFile', 'error', 'err', '_stop', '_run'),
array(&$this->Dispatcher)
);
$this->Shell->params = array(
'connection' => 'test',
'force' => true,
'yes' => true,
);
$this->Shell->args = array('SchemaShellTest', 'articles');
$this->Shell->startup();
$this->Shell->expects($this->never())->method('in');
$this->Shell->expects($this->once())
->method('_run')
->with($this->arrayHasKey('articles'), 'update', $this->isInstanceOf('CakeSchema'));
$this->Shell->update();
@ -463,6 +604,71 @@ class SchemaShellTest extends CakeTestCase {
CakePlugin::unload();
}
/**
* test that underscored names also result in CamelCased class names
*
* @return void
*/
public function testName() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'name' => 'custom_names',
'force' => false,
'overwrite' => true,
);
$this->Shell->startup();
if (file_exists($this->Shell->Schema->path . DS . 'custom_names.php')) {
unlink($this->Shell->Schema->path . DS . 'custom_names.php');
}
$this->Shell->generate();
$contents = file_get_contents($this->Shell->Schema->path . DS . 'custom_names.php');
$this->assertRegExp('/class CustomNamesSchema/', $contents);
unlink($this->Shell->Schema->path . DS . 'custom_names.php');
CakePlugin::unload();
}
/**
* test that passing name and file creates the passed filename with the
* passed class name
*
* @return void
*/
public function testNameAndFile() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$this->Shell->params = array(
'plugin' => 'TestPlugin',
'connection' => 'test',
'name' => 'custom_name',
'file' => 'other_name',
'force' => false,
'overwrite' => true,
);
$this->Shell->startup();
$file = $this->Shell->Schema->path . DS . 'other_name.php';
if (file_exists($file)) {
unlink($file);
}
$this->Shell->generate();
$this->assertFileExists($file);
$contents = file_get_contents($file);
$this->assertRegExp('/class CustomNameSchema/', $contents);
if (file_exists($file)) {
unlink($file);
}
CakePlugin::unload();
}
/**
* test that using Plugin.name with write.
*

View file

@ -0,0 +1,242 @@
<?php
/**
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 2.5
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CommandTask', 'Console/Command/Task');
/**
* CommandTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
*/
class CommandTaskTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
App::build(array(
'Plugin' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS
),
'Console/Command' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'Console' . DS . 'Command' . DS
)
), App::RESET);
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->CommandTask = $this->getMock(
'CommandTask',
array('in', '_stop', 'clear'),
array($out, $out, $in)
);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->CommandTask);
CakePlugin::unload();
}
/**
* Test the resulting list of shells
*
* @return void
*/
public function testGetShellList() {
$result = $this->CommandTask->getShellList();
$expected = array(
'CORE' => array(
'acl',
'api',
'bake',
'command_list',
'completion',
'console',
'i18n',
'schema',
'server',
'test',
'testsuite',
'upgrade'
),
'TestPlugin' => array(
'example',
'test_plugin'
),
'TestPluginTwo' => array(
'example',
'welcome'
),
'app' => array(
'sample'
),
);
$this->assertEquals($expected, $result);
}
/**
* Test the resulting list of commands
*
* @return void
*/
public function testCommands() {
$result = $this->CommandTask->commands();
$expected = array(
'TestPlugin.example',
'TestPlugin.test_plugin',
'TestPluginTwo.example',
'TestPluginTwo.welcome',
'acl',
'api',
'bake',
'command_list',
'completion',
'console',
'i18n',
'schema',
'server',
'test',
'testsuite',
'upgrade',
'sample'
);
$this->assertEquals($expected, $result);
}
/**
* Test the resulting list of subcommands for the given command
*
* @return void
*/
public function testSubCommands() {
$result = $this->CommandTask->subCommands('acl');
$expected = array(
'check',
'create',
'db_config',
'delete',
'deny',
'getPath',
'grant',
'inherit',
'initdb',
'nodeExists',
'parseIdentifier',
'setParent',
'view'
);
$this->assertEquals($expected, $result);
}
/**
* Test that unknown commands return an empty array
*
* @return void
*/
public function testSubCommandsUnknownCommand() {
$result = $this->CommandTask->subCommands('yoghurt');
$expected = array();
$this->assertEquals($expected, $result);
}
/**
* Test that getting a existing shell returns the shell instance
*
* @return void
*/
public function testGetShell() {
$result = $this->CommandTask->getShell('acl');
$this->assertInstanceOf('AclShell', $result);
}
/**
* Test that getting a non-existing shell returns false
*
* @return void
*/
public function testGetShellNonExisting() {
$result = $this->CommandTask->getShell('strawberry');
$this->assertFalse($result);
}
/**
* Test that getting a existing core shell with 'core.' prefix returns the correct shell instance
*
* @return void
*/
public function testGetShellCore() {
$result = $this->CommandTask->getShell('core.bake');
$this->assertInstanceOf('BakeShell', $result);
}
/**
* Test the options array for a known command
*
* @return void
*/
public function testOptions() {
$result = $this->CommandTask->options('bake');
$expected = array(
'--help',
'-h',
'--verbose',
'-v',
'--quiet',
'-q',
'--connection',
'-c',
'--theme',
'-t'
);
$this->assertEquals($expected, $result);
}
/**
* Test the options array for an unknown command
*
* @return void
*/
public function testOptionsUnknownCommand() {
$result = $this->CommandTask->options('pie');
$expected = array(
'--help',
'-h',
'--verbose',
'-v',
'--quiet',
'-q'
);
$this->assertEquals($expected, $result);
}
}

View file

@ -2,19 +2,18 @@
/**
* ControllerTask Test Case
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
@ -39,10 +38,11 @@ $imported = class_exists('BakeArticle') || class_exists('BakeComment') || class_
if (!$imported) {
define('ARTICLE_MODEL_CREATED', true);
/**
* BakeArticle
*/
class BakeArticle extends Model {
public $name = 'BakeArticle';
public $hasMany = array('BakeComment');
public $hasAndBelongsToMany = array('BakeTag');
@ -90,6 +90,10 @@ class ControllerTaskTest extends CakeTestCase {
array($out, $out, $in)
);
$this->Task->Test = $this->getMock('TestTask', array(), array($out, $out, $in));
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Could not run as an Article, Tag or Comment model was already loaded.');
}
}
/**
@ -191,9 +195,9 @@ class ControllerTaskTest extends CakeTestCase {
*/
public function testDoHelpersTrailingSpace() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne '));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Text, Number, CustomOne '));
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$expected = array('Text', 'Number', 'CustomOne');
$this->assertEquals($expected, $result);
}
@ -204,9 +208,9 @@ class ControllerTaskTest extends CakeTestCase {
*/
public function testDoHelpersTrailingCommas() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Javascript, Ajax, CustomOne, , '));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' Text, Number, CustomOne, , '));
$result = $this->Task->doHelpers();
$expected = array('Javascript', 'Ajax', 'CustomOne');
$expected = array('Text', 'Number', 'CustomOne');
$this->assertEquals($expected, $result);
}
@ -218,7 +222,7 @@ class ControllerTaskTest extends CakeTestCase {
public function testDoComponentsNo() {
$this->Task->expects($this->any())->method('in')->will($this->returnValue('n'));
$result = $this->Task->doComponents();
$this->assertSame(array(), $result);
$this->assertSame(array('Paginator'), $result);
}
/**
@ -231,7 +235,7 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security '));
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$expected = array('Paginator', 'RequestHandler', 'Security');
$this->assertEquals($expected, $result);
}
@ -245,7 +249,7 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue(' RequestHandler, Security, , '));
$result = $this->Task->doComponents();
$expected = array('RequestHandler', 'Security');
$expected = array('Paginator', 'RequestHandler', 'Security');
$this->assertEquals($expected, $result);
}
@ -257,11 +261,11 @@ class ControllerTaskTest extends CakeTestCase {
public function testConfirmController() {
$controller = 'Posts';
$scaffold = false;
$helpers = array('Ajax', 'Time');
$helpers = array('Js', 'Time');
$components = array('Acl', 'Auth');
$this->Task->expects($this->at(4))->method('out')->with("Controller Name:\n\t$controller");
$this->Task->expects($this->at(5))->method('out')->with("Helpers:\n\tAjax, Time");
$this->Task->expects($this->at(5))->method('out')->with("Helpers:\n\tJs, Time");
$this->Task->expects($this->at(6))->method('out')->with("Components:\n\tAcl, Auth");
$this->Task->confirmController($controller, $scaffold, $helpers, $components);
}
@ -272,32 +276,21 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testBake() {
$helpers = array('Ajax', 'Time');
$helpers = array('Js', 'Time');
$components = array('Acl', 'Auth');
$this->Task->expects($this->any())->method('createFile')->will($this->returnValue(true));
$result = $this->Task->bake('Articles', '--actions--', $helpers, $components);
$this->assertContains(' * @property Article $Article', $result);
$this->assertContains(' * @property AclComponent $Acl', $result);
$this->assertContains(' * @property AuthComponent $Auth', $result);
$this->assertContains('class ArticlesController extends AppController', $result);
$this->assertContains("public \$components = array('Acl', 'Auth')", $result);
$this->assertContains("public \$helpers = array('Ajax', 'Time')", $result);
$this->assertContains("--actions--", $result);
$result = $this->Task->bake('Articles', null, $helpers, $components);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'NoActions.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bake('Articles', null, array(), array());
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'NoHelpersOrComponents.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bake('Articles', 'scaffold', $helpers, $components);
$this->assertContains("class ArticlesController extends AppController", $result);
$this->assertContains("public \$scaffold", $result);
$this->assertNotContains('@property', $result);
$this->assertNotContains('helpers', $result);
$this->assertNotContains('components', $result);
$result = $this->Task->bake('Articles', '--actions--', array(), array());
$this->assertContains('class ArticlesController extends AppController', $result);
$this->assertSame(substr_count($result, '@property'), 1);
$this->assertNotContains('components', $result);
$this->assertNotContains('helpers', $result);
$this->assertContains('--actions--', $result);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'Scaffold.ctp');
$this->assertTextEquals($expected, $result);
}
/**
@ -340,32 +333,11 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeActionsUsingSessions() {
$this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Comment & Tag Model to be undefined.');
$result = $this->Task->bakeActions('BakeArticles', null, true);
$this->assertContains('function index() {', $result);
$this->assertContains('$this->BakeArticle->recursive = 0;', $result);
$this->assertContains("\$this->set('bakeArticles', \$this->paginate());", $result);
$this->assertContains('function view($id = null)', $result);
$this->assertContains("throw new NotFoundException(__('Invalid bake article'));", $result);
$this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result);
$this->assertContains('function add()', $result);
$this->assertContains("if (\$this->request->is('post'))", $result);
$this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result);
$this->assertContains("\$this->Session->setFlash(__('The bake article has been saved'));", $result);
$this->assertContains('function edit($id = null)', $result);
$this->assertContains("\$this->Session->setFlash(__('The bake article could not be saved. Please, try again.'));", $result);
$this->assertContains('function delete($id = null)', $result);
$this->assertContains('if ($this->BakeArticle->delete())', $result);
$this->assertContains("\$this->Session->setFlash(__('Bake article deleted'));", $result);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'ActionsUsingSessions.ctp');
$this->assertTextEquals($expected, $result);
$result = $this->Task->bakeActions('BakeArticles', 'admin_', true);
$this->assertContains('function admin_index() {', $result);
$this->assertContains('function admin_add()', $result);
$this->assertContains('function admin_view($id = null)', $result);
@ -379,31 +351,9 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeActionsWithNoSessions() {
$this->skipIf(!defined('ARTICLE_MODEL_CREATED'), 'Testing bakeActions requires Article, Tag, Comment Models to be undefined.');
$result = $this->Task->bakeActions('BakeArticles', null, false);
$this->assertContains('function index() {', $result);
$this->assertContains('$this->BakeArticle->recursive = 0;', $result);
$this->assertContains("\$this->set('bakeArticles', \$this->paginate());", $result);
$this->assertContains('function view($id = null)', $result);
$this->assertContains("throw new NotFoundException(__('Invalid bake article'));", $result);
$this->assertContains("\$this->set('bakeArticle', \$this->BakeArticle->read(null, \$id)", $result);
$this->assertContains('function add()', $result);
$this->assertContains("if (\$this->request->is('post'))", $result);
$this->assertContains('if ($this->BakeArticle->save($this->request->data))', $result);
$this->assertContains("\$this->flash(__('The bake article has been saved.'), array('action' => 'index'))", $result);
$this->assertContains('function edit($id = null)', $result);
$this->assertContains("\$this->BakeArticle->BakeTag->find('list')", $result);
$this->assertContains("\$this->set(compact('bakeTags'))", $result);
$this->assertContains('function delete($id = null)', $result);
$this->assertContains('if ($this->BakeArticle->delete())', $result);
$this->assertContains("\$this->flash(__('Bake article deleted'), array('action' => 'index'))", $result);
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'Controller' . DS . 'ActionsWithNoSessions.ctp');
$this->assertTextEquals($expected, $result);
}
/**
@ -511,9 +461,7 @@ class ControllerTaskTest extends CakeTestCase {
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute into all could not be run as an Article, Tag or Comment model was already loaded.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
@ -530,15 +478,45 @@ class ControllerTaskTest extends CakeTestCase {
$this->Task->execute();
}
/**
* Test execute() with all and --admin
*
* @return void
*/
public function testExecuteIntoAllAdmin() {
$count = count($this->Task->listAll('test'));
if ($count != count($this->fixtures)) {
$this->markTestSkipped('Additional tables detected.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params['admin'] = true;
$this->Task->Project->expects($this->any())
->method('getPrefix')
->will($this->returnValue('admin_'));
$this->Task->expects($this->any())
->method('_checkUnitTest')
->will($this->returnValue(true));
$this->Task->Test->expects($this->once())->method('bake');
$filename = '/my/path/BakeArticlesController.php';
$this->Task->expects($this->once())->method('createFile')->with(
$filename,
$this->stringContains('function admin_index')
)->will($this->returnValue(true));
$this->Task->execute();
}
/**
* test that `cake bake controller foos` works.
*
* @return void
*/
public function testExecuteWithController() {
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
@ -570,9 +548,6 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithControllerNameVariations($name) {
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute with scaffold param requires no Article, Tag or Comment model to be defined.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array($name);
@ -590,9 +565,6 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithPublicParam() {
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute with public param requires no Article, Tag or Comment model to be defined.');
}
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('BakeArticles');
@ -612,9 +584,6 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithControllerAndBoth() {
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute with controller and both requires no Article, Tag or Comment model to be defined.');
}
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
@ -634,9 +603,6 @@ class ControllerTaskTest extends CakeTestCase {
* @return void
*/
public function testExecuteWithControllerAndAdmin() {
if (!defined('ARTICLE_MODEL_CREATED')) {
$this->markTestSkipped('Execute with controller and admin requires no Article, Tag or Comment model to be defined.');
}
$this->Task->Project->expects($this->any())->method('getPrefix')->will($this->returnValue('admin_'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';

View file

@ -2,19 +2,18 @@
/**
* DBConfigTask Test Case
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -101,7 +100,7 @@ class DbConfigTaskTest extends CakeTestCase {
$this->Task->expects($this->once())->method('_stop');
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('default')); //name
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('mysql')); //db type
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); //persistant
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n')); //persistent
$this->Task->expects($this->at(3))->method('in')->will($this->returnValue('localhost')); //server
$this->Task->expects($this->at(4))->method('in')->will($this->returnValue('n')); //port
$this->Task->expects($this->at(5))->method('in')->will($this->returnValue('root')); //user
@ -128,6 +127,6 @@ class DbConfigTaskTest extends CakeTestCase {
)
));
$result = $this->Task->execute();
$this->Task->execute();
}
}

View file

@ -4,19 +4,18 @@
*
* Test Case for i18n extraction shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Folder', 'Utility');
@ -49,7 +48,7 @@ class ExtractTaskTest extends CakeTestCase {
array($out, $out, $in)
);
$this->path = TMP . 'tests' . DS . 'extract_task_test';
$Folder = new Folder($this->path . DS . 'locale', true);
new Folder($this->path . DS . 'locale', true);
}
/**
@ -136,23 +135,23 @@ class ExtractTaskTest extends CakeTestCase {
$this->assertRegExp($pattern, $result);
// extract.ctp
$pattern = '/\#: (\\\\|\/)extract\.ctp:15;6\n';
$pattern = '/\#: extract\.ctp:15;6\n';
$pattern .= 'msgid "You have %d new message."\nmsgid_plural "You have %d new messages."/';
$this->assertRegExp($pattern, $result);
$pattern = '/msgid "You have %d new message."\nmsgstr ""/';
$this->assertNotRegExp($pattern, $result, 'No duplicate msgid');
$pattern = '/\#: (\\\\|\/)extract\.ctp:7\n';
$pattern = '/\#: extract\.ctp:7\n';
$pattern .= 'msgid "You deleted %d message."\nmsgid_plural "You deleted %d messages."/';
$this->assertRegExp($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:14\n';
$pattern .= '\#: (\\\\|\/)home\.ctp:99\n';
$pattern = '/\#: extract\.ctp:14\n';
$pattern .= '\#: home\.ctp:68\n';
$pattern .= 'msgid "Editing this Page"\nmsgstr ""/';
$this->assertRegExp($pattern, $result);
$pattern = '/\#: (\\\\|\/)extract\.ctp:22\nmsgid "';
$pattern = '/\#: extract\.ctp:22\nmsgid "';
$pattern .= 'Hot features!';
$pattern .= '\\\n - No Configuration: Set-up the database and let the magic begin';
$pattern .= '\\\n - Extremely Simple: Just look at the name...It\'s Cake';
@ -163,6 +162,21 @@ class ExtractTaskTest extends CakeTestCase {
$this->assertContains('msgid "double \\"quoted\\""', $result, 'Strings with quotes not handled correctly');
$this->assertContains("msgid \"single 'quoted'\"", $result, 'Strings with quotes not handled correctly');
$pattern = '/\#: extract\.ctp:36\nmsgid "letter"/';
$this->assertRegExp($pattern, $result, 'Strings with context should not overwrite strings without context');
$pattern = '/\#: extract\.ctp:37;39\nmsgctxt "A"\nmsgid "letter"/';
$this->assertRegExp($pattern, $result, 'Should contain string with context "A"');
$pattern = '/\#: extract\.ctp:38\nmsgctxt "B"\nmsgid "letter"/';
$this->assertRegExp($pattern, $result, 'Should contain string with context "B"');
$pattern = '/\#: extract\.ctp:40\nmsgid "%d letter"\nmsgid_plural "%d letters"/';
$this->assertRegExp($pattern, $result, 'Plural strings with context should not overwrite strings without context');
$pattern = '/\#: extract\.ctp:41\nmsgctxt "A"\nmsgid "%d letter"\nmsgid_plural "%d letters"/';
$this->assertRegExp($pattern, $result, 'Should contain plural string with context "A"');
// extract.ctp - reading the domain.pot
$result = file_get_contents($this->path . DS . 'domain.pot');
@ -177,6 +191,64 @@ class ExtractTaskTest extends CakeTestCase {
$this->assertRegExp($pattern, $result);
}
/**
* testExtractCategory method
*
* @return void
*/
public function testExtractCategory() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['merge'] = 'no';
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->any())->method('in')
->will($this->returnValue('y'));
$this->Task->expects($this->never())->method('_stop');
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'LC_NUMERIC' . DS . 'default.pot'));
$this->assertFalse(file_exists($this->path . DS . 'LC_TIME' . DS . 'default.pot'));
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = '/\#: .*extract\.ctp:31\n/';
$this->assertNotRegExp($pattern, $result);
$pattern = '/\#: .*extract\.ctp:33\n/';
$this->assertNotRegExp($pattern, $result);
}
/**
* testExtractWithoutLocations method
*
* @return void
*/
public function testExtractWithoutLocations() {
$this->Task->interactive = false;
$this->Task->params['paths'] = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages';
$this->Task->params['output'] = $this->path . DS;
$this->Task->params['extract-core'] = 'no';
$this->Task->params['merge'] = 'no';
$this->Task->params['no-location'] = true;
$this->Task->expects($this->never())->method('err');
$this->Task->expects($this->any())->method('in')
->will($this->returnValue('y'));
$this->Task->expects($this->never())->method('_stop');
$this->Task->execute();
$this->assertTrue(file_exists($this->path . DS . 'default.pot'));
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = '/\n\#: .*\n/';
$this->assertNotRegExp($pattern, $result);
}
/**
* test exclusions
*
@ -267,7 +339,7 @@ class ExtractTaskTest extends CakeTestCase {
$this->out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$this->in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ExtractTask',
array('_isExtractingApp', '_extractValidationMessages', 'in', 'out', 'err', 'clear', '_stop'),
array('_isExtractingApp', 'in', 'out', 'err', 'clear', '_stop'),
array($this->out, $this->out, $this->in)
);
@ -279,6 +351,7 @@ class ExtractTaskTest extends CakeTestCase {
$this->assertNotRegExp('#Pages#', $result);
$this->assertContains('translate.ctp:1', $result);
$this->assertContains('This is a translatable string', $result);
$this->assertContains('I can haz plugin model validation message', $result);
}
/**
@ -308,10 +381,10 @@ class ExtractTaskTest extends CakeTestCase {
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'default.pot');
$pattern = preg_quote('#Model' . DS . 'PersisterOne.php:validation for field title#', '\\');
$pattern = preg_quote('#Model/PersisterOne.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Model' . DS . 'PersisterOne.php:validation for field body#', '\\');
$pattern = preg_quote('#Model/PersisterOne.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';
@ -325,6 +398,9 @@ class ExtractTaskTest extends CakeTestCase {
$pattern = '#msgid "Post body is super required"#';
$this->assertRegExp($pattern, $result);
$this->assertContains('msgid "double \\"quoted\\" validation"', $result, 'Strings with quotes not handled correctly');
$this->assertContains("msgid \"single 'quoted' validation\"", $result, 'Strings with quotes not handled correctly');
}
/**
@ -354,10 +430,10 @@ class ExtractTaskTest extends CakeTestCase {
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'test_plugin.pot');
$pattern = preg_quote('#Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS . 'TestPluginPost.php:validation for field title#', '\\');
$pattern = preg_quote('#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Plugin' . DS . 'TestPlugin' . DS . 'Model' . DS . 'TestPluginPost.php:validation for field body#', '\\');
$pattern = preg_quote('#Plugin/TestPlugin/Model/TestPluginPost.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';
@ -393,10 +469,10 @@ class ExtractTaskTest extends CakeTestCase {
$this->Task->execute();
$result = file_get_contents($this->path . DS . 'test_plugin.pot');
$pattern = preg_quote('#Model' . DS . 'TestPluginPost.php:validation for field title#', '\\');
$pattern = preg_quote('#Model/TestPluginPost.php:validation for field title#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = preg_quote('#Model' . DS . 'TestPluginPost.php:validation for field body#', '\\');
$pattern = preg_quote('#Model/TestPluginPost.php:validation for field body#', '\\');
$this->assertRegExp($pattern, $result);
$pattern = '#msgid "Post title is required"#';

View file

@ -2,19 +2,18 @@
/**
* FixtureTask Test case
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -43,7 +42,7 @@ class FixtureTaskTest extends CakeTestCase {
/**
* Whether backup global state for each test method or not
*
* @var bool false
* @var bool
*/
public $backupGlobals = false;
@ -99,6 +98,7 @@ class FixtureTaskTest extends CakeTestCase {
* @return void
*/
public function testImportOptionsSchemaRecords() {
$this->Task->interactive = true;
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
@ -113,6 +113,7 @@ class FixtureTaskTest extends CakeTestCase {
* @return void
*/
public function testImportOptionsNothing() {
$this->Task->interactive = true;
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('n'));
@ -122,12 +123,70 @@ class FixtureTaskTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test importOptions with overwriting command line options.
*
* @return void
*/
public function testImportOptionsWithCommandLineOptions() {
$this->Task->params = array('schema' => true, 'records' => true);
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article', 'fromTable' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions with overwriting CLI options
*
* @return void
*/
public function testImportOptionsWithCommandLineOptionsPlugin() {
$this->Task->params = array('schema' => true, 'records' => true, 'plugin' => 'TestPlugin');
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'TestPlugin.Article', 'fromTable' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions with schema.
*
* @return void
*/
public function testImportOptionsWithSchema() {
$this->Task->interactive = true;
$this->Task->params = array('schema' => true);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array('schema' => 'Article');
$this->assertEquals($expected, $result);
}
/**
* test importOptions with records.
*
* @return void
*/
public function testImportOptionsWithRecords() {
$this->Task->interactive = true;
$this->Task->params = array('records' => true);
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$result = $this->Task->importOptions('Article');
$expected = array('fromTable' => true);
$this->assertEquals($expected, $result);
}
/**
* test importOptions choosing from Table.
*
* @return void
*/
public function testImportOptionsTable() {
$this->Task->interactive = true;
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('n'));
$this->Task->expects($this->at(2))->method('in')->will($this->returnValue('y'));
@ -145,6 +204,9 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->interactive = true;
$this->Task->expects($this->at(0))->method('in')
->will($this->returnValue('WHERE 1=1'));
$this->Task->expects($this->at(1))->method('in')
->with($this->anything(), $this->anything(), '3')
->will($this->returnValue('2'));
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
@ -156,9 +218,8 @@ class FixtureTaskTest extends CakeTestCase {
$this->assertContains('class ArticleFixture extends CakeTestFixture', $result);
$this->assertContains('public $records', $result);
$this->assertContains('public $import', $result);
$this->assertContains("'title' => 'First Article'", $result, 'Missing import data %s');
$this->assertContains('Second Article', $result, 'Missing import data %s');
$this->assertContains('Third Article', $result, 'Missing import data %s');
$this->assertContains("'title' => 'First Article'", $result, 'Missing import data');
$this->assertContains('Second Article', $result, 'Missing import data');
}
/**
@ -202,8 +263,63 @@ class FixtureTaskTest extends CakeTestCase {
}
/**
* test that execute passes runs bake depending with named model.
* test that execute includes import options
*
* @return void
*/
public function testExecuteWithImportSchema() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$this->Task->params = array(
'schema' => true,
'records' => false,
);
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->never())
->method('in');
$this->Task->expects($this->at(0))
->method('createFile')
->with($filename, $this->logicalAnd(
$this->stringContains('class ArticleFixture'),
$this->stringContains("\$import = array('model' => 'Article'")
));
$this->Task->execute();
}
/**
* test that execute includes import options
*
* @return void
*/
public function testExecuteWithImportRecords() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('article');
$this->Task->params = array(
'schema' => true,
'records' => true,
);
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->never())
->method('in');
$this->Task->expects($this->at(0))
->method('createFile')
->with($filename, $this->logicalAnd(
$this->stringContains('class ArticleFixture'),
$this->stringContains("\$import = array('model' => 'Article', 'connection' => 'test')")
));
$this->Task->execute();
}
/**
* test that execute passes runs bake depending with named model.
*
* @return void
*/
@ -271,6 +387,32 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->all();
}
/**
* test using all() with -schema
*
* @return void
*/
public function testAllWithSchemaImport() {
$this->Task->connection = 'test';
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->params = array('schema' => true);
$this->Task->Model->expects($this->any())->method('listAll')
->will($this->returnValue(array('Articles', 'comments')));
$filename = '/my/path/ArticleFixture.php';
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('public $import = array(\'model\' => \'Article\''));
$filename = '/my/path/CommentFixture.php';
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, $this->stringContains('public $import = array(\'model\' => \'Comment\''));
$this->Task->expects($this->exactly(2))->method('createFile');
$this->Task->all();
}
/**
* test interactive mode of execute
*
@ -360,9 +502,8 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->expects($this->at(1))->method('createFile')
->with($filename, $this->stringContains('<?php'));
$result = $this->Task->generateFixtureFile('Article', array());
$result = $this->Task->generateFixtureFile('Article', array());
$this->Task->generateFixtureFile('Article', array());
$this->Task->generateFixtureFile('Article', array());
}
/**
@ -381,7 +522,7 @@ class FixtureTaskTest extends CakeTestCase {
$this->Task->expects($this->at(0))->method('createFile')
->with($filename, $this->stringContains('class Article'));
$result = $this->Task->generateFixtureFile('Article', array());
$this->Task->generateFixtureFile('Article', array());
CakePlugin::unload();
}

View file

@ -4,19 +4,18 @@
*
* Test Case for test generation shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.6
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -31,6 +30,7 @@ App::uses('ModelTask', 'Console/Command/Task');
* ModelTaskTest class
*
* @package Cake.Test.Case.Console.Command.Task
* @property ModelTask $Task
*/
class ModelTaskTest extends CakeTestCase {
@ -41,7 +41,7 @@ class ModelTaskTest extends CakeTestCase {
*/
public $fixtures = array(
'core.bake_article', 'core.bake_comment', 'core.bake_articles_bake_tag',
'core.bake_tag', 'core.category_thread'
'core.bake_tag', 'core.category_thread', 'core.number_tree'
);
/**
@ -62,7 +62,7 @@ class ModelTaskTest extends CakeTestCase {
}
/**
* Setup a mock that has out mocked. Normally this is not used as it makes $this->at() really tricky.
* Setup a mock that has out mocked. Normally this is not used as it makes $this->at() really tricky.
*
* @return void
*/
@ -173,7 +173,7 @@ class ModelTaskTest extends CakeTestCase {
$this->Task->expects($this->any())->method('in')->will($this->onConsecutiveCalls(99, 1));
$this->Task->expects($this->once())->method('err');
$result = $this->Task->getName('test');
$this->Task->getName('test');
}
/**
@ -189,7 +189,7 @@ class ModelTaskTest extends CakeTestCase {
}
/**
* test gettting a custom table name.
* test getting a custom table name.
*
* @return void
*/
@ -268,7 +268,7 @@ class ModelTaskTest extends CakeTestCase {
*/
public function testInitValidations() {
$result = $this->Task->initValidations();
$this->assertTrue(in_array('notempty', $result));
$this->assertTrue(in_array('notBlank', $result));
}
/**
@ -282,7 +282,7 @@ class ModelTaskTest extends CakeTestCase {
$this->Task->initValidations();
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
$expected = array('notBlank' => 'notBlank');
$this->assertEquals($expected, $result);
$result = $this->Task->fieldValidation('text', array('type' => 'date', 'length' => 10, 'null' => false));
@ -315,10 +315,10 @@ class ModelTaskTest extends CakeTestCase {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('23', 'y', '17', 'n'));
->will($this->onConsecutiveCalls('24', 'y', '18', 'n'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty', 'maxlength' => 'maxlength');
$expected = array('notBlank' => 'notBlank', 'maxLength' => 'maxLength');
$this->assertEquals($expected, $result);
}
@ -333,13 +333,13 @@ class ModelTaskTest extends CakeTestCase {
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('999999', '23', 'n'));
->will($this->onConsecutiveCalls('999999', '24', 'n'));
$this->Task->expects($this->at(10))->method('out')
->with($this->stringContains('make a valid'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notempty' => 'notempty');
$expected = array('notBlank' => 'notBlank');
$this->assertEquals($expected, $result);
}
@ -359,6 +359,100 @@ class ModelTaskTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* Test that skipping fields during rule choice works when doing interactive field validation.
*
* @return void
*/
public function testSkippingChoiceInteractiveFieldValidation() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('24', 'y', 's'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notBlank' => 'notBlank', '_skipFields' => true);
$this->assertEquals($expected, $result);
}
/**
* Test that skipping fields after rule choice works when doing interactive field validation.
*
* @return void
*/
public function testSkippingAnotherInteractiveFieldValidation() {
$this->Task->initValidations();
$this->Task->interactive = true;
$this->Task->expects($this->any())->method('in')
->will($this->onConsecutiveCalls('24', 's'));
$result = $this->Task->fieldValidation('text', array('type' => 'string', 'length' => 10, 'null' => false));
$expected = array('notBlank' => 'notBlank', '_skipFields' => true);
$this->assertEquals($expected, $result);
}
/**
* Test the validation generation routine with skipping the rest of the fields
* when doing interactive field validation.
*
* @return void
*/
public function testInteractiveDoValidationWithSkipping() {
$this->Task->expects($this->any())
->method('in')
->will($this->onConsecutiveCalls('35', '24', 'n', '10', 's'));
$this->Task->interactive = true;
$Model = $this->getMock('Model');
$Model->primaryKey = 'id';
$Model->expects($this->any())
->method('schema')
->will($this->returnValue(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,
)
)
));
$result = $this->Task->doValidation($Model);
$expected = array(
'name' => array(
'notBlank' => 'notBlank'
),
'email' => array(
'email' => 'email',
),
);
$this->assertEquals($expected, $result);
}
/**
* test the validation Generation routine
*
@ -367,45 +461,48 @@ class ModelTaskTest extends CakeTestCase {
public function testNonInteractiveDoValidation() {
$Model = $this->getMock('Model');
$Model->primaryKey = 'id';
$Model->expects($this->any())->method('schema')->will($this->returnValue(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,
$Model->expects($this->any())
->method('schema')
->will($this->returnValue(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'
'notBlank' => 'notBlank'
),
'email' => array(
'email' => 'email',
@ -622,6 +719,20 @@ class ModelTaskTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test non interactive doActsAs
*
* @return void
*/
public function testDoActsAs() {
$this->Task->connection = 'test';
$this->Task->interactive = false;
$model = new Model(array('ds' => 'test', 'name' => 'NumberTree'));
$result = $this->Task->doActsAs($model);
$this->assertEquals(array('Tree'), $result);
}
/**
* Ensure that the fixture object is correctly called.
*
@ -727,7 +838,7 @@ class ModelTaskTest extends CakeTestCase {
public function testBakeValidation() {
$validate = array(
'name' => array(
'notempty' => 'notempty'
'notBlank' => 'notBlank'
),
'email' => array(
'email' => 'email',
@ -744,8 +855,8 @@ class ModelTaskTest extends CakeTestCase {
$this->assertRegExp('/\$validate \= array\(/', $result);
$expected = <<< STRINGEND
array(
'notempty' => array(
'rule' => array('notempty'),
'notBlank' => array(
'rule' => array('notBlank'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
@ -835,6 +946,27 @@ STRINGEND;
$this->assertEquals(count(ClassRegistry::mapKeys()), 0);
}
/**
* test bake() for models with behaviors
*
* @return void
*/
public function testBakeWithBehaviors() {
$result = $this->Task->bake('NumberTree', array('actsAs' => array('Tree', 'PluginName.Sluggable')));
$expected = <<<TEXT
/**
* Behaviors
*
* @var array
*/
public \$actsAs = array(
'Tree',
'PluginName.Sluggable',
);
TEXT;
$this->assertTextContains($expected, $result);
}
/**
* test that execute passes runs bake depending with named model.
*
@ -920,8 +1052,8 @@ STRINGEND;
$this->Task->args = array('all');
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->Fixture->expects($this->exactly(5))->method('bake');
$this->Task->Test->expects($this->exactly(5))->method('bake');
$this->Task->Fixture->expects($this->exactly(6))->method('bake');
$this->Task->Test->expects($this->exactly(6))->method('bake');
$filename = '/my/path/BakeArticle.php';
$this->Task->expects($this->at(1))->method('createFile')
@ -951,6 +1083,10 @@ STRINGEND;
$this->Task->expects($this->at(5))->method('createFile')
->with($filename, $this->stringContains('class CategoryThread'));
$filename = '/my/path/NumberTree.php';
$this->Task->expects($this->at(6))->method('createFile')
->with($filename, $this->stringContains('class NumberTree'));
$this->Task->execute();
$this->assertEquals(count(ClassRegistry::keys()), 0);
@ -958,7 +1094,7 @@ STRINGEND;
}
/**
* test that odd tablenames arent inflected back from modelname
* test that odd tablenames aren't inflected back from modelname
*
* @return void
*/
@ -986,7 +1122,7 @@ STRINGEND;
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ModelTask',
array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'createFile'),
array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'doActsAs', 'createFile'),
array($out, $out, $in)
);
$this->_setupOtherMocks();
@ -1000,6 +1136,7 @@ STRINGEND;
$this->Task->expects($this->once())->method('_getModelObject')->will($this->returnValue($object));
$this->Task->expects($this->once())->method('doAssociations')->will($this->returnValue(array()));
$this->Task->expects($this->once())->method('doValidation')->will($this->returnValue(array()));
$this->Task->expects($this->once())->method('doActsAs')->will($this->returnValue(array()));
$filename = '/my/path/BakeOdd.php';
$this->Task->expects($this->once())->method('createFile')
@ -1013,7 +1150,7 @@ STRINGEND;
}
/**
* test that odd tablenames arent inflected back from modelname
* test that odd tablenames aren't inflected back from modelname
*
* @return void
*/
@ -1041,7 +1178,7 @@ STRINGEND;
$out = $this->getMock('ConsoleOutput', array(), array(), '', false);
$in = $this->getMock('ConsoleInput', array(), array(), '', false);
$this->Task = $this->getMock('ModelTask',
array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'createFile'),
array('in', 'err', '_stop', '_checkUnitTest', 'getAllTables', '_getModelObject', 'doAssociations', 'doValidation', 'doActsAs', 'createFile'),
array($out, $out, $in)
);
$this->_setupOtherMocks();
@ -1055,6 +1192,7 @@ STRINGEND;
$this->Task->expects($this->once())->method('_getModelObject')->will($this->returnValue($object));
$this->Task->expects($this->once())->method('doAssociations')->will($this->returnValue(array()));
$this->Task->expects($this->once())->method('doValidation')->will($this->returnValue(array()));
$this->Task->expects($this->once())->method('doActsAs')->will($this->returnValue(array()));
$filename = '/my/path/BakeOdd.php';
$this->Task->expects($this->once())->method('createFile')
@ -1082,7 +1220,7 @@ STRINGEND;
$this->Task->path = '/my/path/';
$this->Task->args = array('all');
$this->Task->expects($this->once())->method('_checkUnitTest')->will($this->returnValue(true));
$this->Task->skipTables = array('bake_tags');
$this->Task->skipTables = array('bake_tags', 'number_trees');
$this->Task->Fixture->expects($this->exactly(4))->method('bake');
$this->Task->Test->expects($this->exactly(4))->method('bake');

View file

@ -4,19 +4,18 @@
*
* Test Case for plugin generation shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.3.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -59,7 +58,7 @@ class PluginTaskTest extends CakeTestCase {
array_splice($paths, $i, 1);
}
}
$this->_testPath = array_push($paths, TMP . 'tests' . DS);
$this->_testPath = array_push($paths, TMP . 'tests' . DS) - 1;
App::build(array('plugins' => $paths));
}
@ -81,17 +80,23 @@ class PluginTaskTest extends CakeTestCase {
* @return void
*/
public function testBakeFoldersAndFiles() {
$this->Task->expects($this->at(0))->method('in')->will($this->returnValue($this->_testPath));
$this->Task->expects($this->at(1))->method('in')->will($this->returnValue('y'));
$this->Task->expects($this->at(0))
->method('in')
->will($this->returnValue($this->_testPath));
$this->Task->expects($this->at(1))
->method('in')
->will($this->returnValue('y'));
$path = $this->Task->path . 'BakeTestPlugin';
$file = $path . DS . 'Controller' . DS . 'BakeTestPluginAppController.php';
$this->Task->expects($this->at(2))->method('createFile')
$this->Task->expects($this->at(2))
->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$file = $path . DS . 'Model' . DS . 'BakeTestPluginAppModel.php';
$this->Task->expects($this->at(3))->method('createFile')
$this->Task->expects($this->at(3))
->method('createFile')
->with($file, new PHPUnit_Framework_Constraint_IsAnything());
$this->Task->bake('BakeTestPlugin');
@ -101,18 +106,25 @@ class PluginTaskTest extends CakeTestCase {
$directories = array(
'Config' . DS . 'Schema',
'Model' . DS . 'Behavior',
'Model' . DS . 'Datasource',
'Console' . DS . 'Command' . DS . 'Task',
'Console' . DS . 'Templates',
'Controller' . DS . 'Component',
'Lib',
'View' . DS . 'Helper',
'Locale' . DS . 'eng' . DS . 'LC_MESSAGES',
'Model' . DS . 'Behavior',
'Model' . DS . 'Datasource',
'Test' . DS . 'Case' . DS . 'Controller' . DS . 'Component',
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper',
'Test' . DS . 'Case' . DS . 'Lib',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Behavior',
'Test' . DS . 'Case' . DS . 'Model' . DS . 'Datasource',
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper',
'Test' . DS . 'Fixture',
'Vendor',
'webroot'
'View' . DS . 'Elements',
'View' . DS . 'Helper',
'View' . DS . 'Layouts',
'webroot' . DS . 'css',
'webroot' . DS . 'js',
'webroot' . DS . 'img',
);
foreach ($directories as $dir) {
$this->assertTrue(is_dir($path . DS . $dir), 'Missing directory for ' . $dir);
@ -186,7 +198,9 @@ class PluginTaskTest extends CakeTestCase {
public function testFindPathNonExistant() {
$paths = App::path('plugins');
$last = count($paths);
$paths[] = '/fake/path';
array_unshift($paths, '/fake/path');
$paths[] = '/fake/path2';
$this->Task = $this->getMock('PluginTask',
array('in', 'out', 'err', 'createFile', '_stop'),

View file

@ -4,19 +4,18 @@
*
* Test Case for project generation shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.3.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -150,7 +149,7 @@ class ProjectTaskTest extends CakeTestCase {
}
/**
* test bake with CakePHP on the include path. The constants should remain commented out.
* test bake with CakePHP on the include path. The constants should remain commented out.
*
* @return void
*/
@ -198,7 +197,6 @@ class ProjectTaskTest extends CakeTestCase {
'Test' . DS . 'Case' . DS . 'View' . DS . 'Helper' => 'empty',
'Test' . DS . 'Fixture' => 'empty',
'Vendor' => 'empty',
'View' . DS . 'Elements' => 'empty',
'View' . DS . 'Scaffolds' => 'empty',
'tmp' . DS . 'cache' . DS . 'models' => 'empty',
'tmp' . DS . 'cache' . DS . 'persistent' => 'empty',
@ -249,6 +247,24 @@ class ProjectTaskTest extends CakeTestCase {
$this->assertNotRegExp('/76859309657453542496749683645/', $contents, 'Default CipherSeed left behind. %s');
}
/**
* test generation of cache prefix
*
* @return void
*/
public function testCachePrefixGeneration() {
$this->_setupTestProject();
$path = $this->Task->path . 'bake_test_app' . DS;
$result = $this->Task->cachePrefix($path);
$this->assertTrue($result);
$File = new File($path . 'Config' . DS . 'core.php');
$contents = $File->read();
$this->assertRegExp('/\$prefix = \'.+\';/', $contents, '$prefix is not defined');
$this->assertNotRegExp('/\$prefix = \'myapp_\';/', $contents, 'Default cache prefix left behind. %s');
}
/**
* Test that index.php is generated correctly.
*

View file

@ -4,21 +4,20 @@
*
* Test Case for TemplateTask generation shell task
*
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('ConsoleOutput', 'Console');
App::uses('ConsoleInput', 'Console');
@ -93,8 +92,8 @@ class TemplateTaskTest extends CakeTestCase {
}
/**
* 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
* 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
*/

View file

@ -4,19 +4,18 @@
*
* Test Case for test generation shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -32,17 +31,9 @@ App::uses('Model', 'Model');
* Test Article model
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskArticle extends Model {
/**
* Model name
*
* @var string
*/
public $name = 'TestTaskArticle';
/**
* Table name to use
*
@ -106,17 +97,9 @@ class TestTaskArticle extends Model {
* Tag Testing Model
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskTag extends Model {
/**
* Model name
*
* @var string
*/
public $name = 'TestTaskTag';
/**
* Table name
*
@ -143,7 +126,6 @@ class TestTaskTag extends Model {
* Simulated plugin
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskAppModel extends Model {
}
@ -152,17 +134,9 @@ class TestTaskAppModel extends Model {
* Testing AppMode (TaskComment)
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskComment extends TestTaskAppModel {
/**
* Model name
*
* @var string
*/
public $name = 'TestTaskComment';
/**
* Table name
*
@ -187,17 +161,9 @@ class TestTaskComment extends TestTaskAppModel {
* Test Task Comments Controller
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class TestTaskCommentsController extends Controller {
/**
* Controller Name
*
* @var string
*/
public $name = 'TestTaskComments';
/**
* Models to use
*
@ -349,14 +315,14 @@ class TestTaskTest extends CakeTestCase {
));
$keys = ClassRegistry::keys();
$this->assertTrue(in_array('test_task_comment', $keys));
$object = $this->Task->buildTestSubject('Model', 'TestTaskComment');
$this->Task->buildTestSubject('Model', 'TestTaskComment');
$keys = ClassRegistry::keys();
$this->assertFalse(in_array('random', $keys));
}
/**
* test that getClassName returns the user choice as a classname.
* test that getClassName returns the user choice as a class name.
*
* @return void
*/
@ -391,7 +357,7 @@ class TestTaskTest extends CakeTestCase {
}
/**
* test that resolving classnames works
* test that resolving class names works
*
* @return void
*/
@ -425,8 +391,8 @@ class TestTaskTest extends CakeTestCase {
}
/**
* 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.
* test baking files. The conditionally run tests are known to fail in PHP4
* as PHP4 class names are all lower case, breaking the plugin path inflection.
*
* @return void
*/
@ -447,6 +413,8 @@ class TestTaskTest extends CakeTestCase {
$this->assertContains('function testDoSomething()', $result);
$this->assertContains('function testDoSomethingElse()', $result);
$this->assertContains('$this->markTestIncomplete(\'testDoSomething not implemented.\')', $result);
$this->assertContains('$this->markTestIncomplete(\'testDoSomethingElse not implemented.\')', $result);
$this->assertContains("'app.test_task_article'", $result);
$this->assertContains("'app.test_task_comment'", $result);
@ -566,6 +534,8 @@ class TestTaskTest extends CakeTestCase {
/**
* Test generateUses()
*
* @return void
*/
public function testGenerateUses() {
$result = $this->Task->generateUses('model', 'Model', 'Post');
@ -694,7 +664,7 @@ class TestTaskTest extends CakeTestCase {
public function testTestCaseFileNamePlugin() {
$this->Task->path = DS . 'my' . DS . 'path' . DS . 'tests' . DS;
CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS ));
CakePlugin::load('TestTest', array('path' => APP . 'Plugin' . DS . 'TestTest' . DS));
$this->Task->plugin = 'TestTest';
$result = $this->Task->testCaseFileName('Model', 'Post');
$expected = APP . 'Plugin' . DS . 'TestTest' . DS . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'PostTest.php';

View file

@ -4,19 +4,18 @@
*
* Test Case for view generation shell task
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command.Task
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -30,22 +29,15 @@ App::uses('ProjectTask', 'Console/Command/Task');
App::uses('DbConfigTask', 'Console/Command/Task');
App::uses('Model', 'Model');
App::uses('Controller', 'Controller');
App::uses('AppController', 'Controller');
/**
* Test View Task Comment Model
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskComment extends Model {
/**
* Model name
*
* @var string
*/
public $name = 'ViewTaskComment';
/**
* Table name
*
@ -70,17 +62,9 @@ class ViewTaskComment extends Model {
* Test View Task Article Model
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskArticle extends Model {
/**
* Model name
*
* @var string
*/
public $name = 'ViewTaskArticle';
/**
* Table name
*
@ -93,17 +77,9 @@ class ViewTaskArticle extends Model {
* Test View Task Comments Controller
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskCommentsController extends Controller {
/**
* Controller name
*
* @var string
*/
public $name = 'ViewTaskComments';
/**
* Testing public controller action
*
@ -126,17 +102,9 @@ class ViewTaskCommentsController extends Controller {
* Test View Task Articles Controller
*
* @package Cake.Test.Case.Console.Command.Task
* @package Cake.Test.Case.Console.Command.Task
*/
class ViewTaskArticlesController extends Controller {
/**
* Controller name
*
* @var string
*/
public $name = 'ViewTaskArticles';
/**
* Test public controller action
*
@ -355,10 +323,11 @@ class ViewTaskTest extends CakeTestCase {
public function testBakeIndex() {
$this->Task->controllerName = 'ViewTaskComments';
$expected = file_get_contents(CAKE . 'Test' . DS . 'bake_compare' . DS . 'View' . DS . 'index.ctp');
$this->Task->expects($this->at(0))->method('createFile')
->with(
TMP . 'ViewTaskComments' . DS . 'index.ctp',
$this->stringContains("\$viewTaskComment['Article']['title']")
$expected
);
$this->Task->bake('index', true);
}

View file

@ -2,24 +2,28 @@
/**
* TestSuiteShell test case
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('TestShell', 'Console/Command');
/**
* TestTestShell
*
* @package Cake.Test.Case.Console.Command
*/
class TestTestShell extends TestShell {
public function mapFileToCase($file, $category, $throwOnMissingFile = true) {
@ -32,6 +36,11 @@ class TestTestShell extends TestShell {
}
/**
* TestShellTest
*
* @package Cake.Test.Case.Console.Command
*/
class TestShellTest extends CakeTestCase {
/**
@ -332,4 +341,40 @@ class TestShellTest extends CakeTestCase {
);
$this->Shell->main();
}
/**
* Tests that the 'quiet' parameter gets swallowed before calling PHPUnit
*
* @return void
*/
public function testRunnerOptionsQuiet() {
$this->Shell->startup();
$this->Shell->args = array('core', 'Basics');
$this->Shell->params = array('quiet' => true);
$this->Shell->expects($this->once())->method('_run')
->with(
array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'),
array('--colors')
);
$this->Shell->main();
}
/**
* Tests that the '--directive' parameter change to '-d' before calling PHPUnit
*
* @return void
*/
public function testRunnerOptionsDirective() {
$this->Shell->startup();
$this->Shell->args = array('core', 'Basics');
$this->Shell->params = array('directive' => 'memory_limit=128M');
$this->Shell->expects($this->once())->method('_run')
->with(
array('app' => false, 'plugin' => null, 'core' => true, 'output' => 'text', 'case' => 'Basics'),
array('-d', 'memory_limit=128M', '--colors')
);
$this->Shell->main();
}
}

View file

@ -2,19 +2,18 @@
/**
* ConsoleErrorHandler Test case
*
* PHP versions 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleErrorHandler', 'Console');
@ -148,4 +147,31 @@ class ConsoleErrorHandlerTest extends CakeTestCase {
$this->Error->handleException($exception);
}
/**
* test a exception with non-integer code
*
* @return void
*/
public function testNonIntegerExceptionCode() {
if (PHP_VERSION_ID < 50300) {
$this->markTestSkipped('ReflectionProperty::setAccessible() is available since 5.3');
}
$exception = new Exception('Non-integer exception code');
$class = new ReflectionClass('Exception');
$property = $class->getProperty('code');
$property->setAccessible(true);
$property->setValue($exception, '42S22');
ConsoleErrorHandler::$stderr->expects($this->once())->method('write')
->with($this->stringContains('Non-integer exception code'));
$this->Error->expects($this->once())
->method('_stop')
->with(1);
$this->Error->handleException($exception);
}
}

View file

@ -2,23 +2,27 @@
/**
* ConsoleOptionParserTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOptionParser', 'Console');
/**
* ConsoleOptionParserTest
*
* @package Cake.Test.Case.Console
*/
class ConsoleOptionParserTest extends CakeTestCase {
/**
@ -33,7 +37,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals($parser, $result, 'Setting description is not chainable');
$this->assertEquals('A test', $parser->description(), 'getting value is wrong.');
$result = $parser->description(array('A test', 'something'));
$parser->description(array('A test', 'something'));
$this->assertEquals("A test\nsomething", $parser->description(), 'getting value is wrong.');
}
@ -49,7 +53,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals($parser, $result, 'Setting epilog is not chainable');
$this->assertEquals('A test', $parser->epilog(), 'getting value is wrong.');
$result = $parser->epilog(array('A test', 'something'));
$parser->epilog(array('A test', 'something'));
$this->assertEquals("A test\nsomething", $parser->epilog(), 'getting value is wrong.');
}
@ -254,24 +258,26 @@ class ConsoleOptionParserTest extends CakeTestCase {
* test parsing options that do not exist.
*
* @expectedException ConsoleException
* @return void
*/
public function testOptionThatDoesNotExist() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('no-commit', array('boolean' => true));
$result = $parser->parse(array('--fail', 'other'));
$parser->parse(array('--fail', 'other'));
}
/**
* test parsing short options that do not exist.
*
* @expectedException ConsoleException
* @return void
*/
public function testShortOptionThatDoesNotExist() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('no-commit', array('boolean' => true));
$result = $parser->parse(array('-f'));
$parser->parse(array('-f'));
}
/**
@ -288,7 +294,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$expected = array('name' => 'mark', 'help' => false);
$this->assertEquals($expected, $result[0], 'Got the correct value.');
$result = $parser->parse(array('--name', 'jimmy'));
$parser->parse(array('--name', 'jimmy'));
}
/**
@ -378,7 +384,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$result = $parser->parse($expected);
$this->assertEquals($expected, $result[1], 'Arguments are not as expected');
$result = $parser->parse(array('one', 'two', 'three'));
$parser->parse(array('one', 'two', 'three'));
}
/**
@ -424,7 +430,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$expected = array('mark', 'samurai', 'sword');
$this->assertEquals($expected, $result[1], 'Got the correct value.');
$result = $parser->parse(array('jose', 'coder'));
$parser->parse(array('jose', 'coder'));
}
/**
@ -470,6 +476,21 @@ class ConsoleOptionParserTest extends CakeTestCase {
$this->assertEquals('test', $result['test']->name());
}
/**
* test removeSubcommand with an object.
*
* @return void
*/
public function testRemoveSubcommand() {
$parser = new ConsoleOptionParser('test', false);
$parser->addSubcommand(new ConsoleInputSubcommand('test'));
$result = $parser->subcommands();
$this->assertEquals(1, count($result));
$parser->removeSubcommand('test');
$result = $parser->subcommands();
$this->assertEquals(0, count($result), 'Remove a subcommand does not work');
}
/**
* test adding multiple subcommands
*

View file

@ -2,23 +2,27 @@
/**
* ConsoleOutputTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOutput', 'Console');
/**
* ConsoleOutputTest
*
* @package Cake.Test.Case.Console
*/
class ConsoleOutputTest extends CakeTestCase {
/**
@ -90,6 +94,27 @@ class ConsoleOutputTest extends CakeTestCase {
$this->output->write(array('Line', 'Line', 'Line'));
}
/**
* test writing an array of messages.
*
* @return void
*/
public function testOverwrite() {
$testString = "Text";
$this->output->expects($this->at(0))->method('_write')
->with($testString);
$this->output->expects($this->at(1))->method('_write')
->with("");
$this->output->expects($this->at(2))->method('_write')
->with("Overwriting text");
$this->output->write($testString, 0);
$this->output->overwrite("Overwriting text");
}
/**
* test getting a style.
*
@ -227,6 +252,17 @@ class ConsoleOutputTest extends CakeTestCase {
$this->output->write('<error>Bad</error> Regular', false);
}
/**
* test plain output when php://output, as php://output is
* not compatible with posix_ functions.
*
* @return void
*/
public function testOutputAsPlainWhenOutputStream() {
$output = $this->getMock('ConsoleOutput', array('_write'), array('php://output'));
$this->assertEquals(ConsoleOutput::PLAIN, $output->outputAs());
}
/**
* test plain output only strips tags used for formatting.
*

View file

@ -2,24 +2,28 @@
/**
* HelpFormatterTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleOptionParser', 'Console');
App::uses('HelpFormatter', 'Console');
/**
* HelpFormatterTest
*
* @package Cake.Test.Case.Console
*/
class HelpFormatterTest extends CakeTestCase {
/**

View file

@ -0,0 +1,223 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 2.8
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses("ProgressShellHelper", "Console/Helper");
App::uses("ConsoleOutputStub", "TestSuite/Stub");
/**
* ProgressHelper test.
* @property ConsoleOutputStub $consoleOutput
* @property ProgressShellHelper $helper
*/
class ProgressShellHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->consoleOutput = new ConsoleOutputStub();
$this->helper = new ProgressShellHelper($this->consoleOutput);
}
/**
* Test that a callback is required.*
*
* @expectedException \RuntimeException
* @return void
*/
public function testOutputFailure() {
$this->helper->output(array('not a callback'));
}
/**
* Test that the callback is invoked until 100 is reached.
*
* @return void
*/
public function testOutputSuccess() {
$this->helper->output(array(function ($progress) {
$progress->increment(20);
}));
$expected = array(
'',
'==============> 20%',
'',
'=============================> 40%',
'',
'============================================> 60%',
'',
'===========================================================> 80%',
'',
'==========================================================================> 100%',
'',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output with options
*
* @return void
*/
public function testOutputSuccessOptions() {
$this->helper->output(array(
'total' => 10,
'width' => 20,
'callback' => function ($progress) {
$progress->increment(2);
}
));
$expected = array(
'',
'==> 20%',
'',
'=====> 40%',
'',
'========> 60%',
'',
'===========> 80%',
'',
'==============> 100%',
'',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test using the helper manually.
*
* @return void
*/
public function testIncrementAndRender() {
$this->helper->init();
$this->helper->increment(20);
$this->helper->draw();
$this->helper->increment(40);
$this->helper->draw();
$this->helper->increment(40);
$this->helper->draw();
$expected = array(
'',
'==============> 20%',
'',
'============================================> 60%',
'',
'==========================================================================> 100%',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test negative numbers
*
* @return void
*/
public function testIncrementWithNegatives() {
$this->helper->init();
$this->helper->increment(40);
$this->helper->draw();
$this->helper->increment(-60);
$this->helper->draw();
$this->helper->increment(80);
$this->helper->draw();
$expected = array(
'',
'=============================> 40%',
'',
' 0%',
'',
'===========================================================> 80%',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test increment and draw with options
*
* @return void
*/
public function testIncrementWithOptions() {
$this->helper->init(array(
'total' => 10,
'width' => 20,
));
$this->helper->increment(4);
$this->helper->draw();
$this->helper->increment(4);
$this->helper->draw();
$this->helper->increment(4);
$this->helper->draw();
$expected = array(
'',
'=====> 40%',
'',
'===========> 80%',
'',
'==============> 100%',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test increment and draw with value that makes the pad
* be a float
*
* @return void
*/
public function testIncrementFloatPad() {
$this->helper->init(array(
'total' => 50
));
$this->helper->increment(7);
$this->helper->draw();
$this->helper->increment(7);
$this->helper->draw();
$this->helper->increment(7);
$this->helper->draw();
$this->helper->increment(7);
$this->helper->draw();
$this->helper->increment(7);
$this->helper->draw();
$this->helper->increment(3);
$this->helper->draw();
$this->helper->increment(4);
$this->helper->draw();
$this->helper->increment(8);
$this->helper->draw();
$expected = array(
'',
'=========> 14%',
'',
'====================> 28%',
'',
'==============================> 42%',
'',
'=========================================> 56%',
'',
'===================================================> 70%',
'',
'========================================================> 76%',
'',
'==============================================================> 84%',
'',
'==========================================================================> 100%',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
}

View file

@ -0,0 +1,201 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 2.8
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses("TableShellHelper", "Console/Helper");
App::uses("ConsoleOutputStub", "TestSuite/Stub");
/**
* ProgressHelper test.
* @property ConsoleOutputStub $consoleOutput
* @property TableShellHelper $helper
*/
class TableShellHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->consoleOutput = new ConsoleOutputStub();
$this->helper = new TableShellHelper($this->consoleOutput);
}
/**
* Test output
*
* @return void
*/
public function testDefaultOutput() {
$data = array(
array('Header 1', 'Header', 'Long Header'),
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value'),
);
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |',
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output with multibyte characters
*
* @return void
*/
public function testOutputUtf8() {
$data = array(
array('Header 1', 'Head', 'Long Header'),
array('short', 'ÄÄÄÜÜÜ', 'short'),
array('Longer thing', 'longerish', 'Longest Value'),
);
$this->helper->output($data);
$expected = array(
'+--------------+-----------+---------------+',
'| <info>Header 1</info> | <info>Head</info> | <info>Long Header</info> |',
'+--------------+-----------+---------------+',
'| short | ÄÄÄÜÜÜ | short |',
'| Longer thing | longerish | Longest Value |',
'+--------------+-----------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output without headers
*
* @return void
*/
public function testOutputWithoutHeaderStyle() {
$data = array(
array('Header 1', 'Header', 'Long Header'),
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value'),
);
$this->helper->config(array('headerStyle' => false));
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| Header 1 | Header | Long Header |',
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output with different header style
*
* @return void
*/
public function testOutputWithDifferentHeaderStyle() {
$data = array(
array('Header 1', 'Header', 'Long Header'),
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value'),
);
$this->helper->config(array('headerStyle' => 'error'));
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| <error>Header 1</error> | <error>Header</error> | <error>Long Header</error> |',
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output without table headers
*
* @return void
*/
public function testOutputWithoutHeaders() {
$data = array(
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value'),
);
$this->helper->config(array('headers' => false));
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output with row separator
*
* @return void
*/
public function testOutputWithRowSeparator() {
$data = array(
array('Header 1', 'Header', 'Long Header'),
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value')
);
$this->helper->config(array('rowSeparator' => true));
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |',
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'+--------------+---------------+---------------+',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
/**
* Test output with row separator and no headers
*
* @return void
*/
public function testOutputWithRowSeparatorAndHeaders() {
$data = array(
array('Header 1', 'Header', 'Long Header'),
array('short', 'Longish thing', 'short'),
array('Longer thing', 'short', 'Longest Value'),
);
$this->helper->config(array('rowSeparator' => true));
$this->helper->output($data);
$expected = array(
'+--------------+---------------+---------------+',
'| <info>Header 1</info> | <info>Header</info> | <info>Long Header</info> |',
'+--------------+---------------+---------------+',
'| short | Longish thing | short |',
'+--------------+---------------+---------------+',
'| Longer thing | short | Longest Value |',
'+--------------+---------------+---------------+',
);
$this->assertEquals($expected, $this->consoleOutput->messages());
}
}

View file

@ -2,19 +2,18 @@
/**
* ShellDispatcherTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
@ -138,9 +137,8 @@ class ShellDispatcherTest extends CakeTestCase {
*
* @return void
*/
public function testParseParams() {
public function testParseParamsAppWorkingAbsolute() {
$Dispatcher = new TestShellDispatcher();
$params = array(
'/cake/1.2.x.x/cake/console/cake.php',
'bake',
@ -153,11 +151,19 @@ class ShellDispatcherTest extends CakeTestCase {
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('/', DS, '/var/www/htdocs/new'),
'root' => str_replace('/', DS,'/var/www/htdocs')
'root' => str_replace('/', DS, '/var/www/htdocs')
);
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
}
/**
* testParseParams method
*
* @return void
*/
public function testParseParamsNone() {
$Dispatcher = new TestShellDispatcher();
$params = array('cake.php');
$expected = array(
'app' => 'app',
@ -168,7 +174,15 @@ class ShellDispatcherTest extends CakeTestCase {
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
}
/**
* testParseParams method
*
* @return void
*/
public function testParseParamsApp() {
$Dispatcher = new TestShellDispatcher();
$params = array(
'cake.php',
'-app',
@ -183,7 +197,15 @@ class ShellDispatcherTest extends CakeTestCase {
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
}
/**
* testParseParams method
*
* @return void
*/
public function testParseParamsAppWorkingRelative() {
$Dispatcher = new TestShellDispatcher();
$params = array(
'./cake.php',
'bake',
@ -192,17 +214,24 @@ class ShellDispatcherTest extends CakeTestCase {
'-working',
'/cake/1.2.x.x/cake/console'
);
$expected = array(
'app' => 'new',
'webroot' => 'webroot',
'working' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH) . DS . 'new'),
'root' => str_replace('\\', DS, dirname(CAKE_CORE_INCLUDE_PATH))
);
$Dispatcher->params = $Dispatcher->args = array();
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
}
/**
* testParseParams method
*
* @return void
*/
public function testParseParams() {
$Dispatcher = new TestShellDispatcher();
$params = array(
'./console/cake.php',
@ -379,7 +408,7 @@ class ShellDispatcherTest extends CakeTestCase {
'app' => 'old',
'webroot' => 'webroot',
'working' => str_replace('/', DS, '/var/www/htdocs/old'),
'root' => str_replace('/', DS,'/var/www/htdocs')
'root' => str_replace('/', DS, '/var/www/htdocs')
);
$Dispatcher->parseParams($params);
$this->assertEquals($expected, $Dispatcher->params);
@ -428,6 +457,14 @@ class ShellDispatcherTest extends CakeTestCase {
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('TestPlugin.example');
$this->assertInstanceOf('ExampleShell', $result);
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('test_plugin');
$this->assertInstanceOf('TestPluginShell', $result);
$Dispatcher = new TestShellDispatcher();
$result = $Dispatcher->getShell('TestPlugin');
$this->assertInstanceOf('TestPluginShell', $result);
}
/**
@ -437,15 +474,14 @@ class ShellDispatcherTest extends CakeTestCase {
*/
public function testDispatchShellWithMain() {
$Dispatcher = new TestShellDispatcher();
$Mock = $this->getMock('Shell', array(), array(), 'MockWithMainShell');
$Shell = $this->getMock('Shell');
$Mock->expects($this->once())->method('initialize');
$Mock->expects($this->once())->method('loadTasks');
$Mock->expects($this->once())->method('runCommand')
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('runCommand')
->with(null, array())
->will($this->returnValue(true));
$Dispatcher->TestShell = $Mock;
$Dispatcher->TestShell = $Shell;
$Dispatcher->args = array('mock_with_main');
$result = $Dispatcher->dispatch();
@ -460,13 +496,9 @@ class ShellDispatcherTest extends CakeTestCase {
*/
public function testDispatchShellWithoutMain() {
$Dispatcher = new TestShellDispatcher();
$Shell = $this->getMock('Shell', array(), array(), 'MockWithoutMainShell');
$Shell = new MockWithoutMainShell();
$this->mockObjects[] = $Shell;
$Shell = $this->getMock('Shell');
$Shell->expects($this->once())->method('initialize');
$Shell->expects($this->once())->method('loadTasks');
$Shell->expects($this->once())->method('runCommand')
->with('initdb', array('initdb'))
->will($this->returnValue(true));
@ -485,12 +517,11 @@ class ShellDispatcherTest extends CakeTestCase {
*/
public function testDispatchNotAShellWithMain() {
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
$methods = get_class_methods('CakeObject');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods, array(), 'MockWithMainNotAShell');
$Shell = $this->getMock('CakeObject', $methods);
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->never())->method('loadTasks');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
@ -500,8 +531,7 @@ class ShellDispatcherTest extends CakeTestCase {
$this->assertTrue($result);
$this->assertEquals(array(), $Dispatcher->args);
$Shell = new MockWithMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell = $this->getMock('CakeObject', $methods);
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
@ -518,12 +548,11 @@ class ShellDispatcherTest extends CakeTestCase {
*/
public function testDispatchNotAShellWithoutMain() {
$Dispatcher = new TestShellDispatcher();
$methods = get_class_methods('Object');
$methods = get_class_methods('CakeObject');
array_push($methods, 'main', 'initdb', 'initialize', 'loadTasks', 'startup', '_secret');
$Shell = $this->getMock('Object', $methods, array(&$Dispatcher), 'MockWithoutMainNotAShell');
$Shell = $this->getMock('CakeObject', $methods);
$Shell->expects($this->never())->method('initialize');
$Shell->expects($this->never())->method('loadTasks');
$Shell->expects($this->once())->method('startup');
$Shell->expects($this->once())->method('main')->will($this->returnValue(true));
$Dispatcher->TestShell = $Shell;
@ -533,8 +562,7 @@ class ShellDispatcherTest extends CakeTestCase {
$this->assertTrue($result);
$this->assertEquals(array(), $Dispatcher->args);
$Shell = new MockWithoutMainNotAShell($Dispatcher);
$this->mockObjects[] = $Shell;
$Shell = $this->getMock('CakeObject', $methods);
$Shell->expects($this->once())->method('initdb')->will($this->returnValue(true));
$Shell->expects($this->once())->method('startup');
$Dispatcher->TestShell = $Shell;
@ -564,7 +592,7 @@ class ShellDispatcherTest extends CakeTestCase {
$this->assertEquals('a', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array('b' => 'c', 'd'));
$Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
$Dispatcher->args = array(0 => 'a', 2 => 'b', 30 => 'c');
$this->assertEquals('a', $Dispatcher->shiftArgs());
$this->assertSame($Dispatcher->args, array(0 => 'b', 1 => 'c'));

View file

@ -4,24 +4,24 @@
*
* Test Case for Shell
*
* PHP 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Console.Command
* @since CakePHP v 1.2.0.7726
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ShellDispatcher', 'Console');
App::uses('Shell', 'Console');
App::uses('Folder', 'Utility');
App::uses("ProgressHelper", "Console/Helper");
/**
* ShellTestShell class
@ -40,7 +40,7 @@ class ShellTestShell extends Shell {
/**
* stopped property
*
* @var integer
* @var int
*/
public $stopped;
@ -54,7 +54,7 @@ class ShellTestShell extends Shell {
/**
* stop method
*
* @param integer $status
* @param int $status
* @return void
*/
protected function _stop($status = 0) {
@ -194,6 +194,7 @@ class ShellTest extends CakeTestCase {
), App::RESET);
CakePlugin::load('TestPlugin');
$this->Shell->tasks = array('DbConfig' => array('one', 'two'));
$this->Shell->uses = array('TestPlugin.TestPluginPost');
$this->Shell->initialize();
@ -207,6 +208,33 @@ class ShellTest extends CakeTestCase {
$this->assertTrue(isset($this->Shell->Comment));
$this->assertInstanceOf('Comment', $this->Shell->Comment);
$this->assertEquals('Comment', $this->Shell->modelClass);
$this->assertInstanceOf('DbConfigTask', $this->Shell->DbConfig);
App::build();
}
/**
* testLoadModel method
*
* @return void
*/
public function testLoadModel() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
'Model' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Model' . DS)
), App::RESET);
$Shell = new TestMergeShell();
$this->assertEquals('Comment', $Shell->Comment->alias);
$this->assertInstanceOf('Comment', $Shell->Comment);
$this->assertEquals('Comment', $Shell->modelClass);
CakePlugin::load('TestPlugin');
$this->Shell->loadModel('TestPlugin.TestPluginPost');
$this->assertTrue(isset($this->Shell->TestPluginPost));
$this->assertInstanceOf('TestPluginPost', $this->Shell->TestPluginPost);
$this->assertEquals('TestPluginPost', $this->Shell->modelClass);
CakePlugin::unload('TestPlugin');
App::build();
}
@ -341,6 +369,36 @@ class ShellTest extends CakeTestCase {
$this->Shell->out('Quiet', 1, Shell::QUIET);
}
/**
* Test overwriting.
*
* @return void
*/
public function testOverwrite() {
$number = strlen('Some text I want to overwrite');
$this->Shell->stdout->expects($this->at(0))
->method('write')
->with('Some <info>text</info> I want to overwrite', 0)
->will($this->returnValue($number));
$this->Shell->stdout->expects($this->at(1))
->method('write')
->with(str_repeat("\x08", $number), 0);
$this->Shell->stdout->expects($this->at(2))
->method('write')
->with('Less text', 0)
->will($this->returnValue(9));
$this->Shell->stdout->expects($this->at(3))
->method('write')
->with(str_repeat(' ', $number - 9), 0);
$this->Shell->out('Some <info>text</info> I want to overwrite', 0);
$this->Shell->overwrite('Less text');
}
/**
* testErr method
*
@ -545,7 +603,7 @@ class ShellTest extends CakeTestCase {
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
$Folder = new Folder($path, true);
new Folder($path, true);
$this->Shell->interactive = false;
@ -572,7 +630,7 @@ class ShellTest extends CakeTestCase {
$path = TMP . 'shell_test';
$file = $path . DS . 'file1.php';
$Folder = new Folder($path, true);
new Folder($path, true);
$this->Shell->interactive = true;
@ -611,7 +669,7 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testCreateFileNoPermissions() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on Windows.');
$path = TMP . 'shell_test';
$file = $path . DS . 'no_perms';
@ -663,7 +721,6 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testRunCommandMain() {
$methods = get_class_methods('Shell');
$Mock = $this->getMock('Shell', array('main', 'startup'), array(), '', false);
$Mock->expects($this->once())->method('main')->will($this->returnValue(true));
@ -677,7 +734,6 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testRunCommandWithMethod() {
$methods = get_class_methods('Shell');
$Mock = $this->getMock('Shell', array('hit_me', 'startup'), array(), '', false);
$Mock->expects($this->once())->method('hit_me')->will($this->returnValue(true));
@ -700,7 +756,7 @@ class ShellTest extends CakeTestCase {
$Mock->expects($this->never())->method('hr');
$Mock->expects($this->once())->method('out');
$result = $Mock->runCommand('hr', array());
$Mock->runCommand('hr', array());
}
/**
@ -709,7 +765,6 @@ class ShellTest extends CakeTestCase {
* @return void
*/
public function testRunCommandMissingMethod() {
$methods = get_class_methods('Shell');
$Mock = $this->getMock('Shell', array('startup', 'getOptionParser', 'out'), array(), '', false);
$Parser = $this->getMock('ConsoleOptionParser', array(), array(), '', false);
@ -762,7 +817,7 @@ class ShellTest extends CakeTestCase {
$Shell->RunCommand = $task;
$result = $Shell->runCommand('run_command', array('run_command', 'one', 'value'));
$Shell->runCommand('run_command', array('run_command', 'one', 'value'));
}
/**
@ -801,6 +856,51 @@ TEXT;
$this->assertEquals($expected, $this->Shell->TestApple->name);
}
/**
* Test reading params
*
* @dataProvider paramReadingDataProvider
*/
public function testParamReading($toRead, $expected) {
$this->Shell->params = array(
'key' => 'value',
'help' => false,
'emptykey' => '',
'truthy' => true
);
$this->assertSame($expected, $this->Shell->param($toRead));
}
/**
* Data provider for testing reading values with Shell::param()
*
* @return array
*/
public function paramReadingDataProvider() {
return array(
array(
'key',
'value',
),
array(
'help',
false,
),
array(
'emptykey',
'',
),
array(
'truthy',
true,
),
array(
'does_not_exist',
null,
)
);
}
/**
* Test that option parsers are created with the correct name/command.
*
@ -816,8 +916,12 @@ TEXT;
/**
* Test file and console and logging
*
* @return void
*/
public function testFileAndConsoleLogging() {
CakeLog::disable('stdout');
CakeLog::disable('stderr');
// file logging
$this->Shell->log_something();
$this->assertTrue(file_exists(LOGS . 'error.log'));
@ -831,7 +935,7 @@ TEXT;
array('types' => 'error'),
));
TestCakeLog::config('console', array(
'engine' => 'ConsoleLog',
'engine' => 'Console',
'stream' => 'php://stderr',
));
TestCakeLog::replace('console', $mock);
@ -842,13 +946,16 @@ TEXT;
$this->assertTrue(file_exists(LOGS . 'error.log'));
$contents = file_get_contents(LOGS . 'error.log');
$this->assertContains($this->Shell->testMessage, $contents);
CakeLog::enable('stdout');
CakeLog::enable('stderr');
}
/**
* Tests that _useLogger works properly
*
* @return void
**/
*/
public function testProtectedUseLogger() {
CakeLog::drop('stdout');
CakeLog::drop('stderr');
@ -862,6 +969,8 @@ TEXT;
/**
* Test file and console and logging quiet output
*
* @return void
*/
public function testQuietLog() {
$output = $this->getMock('ConsoleOutput', array(), array(), '', false);
@ -872,4 +981,53 @@ TEXT;
$this->Shell->runCommand('foo', array('--quiet'));
}
/**
* Test getting an instance of a helper
*
* @return void
*/
public function testGetInstanceOfHelper() {
$actual = $this->Shell->helper("progress");
$this->assertInstanceOf("ProgressShellHelper", $actual);
}
/**
* Test getting an invalid helper
*
* @expectedException RunTimeException
* @return void
*/
public function testGetInvalidHelper() {
$this->Shell->helper("tomato");
}
/**
* Test that shell loggers do not get overridden in constructor if already configured
*
* @return void
*/
public function testShellLoggersDoNotGetOverridden() {
$shell = $this->getMock(
"Shell", array(
"_loggerIsConfigured",
"configureStdOutLogger",
"configureStdErrLogger",
),
array(),
"",
false
);
$shell->expects($this->exactly(2))
->method("_loggerIsConfigured")
->will($this->returnValue(true));
$shell->expects($this->never())
->method("_configureStdOutLogger");
$shell->expects($this->never())
->method("_configureStdErrLogger");
$shell->__construct();
}
}

View file

@ -2,24 +2,34 @@
/**
* TaskCollectionTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Console
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('TaskCollection', 'Console');
App::uses('Shell', 'Console');
/**
* Extended Task
*/
class DbConfigAliasedTask extends Shell {
}
/**
* TaskCollectionTest
*
* @package Cake.Test.Case.Console
*/
class TaskCollectionTest extends CakeTestCase {
/**
@ -54,8 +64,8 @@ class TaskCollectionTest extends CakeTestCase {
$this->assertInstanceOf('DbConfigTask', $result);
$this->assertInstanceOf('DbConfigTask', $this->Tasks->DbConfig);
$result = $this->Tasks->attached();
$this->assertEquals(array('DbConfig'), $result, 'attached() results are wrong.');
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig'), $result, 'loaded() results are wrong.');
}
/**
@ -78,7 +88,7 @@ class TaskCollectionTest extends CakeTestCase {
* @return void
*/
public function testLoadMissingTask() {
$result = $this->Tasks->load('ThisTaskShouldAlwaysBeMissing');
$this->Tasks->load('ThisTaskShouldAlwaysBeMissing');
}
/**
@ -110,15 +120,36 @@ class TaskCollectionTest extends CakeTestCase {
$this->Tasks->load('Extract');
$this->Tasks->load('DbConfig');
$result = $this->Tasks->attached();
$result = $this->Tasks->loaded();
$this->assertEquals(array('Extract', 'DbConfig'), $result, 'loaded tasks is wrong');
$this->Tasks->unload('DbConfig');
$this->assertFalse(isset($this->Tasks->DbConfig));
$this->assertTrue(isset($this->Tasks->Extract));
$result = $this->Tasks->attached();
$result = $this->Tasks->loaded();
$this->assertEquals(array('Extract'), $result, 'loaded tasks is wrong');
}
/**
* Tests loading as an alias
*
* @return void
*/
public function testLoadWithAlias() {
$result = $this->Tasks->load('DbConfig', array('className' => 'DbConfigAliased'));
$this->assertInstanceOf('DbConfigAliasedTask', $result);
$this->assertInstanceOf('DbConfigAliasedTask', $this->Tasks->DbConfig);
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig'), $result, 'loaded() results are wrong.');
$result = $this->Tasks->load('SomeTask', array('className' => 'TestPlugin.OtherTask'));
$this->assertInstanceOf('OtherTaskTask', $result);
$this->assertInstanceOf('OtherTaskTask', $this->Tasks->SomeTask);
$result = $this->Tasks->loaded();
$this->assertEquals(array('DbConfig', 'SomeTask'), $result, 'loaded() results are wrong.');
}
}

View file

@ -2,19 +2,18 @@
/**
* DbAclTest file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Acl
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ComponentCollection', 'Controller');
@ -34,14 +33,14 @@ class AclNodeTwoTestBase extends AclNode {
/**
* useDbConfig property
*
* @var string 'test'
* @var string
*/
public $useDbConfig = 'test';
/**
* cacheSources property
*
* @var bool false
* @var bool
*/
public $cacheSources = false;
}
@ -56,14 +55,14 @@ class AroTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string 'AroTwoTest'
* @var string
*/
public $name = 'AroTwoTest';
/**
* useTable property
*
* @var string 'aro_twos'
* @var string
*/
public $useTable = 'aro_twos';
@ -85,14 +84,14 @@ class AcoTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string 'AcoTwoTest'
* @var string
*/
public $name = 'AcoTwoTest';
/**
* useTable property
*
* @var string 'aco_twos'
* @var string
*/
public $useTable = 'aco_twos';
@ -114,21 +113,21 @@ class PermissionTwoTest extends Permission {
/**
* name property
*
* @var string 'PermissionTwoTest'
* @var string
*/
public $name = 'PermissionTwoTest';
/**
* useTable property
*
* @var string 'aros_aco_twos'
* @var string
*/
public $useTable = 'aros_aco_twos';
/**
* cacheQueries property
*
* @var bool false
* @var bool
*/
public $cacheQueries = false;
@ -142,7 +141,7 @@ class PermissionTwoTest extends Permission {
/**
* actsAs property
*
* @var mixed null
* @var mixed
*/
public $actsAs = null;
}
@ -156,8 +155,6 @@ class DbAclTwoTest extends DbAcl {
/**
* construct method
*
* @return void
*/
public function __construct() {
$this->Aro = new AroTwoTest();
@ -258,7 +255,6 @@ class DbAclTest extends CakeTestCase {
/**
* testDbAclAllow method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testAllow() {
@ -282,7 +278,7 @@ class DbAclTest extends CakeTestCase {
$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->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'));
@ -292,14 +288,23 @@ class DbAclTest extends CakeTestCase {
$this->assertFalse($this->Acl->allow('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
/**
* Test that allow() with an invalid permission name triggers an error.
*
* @expectedException CakeException
* @return void
*/
public function testAllowInvalidPermission() {
$this->assertFalse($this->Acl->allow('Micheal', 'tpsReports', 'derp'));
}
/**
* testAllowInvalidNode method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testAllowInvalidNode() {
$this->Acl->allow('Homer', 'tpsReports', 'create');
$this->assertFalse($this->Acl->allow('Homer', 'tpsReports', 'create'));
}
/**
@ -325,7 +330,6 @@ class DbAclTest extends CakeTestCase {
/**
* testCheckInvalidNode method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testCheckInvalidNode() {
@ -335,21 +339,19 @@ class DbAclTest extends CakeTestCase {
/**
* testCheckInvalidPermission method
*
* @expectedException PHPUnit_Framework_Error_Notice
* @return void
*/
public function testCheckInvalidPermission() {
$this->Acl->check('Lumbergh', 'smash', 'foobar');
$this->assertFalse($this->Acl->check('Lumbergh', 'smash', 'foobar'));
}
/**
* testCheckMissingPermission method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testCheckMissingPermission() {
$this->Acl->check('users', 'NonExistent', 'read');
$this->assertFalse($this->Acl->check('users', 'NonExistent', 'read'));
}
/**
@ -372,7 +374,6 @@ class DbAclTest extends CakeTestCase {
/**
* testDbAclDeny method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testDeny() {
@ -428,21 +429,63 @@ class DbAclTest extends CakeTestCase {
* @return void
*/
public function testInherit() {
//parent doesn't have access inherit should still deny
// 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
// inherit parent
$this->assertFalse($this->Acl->check('Milton', 'smash', 'read'));
$this->Acl->inherit('Milton', 'smash', 'read');
$this->assertTrue($this->Acl->check('Milton', 'smash', 'read'));
}
/**
* test inherit from deny method
*
* @return void
*/
public function testInheritParentDeny() {
$this->Acl->Aco->create(array('parent_id' => null, 'alias' => 'world'));
$this->Acl->Aco->save();
$this->Acl->Aco->create(array('parent_id' => $this->Acl->Aco->id, 'alias' => 'town'));
$this->Acl->Aco->save();
$this->Acl->Aco->create(array('parent_id' => null, 'alias' => 'bizzaro_world'));
$this->Acl->Aco->save();
$this->Acl->Aco->create(array('parent_id' => $this->Acl->Aco->id, 'alias' => 'bizzaro_town'));
$this->Acl->Aco->save();
$this->Acl->Aro->create(array('parent_id' => null, 'alias' => 'Jane'));
$this->Acl->Aro->save();
// Setup deny on create for parent
$this->Acl->allow('Jane', 'world', '*');
$this->Acl->deny('Jane', 'world', 'create');
// Setup inherit and specify allow for create on child.
$this->Acl->inherit('Jane', 'town', '*');
$this->Acl->allow('Jane', 'town', 'create');
// Setup deny on create for parent
$this->Acl->deny('Jane', 'bizzaro_world', '*');
$this->Acl->allow('Jane', 'bizzaro_world', 'create');
// Setup inherit.
$this->Acl->inherit('Jane', 'bizzaro_town', '*');
$this->assertTrue($this->Acl->check('Jane', 'town', 'create'), 'Should have access due to override');
$this->assertTrue($this->Acl->check('Jane', 'town', '*'), 'Should have access due to inherit');
$this->assertTrue($this->Acl->check('Jane', 'bizzaro_town', 'create'), 'Should have access due explicit allow');
$this->assertFalse($this->Acl->check('Jane', 'bizzaro_town', '*'), 'Should not have access due to inherit');
}
/**
* testDbGrant method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testGrant() {
@ -463,7 +506,6 @@ class DbAclTest extends CakeTestCase {
/**
* testDbRevoke method
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testRevoke() {
@ -503,12 +545,12 @@ class DbAclTest extends CakeTestCase {
$perms = '';
foreach ($rights as $right) {
if ($this->Acl->check($aro, $aco, $right)) {
if ($right == '*') {
if ($right === '*') {
$perms .= '****';
break;
}
$perms .= $right[0];
} elseif ($right != '*') {
} elseif ($right !== '*') {
$perms .= ' ';
}
}
@ -519,9 +561,9 @@ class DbAclTest extends CakeTestCase {
foreach ($permissions as $key => $values) {
array_unshift($values, $key);
$values = array_map(array(&$this, '_pad'), $values);
$permissions[$key] = implode (' ', $values);
$permissions[$key] = implode(' ', $values);
}
$permisssions = array_map(array(&$this, '_pad'), $permissions);
$permissions = 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()));
@ -534,7 +576,7 @@ class DbAclTest extends CakeTestCase {
* Used by debug to format strings used in the data dump
*
* @param string $string
* @param integer $len
* @param int $len
* @return void
*/
protected function _pad($string = '', $len = 14) {

View file

@ -2,20 +2,20 @@
/**
* IniAclTest file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Acl
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('IniAcl', 'Controller/Component/Acl');
/**
@ -66,4 +66,3 @@ class IniAclTest extends CakeTestCase {
$this->assertTrue($Ini->check($user, 'posts'));
}
}

View file

@ -2,19 +2,18 @@
/**
* PhpAclTest file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Acl
* @since CakePHP(tm) v 2.1
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclComponent', 'Controller/Component');
@ -28,6 +27,11 @@ class_exists('AclComponent');
*/
class PhpAclTest extends CakeTestCase {
/**
* Setup
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Acl.classname', 'PhpAcl');
@ -40,6 +44,11 @@ class PhpAclTest extends CakeTestCase {
));
}
/**
* Test role inheritance
*
* @return void
*/
public function testRoleInheritance() {
$roles = $this->Acl->Aro->roles('User/peter');
$this->assertEquals(array('Role/accounting'), $roles[0]);
@ -52,14 +61,23 @@ class PhpAclTest extends CakeTestCase {
$this->assertEquals(array('User/hardy'), $roles[3]);
}
/**
* Test adding a role
*
* @return void
*/
public function testAddRole() {
$this->assertEquals(array(array(PhpAro::DEFAULT_ROLE)), $this->Acl->Aro->roles('foobar'));
$this->Acl->Aro->addRole(array('User/foobar' => 'Role/accounting'));
$this->assertEquals(array(array('Role/accounting'), array('User/foobar')), $this->Acl->Aro->roles('foobar'));
}
/**
* Test resolving ARO
*
* @return void
*/
public function testAroResolve() {
$map = $this->Acl->Aro->map;
$this->Acl->Aro->map = array(
'User' => 'FooModel/nickname',
'Role' => 'FooModel/role',
@ -82,6 +100,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test correct resolution of defined aliases
*
* @return void
*/
public function testAroAliases() {
$this->Acl->Aro->map = array(
@ -118,7 +138,7 @@ class PhpAclTest extends CakeTestCase {
$this->Acl->Aro->addAlias(array('Role/25' => 'Role/IT'));
$this->Acl->allow('Role/IT', '/rules/debugging/*');
$this->assertEquals(array(array('Role/IT', )), $this->Acl->Aro->roles($user));
$this->assertEquals(array(array('Role/IT')), $this->Acl->Aro->roles($user));
$this->assertTrue($this->Acl->check($user, '/rules/debugging/stats/pageload'));
$this->assertTrue($this->Acl->check($user, '/rules/debugging/sql/queries'));
// Role/default is allowed users dashboard, but not Role/IT
@ -183,6 +203,8 @@ class PhpAclTest extends CakeTestCase {
/**
* lhs of defined rules are case insensitive
*
* @return void
*/
public function testCheckIsCaseInsensitive() {
$this->assertTrue($this->Acl->check('hardy', 'controllers/forms/new'));
@ -193,6 +215,8 @@ class PhpAclTest extends CakeTestCase {
/**
* allow should work in-memory
*
* @return void
*/
public function testAllow() {
$this->assertFalse($this->Acl->check('jeff', 'foo/bar'));
@ -213,6 +237,8 @@ class PhpAclTest extends CakeTestCase {
/**
* deny should work in-memory
*
* @return void
*/
public function testDeny() {
$this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_foo'));
@ -227,6 +253,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test that a deny rule wins over an equally specific allow rule
*
* @return void
*/
public function testDenyRuleIsStrongerThanAllowRule() {
$this->assertFalse($this->Acl->check('peter', 'baz/bam'));
@ -251,6 +279,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test that an invalid configuration throws exception
*
* @return void
*/
public function testInvalidConfigWithAroMissing() {
$this->setExpectedException(
@ -276,6 +306,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test resolving of ACOs
*
* @return void
*/
public function testAcoResolve() {
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo/bar'));
@ -295,6 +327,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test that declaring cyclic dependencies should give an error when building the tree
*
* @return void
*/
public function testAroDeclarationContainsCycles() {
$config = array(
@ -318,6 +352,8 @@ class PhpAclTest extends CakeTestCase {
/**
* test that with policy allow, only denies count
*
* @return void
*/
public function testPolicy() {
// allow by default
@ -334,4 +370,5 @@ class PhpAclTest extends CakeTestCase {
$this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar/delete'));
$this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar', 'delete'));
}
}

View file

@ -2,20 +2,20 @@
/**
* AclComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5435
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclComponent', 'Controller/Component');
class_exists('AclComponent');
@ -61,7 +61,7 @@ class AclComponentTest extends CakeTestCase {
public function testConstrutorException() {
Configure::write('Acl.classname', 'AclClassNameThatDoesNotExist');
$Collection = new ComponentCollection();
$acl = new AclComponent($Collection);
new AclComponent($Collection);
}
/**
@ -70,15 +70,15 @@ class AclComponentTest extends CakeTestCase {
* @return void
*/
public function testAdapter() {
$implementation = new MockAclImplementation();
$implementation->expects($this->once())->method('initialize')->with($this->Acl);
$this->assertNull($this->Acl->adapter($implementation));
$Adapter = $this->getMock('AclInterface');
$Adapter->expects($this->once())->method('initialize')->with($this->Acl);
$this->assertEquals($this->Acl->adapter(), $implementation, 'Returned object is different %s');
$this->assertNull($this->Acl->adapter($Adapter));
$this->assertEquals($this->Acl->adapter(), $Adapter, 'Returned object is different %s');
}
/**
* test that adapter() whines when the class is not an AclBase
* test that adapter() whines when the class does not implement AclInterface
*
* @expectedException CakeException
* @return void

View file

@ -2,19 +2,18 @@
/**
* ActionsAuthorizeTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ActionsAuthorize', 'Controller/Component/Auth');
@ -23,6 +22,11 @@ App::uses('AclComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* ActionsAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class ActionsAuthorizeTest extends CakeTestCase {
/**
@ -164,11 +168,12 @@ class ActionsAuthorizeTest extends CakeTestCase {
*/
public function testActionNoDoubleSlash() {
$this->auth->settings['actionPath'] = '/controllers/';
$request = array(
$request = new CakeRequest('/posts/index', false);
$request->addParams(array(
'plugin' => null,
'controller' => 'posts',
'action' => 'index'
);
));
$result = $this->auth->action($request);
$this->assertEquals('controllers/Posts/index', $result);
}

View file

@ -2,19 +2,18 @@
/**
* BasicAuthenticateTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AuthComponent', 'Controller/Component');
@ -23,7 +22,6 @@ App::uses('AppModel', 'Model');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
/**
@ -33,7 +31,12 @@ require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
*/
class BasicAuthenticateTest extends CakeTestCase {
public $fixtures = array('core.user', 'core.auth_user');
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user', 'core.article');
/**
* setup
@ -79,11 +82,10 @@ class BasicAuthenticateTest extends CakeTestCase {
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$this->response->expects($this->once())
->method('header')
->with('WWW-Authenticate: Basic realm="localhost"');
$this->response->expects($this->never())
->method('header');
$this->assertFalse($this->auth->authenticate($request, $this->response));
$this->assertFalse($this->auth->getUser($request));
}
/**
@ -95,10 +97,6 @@ class BasicAuthenticateTest extends CakeTestCase {
$request = new CakeRequest('posts/index', false);
$_SERVER['PHP_AUTH_PW'] = 'foobar';
$this->response->expects($this->once())
->method('header')
->with('WWW-Authenticate: Basic realm="localhost"');
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
@ -112,10 +110,6 @@ class BasicAuthenticateTest extends CakeTestCase {
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = null;
$this->response->expects($this->once())
->method('header')
->with('WWW-Authenticate: Basic realm="localhost"');
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
@ -131,9 +125,36 @@ class BasicAuthenticateTest extends CakeTestCase {
$_SERVER['PHP_AUTH_USER'] = '> 1';
$_SERVER['PHP_AUTH_PW'] = "' OR 1 = 1";
$this->assertFalse($this->auth->getUser($request));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* Test that username of 0 works.
*
* @return void
*/
public function testAuthenticateUsernameZero() {
$User = ClassRegistry::init('User');
$User->updateAll(array('user' => $User->getDataSource()->value('0')), array('user' => 'mariano'));
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => '0',
'password' => 'password'
));
$_SERVER['PHP_AUTH_USER'] = '0';
$_SERVER['PHP_AUTH_PW'] = 'password';
$expected = array(
'id' => 1,
'user' => '0',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
);
$this->assertEquals($expected, $this->auth->authenticate($request, $this->response));
}
/**
* test that challenge headers are sent when no credentials are found.
*
@ -143,19 +164,19 @@ class BasicAuthenticateTest extends CakeTestCase {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$this->response->expects($this->at(0))
->method('header')
->with('WWW-Authenticate: Basic realm="localhost"');
try {
$this->auth->unauthenticated($request, $this->response);
} catch (UnauthorizedException $e) {
}
$this->response->expects($this->at(1))
->method('send');
$this->assertNotEmpty($e);
$result = $this->auth->authenticate($request, $this->response);
$this->assertFalse($result);
$expected = array('WWW-Authenticate: Basic realm="localhost"');
$this->assertEquals($expected, $e->responseHeader());
}
/**
* test authenticate sucesss
* test authenticate success
*
* @return void
*/
@ -176,9 +197,89 @@ class BasicAuthenticateTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test contain success
*
* @return void
*/
public function testAuthenticateContainSuccess() {
$User = ClassRegistry::init('User');
$User->bindModel(array('hasMany' => array('Article')));
$User->Behaviors->load('Containable');
$this->auth->settings['contain'] = 'Article';
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'user_id' => 1,
'title' => 'First Article',
'body' => 'First Article Body',
'published' => 'Y',
'created' => '2007-03-18 10:39:23',
'updated' => '2007-03-18 10:41:31'
);
$this->assertEquals($expected, $result['Article'][0]);
}
/**
* test userFields success
*
* @return void
*/
public function testAuthenticateUserFieldsSuccess() {
$this->auth->settings['userFields'] = array('id', 'user');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'user' => 'mariano',
);
$this->assertEquals($expected, $result);
}
/**
* test userFields and related models success
*
* @return void
*/
public function testAuthenticateUserFieldsRelatedModelsSuccess() {
$User = ClassRegistry::init('User');
$User->bindModel(array('hasOne' => array(
'Article' => array(
'order' => 'Article.id ASC'
)
)));
$this->auth->settings['recursive'] = 0;
$this->auth->settings['userFields'] = array('Article.id', 'Article.title');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'title' => 'First Article',
);
$this->assertEquals($expected, $result['Article']);
}
/**
* test scope failure.
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateFailReChallenge() {
@ -189,18 +290,40 @@ class BasicAuthenticateTest extends CakeTestCase {
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$this->response->expects($this->at(0))
->method('header')
->with('WWW-Authenticate: Basic realm="localhost"');
$this->auth->unauthenticated($request, $this->response);
}
$this->response->expects($this->at(1))
->method('statusCode')
->with(401);
/**
* testAuthenticateWithBlowfish
*
* @return void
*/
public function testAuthenticateWithBlowfish() {
$hash = Security::hash('password', 'blowfish');
$this->skipIf(strpos($hash, '$2a$') === false, 'Skipping blowfish tests as hashing is not working');
$this->response->expects($this->at(2))
->method('send');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$this->assertFalse($this->auth->authenticate($request, $this->response));
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$User = ClassRegistry::init('User');
$User->updateAll(
array('password' => $User->getDataSource()->value($hash)),
array('User.user' => 'mariano')
);
$this->auth->settings['passwordHasher'] = 'Blowfish';
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'user' => 'mariano',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
);
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,208 @@
<?php
/**
* BlowfishAuthenticateTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under the MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AuthComponent', 'Controller/Component');
App::uses('BlowfishAuthenticate', 'Controller/Component/Auth');
App::uses('AppModel', 'Model');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('Security', 'Utility');
require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
/**
* Test case for BlowfishAuthentication
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class BlowfishAuthenticateTest extends CakeTestCase {
public $fixtures = array('core.user', 'core.auth_user');
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Collection = $this->getMock('ComponentCollection');
$this->auth = new BlowfishAuthenticate($this->Collection, array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User'
));
$password = Security::hash('password', 'blowfish');
$User = ClassRegistry::init('User');
$User->updateAll(array('password' => $User->getDataSource()->value($password)));
$this->response = $this->getMock('CakeResponse');
$hash = Security::hash('password', 'blowfish');
$this->skipIf(strpos($hash, '$2a$') === false, 'Skipping blowfish tests as hashing is not working');
}
/**
* test applying settings in the constructor
*
* @return void
*/
public function testConstructor() {
$Object = new BlowfishAuthenticate($this->Collection, array(
'userModel' => 'AuthUser',
'fields' => array('username' => 'user', 'password' => 'password')
));
$this->assertEquals('AuthUser', $Object->settings['userModel']);
$this->assertEquals(array('username' => 'user', 'password' => 'password'), $Object->settings['fields']);
}
/**
* testAuthenticateNoData method
*
* @return void
*/
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$request->data = array();
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testAuthenticateNoUsername method
*
* @return void
*/
public function testAuthenticateNoUsername() {
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array('password' => 'foobar'));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testAuthenticateNoPassword method
*
* @return void
*/
public function testAuthenticateNoPassword() {
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array('user' => 'mariano'));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testAuthenticatePasswordIsFalse method
*
* @return void
*/
public function testAuthenticatePasswordIsFalse() {
$request = new CakeRequest('posts/index', false);
$request->data = array(
'User' => array(
'user' => 'mariano',
'password' => null
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testAuthenticateInjection method
*
* @return void
*/
public function testAuthenticateInjection() {
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => '> 1',
'password' => "' OR 1 = 1"
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testAuthenticateSuccess method
*
* @return void
*/
public function testAuthenticateSuccess() {
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => 'mariano',
'password' => 'password'
));
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'user' => 'mariano',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31',
);
$this->assertEquals($expected, $result);
}
/**
* testAuthenticateScopeFail method
*
* @return void
*/
public function testAuthenticateScopeFail() {
$this->auth->settings['scope'] = array('user' => 'nate');
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => 'mariano',
'password' => 'password'
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* testPluginModel method
*
* @return void
*/
public function testPluginModel() {
Cache::delete('object_map', '_cake_core_');
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$PluginModel = ClassRegistry::init('TestPlugin.TestPluginAuthUser');
$user['id'] = 1;
$user['username'] = 'gwoo';
$user['password'] = Security::hash('password', 'blowfish');
$PluginModel->save($user, false);
$this->auth->settings['userModel'] = 'TestPlugin.TestPluginAuthUser';
$this->auth->settings['fields']['username'] = 'username';
$request = new CakeRequest('posts/index', false);
$request->data = array('TestPluginAuthUser' => array(
'username' => 'gwoo',
'password' => 'password'
));
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'username' => 'gwoo',
'created' => '2007-03-17 01:16:23'
);
$this->assertEquals(static::date(), $result['updated']);
unset($result['updated']);
$this->assertEquals($expected, $result);
CakePlugin::unload();
}
}

View file

@ -2,19 +2,18 @@
/**
* ControllerAuthorizeTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
@ -22,6 +21,11 @@ App::uses('ControllerAuthorize', 'Controller/Component/Auth');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* ControllerAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class ControllerAuthorizeTest extends CakeTestCase {
/**
@ -41,14 +45,26 @@ class ControllerAuthorizeTest extends CakeTestCase {
}
/**
* testControllerTypeError
*
* @expectedException PHPUnit_Framework_Error
* @return void
* @throws PHPUnit_Framework_Error
*/
public function testControllerTypeError() {
$this->auth->controller(new StdClass());
try {
$this->auth->controller(new StdClass());
$this->fail('No exception thrown');
} catch (TypeError $e) {
throw new PHPUnit_Framework_Error('Raised an error', 100, __FILE__, __LINE__);
}
}
/**
* testControllerErrorOnMissingMethod
*
* @expectedException CakeException
* @return void
*/
public function testControllerErrorOnMissingMethod() {
$this->auth->controller(new Controller());
@ -81,4 +97,5 @@ class ControllerAuthorizeTest extends CakeTestCase {
$this->assertTrue($this->auth->authorize($user, $request));
}
}

View file

@ -2,19 +2,18 @@
/**
* CrudAuthorizeTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CrudAuthorize', 'Controller/Component/Auth');
@ -23,6 +22,11 @@ App::uses('AclComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* CrudAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class CrudAuthorizeTest extends CakeTestCase {
/**
@ -33,6 +37,7 @@ class CrudAuthorizeTest extends CakeTestCase {
public function setUp() {
parent::setUp();
Configure::write('Routing.prefixes', array());
Router::reload();
$this->Acl = $this->getMock('AclComponent', array(), array(), '', false);
$this->Components = $this->getMock('ComponentCollection');
@ -155,7 +160,6 @@ class CrudAuthorizeTest extends CakeTestCase {
'create' => 'create',
'read' => 'read',
'index' => 'read',
'add' => 'create',
'edit' => 'update',
'view' => 'read',
'delete' => 'delete',

View file

@ -2,19 +2,18 @@
/**
* DigestAuthenticateTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DigestAuthenticate', 'Controller/Component/Auth');
@ -31,6 +30,11 @@ require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
*/
class DigestAuthenticateTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user');
/**
@ -93,16 +97,17 @@ class DigestAuthenticateTest extends CakeTestCase {
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$this->response->expects($this->once())
->method('header')
->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
$this->response->expects($this->never())
->method('header');
$this->assertFalse($this->auth->authenticate($request, $this->response));
$this->assertFalse($this->auth->getUser($request, $this->response));
}
/**
* test the authenticate method
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateWrongUsername() {
@ -121,18 +126,7 @@ response="6629fae49393a05397450978507c4ef1",
opaque="123abc"
DIGEST;
$this->response->expects($this->at(0))
->method('header')
->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
$this->response->expects($this->at(1))
->method('statusCode')
->with(401);
$this->response->expects($this->at(2))
->method('send');
$this->assertFalse($this->auth->authenticate($request, $this->response));
$this->auth->unauthenticated($request, $this->response);
}
/**
@ -144,19 +138,15 @@ DIGEST;
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$this->response->expects($this->at(0))
->method('header')
->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
try {
$this->auth->unauthenticated($request, $this->response);
} catch (UnauthorizedException $e) {
}
$this->response->expects($this->at(1))
->method('statusCode')
->with(401);
$this->assertNotEmpty($e);
$this->response->expects($this->at(2))
->method('send');
$result = $this->auth->authenticate($request, $this->response);
$this->assertFalse($result);
$expected = array('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
$this->assertEquals($expected, $e->responseHeader());
}
/**
@ -193,6 +183,8 @@ DIGEST;
/**
* test scope failure.
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateFailReChallenge() {
@ -212,18 +204,7 @@ response="6629fae49393a05397450978507c4ef1",
opaque="123abc"
DIGEST;
$this->response->expects($this->at(0))
->method('header')
->with('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
$this->response->expects($this->at(1))
->method('statusCode')
->with(401);
$this->response->expects($this->at(2))
->method('send');
$this->assertFalse($this->auth->authenticate($request, $this->response));
$this->auth->unauthenticated($request, $this->response);
}
/**
@ -236,7 +217,7 @@ DIGEST;
Digest username="Mufasa",
realm="testrealm@host.com",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
uri="/dir/index.html?query=string&value=some%20value",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
@ -247,7 +228,7 @@ DIGEST;
'username' => 'Mufasa',
'realm' => 'testrealm@host.com',
'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
'uri' => '/dir/index.html',
'uri' => '/dir/index.html?query=string&value=some%20value',
'qop' => 'auth',
'nc' => '00000001',
'cnonce' => '0a4f113b',
@ -261,6 +242,29 @@ DIGEST;
$this->assertNull($result);
}
/**
* Test parsing a full URI. While not part of the spec some mobile clients will do it wrong.
*
* @return void
*/
public function testParseAuthDataFullUri() {
$digest = <<<DIGEST
Digest username="admin",
realm="192.168.0.2",
nonce="53a7f9b83f61b",
uri="http://192.168.0.2/pvcollection/sites/pull/HFD%200001.json#fragment",
qop=auth,
nc=00000001,
cnonce="b85ff144e496e6e18d1c73020566ea3b",
response="5894f5d9cd41d012bac09eeb89d2ddf2",
opaque="6f65e91667cf98dd13464deaf2739fde"
DIGEST;
$expected = 'http://192.168.0.2/pvcollection/sites/pull/HFD%200001.json#fragment';
$result = $this->auth->parseAuthData($digest);
$this->assertSame($expected, $result['uri']);
}
/**
* test parsing digest information with email addresses
*

View file

@ -1,20 +1,17 @@
<?php
/**
* FormAuthenticateTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AuthComponent', 'Controller/Component');
@ -32,6 +29,11 @@ require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
*/
class FormAuthenticateTest extends CakeTestCase {
/**
* Fixtrues
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user');
/**
@ -99,6 +101,84 @@ class FormAuthenticateTest extends CakeTestCase {
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test authenticate password is false method
*
* @return void
*/
public function testAuthenticatePasswordIsFalse() {
$request = new CakeRequest('posts/index', false);
$request->data = array(
'User' => array(
'user' => 'mariano',
'password' => null
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* Test for password as empty string with _checkFields() call skipped
* Refs https://github.com/cakephp/cakephp/pull/2441
*
* @return void
*/
public function testAuthenticatePasswordIsEmptyString() {
$request = new CakeRequest('posts/index', false);
$request->data = array(
'User' => array(
'user' => 'mariano',
'password' => ''
));
$this->auth = $this->getMock(
'FormAuthenticate',
array('_checkFields'),
array(
$this->Collection,
array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User'
)
)
);
// Simulate that check for ensuring password is not empty is missing.
$this->auth->expects($this->once())
->method('_checkFields')
->will($this->returnValue(true));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test authenticate field is not string
*
* @return void
*/
public function testAuthenticateFieldsAreNotString() {
$request = new CakeRequest('posts/index', false);
$request->data = array(
'User' => array(
'user' => array('mariano', 'phpnut'),
'password' => 'my password'
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
$request->data = array(
'User' => array(
'user' => array(),
'password' => 'my password'
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
$request->data = array(
'User' => array(
'user' => 'mariano',
'password' => array('password1', 'password2')
));
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test the authenticate method
*
@ -151,6 +231,30 @@ class FormAuthenticateTest extends CakeTestCase {
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* Test that username of 0 works.
*
* @return void
*/
public function testAuthenticateUsernameZero() {
$User = ClassRegistry::init('User');
$User->updateAll(array('user' => $User->getDataSource()->value('0')), array('user' => 'mariano'));
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => '0',
'password' => 'password'
));
$expected = array(
'id' => 1,
'user' => '0',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
);
$this->assertEquals($expected, $this->auth->authenticate($request, $this->response));
}
/**
* test a model in a plugin.
*
@ -184,10 +288,58 @@ class FormAuthenticateTest extends CakeTestCase {
'username' => 'gwoo',
'created' => '2007-03-17 01:16:23'
);
$this->assertEquals(self::date(), $result['updated']);
$this->assertEquals(static::date(), $result['updated']);
unset($result['updated']);
$this->assertEquals($expected, $result);
CakePlugin::unload();
}
/**
* test password hasher settings
*
* @return void
*/
public function testPasswordHasherSettings() {
$this->auth->settings['passwordHasher'] = array(
'className' => 'Simple',
'hashType' => 'md5'
);
$passwordHasher = $this->auth->passwordHasher();
$result = $passwordHasher->config();
$this->assertEquals('md5', $result['hashType']);
$hash = Security::hash('mypass', 'md5', true);
$User = ClassRegistry::init('User');
$User->updateAll(
array('password' => $User->getDataSource()->value($hash)),
array('User.user' => 'mariano')
);
$request = new CakeRequest('posts/index', false);
$request->data = array('User' => array(
'user' => 'mariano',
'password' => 'mypass'
));
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'user' => 'mariano',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
);
$this->assertEquals($expected, $result);
$this->auth = new FormAuthenticate($this->Collection, array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User'
));
$this->auth->settings['passwordHasher'] = array(
'className' => 'Simple',
'hashType' => 'sha1'
);
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
}

File diff suppressed because it is too large Load diff

View file

@ -2,26 +2,24 @@
/**
* CookieComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5435
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Component', 'Controller');
App::uses('Controller', 'Controller');
App::uses('CookieComponent', 'Controller/Component');
/**
* CookieComponentTestController class
*
@ -72,6 +70,7 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
public function setUp() {
parent::setUp();
$_COOKIE = array();
$this->Controller = new CookieComponentTestController(new CakeRequest(), new CakeResponse());
$this->Controller->constructClasses();
@ -93,6 +92,7 @@ class CookieComponentTest extends CakeTestCase {
* @return void
*/
public function tearDown() {
parent::tearDown();
$this->Cookie->destroy();
}
@ -153,6 +153,24 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEquals($expected, $data);
}
/**
* test read operations on corrupted cookie data.
*
* @return void
*/
public function testReadCorruptedCookieData() {
$this->Cookie->type('aes');
$this->Cookie->key = sha1('some bad key');
$data = $this->_implode(array('name' => 'jill', 'age' => 24));
// Corrupt the cookie data by slicing some bytes off.
$_COOKIE['CakeTestCookie'] = array(
'BadData' => substr(Security::encrypt($data, $this->Cookie->key), 0, -5)
);
$this->assertFalse($this->Cookie->check('BadData.name'), 'Key does not exist');
$this->assertNull($this->Cookie->read('BadData.name'), 'Key does not exist');
}
/**
* testReadPlainCookieData
*
@ -169,6 +187,19 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEquals($expected, $data);
}
/**
* test read array keys from string data.
*
* @return void
*/
public function testReadNestedDataFromStrings() {
$_COOKIE['CakeTestCookie'] = array(
'User' => 'bad data'
);
$this->assertFalse($this->Cookie->check('User.name'), 'No key');
$this->assertNull($this->Cookie->read('User.name'), 'No key');
}
/**
* test read() after switching the cookie name.
*
@ -201,6 +232,84 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEquals('value', $result);
}
/**
* test write() encrypted data with falsey value
*
* @return void
*/
public function testWriteWithFalseyValue() {
$this->skipIf(!extension_loaded('mcrypt'), 'No Mcrypt, skipping.');
$this->Cookie->type('aes');
$this->Cookie->key = 'qSI232qs*&sXOw!adre@34SAv!@*(XSL#$%)asGb$@11~_+!@#HKis~#^';
$this->Cookie->write('Testing');
$result = $this->Cookie->read('Testing');
$this->assertNull($result);
$this->Cookie->write('Testing', '');
$result = $this->Cookie->read('Testing');
$this->assertEquals('', $result);
$this->Cookie->write('Testing', false);
$result = $this->Cookie->read('Testing');
$this->assertFalse($result);
$this->Cookie->write('Testing', 1);
$result = $this->Cookie->read('Testing');
$this->assertEquals(1, $result);
$this->Cookie->write('Testing', '0');
$result = $this->Cookie->read('Testing');
$this->assertSame('0', $result);
$this->Cookie->write('Testing', 0);
$result = $this->Cookie->read('Testing');
$this->assertSame(0, $result);
}
/**
* test that two write() calls use the expiry.
*
* @return void
*/
public function testWriteMultipleShareExpiry() {
$this->Cookie->write('key1', 'value1', false);
$this->Cookie->write('key2', 'value2', false);
$name = $this->Cookie->name . '[key1]';
$result = $this->Controller->response->cookie($name);
$this->assertWithinMargin(time() + 10, $result['expire'], 2, 'Expiry time is wrong');
$name = $this->Cookie->name . '[key2]';
$result = $this->Controller->response->cookie($name);
$this->assertWithinMargin(time() + 10, $result['expire'], 2, 'Expiry time is wrong');
}
/**
* test write with distant future cookies
*
* @return void
*/
public function testWriteFarFuture() {
$this->Cookie->write('Testing', 'value', false, '+90 years');
$future = new DateTime('now');
$future->modify('+90 years');
$expected = array(
'name' => $this->Cookie->name . '[Testing]',
'value' => 'value',
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => false);
$result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]');
$this->assertEquals($future->format('U'), $result['expire'], '', 3);
unset($result['expire']);
$this->assertEquals($expected, $result);
}
/**
* test write with httpOnly cookies
*
@ -282,6 +391,44 @@ class CookieComponentTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* Test that writing mixed arrays results in the correct data.
*
* @return void
*/
public function testWriteMixedArray() {
$this->Cookie->encrypt = false;
$this->Cookie->write('User', array('name' => 'mark'), false);
$this->Cookie->write('User.email', 'mark@example.com', false);
$expected = array(
'name' => $this->Cookie->name . '[User]',
'value' => '{"name":"mark","email":"mark@example.com"}',
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => false
);
$result = $this->Controller->response->cookie($this->Cookie->name . '[User]');
unset($result['expire']);
$this->assertEquals($expected, $result);
$this->Cookie->write('User.email', 'mark@example.com', false);
$this->Cookie->write('User', array('name' => 'mark'), false);
$expected = array(
'name' => $this->Cookie->name . '[User]',
'value' => '{"name":"mark"}',
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => false
);
$result = $this->Controller->response->cookie($this->Cookie->name . '[User]');
unset($result['expire']);
$this->assertEquals($expected, $result);
}
/**
* testReadingCookieValue
*
@ -336,6 +483,25 @@ class CookieComponentTest extends CakeTestCase {
$this->assertNull($data);
}
/**
* test delete() on corrupted/truncated cookie data.
*
* @return void
*/
public function testDeleteCorruptedCookieData() {
$this->Cookie->type('aes');
$this->Cookie->key = sha1('some bad key');
$data = $this->_implode(array('name' => 'jill', 'age' => 24));
// Corrupt the cookie data by slicing some bytes off.
$_COOKIE['CakeTestCookie'] = array(
'BadData' => substr(Security::encrypt($data, $this->Cookie->key), 0, -5)
);
$this->assertNull($this->Cookie->delete('BadData.name'));
$this->assertNull($this->Cookie->read('BadData.name'));
}
/**
* testReadingCookieArray
*
@ -513,17 +679,21 @@ class CookieComponentTest extends CakeTestCase {
/**
* Test reading empty values.
*
* @return void
*/
public function testReadEmpty() {
$_COOKIE['CakeTestCookie'] = array(
'JSON' => '{"name":"value"}',
'Empty' => '',
'String' => '{"somewhat:"broken"}'
'String' => '{"somewhat:"broken"}',
'Array' => '{}'
);
$this->assertEquals(array('name' => 'value'), $this->Cookie->read('JSON'));
$this->assertEquals('value', $this->Cookie->read('JSON.name'));
$this->assertEquals('', $this->Cookie->read('Empty'));
$this->assertEquals('{"somewhat:"broken"}', $this->Cookie->read('String'));
$this->assertEquals(array(), $this->Cookie->read('Array'));
}
/**
@ -538,6 +708,60 @@ class CookieComponentTest extends CakeTestCase {
$this->assertNull($this->Cookie->read('value'));
}
/**
* testCheck method
*
* @return void
*/
public function testCheck() {
$this->Cookie->write('CookieComponentTestCase', 'value');
$this->assertTrue($this->Cookie->check('CookieComponentTestCase'));
$this->assertFalse($this->Cookie->check('NotExistingCookieComponentTestCase'));
}
/**
* testCheckingSavedEmpty method
*
* @return void
*/
public function testCheckingSavedEmpty() {
$this->Cookie->write('CookieComponentTestCase', 0);
$this->assertTrue($this->Cookie->check('CookieComponentTestCase'));
$this->Cookie->write('CookieComponentTestCase', '0');
$this->assertTrue($this->Cookie->check('CookieComponentTestCase'));
$this->Cookie->write('CookieComponentTestCase', false);
$this->assertTrue($this->Cookie->check('CookieComponentTestCase'));
$this->Cookie->write('CookieComponentTestCase', null);
$this->assertFalse($this->Cookie->check('CookieComponentTestCase'));
}
/**
* testCheckKeyWithSpaces method
*
* @return void
*/
public function testCheckKeyWithSpaces() {
$this->Cookie->write('CookieComponent Test', "test");
$this->assertTrue($this->Cookie->check('CookieComponent Test'));
$this->Cookie->delete('CookieComponent Test');
$this->Cookie->write('CookieComponent Test.Test Case', "test");
$this->assertTrue($this->Cookie->check('CookieComponent Test.Test Case'));
}
/**
* testCheckEmpty
*
* @return void
*/
public function testCheckEmpty() {
$this->assertFalse($this->Cookie->check());
}
/**
* test that deleting a top level keys kills the child elements too.
*

View file

@ -4,20 +4,20 @@
*
* Series of tests for email component.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5347
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('EmailComponent', 'Controller/Component');
App::uses('AbstractTransport', 'Network/Email');
@ -58,7 +58,7 @@ class DebugCompTransport extends AbstractTransport {
* Send mail
*
* @params object $email CakeEmail
* @return boolean
* @return bool
*/
public function send(CakeEmail $email) {
$email->addHeaders(array('Date' => EmailComponentTest::$sentDate));
@ -77,7 +77,7 @@ class DebugCompTransport extends AbstractTransport {
$last .= sprintf("%s\n\n%s", 'Message:', $message);
$last .= '</pre>';
self::$lastEmail = $last;
static::$lastEmail = $last;
return true;
}
@ -91,17 +91,10 @@ class DebugCompTransport extends AbstractTransport {
*/
class EmailTestController extends Controller {
/**
* name property
*
* @var string 'EmailTest'
*/
public $name = 'EmailTest';
/**
* uses property
*
* @var mixed null
* @var mixed
*/
public $uses = null;
@ -131,7 +124,7 @@ class EmailComponentTest extends CakeTestCase {
/**
* name property
*
* @var string 'Email'
* @var string
*/
public $name = 'Email';
@ -156,7 +149,7 @@ class EmailComponentTest extends CakeTestCase {
$this->Controller->Components->init($this->Controller);
$this->Controller->EmailTest->initialize($this->Controller, array());
self::$sentDate = date(DATE_RFC2822);
static::$sentDate = date(DATE_RFC2822);
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
@ -177,7 +170,7 @@ class EmailComponentTest extends CakeTestCase {
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->messageId = false;
$date = self::$sentDate;
$date = static::$sentDate;
$message = <<<MSGBLOC
<pre>To: postmaster@example.com
From: noreply@example.com
@ -198,14 +191,14 @@ This is the body of the message
MSGBLOC;
$this->Controller->EmailTest->sendAs = 'text';
$expect = str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $message);
$expected = str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $message);
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(DebugCompTransport::$lastEmail, $expect);
$this->assertTextEquals($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'html';
$expect = str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $message);
$expected = str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $message);
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(DebugCompTransport::$lastEmail, $expect);
$this->assertTextEquals($expected, DebugCompTransport::$lastEmail);
}
/**
@ -224,7 +217,7 @@ MSGBLOC;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->messageId = false;
$date = self::$sentDate;
$date = static::$sentDate;
$header = <<<HEADBLOC
To: postmaster@example.com
From: noreply@example.com
@ -269,37 +262,34 @@ TEXTBLOC;
HTMLBLOC;
$this->Controller->EmailTest->sendAs = 'text';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $header) . $text . "\n" . '</pre>';
$expected = '<pre>' . str_replace('{CONTENTTYPE}', 'text/plain; charset=UTF-8', $header) . $text . "\n" . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(DebugCompTransport::$lastEmail, $expect);
$this->assertTextEquals($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'html';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . "\n" . '</pre>';
$expected = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . "\n" . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(DebugCompTransport::$lastEmail, $expect);
$this->assertTextEquals($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'both';
$expect = str_replace('{CONTENTTYPE}', 'multipart/mixed; boundary="{boundary}"', $header);
$expect .= "--{boundary}\n" .
'Content-Type: multipart/alternative; boundary="alt-{boundary}"' . "\n\n" .
'--alt-{boundary}' . "\n" .
$expected = str_replace('{CONTENTTYPE}', 'multipart/alternative; boundary="{boundary}"', $header);
$expected .= "--{boundary}\n" .
'Content-Type: text/plain; charset=UTF-8' . "\n" .
'Content-Transfer-Encoding: 8bit' . "\n\n" .
$text .
"\n\n" .
'--alt-{boundary}' . "\n" .
'--{boundary}' . "\n" .
'Content-Type: text/html; charset=UTF-8' . "\n" .
'Content-Transfer-Encoding: 8bit' . "\n\n" .
$html .
"\n\n" .
'--alt-{boundary}--' . "\n\n\n" .
"\n\n\n" .
'--{boundary}--' . "\n";
$expect = '<pre>' . $expect . '</pre>';
$expected = '<pre>' . $expected . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(
$expect,
$expected,
preg_replace('/[a-z0-9]{32}/i', '{boundary}', DebugCompTransport::$lastEmail)
);
@ -320,9 +310,9 @@ HTMLBLOC;
HTMLBLOC;
$this->Controller->EmailTest->sendAs = 'html';
$expect = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . '</pre>';
$expected = '<pre>' . str_replace('{CONTENTTYPE}', 'text/html; charset=UTF-8', $header) . $html . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message', 'default', 'thin'));
$this->assertTextEquals(DebugCompTransport::$lastEmail, $expect);
$this->assertTextEquals($expected, DebugCompTransport::$lastEmail);
}
/**
@ -349,6 +339,32 @@ HTMLBLOC;
$this->assertRegExp('/http\:\/\/example\.com/', $result);
}
/**
* test send with null properties
*
* @return void
*/
public function testSendNullProperties() {
$this->Controller->EmailTest->to = 'test@example.com';
$this->Controller->EmailTest->from = 'test@example.com';
$this->Controller->EmailTest->subject = null;
$this->Controller->EmailTest->replyTo = null;
$this->Controller->EmailTest->messageId = null;
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send(null));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/To: test@example.com\n/', $result);
$this->assertRegExp('/Subject: \n/', $result);
$this->assertRegExp('/From: test@example.com\n/', $result);
$this->assertRegExp('/Date: ' . preg_quote(static::$sentDate) . '\n/', $result);
$this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result);
$this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result);
$this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result);
}
/**
* testSendDebug method
*
@ -373,7 +389,7 @@ HTMLBLOC;
$this->assertRegExp('/From: noreply@example.com\n/', $result);
$this->assertRegExp('/Cc: cc@example.com\n/', $result);
$this->assertRegExp('/Bcc: bcc@example.com\n/', $result);
$this->assertRegExp('/Date: ' . preg_quote(self::$sentDate) . '\n/', $result);
$this->assertRegExp('/Date: ' . preg_quote(static::$sentDate) . '\n/', $result);
$this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result);
$this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result);
$this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result);
@ -402,7 +418,7 @@ HTMLBLOC;
$this->assertRegExp('/Subject: Cake Debug Test\n/', $result);
$this->assertRegExp('/Reply-To: noreply@example.com\n/', $result);
$this->assertRegExp('/From: noreply@example.com\n/', $result);
$this->assertRegExp('/Date: ' . preg_quote(self::$sentDate) . '\n/', $result);
$this->assertRegExp('/Date: ' . preg_quote(static::$sentDate) . '\n/', $result);
$this->assertRegExp('/X-Mailer: CakePHP Email Component\n/', $result);
$this->assertRegExp('/Content-Type: text\/plain; charset=UTF-8\n/', $result);
$this->assertRegExp('/Content-Transfer-Encoding: 8bitMessage:\n/', $result);
@ -573,7 +589,7 @@ HTMLBLOC;
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->date = self::$sentDate = 'Today!';
$this->Controller->EmailTest->date = static::$sentDate = 'Today!';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
@ -596,13 +612,13 @@ HTMLBLOC;
$this->assertEquals($expected, $result);
$content = '<p>Some HTML content with an <a href="mailto:test@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEquals($expected, $result);
$content = '<p>Some HTML content with an ';
$content = '<p>Some HTML content with an ';
$content .= '<a href="mailto:test@example.com,test2@example.com">email link</a>';
$result = $this->Controller->EmailTest->strip($content, true);
$result = $this->Controller->EmailTest->strip($content, true);
$expected = $content;
$this->assertEquals($expected, $result);
}
@ -870,6 +886,8 @@ HTMLBLOC;
/**
* Make sure from/to are not double encoded when UTF-8 is present
*
* @return void
*/
public function testEncodingFrom() {
$this->Controller->EmailTest->to = 'Teßt <test@example.com>';

View file

@ -0,0 +1,181 @@
<?php
/**
* FlashComponentTest file
*
* Series of tests for flash component.
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 2.7.0-dev
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('FlashComponent', 'Controller/Component');
App::uses('ComponentCollection', 'Controller');
/**
* FlashComponentTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class FlashComponentTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Components = new ComponentCollection();
$this->Flash = new FlashComponent($this->Components);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
CakeSession::destroy();
}
/**
* testSet method
*
* @return void
*/
public function testSet() {
$this->assertNull(CakeSession::read('Message.flash'));
$this->Flash->set('This is a test message');
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/default',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array(
'element' => 'test',
'params' => array('foo' => 'bar')
));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/test',
'params' => array('foo' => 'bar')
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array('element' => 'MyPlugin.alert'));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'MyPlugin.Flash/alert',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
$this->Flash->set('This is a test message', array('key' => 'foobar'));
$expected = array(
'message' => 'This is a test message',
'key' => 'foobar',
'element' => 'Flash/default',
'params' => array()
);
$result = CakeSession::read('Message.foobar');
$this->assertEquals($expected, $result);
}
/**
* testSetWithException method
*
* @return void
*/
public function testSetWithException() {
$this->assertNull(CakeSession::read('Message.flash'));
$this->Flash->set(new Exception('This is a test message', 404));
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/default',
'params' => array('code' => 404)
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
}
/**
* testSetWithComponentConfiguration method
*
* @return void
*/
public function testSetWithComponentConfiguration() {
$this->assertNull(CakeSession::read('Message.flash'));
$FlashWithSettings = $this->Components->load('Flash', array('element' => 'test'));
$FlashWithSettings->set('This is a test message');
$expected = array(
'message' => 'This is a test message',
'key' => 'flash',
'element' => 'Flash/test',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
}
/**
* Test magic call method.
*
* @return void
*/
public function testCall() {
$this->assertNull(CakeSession::read('Message.flash'));
$this->Flash->success('It worked');
$expected = array(
'message' => 'It worked',
'key' => 'flash',
'element' => 'Flash/success',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
$this->Flash->alert('It worked', array('plugin' => 'MyPlugin'));
$expected = array(
'message' => 'It worked',
'key' => 'flash',
'element' => 'MyPlugin.Flash/alert',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result);
$this->Flash->error('It did not work', array('element' => 'error_thing'));
$expected = array(
'message' => 'It did not work',
'key' => 'flash',
'element' => 'Flash/error',
'params' => array()
);
$result = CakeSession::read('Message.flash');
$this->assertEquals($expected, $result, 'Element is ignored in magic call.');
}
}

View file

@ -4,19 +4,18 @@
*
* Series of tests for paginator component.
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
@ -31,13 +30,6 @@ App::uses('CakeResponse', 'Network');
*/
class PaginatorTestController extends Controller {
/**
* name property
*
* @var string 'PaginatorTest'
*/
public $name = 'PaginatorTest';
/**
* components property
*
@ -53,17 +45,10 @@ class PaginatorTestController extends Controller {
*/
class PaginatorControllerPost extends CakeTestModel {
/**
* name property
*
* @var string 'PaginatorControllerPost'
*/
public $name = 'PaginatorControllerPost';
/**
* useTable property
*
* @var string 'posts'
* @var string
*/
public $useTable = 'posts';
@ -106,7 +91,7 @@ class PaginatorControllerPost extends CakeTestModel {
* @return void
*/
public function find($conditions = null, $fields = array(), $order = null, $recursive = null) {
if ($conditions == 'popular') {
if ($conditions === 'popular') {
$conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1');
$options = Hash::merge($fields, compact('conditions'));
return parent::find('all', $options);
@ -123,27 +108,21 @@ class PaginatorControllerPost extends CakeTestModel {
*/
class ControllerPaginateModel extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerPaginateModel'
*/
public $name = 'ControllerPaginateModel';
/**
* useTable property
*
* @var string 'comments'
* @var string
*/
public $useTable = 'comments';
/**
* paginate method
*
* @return void
* @return bool
*/
public function paginate($conditions, $fields, $order, $limit, $page, $recursive, $extra) {
$this->extra = $extra;
return true;
}
/**
@ -167,21 +146,21 @@ class PaginatorControllerComment extends CakeTestModel {
/**
* name property
*
* @var string 'Comment'
* @var string
*/
public $name = 'Comment';
/**
* useTable property
*
* @var string 'comments'
* @var string
*/
public $useTable = 'comments';
/**
* alias property
*
* @var string 'PaginatorControllerComment'
* @var string
*/
public $alias = 'PaginatorControllerComment';
}
@ -193,35 +172,21 @@ class PaginatorControllerComment extends CakeTestModel {
*/
class PaginatorAuthor extends CakeTestModel {
/**
* name property
*
* @var string 'PaginatorAuthor'
*/
public $name = 'PaginatorAuthor';
/**
* useTable property
*
* @var string 'authors'
* @var string
*/
public $useTable = 'authors';
/**
* alias property
*
* @var string 'PaginatorAuthor'
*/
public $alias = 'PaginatorAuthor';
/**
* alias property
*
* @var string 'PaginatorAuthor'
* @var string
*/
public $virtualFields = array(
'joined_offset' => 'PaginatorAuthor.id + 1'
);
'joined_offset' => 'PaginatorAuthor.id + 1'
);
}
@ -276,7 +241,7 @@ class PaginatorCustomPost extends CakeTestModel {
* @return array
*/
protected function _findTotals($state, $query, $results = array()) {
if ($state == 'before') {
if ($state === 'before') {
$query['fields'] = array('author_id');
$this->virtualFields['total_posts'] = "COUNT({$this->alias}.id)";
$query['fields'][] = 'total_posts';
@ -294,7 +259,7 @@ class PaginatorCustomPost extends CakeTestModel {
* @return array
*/
protected function _findTotalsOperation($state, $query, $results = array()) {
if ($state == 'before') {
if ($state === 'before') {
if (!empty($query['operation']) && $query['operation'] === 'count') {
unset($query['limit']);
$query['recursive'] = -1;
@ -353,12 +318,20 @@ class PaginatorComponentTest extends CakeTestCase {
$Controller->request->query = array();
$Controller->constructClasses();
$results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
$this->assertEquals(array(1, 2, 3), $results);
$Controller->PaginatorControllerPost->order = null;
$Controller->Paginator->settings = array(
'order' => array('PaginatorControllerComment.id' => 'ASC')
);
$results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerComment'), '{n}.PaginatorControllerComment.id');
$this->assertEquals(array(1, 2, 3, 4, 5, 6), $results);
$Controller->Paginator->settings = array(
'order' => array('PaginatorControllerPost.id' => 'ASC')
);
$results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
$this->assertEquals(array(1, 2, 3), $results);
$Controller->modelClass = null;
$Controller->uses[0] = 'Plugin.PaginatorControllerPost';
@ -385,16 +358,16 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertEquals(array(3, 2, 1), $results);
$Controller->request->params['named'] = array('sort' => 'NotExisting.field', 'direction' => 'desc');
$results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page'], 'Invalid field in query %s');
$this->assertEquals(array(1, 2, 3), $results);
$Controller->request->params['named'] = array('sort' => 'NotExisting.field', 'direction' => 'desc', 'limit' => 2);
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertEquals(array(), $Controller->PaginatorControllerPost->lastQueries[1]['order'], 'no order should be set.');
$Controller->request->params['named'] = array(
'sort' => 'PaginatorControllerPost.author_id', 'direction' => 'allYourBase'
);
$results = Hash::extract($Controller->Paginator->paginate('PaginatorControllerPost'), '{n}.PaginatorControllerPost.id');
$this->assertEquals(array('PaginatorControllerPost.author_id' => 'asc'), $Controller->PaginatorControllerPost->lastQueries[1]['order'][0]);
$this->assertEquals(array('PaginatorControllerPost.author_id' => 'asc'), $Controller->PaginatorControllerPost->lastQueries[0]['order']);
$this->assertEquals(array(1, 3, 2), $results);
$Controller->request->params['named'] = array();
@ -402,16 +375,16 @@ class PaginatorComponentTest extends CakeTestCase {
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true);
$this->assertFalse($Controller->params['paging']['PaginatorControllerPost']['prevPage']);
$this->assertTrue($Controller->params['paging']['PaginatorControllerPost']['nextPage']);
$Controller->request->params['named'] = array();
$Controller->Paginator->settings = array('limit' => 'garbage!', 'maxLimit' => 10, 'paramType' => 'named');
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true);
$this->assertFalse($Controller->params['paging']['PaginatorControllerPost']['prevPage']);
$this->assertTrue($Controller->params['paging']['PaginatorControllerPost']['nextPage']);
$Controller->request->params['named'] = array();
$Controller->Paginator->settings = array('limit' => '-1', 'maxLimit' => 10, 'paramType' => 'named');
@ -420,8 +393,8 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['limit'], 1);
$this->assertSame(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['pageCount'], 3);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['prevPage'], false);
$this->assertSame($Controller->params['paging']['PaginatorControllerPost']['nextPage'], true);
$this->assertFalse($Controller->params['paging']['PaginatorControllerPost']['prevPage']);
$this->assertTrue($Controller->params['paging']['PaginatorControllerPost']['nextPage']);
$Controller->Paginator->settings = array('conditions' => array('PaginatorAuthor.user' => 'mariano'));
$Controller->Paginator->paginate('PaginatorControllerPost');
@ -473,23 +446,34 @@ class PaginatorComponentTest extends CakeTestCase {
$Controller->constructClasses();
$Controller->request->params['named'] = array('page' => '-1', 'contain' => array('PaginatorControllerComment'));
$Controller->Paginator->settings = array(
'order' => array('PaginatorControllerPost.id' => 'ASC')
);
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
$this->assertTrue(!isset($Controller->PaginatorControllerPost->lastQueries[1]['contain']));
$Controller->Paginator->settings = array(
'order' => array('PaginatorControllerPost.author_id')
);
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertEquals(array(1, 3, 2), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
$Controller->request->params['named'] = array('page' => '-1');
$Controller->Paginator->settings = array(
'PaginatorControllerPost' => array(
'contain' => array('PaginatorControllerComment'),
'maxLimit' => 10,
'paramType' => 'named'
'paramType' => 'named',
'order' => array('PaginatorControllerPost.id' => 'ASC')
),
);
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(1, $Controller->params['paging']['PaginatorControllerPost']['page']);
$this->assertEquals(array(1, 2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
$this->assertTrue(isset($Controller->PaginatorControllerPost->lastQueries[1]['contain']));
$this->assertTrue(isset($Controller->PaginatorControllerPost->lastQueries[0]['contain']));
$Controller->Paginator->settings = array(
'PaginatorControllerPost' => array(
@ -498,14 +482,14 @@ class PaginatorComponentTest extends CakeTestCase {
);
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
$this->assertEquals(array('PaginatorControllerPost.id > ' => '1'), $Controller->PaginatorControllerPost->lastQueries[1]['conditions']);
$this->assertEquals(array('PaginatorControllerPost.id > ' => '1'), $Controller->PaginatorControllerPost->lastQueries[0]['conditions']);
$Controller->request->params['named'] = array('limit' => 12);
$Controller->Paginator->settings = array('limit' => 30, 'maxLimit' => 100, 'paramType' => 'named');
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$Controller->Paginator->paginate('PaginatorControllerPost');
$paging = $Controller->params['paging']['PaginatorControllerPost'];
$this->assertEquals(12, $Controller->PaginatorControllerPost->lastQueries[1]['limit']);
$this->assertEquals(12, $Controller->PaginatorControllerPost->lastQueries[0]['limit']);
$this->assertEquals(12, $paging['options']['limit']);
$Controller = new PaginatorTestController($this->request);
@ -520,7 +504,7 @@ class PaginatorComponentTest extends CakeTestCase {
'paramType' => 'named'
)
);
$result = $Controller->Paginator->paginate('ControllerPaginateModel');
$Controller->Paginator->paginate('ControllerPaginateModel');
$expected = array(
'contain' => array('ControllerPaginateModel'),
'group' => 'Comment.author_id',
@ -558,7 +542,7 @@ class PaginatorComponentTest extends CakeTestCase {
public function testPaginateSpecialType() {
$Controller = new PaginatorTestController($this->request);
$Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment');
$Controller->passedArgs[] = '1';
$Controller->request->params['pass'][] = '1';
$Controller->params['url'] = array();
$Controller->constructClasses();
@ -574,7 +558,7 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals(array(2, 3), Hash::extract($result, '{n}.PaginatorControllerPost.id'));
$this->assertEquals(
$Controller->PaginatorControllerPost->lastQueries[1]['conditions'],
$Controller->PaginatorControllerPost->lastQueries[0]['conditions'],
array('PaginatorControllerPost.id > ' => '1')
);
$this->assertFalse(isset($Controller->params['paging']['PaginatorControllerPost']['options'][0]));
@ -600,6 +584,53 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals(array(3, 2, 1), $results);
}
/**
* test paginate() and model default order
*
* @return void
*/
public function testPaginateOrderModelDefault() {
$Controller = new PaginatorTestController($this->request);
$Controller->uses = array('PaginatorControllerPost');
$Controller->params['url'] = array();
$Controller->constructClasses();
$Controller->PaginatorControllerPost->order = array(
$Controller->PaginatorControllerPost->alias . '.created' => 'desc'
);
$Controller->Paginator->settings = array(
'fields' => array('id', 'title', 'created'),
'maxLimit' => 10,
'paramType' => 'named'
);
$result = $Controller->Paginator->paginate('PaginatorControllerPost');
$expected = array('2007-03-18 10:43:23', '2007-03-18 10:41:23', '2007-03-18 10:39:23');
$this->assertEquals($expected, Hash::extract($result, '{n}.PaginatorControllerPost.created'));
$this->assertEquals(
$Controller->PaginatorControllerPost->order,
$Controller->request->paging['PaginatorControllerPost']['options']['order']
);
$Controller->PaginatorControllerPost->order = array('PaginatorControllerPost.id');
$result = $Controller->Paginator->validateSort($Controller->PaginatorControllerPost, array());
$this->assertEquals(array('PaginatorControllerPost.id' => 'asc'), $result['order']);
$Controller->PaginatorControllerPost->order = 'PaginatorControllerPost.id';
$result = $Controller->Paginator->validateSort($Controller->PaginatorControllerPost, array());
$this->assertArrayNotHasKey('order', $result);
$Controller->PaginatorControllerPost->order = array(
'PaginatorControllerPost.id',
'PaginatorControllerPost.created' => 'asc'
);
$result = $Controller->Paginator->validateSort($Controller->PaginatorControllerPost, array());
$expected = array(
'PaginatorControllerPost.id' => 'asc',
'PaginatorControllerPost.created' => 'asc'
);
$this->assertEquals($expected, $result['order']);
}
/**
* test paginate() and virtualField interactions
*
@ -656,6 +687,7 @@ class PaginatorComponentTest extends CakeTestCase {
* Tests for missing models
*
* @expectedException MissingModelException
* @return void
*/
public function testPaginateMissingModel() {
$Controller = new PaginatorTestController($this->request);
@ -710,6 +742,28 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test mergeOptions with customFind key
*
* @return void
*/
public function testMergeOptionsCustomFindKey() {
$this->request->params['named'] = array(
'page' => 10,
'limit' => 10
);
$this->Paginator->settings = array(
'page' => 1,
'limit' => 20,
'maxLimit' => 100,
'paramType' => 'named',
'findType' => 'myCustomFind'
);
$result = $this->Paginator->mergeOptions('Post');
$expected = array('page' => 10, 'limit' => 10, 'maxLimit' => 100, 'paramType' => 'named', 'findType' => 'myCustomFind');
$this->assertEquals($expected, $result);
}
/**
* test merging options from the querystring.
*
@ -788,6 +842,40 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test mergeOptions with limit > maxLimit in code.
*
* @return void
*/
public function testMergeOptionsMaxLimit() {
$this->Paginator->settings = array(
'limit' => 200,
'paramType' => 'named',
);
$result = $this->Paginator->mergeOptions('Post');
$expected = array('page' => 1, 'limit' => 200, 'maxLimit' => 100, 'paramType' => 'named');
$this->assertEquals($expected, $result);
$this->Paginator->settings = array(
'maxLimit' => 10,
'paramType' => 'named',
);
$result = $this->Paginator->mergeOptions('Post');
$expected = array('page' => 1, 'limit' => 20, 'maxLimit' => 10, 'paramType' => 'named');
$this->assertEquals($expected, $result);
$this->request->params['named'] = array(
'limit' => 500
);
$this->Paginator->settings = array(
'limit' => 150,
'paramType' => 'named',
);
$result = $this->Paginator->mergeOptions('Post');
$expected = array('page' => 1, 'limit' => 500, 'maxLimit' => 100, 'paramType' => 'named');
$this->assertEquals($expected, $result);
}
/**
* test that invalid directions are ignored.
*
@ -806,6 +894,9 @@ class PaginatorComponentTest extends CakeTestCase {
/**
* Test that a really large page number gets clamped to the max page size.
*
* @expectedException NotFoundException
* @return void
*/
public function testOutOfRangePageNumberGetsClamped() {
$Controller = new PaginatorTestController($this->request);
@ -816,21 +907,52 @@ class PaginatorComponentTest extends CakeTestCase {
$Controller->constructClasses();
$Controller->PaginatorControllerPost->recursive = 0;
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(
1,
$Controller->request->params['paging']['PaginatorControllerPost']['page'],
'Super big page number should be capped to max number of pages'
);
}
/**
* Test that a really REALLY large page number gets clamped to the max page size.
*
* @expectedException NotFoundException
* @return void
*/
public function testOutOfVeryBigPageNumberGetsClamped() {
$Controller = new PaginatorTestController($this->request);
$Controller->uses = array('PaginatorControllerPost');
$Controller->params['named'] = array(
'page' => '3000000000000000000000000',
);
$Controller->constructClasses();
$Controller->PaginatorControllerPost->recursive = 0;
$Controller->Paginator->paginate('PaginatorControllerPost');
}
/**
* testOutOfRangePageNumberAndPageCountZero
*
* @return void
*/
public function testOutOfRangePageNumberAndPageCountZero() {
$Controller = new PaginatorTestController($this->request);
$Controller->uses = array('PaginatorControllerPost');
$Controller->params['named'] = array(
'page' => '3000',
);
$Controller->constructClasses();
$Controller->PaginatorControllerPost->recursive = 0;
$Controller->paginate = array(
'conditions' => array('PaginatorControllerPost.id >' => 100)
);
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->assertEquals(
1,
$Controller->request->params['paging']['PaginatorControllerPost']['page'],
'Page number should not be 0'
);
try {
$Controller->Paginator->paginate('PaginatorControllerPost');
$this->fail();
} catch (NotFoundException $e) {
$this->assertEquals(
1,
$Controller->request->params['paging']['PaginatorControllerPost']['page'],
'Page number should not be 0'
);
}
}
/**
@ -849,6 +971,23 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertNull($result['order']);
}
/**
* test that fields in the whitelist are not validated
*
* @return void
*/
public function testValidateSortWhitelistTrusted() {
$model = $this->getMock('Model');
$model->alias = 'model';
$model->expects($this->never())->method('hasField');
$options = array('sort' => 'body', 'direction' => 'asc');
$result = $this->Paginator->validateSort($model, $options, array('body'));
$expected = array('body' => 'asc');
$this->assertEquals($expected, $result['order']);
}
/**
* test that virtual fields work.
*
@ -874,6 +1013,30 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals('desc', $result['order']['something']);
}
/**
* test that sorting fields is alias specific
*
* @return void
*/
public function testValidateSortSharedFields() {
$model = $this->getMock('Model');
$model->alias = 'Parent';
$model->Child = $this->getMock('Model');
$model->Child->alias = 'Child';
$model->expects($this->never())
->method('hasField');
$model->Child->expects($this->at(0))
->method('hasField')
->with('something')
->will($this->returnValue(true));
$options = array('sort' => 'Child.something', 'direction' => 'desc');
$result = $this->Paginator->validateSort($model, $options);
$this->assertEquals('desc', $result['order']['Child.something']);
}
/**
* test that multiple sort works.
*
@ -884,10 +1047,12 @@ class PaginatorComponentTest extends CakeTestCase {
$model->alias = 'model';
$model->expects($this->any())->method('hasField')->will($this->returnValue(true));
$options = array('order' => array(
'author_id' => 'asc',
'title' => 'asc'
));
$options = array(
'order' => array(
'author_id' => 'asc',
'title' => 'asc'
)
);
$result = $this->Paginator->validateSort($model, $options);
$expected = array(
'model.author_id' => 'asc',
@ -917,6 +1082,21 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertEquals($options['order'], $result['order']);
}
/**
* Test sorting with incorrect aliases on valid fields.
*
* @return void
*/
public function testValidateSortInvalidAlias() {
$model = $this->getMock('Model');
$model->alias = 'Model';
$model->expects($this->any())->method('hasField')->will($this->returnValue(true));
$options = array('sort' => 'Derp.id');
$result = $this->Paginator->validateSort($model, $options);
$this->assertEquals(array(), $result['order']);
}
/**
* test that maxLimit is respected
*
@ -948,32 +1128,32 @@ class PaginatorComponentTest extends CakeTestCase {
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorControllerPost', 'ControllerComment');
$Controller->passedArgs[] = '1';
$Controller->request->params['pass'][] = '1';
$Controller->constructClasses();
$Controller->request->params['named'] = array(
'contain' => array('ControllerComment'), 'limit' => '1000'
);
$result = $Controller->paginate('PaginatorControllerPost');
$Controller->paginate('PaginatorControllerPost');
$this->assertEquals(100, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']);
$Controller->request->params['named'] = array(
'contain' => array('ControllerComment'), 'limit' => '1000', 'maxLimit' => 1000
);
$result = $Controller->paginate('PaginatorControllerPost');
$Controller->paginate('PaginatorControllerPost');
$this->assertEquals(100, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']);
$Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '10');
$result = $Controller->paginate('PaginatorControllerPost');
$Controller->paginate('PaginatorControllerPost');
$this->assertEquals(10, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']);
$Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '1000');
$Controller->paginate = array('maxLimit' => 2000, 'paramType' => 'named');
$result = $Controller->paginate('PaginatorControllerPost');
$Controller->paginate('PaginatorControllerPost');
$this->assertEquals(1000, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']);
$Controller->request->params['named'] = array('contain' => array('ControllerComment'), 'limit' => '5000');
$result = $Controller->paginate('PaginatorControllerPost');
$Controller->paginate('PaginatorControllerPost');
$this->assertEquals(2000, $Controller->params['paging']['PaginatorControllerPost']['options']['limit']);
}
@ -999,11 +1179,26 @@ class PaginatorComponentTest extends CakeTestCase {
), false);
$Controller->paginate = array(
'fields' => array('PaginatorControllerComment.id', 'title', 'PaginatorControllerPost.title'),
'fields' => array(
'PaginatorControllerComment.id',
'title',
'PaginatorControllerPost.title'
),
);
$Controller->passedArgs = array('sort' => 'PaginatorControllerPost.title', 'dir' => 'asc');
$result = $Controller->paginate('PaginatorControllerComment');
$this->assertEquals(array(1, 2, 3, 4, 5, 6), Hash::extract($result, '{n}.PaginatorControllerComment.id'));
$Controller->request->params['named'] = array(
'sort' => 'PaginatorControllerPost.title',
'direction' => 'desc'
);
$result = Hash::extract(
$Controller->paginate('PaginatorControllerComment'),
'{n}.PaginatorControllerComment.id'
);
$result1 = array_splice($result, 0, 2);
sort($result1);
$this->assertEquals(array(5, 6), $result1);
sort($result);
$this->assertEquals(array(1, 2, 3, 4), $result);
}
/**
@ -1012,7 +1207,7 @@ class PaginatorComponentTest extends CakeTestCase {
* @return void
*/
public function testPaginateCustomFind() {
$Controller =& new Controller($this->request);
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorCustomPost');
$Controller->constructClasses();
$data = array('author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N');
@ -1052,7 +1247,7 @@ class PaginatorComponentTest extends CakeTestCase {
* @return void
*/
public function testPaginateCustomFindFieldsArray() {
$Controller =& new Controller($this->request);
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorCustomPost');
$Controller->constructClasses();
$data = array('author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N');
@ -1078,6 +1273,38 @@ class PaginatorComponentTest extends CakeTestCase {
$this->assertTrue($result['nextPage']);
$this->assertFalse($result['prevPage']);
}
/**
* test paginate() and custom find with customFind key, to make sure the correct count is returned.
*
* @return void
*/
public function testPaginateCustomFindWithCustomFindKey() {
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorCustomPost');
$Controller->constructClasses();
$data = array('author_id' => 3, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N');
$Controller->PaginatorCustomPost->create($data);
$result = $Controller->PaginatorCustomPost->save();
$this->assertTrue(!empty($result));
$Controller->paginate = array(
'conditions' => array('PaginatorCustomPost.published' => 'Y'),
'findType' => 'list',
'limit' => 2
);
$result = $Controller->paginate();
$expected = array(
1 => 'First Post',
2 => 'Second Post',
);
$this->assertEquals($expected, $result);
$result = $Controller->params['paging']['PaginatorCustomPost'];
$this->assertEquals(2, $result['current']);
$this->assertEquals(3, $result['count']);
$this->assertEquals(2, $result['pageCount']);
$this->assertTrue($result['nextPage']);
$this->assertFalse($result['prevPage']);
}
/**
* test paginate() and custom find with fields array, to make sure the correct count is returned.
@ -1085,7 +1312,7 @@ class PaginatorComponentTest extends CakeTestCase {
* @return void
*/
public function testPaginateCustomFindGroupBy() {
$Controller =& new Controller($this->request);
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorCustomPost');
$Controller->constructClasses();
$data = array('author_id' => 2, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N');
@ -1150,7 +1377,7 @@ class PaginatorComponentTest extends CakeTestCase {
* @return void
*/
public function testPaginateCustomFindCount() {
$Controller =& new Controller($this->request);
$Controller = new Controller($this->request);
$Controller->uses = array('PaginatorCustomPost');
$Controller->constructClasses();
$data = array('author_id' => 2, 'title' => 'Fourth Article', 'body' => 'Article Body, unpublished', 'published' => 'N');

View file

@ -2,25 +2,26 @@
/**
* RequestHandlerComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5435
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('RequestHandlerComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('Router', 'Routing');
App::uses('JsonView', 'View');
/**
* RequestHandlerTestController class
@ -32,7 +33,7 @@ class RequestHandlerTestController extends Controller {
/**
* uses property
*
* @var mixed null
* @var mixed
*/
public $uses = null;
@ -70,6 +71,14 @@ class RequestHandlerTestController extends Controller {
}
/**
* CustomJsonView class
*
* @package Cake.Test.Case.Controller.Component
*/
class CustomJsonView extends JsonView {
}
/**
* RequestHandlerComponentTest class
@ -137,12 +146,14 @@ class RequestHandlerComponentTest extends CakeTestCase {
*/
public function testConstructorSettings() {
$settings = array(
'ajaxLayout' => 'test_ajax'
'ajaxLayout' => 'test_ajax',
'viewClassMap' => array('json' => 'MyPlugin.MyJson')
);
$Collection = new ComponentCollection();
$Collection->init($this->Controller);
$RequestHandler = new RequestHandlerComponent($Collection, $settings);
$this->assertEquals('test_ajax', $RequestHandler->ajaxLayout);
$this->assertEquals(array('json' => 'MyPlugin.MyJson'), $RequestHandler->settings['viewClassMap']);
}
/**
@ -178,7 +189,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
public function testInitializeContentTypeWithjQueryAccept() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, */*; q=0.01';
$_SERVER['HTTP_ACCEPT'] = 'application/json, application/javascript, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('json');
@ -186,6 +197,20 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertEquals('json', $this->RequestHandler->ext);
}
/**
* Test that RequestHandler does not set extension to csv for text/plain mimetype
*
* @return void
*/
public function testInitializeContentTypeWithjQueryTextPlainAccept() {
$_SERVER['HTTP_ACCEPT'] = 'text/plain, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('csv');
$this->RequestHandler->initialize($this->Controller);
$this->assertNull($this->RequestHandler->ext);
}
/**
* Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers
* and the application is configured to handle multiple extensions
@ -193,7 +218,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* @return void
*/
public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, */*; q=0.01';
$_SERVER['HTTP_ACCEPT'] = 'application/json, application/javascript, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('rss', 'json');
@ -216,17 +241,40 @@ class RequestHandlerComponentTest extends CakeTestCase {
}
/**
* Test that ext is not set with multiple accepted content types.
* Test that ext is set to the first listed extension with multiple accepted
* content types.
* Having multiple types accepted with same weight, means the client lets the
* server choose the returned content type.
*
* @return void
*/
public function testInitializeNoContentTypeWithMultipleAcceptedTypes() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, text/javascript, application/xml, */*; q=0.01';
$_SERVER['HTTP_ACCEPT'] = 'application/json, application/javascript, application/xml, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('xml', 'json');
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('xml', $this->RequestHandler->ext);
$this->RequestHandler->ext = null;
Router::setExtensions(array('json', 'xml'), false);
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $this->RequestHandler->ext);
}
/**
* Test that ext is set to type with highest weight
*
* @return void
*/
public function testInitializeContentTypeWithMultipleAcceptedTypes() {
$_SERVER['HTTP_ACCEPT'] = 'text/csv;q=1.0, application/json;q=0.8, application/xml;q=0.7';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('xml', 'json');
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $this->RequestHandler->ext);
}
/**
@ -243,6 +291,19 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertNull($this->RequestHandler->ext);
}
/**
* Test that the headers sent by firefox are not treated as XML requests.
*
* @return void
*/
public function testInititalizeFirefoxHeaderNotXml() {
$_SERVER['HTTP_ACCEPT'] = 'text/html,application/xhtml+xml,application/xml;image/png,image/jpeg,image/*;q=0.9,*/*;q=0.8';
Router::parseExtensions('xml', 'json');
$this->RequestHandler->initialize($this->Controller);
$this->assertNull($this->RequestHandler->ext);
}
/**
* Test that a type mismatch doesn't incorrectly set the ext
*
@ -264,6 +325,33 @@ class RequestHandlerComponentTest extends CakeTestCase {
call_user_func_array(array('Router', 'parseExtensions'), $extensions);
}
/**
* testViewClassMap method
*
* @return void
*/
public function testViewClassMap() {
$this->RequestHandler->settings = array('viewClassMap' => array('json' => 'CustomJson'));
$this->RequestHandler->initialize($this->Controller);
$result = $this->RequestHandler->viewClassMap();
$expected = array(
'json' => 'CustomJson',
'xml' => 'Xml'
);
$this->assertEquals($expected, $result);
$result = $this->RequestHandler->viewClassMap('xls', 'Excel.Excel');
$expected = array(
'json' => 'CustomJson',
'xml' => 'Xml',
'xls' => 'Excel.Excel'
);
$this->assertEquals($expected, $result);
$this->RequestHandler->renderAs($this->Controller, 'json');
$this->assertEquals('CustomJson', $this->Controller->viewClass);
}
/**
* testDisabling method
*
@ -278,19 +366,6 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertEquals(true, $this->Controller->params['isAjax']);
}
/**
* testAutoResponseType method
*
* @return void
*/
public function testAutoResponseType() {
$this->Controller->ext = '.thtml';
$this->Controller->request->params['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertEquals('.ctp', $this->Controller->ext);
}
/**
* testAutoAjaxLayout method
*
@ -372,6 +447,23 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertNull($this->RequestHandler->beforeRedirect($this->Controller, '/'));
}
/**
* test that redirects with ajax and no URL don't do anything.
*
* @return void
*/
public function testAjaxRedirectWithNoUrl() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->Controller->response = $this->getMock('CakeResponse');
$this->Controller->response->expects($this->never())
->method('body');
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertNull($this->RequestHandler->beforeRedirect($this->Controller, null));
}
/**
* testRenderAs method
*
@ -523,6 +615,22 @@ class RequestHandlerComponentTest extends CakeTestCase {
$result = $this->RequestHandler->requestedWith(array('rss', 'atom'));
$this->assertFalse($result);
$_SERVER['REQUEST_METHOD'] = 'DELETE';
$this->assertEquals('json', $this->RequestHandler->requestedWith());
$_SERVER['REQUEST_METHOD'] = 'PATCH';
$this->assertEquals('json', $this->RequestHandler->requestedWith());
$_SERVER['REQUEST_METHOD'] = 'POST';
unset($_SERVER['CONTENT_TYPE']);
$_SERVER['HTTP_CONTENT_TYPE'] = 'application/json';
$result = $this->RequestHandler->requestedWith(array('json', 'xml'));
$this->assertEquals('json', $result);
$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->assertTrue($this->RequestHandler->isXml());
$this->assertFalse($this->RequestHandler->isAtom());
@ -630,7 +738,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
$this->assertEquals('text/vnd.wap.wml', $result);
$result = $this->RequestHandler->mapAlias(array('xml', 'js', 'json'));
$expected = array('application/xml', 'text/javascript', 'application/json');
$expected = array('application/xml', 'application/javascript', 'application/json');
$this->assertEquals($expected, $result);
}
@ -762,10 +870,9 @@ class RequestHandlerComponentTest extends CakeTestCase {
/**
* test that the beforeRedirect callback properly converts
* array urls into their correct string ones, and adds base => false so
* the correct urls are generated.
* 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
*/
public function testBeforeRedirectCallbackWithArrayUrl() {
@ -800,7 +907,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
$controller = $this->getMock('Controller', array('header'));
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader','statusCode'));
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader', 'statusCode'));
$RequestHandler->request = $this->getMock('CakeRequest');
$RequestHandler->request->expects($this->once())->method('is')
->with('ajax')
@ -810,7 +917,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
ob_start();
$RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403);
$result = ob_get_clean();
ob_get_clean();
}
/**
@ -825,7 +932,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* Test checkNotModified method
*
* @return void
**/
*/
public function testCheckNotModifiedByEtagStar() {
$_SERVER['HTTP_IF_NONE_MATCH'] = '*';
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
@ -839,7 +946,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* Test checkNotModified method
*
* @return void
**/
*/
public function testCheckNotModifiedByEtagExact() {
$_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
@ -853,7 +960,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* Test checkNotModified method
*
* @return void
**/
*/
public function testCheckNotModifiedByEtagAndTime() {
$_SERVER['HTTP_IF_NONE_MATCH'] = 'W/"something", "other"';
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = '2012-01-01 00:00:00';
@ -869,7 +976,7 @@ class RequestHandlerComponentTest extends CakeTestCase {
* Test checkNotModified method
*
* @return void
**/
*/
public function testCheckNotModifiedNoInfo() {
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('notModified'));

View file

@ -2,19 +2,18 @@
/**
* SecurityComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5435
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('SecurityComponent', 'Controller/Component');
@ -31,7 +30,7 @@ class TestSecurityComponent extends SecurityComponent {
* validatePost method
*
* @param Controller $controller
* @return boolean
* @return bool
*/
public function validatePost(Controller $controller) {
return $this->_validatePost($controller);
@ -46,13 +45,6 @@ class TestSecurityComponent extends SecurityComponent {
*/
class SecurityTestController extends Controller {
/**
* name property
*
* @var string 'SecurityTest'
*/
public $name = 'SecurityTest';
/**
* components property
*
@ -63,7 +55,7 @@ class SecurityTestController extends Controller {
/**
* failed property
*
* @var boolean false
* @var bool
*/
public $failed = false;
@ -150,8 +142,12 @@ class SecurityComponentTest extends CakeTestCase {
public function setUp() {
parent::setUp();
$request = new CakeRequest('posts/index', false);
$request = $this->getMock('CakeRequest', array('here'), array('posts/index', false));
$request->addParams(array('controller' => 'posts', 'action' => 'index'));
$request->expects($this->any())
->method('here')
->will($this->returnValue('/posts/index'));
$this->Controller = new SecurityTestController($request);
$this->Controller->Components->init($this->Controller);
$this->Controller->Security = $this->Controller->TestSecurity;
@ -180,6 +176,7 @@ class SecurityComponentTest extends CakeTestCase {
* visibility keyword in the blackhole callback
*
* @expectedException BadRequestException
* @return void
*/
public function testBlackholeWithBrokenCallback() {
$request = new CakeRequest('posts/index', false);
@ -333,19 +330,23 @@ class SecurityComponentTest extends CakeTestCase {
*/
public function testRequireAuthSucceed() {
$_SERVER['REQUEST_METHOD'] = 'AUTH';
$this->Controller->Security->unlockedActions = array('posted');
$this->Controller->request['action'] = 'posted';
$this->Controller->Security->requireAuth('posted');
$this->Controller->Security->startup($this->Controller);
$this->assertFalse($this->Controller->failed);
$this->Controller->Security->Session->write('_Token', array(
'allowedControllers' => array('SecurityTest'), 'allowedActions' => array('posted')
'allowedControllers' => array('SecurityTest'),
'allowedActions' => array('posted')
));
$this->Controller->request['controller'] = 'SecurityTest';
$this->Controller->request['action'] = 'posted';
$this->Controller->request->data = array(
'username' => 'willy', 'password' => 'somePass', '_Token' => ''
'username' => 'willy',
'password' => 'somePass',
'_Token' => ''
);
$this->Controller->action = 'posted';
$this->Controller->Security->requireAuth('posted');
@ -483,6 +484,29 @@ class SecurityComponentTest extends CakeTestCase {
$this->assertFalse($this->Controller->failed);
}
/**
* Test that validatePost fires on GET with request data.
* This could happen when method overriding is used.
*
* @return void
* @triggers Controller.startup $this->Controller
*/
public function testValidatePostOnGetWithData() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->Controller->Security->startup($this->Controller);
$fields = 'an-invalid-token';
$unlocked = '';
$this->Controller->request->data = array(
'Model' => array('username' => 'nate', 'password' => 'foo', 'valid' => '0'),
'_Token' => compact('fields', 'unlocked')
);
$this->assertFalse($this->Controller->failed, 'Should not be failed yet');
$this->Controller->Security->startup($this->Controller);
$this->assertTrue($this->Controller->failed, 'Should fail because of validatePost.');
}
/**
* Simple hash validation test
*
@ -492,7 +516,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
$fields = '01c1f6dbba02ac6f21b229eab1cc666839b14303%3AModel.valid';
$unlocked = '';
$this->Controller->request->data = array(
@ -572,7 +596,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'f7d573650a295b94e0938d32b323fde775e5f32b%3A';
$fields = '38504e4a341d4e6eadb437217efd91270e558d55%3A';
$unlocked = '';
$this->Controller->request->data = array(
@ -591,7 +615,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '540ac9c60d323c22bafe997b72c0790f39a8bdef%3A';
$fields = 'c5bc49a6c938c820e7e538df3d8ab7bffbc97ef9%3A';
$unlocked = '';
$this->Controller->request->data = array(
@ -612,10 +636,10 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '69f493434187b867ea14b901fdf58b55d27c935d%3A';
$fields = '5415d31b4483c1e09ddb58d2a91ba9650b12aa83%3A';
$unlocked = '';
$this->Controller->request->data = $data = array(
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => ''),
'_Token' => compact('key', 'fields', 'unlocked')
);
@ -633,7 +657,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'c9118120e680a7201b543f562e5301006ccfcbe2%3AAddresses.0.id%7CAddresses.1.id';
$fields = 'b72a99e923687687bb5e64025d3cc65e1cecced4%3AAddresses.0.id%7CAddresses.1.id';
$unlocked = '';
$this->Controller->request->data = array(
@ -662,7 +686,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '422cde416475abc171568be690a98cad20e66079%3A';
$fields = '8a764bdb989132c1d46f9a45f64ce2da5f9eebb9%3A';
$unlocked = '';
$this->Controller->request->data = array(
@ -686,7 +710,7 @@ class SecurityComponentTest extends CakeTestCase {
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$fields = '19464422eafe977ee729c59222af07f983010c5f%3A';
$fields = '722de3615e63fdff899e86e85e6498b11c50bb66%3A';
$this->Controller->request->data = array(
'User.password' => 'bar', 'User.name' => 'foo', 'User.is_valid' => '1',
'Tag' => array('Tag' => array(1)),
@ -707,7 +731,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testValidatePostCheckbox() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a5475372b40f6e3ccbf9f8af191f20e1642fd877%3AModel.valid';
$fields = '01c1f6dbba02ac6f21b229eab1cc666839b14303%3AModel.valid';
$unlocked = '';
$this->Controller->request->data = array(
@ -718,7 +742,7 @@ class SecurityComponentTest extends CakeTestCase {
$result = $this->Controller->Security->validatePost($this->Controller);
$this->assertTrue($result);
$fields = '874439ca69f89b4c4a5f50fb9c36ff56a28f5d42%3A';
$fields = 'efbcf463a2c31e97c85d95eedc41dff9e9c6a026%3A';
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
@ -732,7 +756,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$this->Controller->request->data = $data = array(
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => '', 'valid' => '0'),
'_Token' => compact('key', 'fields', 'unlocked')
);
@ -749,7 +773,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testValidatePostHidden() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '51ccd8cb0997c7b3d4523ecde5a109318405ef8c%3AModel.hidden%7CModel.other_hidden';
$fields = 'baaf832a714b39a0618238ac89c7065fc8ec853e%3AModel.hidden%7CModel.other_hidden';
$unlocked = '';
$this->Controller->request->data = array(
@ -772,7 +796,7 @@ class SecurityComponentTest extends CakeTestCase {
$this->Controller->Security->disabledFields = array('Model.username', 'Model.password');
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'ef1082968c449397bcd849f963636864383278b1%3AModel.hidden';
$fields = 'aa7f254ebd8bf2ef118bc5ca1e191d1ae96857f5%3AModel.hidden';
$unlocked = '';
$this->Controller->request->data = array(
@ -796,7 +820,12 @@ class SecurityComponentTest extends CakeTestCase {
$key = $this->Controller->request->params['_Token']['key'];
$unlocked = 'Model.username';
$fields = array('Model.hidden', 'Model.password');
$fields = urlencode(Security::hash(serialize($fields) . $unlocked . Configure::read('Security.salt')));
$fields = urlencode(Security::hash(
'/posts/index' .
serialize($fields) .
$unlocked .
Configure::read('Security.salt'))
);
$this->Controller->request->data = array(
'Model' => array(
@ -838,7 +867,7 @@ class SecurityComponentTest extends CakeTestCase {
/**
* Test that validatePost fails when unlocked fields are changed.
*
* @return
* @return void
*/
public function testValidatePostFailDisabledFieldTampering() {
$this->Controller->Security->startup($this->Controller);
@ -871,7 +900,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testValidateHiddenMultipleModel() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = 'a2d01072dc4660eea9d15007025f35a7a5b58e18%3AModel.valid%7CModel2.valid%7CModel3.valid';
$fields = '38dd8a37bbb52e67ee4eb812bf1725a6a18b989b%3AModel.valid%7CModel2.valid%7CModel3.valid';
$unlocked = '';
$this->Controller->request->data = array(
@ -892,7 +921,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testValidateHasManyModel() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '51e3b55a6edd82020b3f29c9ae200e14bbeb7ee5%3AModel.0.hidden%7CModel.0.valid';
$fields = 'dcef68de6634c60d2e60484ad0e2faec003456e6%3AModel.0.hidden%7CModel.0.valid';
$fields .= '%7CModel.1.hidden%7CModel.1.valid';
$unlocked = '';
@ -922,7 +951,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testValidateHasManyRecordsPass() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '7a203edb3d345bbf38fe0dccae960da8842e11d7%3AAddress.0.id%7CAddress.0.primary%7C';
$fields = '8b6880fbbd4b69279155f899652ecffdd9b4c5a1%3AAddress.0.id%7CAddress.0.primary%7C';
$fields .= 'Address.1.id%7CAddress.1.primary';
$unlocked = '';
@ -966,7 +995,13 @@ class SecurityComponentTest extends CakeTestCase {
$key = $this->Controller->request->params['_Token']['key'];
$unlocked = '';
$hashFields = array('TaxonomyData');
$fields = urlencode(Security::hash(serialize($hashFields) . $unlocked . Configure::read('Security.salt')));
$fields = urlencode(
Security::hash(
'/posts/index' .
serialize($hashFields) .
$unlocked .
Configure::read('Security.salt'), 'sha1')
);
$this->Controller->request->data = array(
'TaxonomyData' => array(
@ -1031,7 +1066,7 @@ class SecurityComponentTest extends CakeTestCase {
public function testFormDisabledFields() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '11842060341b9d0fc3808b90ba29fdea7054d6ad%3An%3A0%3A%7B%7D';
$fields = '216ee717efd1a251a6d6e9efbb96005a9d09f1eb%3An%3A0%3A%7B%7D';
$unlocked = '';
$this->Controller->request->data = array(
@ -1059,10 +1094,10 @@ class SecurityComponentTest extends CakeTestCase {
*
* @return void
*/
public function testRadio() {
public function testValidatePostRadio() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '575ef54ca4fc8cab468d6d898e9acd3a9671c17e%3An%3A0%3A%7B%7D';
$fields = '3be63770e7953c6d2119f5377a9303372040f66f%3An%3A0%3A%7B%7D';
$unlocked = '';
$this->Controller->request->data = array(
@ -1093,12 +1128,42 @@ class SecurityComponentTest extends CakeTestCase {
$this->assertTrue($result);
}
/**
* test validatePost uses here() as a hash input.
*
* @return void
*/
public function testValidatePostUrlAsHashInput() {
$this->Controller->Security->startup($this->Controller);
$key = $this->Controller->request->params['_Token']['key'];
$fields = '5415d31b4483c1e09ddb58d2a91ba9650b12aa83%3A';
$unlocked = '';
$this->Controller->request->data = array(
'Model' => array('username' => '', 'password' => ''),
'_Token' => compact('key', 'fields', 'unlocked')
);
$this->assertTrue($this->Controller->Security->validatePost($this->Controller));
$request = $this->getMock('CakeRequest', array('here'), array('articles/edit/1', false));
$request->expects($this->at(0))
->method('here')
->will($this->returnValue('/posts/index?page=1'));
$request->expects($this->at(1))
->method('here')
->will($this->returnValue('/posts/edit/1'));
$this->Controller->Security->request = $request;
$this->assertFalse($this->Controller->Security->validatePost($this->Controller));
$this->assertFalse($this->Controller->Security->validatePost($this->Controller));
}
/**
* test that a requestAction's controller will have the _Token appended to
* the params.
*
* @return void
* @see http://cakephp.lighthouseapp.com/projects/42648/tickets/68
*/
public function testSettingTokenForRequestAction() {
$this->Controller->Security->startup($this->Controller);
@ -1115,7 +1180,6 @@ class SecurityComponentTest extends CakeTestCase {
* test that blackhole doesn't delete the _Token session key so repeat data submissions
* stay blackholed.
*
* @link http://cakephp.lighthouseapp.com/projects/42648/tickets/214
* @return void
*/
public function testBlackHoleNotDeletingSessionInformation() {
@ -1174,9 +1238,8 @@ class SecurityComponentTest extends CakeTestCase {
$token = $this->Security->Session->read('_Token');
$this->assertEquals(2, count($token['csrfTokens']), 'Missing the csrf token.');
foreach ($token['csrfTokens'] as $key => $expires) {
$diff = $csrfExpires - $expires;
$this->assertTrue($diff === 0 || $diff === 1, 'Token expiry does not match');
foreach ($token['csrfTokens'] as $expires) {
$this->assertWithinMargin($expires, $csrfExpires, 2, 'Token expiry does not match');
}
}
@ -1192,11 +1255,6 @@ class SecurityComponentTest extends CakeTestCase {
$this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
$this->Controller->request = $this->getMock('CakeRequest', array('is'));
$this->Controller->request->expects($this->once())->method('is')
->with('post')
->will($this->returnValue(true));
$this->Controller->request->params['action'] = 'index';
$this->Controller->request->data = array(
'_Token' => array(
@ -1211,6 +1269,23 @@ class SecurityComponentTest extends CakeTestCase {
$this->assertFalse(isset($token['csrfTokens']['nonce1']), 'Token was not consumed');
}
/**
* tests that reusable CSRF-token expiry is renewed
*/
public function testCsrfReusableTokenRenewal() {
$this->Security->validatePost = false;
$this->Security->csrfCheck = true;
$this->Security->csrfUseOnce = false;
$csrfExpires = '+10 minutes';
$this->Security->csrfExpires = $csrfExpires;
$this->Security->Session->write('_Token.csrfTokens', array('token' => strtotime('+1 minutes')));
$this->Security->startup($this->Controller);
$tokens = $this->Security->Session->read('_Token.csrfTokens');
$this->assertWithinMargin($tokens['token'], strtotime($csrfExpires), 2, 'Token expiry was not renewed');
}
/**
* test that expired values in the csrfTokens are cleaned up.
*
@ -1244,11 +1319,6 @@ class SecurityComponentTest extends CakeTestCase {
$this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
$this->Controller->request = $this->getMock('CakeRequest', array('is'));
$this->Controller->request->expects($this->once())->method('is')
->with('post')
->will($this->returnValue(true));
$this->Controller->request->params['action'] = 'index';
$this->Controller->request->data = array(
'_Token' => array(
@ -1274,11 +1344,6 @@ class SecurityComponentTest extends CakeTestCase {
$this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('-5 minutes')));
$this->Controller->request = $this->getMock('CakeRequest', array('is'));
$this->Controller->request->expects($this->once())->method('is')
->with('post')
->will($this->returnValue(true));
$this->Controller->request->params['action'] = 'index';
$this->Controller->request->data = array(
'_Token' => array(
@ -1331,10 +1396,6 @@ class SecurityComponentTest extends CakeTestCase {
$this->Security->Session->write('_Token.csrfTokens', array('nonce1' => strtotime('+10 minutes')));
$this->Controller->request = $this->getMock('CakeRequest', array('is'));
$this->Controller->request->expects($this->once())->method('is')
->with('post')
->will($this->returnValue(true));
$this->Controller->request->params['action'] = 'index';
$this->Controller->request->data = array(
'_Token' => array(
@ -1388,4 +1449,18 @@ class SecurityComponentTest extends CakeTestCase {
$this->assertTrue(isset($result['4']));
$this->assertTrue(isset($result['5']));
}
/**
* Test unlocked actions
*
* @return void
*/
public function testUnlockedActions() {
$_SERVER['REQUEST_METHOD'] = 'POST';
$this->Controller->request->data = array('data');
$this->Controller->Security->unlockedActions = 'index';
$this->Controller->Security->blackHoleCallback = null;
$result = $this->Controller->Security->startup($this->Controller);
$this->assertNull($result);
}
}

View file

@ -2,20 +2,20 @@
/**
* SessionComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller.Component
* @since CakePHP(tm) v 1.2.0.5436
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('SessionComponent', 'Controller/Component');
@ -91,7 +91,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
public static function setupBeforeClass() {
self::$_sessionBackup = Configure::read('Session');
static::$_sessionBackup = Configure::read('Session');
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 100,
@ -105,7 +105,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
public static function teardownAfterClass() {
Configure::write('Session', self::$_sessionBackup);
Configure::write('Session', static::$_sessionBackup);
}
/**
@ -135,11 +135,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
public function testSessionIdConsistentAcrossRequestAction() {
$Session = new SessionComponent($this->ComponentCollection);
$Session->check('Test');
$this->assertTrue(isset($_SESSION));
$Object = new Object();
$Object = new CakeObject();
$Session = new SessionComponent($this->ComponentCollection);
$expected = $Session->id();
@ -175,6 +171,7 @@ class SessionComponentTest extends CakeTestCase {
* @return void
*/
public function testSessionError() {
CakeSession::$lastError = null;
$Session = new SessionComponent($this->ComponentCollection);
$this->assertFalse($Session->error());
}
@ -205,7 +202,6 @@ class SessionComponentTest extends CakeTestCase {
$this->assertEquals($Session->read('Test'), $array);
$Session->delete('Test');
$this->assertFalse($Session->write(array('Test'), 'some value'));
$this->assertTrue($Session->write(array('Test' => 'some value')));
$this->assertEquals('some value', $Session->read('Test'));
$Session->delete('Test');
@ -273,7 +269,7 @@ class SessionComponentTest extends CakeTestCase {
public function testSessionId() {
unset($_SESSION);
$Session = new SessionComponent($this->ComponentCollection);
$Session->check('test');
CakeSession::start();
$this->assertEquals(session_id(), $Session->id());
}

View file

@ -2,20 +2,20 @@
/**
* ComponentCollectionTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeResponse', 'Network');
App::uses('CookieComponent', 'Controller/Component');
App::uses('SecurityComponent', 'Controller/Component');
@ -59,8 +59,8 @@ class ComponentCollectionTest extends CakeTestCase {
$this->assertInstanceOf('CookieComponent', $result);
$this->assertInstanceOf('CookieComponent', $this->Components->Cookie);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.');
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie'), $result, 'loaded() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
@ -79,8 +79,8 @@ class ComponentCollectionTest extends CakeTestCase {
$this->assertInstanceOf('CookieAliasComponent', $this->Components->Cookie);
$this->assertTrue($this->Components->Cookie->settings['somesetting']);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie'), $result, 'attached() results are wrong.');
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie'), $result, 'loaded() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
@ -93,8 +93,8 @@ class ComponentCollectionTest extends CakeTestCase {
$this->assertInstanceOf('OtherComponent', $result);
$this->assertInstanceOf('OtherComponent', $this->Components->SomeOther);
$result = $this->Components->attached();
$this->assertEquals(array('Cookie', 'SomeOther'), $result, 'attached() results are wrong.');
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie', 'SomeOther'), $result, 'loaded() results are wrong.');
App::build();
CakePlugin::unload();
}
@ -148,14 +148,14 @@ class ComponentCollectionTest extends CakeTestCase {
$this->Components->load('Cookie');
$this->Components->load('Security');
$result = $this->Components->attached();
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie', 'Security'), $result, 'loaded components is wrong');
$this->Components->unload('Cookie');
$this->assertFalse(isset($this->Components->Cookie));
$this->assertTrue(isset($this->Components->Security));
$result = $this->Components->attached();
$result = $this->Components->loaded();
$this->assertEquals(array('Security'), $result, 'loaded components is wrong');
$result = $this->Components->enabled();

View file

@ -2,19 +2,18 @@
/**
* ComponentTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 1.2.0.5436
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
@ -27,19 +26,15 @@ App::uses('Component', 'Controller');
*/
class ParamTestComponent extends Component {
/**
* name property
*
* @var string 'ParamTest'
*/
public $name = 'ParamTest';
/**
* components property
*
* @var array
*/
public $components = array('Banana' => array('config' => 'value'));
public $components = array(
'Apple' => array('enabled' => true),
'Banana' => array('config' => 'value'),
);
}
/**
@ -49,13 +44,6 @@ class ParamTestComponent extends Component {
*/
class ComponentTestController extends Controller {
/**
* name property
*
* @var string 'ComponentTest'
*/
public $name = 'ComponentTest';
/**
* uses property
*
@ -82,7 +70,7 @@ class AppleComponent extends Component {
/**
* testName property
*
* @var mixed null
* @var mixed
*/
public $testName = null;
@ -145,7 +133,7 @@ class BananaComponent extends Component {
/**
* testField property
*
* @var string 'BananaField'
* @var string
*/
public $testField = 'BananaField';
@ -206,7 +194,6 @@ class SomethingWithEmailComponent extends Component {
public $components = array('Email');
}
/**
* ComponentTest class
*
@ -302,4 +289,17 @@ class ComponentTest extends CakeTestCase {
$this->assertInstanceOf('EmailComponent', $Controller->SomethingWithEmail->Email);
}
/**
* Test lazy loading of components inside components and both explicit and
* implicit 'enabled' setting.
*
* @return void
*/
public function testGet() {
$Collection = new ComponentCollection();
$ParamTest = $Collection->load('ParamTest');
$this->assertTrue($ParamTest->Apple->settings['enabled']);
$this->assertFalse($ParamTest->Banana->settings['enabled']);
}
}

View file

@ -4,27 +4,26 @@
*
* Isolated from the Controller and Component test as to not pollute their AppController class
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 1.2.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
/**
* Test case AppController
*
* @package Cake.Test.Case.Controller
* @package Cake.Test.Case.Controller
*/
class MergeVarsAppController extends Controller {
@ -48,7 +47,7 @@ class MergeVarsAppController extends Controller {
*
* @package Cake.Test.Case.Controller
*/
class MergeVarComponent extends Object {
class MergeVarComponent extends CakeObject {
}
@ -59,13 +58,6 @@ class MergeVarComponent extends Object {
*/
class MergeVariablesController extends MergeVarsAppController {
/**
* name
*
* @var string
*/
public $name = 'MergeVariables';
/**
* uses
*
@ -100,7 +92,7 @@ class MergeVarPluginAppController extends MergeVarsAppController {
*
* @var array
*/
public $helpers = array('Javascript');
public $helpers = array('Js');
/**
* parent for mergeVars
@ -117,13 +109,6 @@ class MergeVarPluginAppController extends MergeVarsAppController {
*/
class MergePostsController extends MergeVarPluginAppController {
/**
* name
*
* @var string
*/
public $name = 'MergePosts';
/**
* uses
*
@ -132,7 +117,6 @@ class MergePostsController extends MergeVarPluginAppController {
public $uses = array();
}
/**
* Test Case for Controller Merging of Vars.
*
@ -219,7 +203,7 @@ class ControllerMergeVarsTest extends CakeTestCase {
$expected = array(
'MergeVar' => array('format' => 'html', 'terse'),
'Javascript' => null
'Js' => null
);
$this->assertEquals($expected, $Controller->helpers, 'Helpers are unexpected.');
@ -249,4 +233,18 @@ class ControllerMergeVarsTest extends CakeTestCase {
$this->assertFalse(isset($Controller->Session));
}
/**
* Ensure that $modelClass is correct even when Controller::$uses
* has been iterated, eg: by a Component, or event handlers.
*
* @return void
*/
public function testMergeVarsModelClass() {
$Controller = new MergeVariablescontroller();
$Controller->uses = array('Test', 'TestAlias');
$Controller->constructClasses();
$this->assertEquals($Controller->uses[0], $Controller->modelClass);
}
}

View file

@ -1,17 +1,19 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 1.2.0.5436
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('Router', 'Routing');
App::uses('CakeRequest', 'Network');
@ -48,7 +50,6 @@ class ControllerTestAppController extends Controller {
public $components = array('Cookie');
}
/**
* ControllerPost class
*
@ -56,17 +57,10 @@ class ControllerTestAppController extends Controller {
*/
class ControllerPost extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerPost'
*/
public $name = 'ControllerPost';
/**
* useTable property
*
* @var string 'posts'
* @var string
*/
public $useTable = 'posts';
@ -80,7 +74,7 @@ class ControllerPost extends CakeTestModel {
/**
* lastQuery property
*
* @var mixed null
* @var mixed
*/
public $lastQuery = null;
@ -102,7 +96,7 @@ class ControllerPost extends CakeTestModel {
* @return void
*/
public function find($type = 'first', $options = array()) {
if ($type == 'popular') {
if ($type === 'popular') {
$conditions = array($this->name . '.' . $this->primaryKey . ' > ' => '1');
$options = Hash::merge($options, compact('conditions'));
return parent::find('all', $options);
@ -119,13 +113,6 @@ class ControllerPost extends CakeTestModel {
*/
class ControllerCommentsController extends ControllerTestAppController {
/**
* name property
*
* @var string 'ControllerPost'
*/
public $name = 'ControllerComments';
protected $_mergeParent = 'ControllerTestAppController';
}
@ -139,14 +126,14 @@ class ControllerComment extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerComment'
* @var string
*/
public $name = 'Comment';
/**
* useTable property
*
* @var string 'comments'
* @var string
*/
public $useTable = 'comments';
@ -160,7 +147,7 @@ class ControllerComment extends CakeTestModel {
/**
* alias property
*
* @var string 'ControllerComment'
* @var string
*/
public $alias = 'ControllerComment';
}
@ -172,24 +159,17 @@ class ControllerComment extends CakeTestModel {
*/
class ControllerAlias extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerAlias'
*/
public $name = 'ControllerAlias';
/**
* alias property
*
* @var string 'ControllerSomeAlias'
* @var string
*/
public $alias = 'ControllerSomeAlias';
/**
* useTable property
*
* @var string 'posts'
* @var string
*/
public $useTable = 'posts';
}
@ -203,20 +183,20 @@ class NameTest extends CakeTestModel {
/**
* name property
* @var string 'Name'
* @var string
*/
public $name = 'Name';
/**
* useTable property
* @var string 'names'
* @var string
*/
public $useTable = 'comments';
/**
* alias property
*
* @var string 'ControllerComment'
* @var string
*/
public $alias = 'Name';
}
@ -228,12 +208,6 @@ class NameTest extends CakeTestModel {
*/
class TestController extends ControllerTestAppController {
/**
* name property
* @var string 'Name'
*/
public $name = 'Test';
/**
* helpers property
*
@ -310,7 +284,7 @@ class TestController extends ControllerTestAppController {
*
* @package Cake.Test.Case.Controller
*/
class TestComponent extends Object {
class TestComponent extends CakeObject {
/**
* beforeRedirect method
@ -359,6 +333,13 @@ class TestComponent extends Object {
class Test2Component extends TestComponent {
public $model;
public function __construct(ComponentCollection $collection, $settings) {
$this->controller = $collection->getController();
$this->model = $this->controller->modelClass;
}
public function beforeRender(Controller $controller) {
return false;
}
@ -372,12 +353,6 @@ class Test2Component extends TestComponent {
*/
class AnotherTestController extends ControllerTestAppController {
/**
* name property
* @var string 'Name'
*/
public $name = 'AnotherTest';
/**
* uses property
*
@ -446,11 +421,24 @@ class ControllerTest extends CakeTestCase {
$result = $Controller->loadModel('ControllerPost');
$this->assertTrue($result);
$this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost'));
$this->assertTrue(in_array('ControllerPost', $Controller->uses));
$this->assertInstanceOf('ControllerPost', $Controller->ControllerPost);
$this->assertContains('ControllerPost', $Controller->uses);
}
ClassRegistry::flush();
unset($Controller);
/**
* Test loadModel() when uses = true.
*
* @return void
*/
public function testLoadModelUsesTrue() {
$request = new CakeRequest('controller_posts/index');
$response = $this->getMock('CakeResponse');
$Controller = new Controller($request, $response);
$Controller->uses = true;
$Controller->loadModel('ControllerPost');
$this->assertInstanceOf('ControllerPost', $Controller->ControllerPost);
$this->assertContains('ControllerPost', $Controller->uses);
}
/**
@ -494,8 +482,8 @@ class ControllerTest extends CakeTestCase {
$Controller = new Controller($request);
$Controller->uses = array('ControllerPost', 'ControllerComment');
$Controller->constructClasses();
$this->assertTrue(is_a($Controller->ControllerPost, 'ControllerPost'));
$this->assertTrue(is_a($Controller->ControllerComment, 'ControllerComment'));
$this->assertInstanceOf('ControllerPost', $Controller->ControllerPost);
$this->assertInstanceOf('ControllerComment', $Controller->ControllerComment);
$this->assertEquals('Comment', $Controller->ControllerComment->name);
@ -509,7 +497,23 @@ class ControllerTest extends CakeTestCase {
$Controller->constructClasses();
$this->assertTrue(isset($Controller->TestPluginPost));
$this->assertTrue(is_a($Controller->TestPluginPost, 'TestPluginPost'));
$this->assertInstanceOf('TestPluginPost', $Controller->TestPluginPost);
}
/**
* testConstructClassesWithComponents method
*
* @return void
*/
public function testConstructClassesWithComponents() {
$Controller = new TestPluginController(new CakeRequest(), new CakeResponse());
$Controller->uses = array('NameTest');
$Controller->components[] = 'Test2';
$Controller->constructClasses();
$this->assertEquals('NameTest', $Controller->Test2->model);
$this->assertEquals('Name', $Controller->NameTest->name);
$this->assertEquals('Name', $Controller->NameTest->alias);
}
/**
@ -543,8 +547,8 @@ class ControllerTest extends CakeTestCase {
$Controller->flash('this should work', '/flash');
$result = $Controller->response->body();
$expected = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
$expected = '<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>this should work</title>
@ -601,7 +605,6 @@ class ControllerTest extends CakeTestCase {
$Controller->set('title', 'someTitle');
$this->assertSame($Controller->viewVars['title'], 'someTitle');
$this->assertTrue(empty($Controller->pageTitle));
$Controller->viewVars = array();
$expected = array('ModelName' => 'name', 'ModelName2' => 'name2');
@ -650,7 +653,7 @@ class ControllerTest extends CakeTestCase {
$expected = $Controller->ControllerComment->validationErrors;
$Controller->viewPath = 'Posts';
$result = $Controller->render('index');
$Controller->render('index');
$View = $Controller->View;
$this->assertTrue(isset($View->validationErrors['ControllerComment']));
$this->assertEquals($expected, $View->validationErrors['ControllerComment']);
@ -990,6 +993,7 @@ class ControllerTest extends CakeTestCase {
$Controller->constructClasses();
$this->assertFalse(isset($Controller->Session));
$this->assertFalse(isset($Controller->Flash));
}
/**
@ -1028,6 +1032,30 @@ class ControllerTest extends CakeTestCase {
$this->assertEquals('/', $result);
}
/**
* Test that the referer is not absolute if it is '/'.
*
* This avoids the base path being applied twice on string urls.
*
* @return void
*/
public function testRefererSlash() {
$request = $this->getMock('CakeRequest', array('referer'));
$request->base = '/base';
$request->expects($this->any())
->method('referer')
->will($this->returnValue('/'));
Router::setRequestInfo($request);
$controller = new Controller($request);
$result = $controller->referer('/', true);
$this->assertEquals('/', $result);
$controller = new Controller($request);
$result = $controller->referer('/some/path', true);
$this->assertEquals('/base/some/path', $result);
}
/**
* testSetAction method
*
@ -1075,10 +1103,11 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
public function testValidateErrorsOnArbitraryModels() {
Configure::write('Config.language', 'eng');
$TestController = new TestController();
$Post = new ControllerPost();
$Post->validate = array('title' => 'notEmpty');
$Post->validate = array('title' => 'notBlank');
$Post->set('title', '');
$result = $TestController->validateErrors($Post);
@ -1254,7 +1283,7 @@ class ControllerTest extends CakeTestCase {
* @return void
*/
public function testPropertyBackwardsCompatibility() {
$request = new CakeRequest('posts/index', null);
$request = new CakeRequest('posts/index', false);
$request->addParams(array('controller' => 'posts', 'action' => 'index'));
$request->data = array('Post' => array('id' => 1));
$request->here = '/posts/index';
@ -1311,13 +1340,13 @@ class ControllerTest extends CakeTestCase {
$this->assertEquals(array(1, 2, 3), $results);
$Controller->passedArgs = array();
$Controller->paginate = array('limit' => '-1');
$this->assertEquals(array('limit' => '-1'), $Controller->paginate);
$Controller->paginate = array('limit' => '1');
$this->assertEquals(array('limit' => '1'), $Controller->paginate);
$Controller->paginate('ControllerPost');
$this->assertSame($Controller->params['paging']['ControllerPost']['page'], 1);
$this->assertSame($Controller->params['paging']['ControllerPost']['pageCount'], 3);
$this->assertSame($Controller->params['paging']['ControllerPost']['prevPage'], false);
$this->assertSame($Controller->params['paging']['ControllerPost']['nextPage'], true);
$this->assertFalse($Controller->params['paging']['ControllerPost']['prevPage']);
$this->assertTrue($Controller->params['paging']['ControllerPost']['nextPage']);
}
/**
@ -1419,6 +1448,25 @@ class ControllerTest extends CakeTestCase {
$Controller->invokeAction($url);
}
/**
* test invoking controller methods.
*
* @expectedException PrivateActionException
* @expectedExceptionMessage Private Action TestController::Admin_add() is not directly accessible.
* @return void
*/
public function testInvokeActionPrefixProtectionCasing() {
Router::reload();
Router::connect('/admin/:controller/:action/*', array('prefix' => 'admin'));
$url = new CakeRequest('test/Admin_add/');
$url->addParams(array('controller' => 'test_controller', 'action' => 'Admin_add'));
$response = $this->getMock('CakeResponse');
$Controller = new TestController($url, $response);
$Controller->invokeAction($url);
}
/**
* test invoking controller methods.
*

View file

@ -2,19 +2,18 @@
/**
* PagesControllerTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 1.2.0.5436
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('PagesController', 'Controller');
@ -50,4 +49,47 @@ class PagesControllerTest extends CakeTestCase {
$this->assertEquals('TestTheme', $Pages->viewVars['page']);
$this->assertEquals('Posts', $Pages->viewVars['subpage']);
}
/**
* Test that missing view renders 404 page in production
*
* @expectedException NotFoundException
* @expectedExceptionCode 404
* @return void
*/
public function testMissingView() {
Configure::write('debug', 0);
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->display('non_existing_page');
}
/**
* Test that missing view in debug mode renders missing_view error page
*
* @expectedException MissingViewException
* @expectedExceptionCode 500
* @return void
*/
public function testMissingViewInDebug() {
Configure::write('debug', 1);
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->display('non_existing_page');
}
/**
* Test directory traversal protection
*
* @expectedException ForbiddenException
* @expectedExceptionCode 403
* @return void
*/
public function testDirectoryTraversalProtection() {
App::build(array(
'View' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
)
));
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->display('..', 'Posts', 'index');
}
}

View file

@ -2,20 +2,20 @@
/**
* ScaffoldTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 1.2.0.5436
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Router', 'Routing');
App::uses('Controller', 'Controller');
App::uses('Scaffold', 'Controller');
@ -31,13 +31,6 @@ require_once dirname(dirname(__FILE__)) . DS . 'Model' . DS . 'models.php';
*/
class ScaffoldMockController extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
*/
public $name = 'ScaffoldMock';
/**
* scaffold property
*
@ -56,7 +49,7 @@ class ScaffoldMockControllerWithFields extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
* @var string
*/
public $name = 'ScaffoldMock';
@ -70,7 +63,8 @@ class ScaffoldMockControllerWithFields extends Controller {
/**
* function beforeScaffold
*
* @param string method
* @param string $method Method name.
* @return bool true
*/
public function beforeScaffold($method) {
$this->set('scaffoldFields', array('title'));
@ -79,6 +73,39 @@ class ScaffoldMockControllerWithFields extends Controller {
}
/**
* ScaffoldMockControllerWithError class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldMockControllerWithError extends Controller {
/**
* name property
*
* @var string
*/
public $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
*/
public $scaffold;
/**
* function beforeScaffold
*
* @param string $method Method name.
* @return bool false
*/
public function beforeScaffold($method) {
return false;
}
}
/**
* TestScaffoldMock class
*
@ -89,7 +116,8 @@ class TestScaffoldMock extends Scaffold {
/**
* Overload _scaffold
*
* @param unknown_type $params
* @param CakeRequest $request Request object for scaffolding
* @return void
*/
protected function _scaffold(CakeRequest $request) {
$this->_params = $request;
@ -134,6 +162,7 @@ class ScaffoldTest extends CakeTestCase {
*/
public function setUp() {
parent::setUp();
Configure::write('Config.language', 'eng');
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockController($request);
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
@ -230,7 +259,7 @@ class ScaffoldTest extends CakeTestCase {
$this->Controller->theme = 'TestTheme';
$this->Controller->viewClass = 'Theme';
$this->Controller->constructClasses();
$Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request);
new TestScaffoldMock($this->Controller, $this->Controller->request);
$this->assertEquals('Scaffold', $this->Controller->viewClass);
}
@ -348,4 +377,40 @@ class ScaffoldTest extends CakeTestCase {
$this->assertNotRegExp('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
}
/**
* test in case of scaffold error
*
* @return void
*/
public function testScaffoldError() {
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockControllerWithError($request);
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/Scaffold Error/', $result);
}
}

View file

@ -2,19 +2,18 @@
/**
* AppTest file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Core
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
@ -96,7 +95,7 @@ class AppTest extends CakeTestCase {
}
/**
* tests that it is possible to set up paths using the cake 1.3 notation for them (models, behaviors, controllers...)
* tests that it is possible to set up paths using the CakePHP 1.3 notation for them (models, behaviors, controllers...)
*
* @return void
*/
@ -302,7 +301,7 @@ class AppTest extends CakeTestCase {
* @return void
*/
public function testListObjects() {
$result = App::objects('class', CAKE . 'Routing', false);
$result = App::objects('class', CAKE . 'Routing', false);
$this->assertTrue(in_array('Dispatcher', $result));
$this->assertTrue(in_array('Router', $result));
@ -363,6 +362,8 @@ class AppTest extends CakeTestCase {
/**
* Make sure that .svn and friends are excluded from App::objects('plugin')
*
* @return void
*/
public function testListObjectsIgnoreDotDirectories() {
$path = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS;
@ -429,27 +430,6 @@ class AppTest extends CakeTestCase {
App::build();
}
/**
* test that pluginPath can find paths for plugins.
*
* @return void
*/
public function testPluginPath() {
App::build(array(
'plugins' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$path = App::pluginPath('TestPlugin');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS;
$this->assertEquals($expected, $path);
$path = App::pluginPath('TestPluginTwo');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPluginTwo' . DS;
$this->assertEquals($expected, $path);
App::build();
}
/**
* test that themePath can find paths for themes.
*
@ -596,7 +576,6 @@ class AppTest extends CakeTestCase {
* test that building helper paths actually works.
*
* @return void
* @link http://cakephp.lighthouseapp.com/projects/42648/tickets/410
*/
public function testImportingHelpersFromAlternatePaths() {
$this->assertFalse(class_exists('BananaHelper', false), 'BananaHelper exists, cannot test importing it.');
@ -749,7 +728,7 @@ class AppTest extends CakeTestCase {
$result = App::import('Vendor', 'css/TestAsset', array('ext' => 'css'));
$text = ob_get_clean();
$this->assertTrue($result);
$this->assertEquals('this is the test asset css file', $text);
$this->assertEquals('/* this is the test asset css file */', trim($text));
$result = App::import('Vendor', 'TestPlugin.sample/SamplePlugin');
$this->assertTrue($result);
@ -794,6 +773,7 @@ class AppTest extends CakeTestCase {
* Tests that the automatic class loader will also find in "libs" folder for both
* app and plugins if it does not find the class in other configured paths
*
* @return void
*/
public function testLoadClassInLibs() {
App::build(array(
@ -808,11 +788,11 @@ class AppTest extends CakeTestCase {
$this->assertFalse(class_exists('TestUtilityClass', false));
App::uses('TestUtilityClass', 'Utility');
$this->assertTrue(class_exists('CustomLibClass'));
$this->assertTrue(class_exists('TestUtilityClass'));
}
/**
* Tests that App::location() returns the defined path for a class
* Tests that App::location() returns the defined path for a class
*
* @return void
*/
@ -848,4 +828,36 @@ class AppTest extends CakeTestCase {
App::uses('TestPluginOtherLibrary', 'TestPlugin.Lib');
$this->assertTrue(class_exists('TestPluginOtherLibrary'));
}
/**
* Test that increaseMemoryLimit increases the maximum amount of memory actually
*
* @dataProvider memoryVariationProvider
* @return void
*/
public function testIncreaseMemoryLimit($memoryLimit, $additionalKb, $expected) {
$this->skipIf(!function_exists('ini_set'));
$originalMemoryLimit = ini_get('memory_limit');
ini_set('memory_limit', $memoryLimit);
App::increaseMemoryLimit($additionalKb);
$this->assertEquals($expected, ini_get('memory_limit'));
ini_set('memory_limit', $originalMemoryLimit);
}
/**
* Data provider function for testIncreaseMemoryLimit
*
* @return void
*/
public function memoryVariationProvider() {
return array(
array('131072K', 100000, '231072K'),
array('256M', 1, '262145K'),
array('1G', 1, '1048577K'),
array('-1', 100000, '-1')
);
}
}

View file

@ -2,21 +2,21 @@
/**
* ObjectTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Core
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeObject', 'Core');
App::uses('Object', 'Core');
App::uses('Router', 'Routing');
App::uses('Controller', 'Controller');
@ -29,17 +29,10 @@ App::uses('Model', 'Model');
*/
class RequestActionPost extends CakeTestModel {
/**
* name property
*
* @var string 'ControllerPost'
*/
public $name = 'RequestActionPost';
/**
* useTable property
*
* @var string 'posts'
* @var string
*/
public $useTable = 'posts';
}
@ -55,14 +48,12 @@ class RequestActionController extends Controller {
* uses property
*
* @var array
* @access public
*/
public $uses = array('RequestActionPost');
/**
* test_request_action method
*
* @access public
* @return void
*/
public function test_request_action() {
@ -74,7 +65,6 @@ class RequestActionController extends Controller {
*
* @param mixed $id
* @param mixed $other
* @access public
* @return void
*/
public function another_ra_test($id, $other) {
@ -84,7 +74,7 @@ class RequestActionController extends Controller {
/**
* normal_request_action method
*
* @return void
* @return string Hello World!
*/
public function normal_request_action() {
return 'Hello World';
@ -93,19 +83,19 @@ class RequestActionController extends Controller {
/**
* returns $this->here
*
* @return void
* @return string $this->here.
*/
public function return_here() {
return $this->here;
return $this->request->here();
}
/**
* paginate_request_action method
*
* @return void
* @return true
*/
public function paginate_request_action() {
$data = $this->paginate();
$this->paginate();
return true;
}
@ -139,23 +129,23 @@ class RequestActionController extends Controller {
}
/**
* TestObject class
* TestCakeObject class
*
* @package Cake.Test.Case.Core
*/
class TestObject extends Object {
class TestCakeObject extends CakeObject {
/**
* firstName property
*
* @var string 'Joel'
* @var string
*/
public $firstName = 'Joel';
/**
* lastName property
*
* @var string 'Moss'
* @var string
*/
public $lastName = 'Moss';
@ -262,8 +252,9 @@ class TestObject extends Object {
}
/**
* undocumented function
* Set properties.
*
* @param array $properties The $properties.
* @return void
*/
public function set($properties = array()) {
@ -281,12 +272,10 @@ class ObjectTestModel extends CakeTestModel {
public $useTable = false;
public $name = 'ObjectTestModel';
}
/**
* Object Test class
* CakeObject Test class
*
* @package Cake.Test.Case.Core
*/
@ -306,7 +295,7 @@ class ObjectTest extends CakeTestCase {
*/
public function setUp() {
parent::setUp();
$this->object = new TestObject();
$this->object = new TestCakeObject();
}
/**
@ -377,7 +366,7 @@ class ObjectTest extends CakeTestCase {
*/
public function testToString() {
$result = strtolower($this->object->toString());
$this->assertEquals('testobject', $result);
$this->assertEquals('testcakeobject', $result);
}
/**
@ -388,62 +377,62 @@ class ObjectTest extends CakeTestCase {
public function testMethodDispatching() {
$this->object->emptyMethod();
$expected = array('emptyMethod');
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->oneParamMethod('Hello');
$expected[] = array('oneParamMethod' => array('Hello'));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->twoParamMethod(true, false);
$expected[] = array('twoParamMethod' => array(true, false));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->threeParamMethod(true, false, null);
$expected[] = array('threeParamMethod' => array(true, false, null));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->crazyMethod(1, 2, 3, 4, 5, 6, 7);
$expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object = new TestObject();
$this->object = new TestCakeObject();
$this->assertSame($this->object->methodCalls, array());
$this->object->dispatchMethod('emptyMethod');
$expected = array('emptyMethod');
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('oneParamMethod', array('Hello'));
$expected[] = array('oneParamMethod' => array('Hello'));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('twoParamMethod', array(true, false));
$expected[] = array('twoParamMethod' => array(true, false));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('threeParamMethod', array(true, false, null));
$expected[] = array('threeParamMethod' => array(true, false, null));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('fourParamMethod', array(1, 2, 3, 4));
$expected[] = array('fourParamMethod' => array(1, 2, 3, 4));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('fiveParamMethod', array(1, 2, 3, 4, 5));
$expected[] = array('fiveParamMethod' => array(1, 2, 3, 4, 5));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('crazyMethod', array(1, 2, 3, 4, 5, 6, 7));
$expected[] = array('crazyMethod' => array(1, 2, 3, 4, 5, 6, 7));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('methodWithOptionalParam', array('Hello'));
$expected[] = array('methodWithOptionalParam' => array("Hello"));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
$this->object->dispatchMethod('methodWithOptionalParam');
$expected[] = array('methodWithOptionalParam' => array(null));
$this->assertSame($this->object->methodCalls, $expected);
$this->assertSame($expected, $this->object->methodCalls);
}
/**
@ -466,7 +455,9 @@ class ObjectTest extends CakeTestCase {
$expected = 'This is a test';
$this->assertEquals($expected, $result);
$result = $this->object->requestAction(FULL_BASE_URL . '/request_action/test_request_action');
$result = $this->object->requestAction(
Configure::read('App.fullBaseUrl') . '/request_action/test_request_action'
);
$expected = 'This is a test';
$this->assertEquals($expected, $result);
@ -492,6 +483,17 @@ class ObjectTest extends CakeTestCase {
$this->assertNull(Router::getRequest(), 'requests were not popped off the stack, this will break url generation');
}
/**
* Test that here() is calculated correctly in requestAction
*
* @return void
*/
public function testRequestActionHere() {
$url = '/request_action/return_here?key=value';
$result = $this->object->requestAction($url);
$this->assertStringEndsWith($url, $result);
}
/**
* test requestAction() and plugins.
*
@ -609,7 +611,7 @@ class ObjectTest extends CakeTestCase {
$this->assertEquals(null, $result['plugin']);
$result = $this->object->requestAction('/request_action/params_pass/sort:desc/limit:5');
$expected = array('sort' => 'desc', 'limit' => 5,);
$expected = array('sort' => 'desc', 'limit' => 5);
$this->assertEquals($expected, $result['named']);
$result = $this->object->requestAction(
@ -687,4 +689,15 @@ class ObjectTest extends CakeTestCase {
);
$this->assertEquals($data, $result);
}
/**
* Test backward compatibility
*
* @return voind
*/
public function testBackwardCompatibility() {
$this->skipIf(version_compare(PHP_VERSION, '7.0.0', '>='));
$this->assertInstanceOf('Object', new ObjectTestModel);
}
}

View file

@ -2,26 +2,24 @@
/**
* CakePluginTest file.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Core
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakePlugin', 'Core');
/**
* CakePluginTest class
*
*/
class CakePluginTest extends CakeTestCase {
@ -179,6 +177,20 @@ class CakePluginTest extends CakeTestCase {
CakePlugin::routes();
}
/**
* Test ignoring missing bootstrap/routes file
*
* @return void
*/
public function testIgnoreMissingFiles() {
CakePlugin::loadAll(array(array(
'bootstrap' => true,
'routes' => true,
'ignoreMissing' => true
)));
CakePlugin::routes();
}
/**
* Tests that CakePlugin::load() throws an exception on unknown plugin
*
@ -197,10 +209,10 @@ class CakePluginTest extends CakeTestCase {
public function testPath() {
CakePlugin::load(array('TestPlugin', 'TestPluginTwo'));
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPlugin' . DS;
$this->assertEquals(CakePlugin::path('TestPlugin'), $expected);
$this->assertEquals($expected, CakePlugin::path('TestPlugin'));
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS . 'TestPluginTwo' . DS;
$this->assertEquals(CakePlugin::path('TestPluginTwo'), $expected);
$this->assertEquals($expected, CakePlugin::path('TestPluginTwo'));
}
/**
@ -240,8 +252,8 @@ class CakePluginTest extends CakeTestCase {
}
/**
* Tests that CakePlugin::loadAll() will load all plugins in the configured folder wit defaults
* and overrides for a plugin
* Tests that CakePlugin::loadAll() will load all plugins in the configured folder with defaults
* and merges in global defaults.
*
* @return void
*/
@ -249,6 +261,24 @@ class CakePluginTest extends CakeTestCase {
CakePlugin::loadAll(array(array('bootstrap' => true), 'TestPlugin' => array('routes' => true)));
CakePlugin::routes();
$expected = array('PluginJs', 'TestPlugin', 'TestPluginTwo');
$this->assertEquals($expected, CakePlugin::loaded());
$this->assertEquals('loaded js plugin bootstrap', Configure::read('CakePluginTest.js_plugin.bootstrap'));
$this->assertEquals('loaded plugin routes', Configure::read('CakePluginTest.test_plugin.routes'));
$this->assertEquals('loaded plugin bootstrap', Configure::read('CakePluginTest.test_plugin.bootstrap'));
$this->assertEquals('loaded plugin two bootstrap', Configure::read('CakePluginTest.test_plugin_two.bootstrap'));
}
/**
* Tests that CakePlugin::loadAll() will load all plugins in the configured folder with defaults
* and overrides for a plugin
*
* @return void
*/
public function testLoadAllWithDefaultsAndOverrideComplex() {
CakePlugin::loadAll(array(array('bootstrap' => true), 'TestPlugin' => array('routes' => true, 'bootstrap' => false)));
CakePlugin::routes();
$expected = array('PluginJs', 'TestPlugin', 'TestPluginTwo');
$this->assertEquals($expected, CakePlugin::loaded());
$this->assertEquals('loaded js plugin bootstrap', Configure::read('CakePluginTest.js_plugin.bootstrap'));

View file

@ -4,20 +4,20 @@
*
* Holds several tests
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Core
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('PhpReader', 'Configure');
/**
@ -67,6 +67,24 @@ class ConfigureTest extends CakeTestCase {
Configure::drop('test');
}
/**
* Test to ensure bootrapping doesn't overwrite prior configs set under 'App' key
*
* @return void
*/
public function testBootstrap() {
$expected = array(
'foo' => 'bar'
);
Configure::write('App', $expected);
Configure::bootstrap(true);
$result = Configure::read('App');
$this->assertEquals($expected['foo'], $result['foo']);
$this->assertFalse($result['base']);
}
/**
* testRead method
*
@ -131,6 +149,39 @@ class ConfigureTest extends CakeTestCase {
$this->assertEquals('4', $result);
}
/**
* Test the consume method.
*
* @return void
*/
public function testConsume() {
$this->assertNull(Configure::consume('DoesNotExist'), 'Should be null on empty value');
Configure::write('Test', array('key' => 'value', 'key2' => 'value2'));
$result = Configure::consume('Test.key');
$this->assertEquals('value', $result);
$result = Configure::read('Test.key2');
$this->assertEquals('value2', $result, 'Other values should remain.');
$result = Configure::consume('Test');
$expected = array('key2' => 'value2');
$this->assertEquals($expected, $result);
}
/**
* testConsumeEmpty
*
* @return void
*/
public function testConsumeEmpty() {
Configure::write('Test', array('key' => 'value', 'key2' => 'value2'));
$result = Configure::consume('');
$this->assertNull($result);
$result = Configure::consume(null);
$this->assertNull($result);
}
/**
* test setting display_errors with debug.
*
@ -158,7 +209,7 @@ class ConfigureTest extends CakeTestCase {
Configure::delete('SomeName.someKey');
$result = Configure::read('SomeName.someKey');
$this->assertTrue($result === null);
$this->assertNull($result);
Configure::write('SomeName', array('someKey' => 'myvalue', 'otherKey' => 'otherValue'));
@ -171,10 +222,65 @@ class ConfigureTest extends CakeTestCase {
Configure::delete('SomeName');
$result = Configure::read('SomeName.someKey');
$this->assertTrue($result === null);
$this->assertNull($result);
$result = Configure::read('SomeName.otherKey');
$this->assertTrue($result === null);
$this->assertNull($result);
}
/**
* testCheck method
*
* @return void
*/
public function testCheck() {
Configure::write('ConfigureTestCase', 'value');
$this->assertTrue(Configure::check('ConfigureTestCase'));
$this->assertFalse(Configure::check('NotExistingConfigureTestCase'));
}
/**
* testCheckingSavedEmpty method
*
* @return void
*/
public function testCheckingSavedEmpty() {
$this->assertTrue(Configure::write('ConfigureTestCase', 0));
$this->assertTrue(Configure::check('ConfigureTestCase'));
$this->assertTrue(Configure::write('ConfigureTestCase', '0'));
$this->assertTrue(Configure::check('ConfigureTestCase'));
$this->assertTrue(Configure::write('ConfigureTestCase', false));
$this->assertTrue(Configure::check('ConfigureTestCase'));
$this->assertTrue(Configure::write('ConfigureTestCase', null));
$this->assertFalse(Configure::check('ConfigureTestCase'));
}
/**
* testCheckKeyWithSpaces method
*
* @return void
*/
public function testCheckKeyWithSpaces() {
$this->assertTrue(Configure::write('Configure Test', "test"));
$this->assertTrue(Configure::check('Configure Test'));
Configure::delete('Configure Test');
$this->assertTrue(Configure::write('Configure Test.Test Case', "test"));
$this->assertTrue(Configure::check('Configure Test.Test Case'));
}
/**
* testCheckEmpty
*
* @return void
*/
public function testCheckEmpty() {
$this->assertFalse(Configure::check(''));
$this->assertFalse(Configure::check(null));
}
/**
@ -185,7 +291,7 @@ class ConfigureTest extends CakeTestCase {
*/
public function testLoadExceptionOnNonExistantFile() {
Configure::config('test', new PhpReader());
$result = Configure::load('non_existing_configuration_file', 'test');
Configure::load('non_existing_configuration_file', 'test');
}
/**
@ -345,10 +451,16 @@ class ConfigureTest extends CakeTestCase {
*
* @expectedException PHPUnit_Framework_Error
* @return void
* @throws PHPUnit_Framework_Error
*/
public function testReaderExceptionOnIncorrectClass() {
$reader = new StdClass();
Configure::config('test', $reader);
try {
Configure::config('test', $reader);
} catch (TypeError $e) {
throw new PHPUnit_Framework_Error('Raised an error', 100, __FILE__, __LINE__);
}
}
/**
@ -364,7 +476,10 @@ class ConfigureTest extends CakeTestCase {
}
/**
* testDumpNoAdapter
*
* @expectedException ConfigureException
* @return void
*/
public function testDumpNoAdapter() {
Configure::dump(TMP . 'test.php', 'does_not_exist');
@ -391,7 +506,7 @@ class ConfigureTest extends CakeTestCase {
/**
* Test dumping only some of the data.
*
* @return
* @return void
*/
public function testDumpPartial() {
Configure::config('test_reader', new PhpReader(TMP));

View file

@ -2,24 +2,41 @@
/**
* ErrorHandlerTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Error
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ErrorHandler', 'Error');
App::uses('Controller', 'Controller');
App::uses('Router', 'Routing');
App::uses('Debugger', 'Utility');
/**
* A faulty ExceptionRenderer to test nesting.
*/
class FaultyExceptionRenderer extends ExceptionRenderer {
/**
* Dummy rendering implementation.
*
* @return void
* @throws Exception
*/
public function render() {
throw new Exception('Error from renderer.');
}
}
/**
* ErrorHandlerTest class
@ -76,6 +93,8 @@ class ErrorHandlerTest extends CakeTestCase {
set_error_handler('ErrorHandler::handleError');
$this->_restoreError = true;
Debugger::getInstance()->output('html');
ob_start();
$wrong .= '';
$result = ob_get_clean();
@ -107,6 +126,8 @@ class ErrorHandlerTest extends CakeTestCase {
set_error_handler('ErrorHandler::handleError');
$this->_restoreError = true;
Debugger::getInstance()->output('html');
ob_start();
trigger_error('Test error', $error);
@ -182,7 +203,7 @@ class ErrorHandlerTest extends CakeTestCase {
$result[0]
);
$this->assertRegExp('/^Trace:/', $result[1]);
$this->assertRegExp('/^ErrorHandlerTest\:\:testHandleErrorLoggingTrace\(\)/', $result[2]);
$this->assertRegExp('/^ErrorHandlerTest\:\:testHandleErrorLoggingTrace\(\)/', $result[3]);
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
@ -194,8 +215,6 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
public function testHandleException() {
$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
$error = new NotFoundException('Kaboom!');
ob_start();
ErrorHandler::handleException($error);
@ -209,8 +228,6 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
public function testHandleExceptionLog() {
$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
@ -223,8 +240,37 @@ class ErrorHandlerTest extends CakeTestCase {
$this->assertRegExp('/Kaboom!/', $result, 'message missing.');
$log = file(LOGS . 'error.log');
$this->assertRegExp('/\[NotFoundException\] Kaboom!/', $log[0], 'message missing.');
$this->assertRegExp('/\#0.*ErrorHandlerTest->testHandleExceptionLog/', $log[1], 'Stack trace missing.');
$this->assertContains('[NotFoundException] Kaboom!', $log[0], 'message missing.');
$this->assertContains('ErrorHandlerTest->testHandleExceptionLog', $log[2], 'Stack trace missing.');
}
/**
* test handleException generating log.
*
* @return void
*/
public function testHandleExceptionLogSkipping() {
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
Configure::write('Exception.log', true);
Configure::write('Exception.skipLog', array('NotFoundException'));
$notFound = new NotFoundException('Kaboom!');
$forbidden = new ForbiddenException('Fooled you!');
ob_start();
ErrorHandler::handleException($notFound);
$result = ob_get_clean();
$this->assertRegExp('/Kaboom!/', $result, 'message missing.');
ob_start();
ErrorHandler::handleException($forbidden);
$result = ob_get_clean();
$this->assertRegExp('/Fooled you!/', $result, 'message missing.');
$log = file(LOGS . 'error.log');
$this->assertNotContains('[NotFoundException] Kaboom!', $log[0], 'message should not be logged.');
$this->assertContains('[ForbiddenException] Fooled you!', $log[0], 'message missing.');
}
/**
@ -251,14 +297,14 @@ class ErrorHandlerTest extends CakeTestCase {
/**
* test handleFatalError generating a page.
*
* These tests start two buffers as handleFatalError blows the outer one up.
*
* @return void
*/
public function testHandleFatalErrorPage() {
$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
$originalDebugLevel = Configure::read('debug');
$line = __LINE__;
ob_start();
ob_start();
Configure::write('debug', 1);
ErrorHandler::handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
@ -267,6 +313,7 @@ class ErrorHandlerTest extends CakeTestCase {
$this->assertContains(__FILE__, $result, 'filename missing.');
$this->assertContains((string)$line, $result, 'line missing.');
ob_start();
ob_start();
Configure::write('debug', 0);
ErrorHandler::handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
@ -274,8 +321,6 @@ class ErrorHandlerTest extends CakeTestCase {
$this->assertNotContains('Something wrong', $result, 'message must not appear.');
$this->assertNotContains(__FILE__, $result, 'filename must not appear.');
$this->assertContains('An Internal Error Has Occurred', $result);
Configure::write('debug', $originalDebugLevel);
}
/**
@ -284,8 +329,6 @@ class ErrorHandlerTest extends CakeTestCase {
* @return void
*/
public function testHandleFatalErrorLog() {
$this->skipIf(file_exists(APP . 'app_error.php'), 'App error exists cannot run.');
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
@ -299,4 +342,48 @@ class ErrorHandlerTest extends CakeTestCase {
$this->assertContains('[FatalErrorException] Something wrong', $log[1], 'message missing.');
}
/**
* testExceptionRendererNestingDebug method
*
* @return void
*/
public function testExceptionRendererNestingDebug() {
Configure::write('debug', 2);
Configure::write('Exception.renderer', 'FaultyExceptionRenderer');
$result = false;
try {
ob_start();
ob_start();
ErrorHandler::handleFatalError(E_USER_ERROR, 'Initial error', __FILE__, __LINE__);
} catch (Exception $e) {
$result = $e instanceof FatalErrorException;
}
restore_error_handler();
$this->assertTrue($result);
}
/**
* testExceptionRendererNestingProduction method
*
* @return void
*/
public function testExceptionRendererNestingProduction() {
Configure::write('debug', 0);
Configure::write('Exception.renderer', 'FaultyExceptionRenderer');
$result = false;
try {
ob_start();
ob_start();
ErrorHandler::handleFatalError(E_USER_ERROR, 'Initial error', __FILE__, __LINE__);
} catch (Exception $e) {
$result = $e instanceof InternalErrorException;
}
restore_error_handler();
$this->assertTrue($result);
}
}

View file

@ -2,25 +2,25 @@
/**
* ExceptionRendererTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Error
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ExceptionRenderer', 'Error');
App::uses('Controller', 'Controller');
App::uses('Component', 'Controller');
App::uses('Router', 'Routing');
App::uses('CakeEventManager', 'Event');
/**
* Short description for class.
@ -29,13 +29,6 @@ App::uses('Router', 'Routing');
*/
class AuthBlueberryUser extends CakeTestModel {
/**
* name property
*
* @var string 'AuthBlueberryUser'
*/
public $name = 'AuthBlueberryUser';
/**
* useTable property
*
@ -137,7 +130,6 @@ class MyCustomExceptionRenderer extends ExceptionRenderer {
class MissingWidgetThingException extends NotFoundException {
}
/**
* ExceptionRendererTest class
*
@ -154,6 +146,7 @@ class ExceptionRendererTest extends CakeTestCase {
*/
public function setUp() {
parent::setUp();
Configure::write('Config.language', 'eng');
App::build(array(
'View' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
@ -278,6 +271,8 @@ class ExceptionRendererTest extends CakeTestCase {
/**
* test that helpers in custom CakeErrorController are not lost
*
* @return void
*/
public function testCakeErrorHelpersNotLost() {
$testApp = CAKE . 'Test' . DS . 'test_app' . DS;
@ -479,6 +474,27 @@ class ExceptionRendererTest extends CakeTestCase {
$this->assertRegExp('/<h2>An Internal Error Has Occurred<\/h2>/', $result);
}
/**
* testExceptionResponseHeader method
*
* @return void
*/
public function testExceptionResponseHeader() {
$exception = new MethodNotAllowedException('Only allowing POST and DELETE');
$exception->responseHeader(array('Allow: POST, DELETE'));
$ExceptionRenderer = new ExceptionRenderer($exception);
//Replace response object with mocked object add back the original headers which had been set in ExceptionRenderer constructor
$headers = $ExceptionRenderer->controller->response->header();
$ExceptionRenderer->controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$ExceptionRenderer->controller->response->header($headers);
$ExceptionRenderer->controller->response->expects($this->at(1))->method('_sendHeader')->with('Allow', 'POST, DELETE');
ob_start();
$ExceptionRenderer->render();
ob_get_clean();
}
/**
* testMissingController method
*
@ -512,7 +528,7 @@ class ExceptionRendererTest extends CakeTestCase {
404
),
array(
new PrivateActionException(array('controller' => 'PostsController' , 'action' => '_secretSauce')),
new PrivateActionException(array('controller' => 'PostsController', 'action' => '_secretSauce')),
array(
'/<h2>Private Method in PostsController<\/h2>/',
'/<em>PostsController::<\/em><em>_secretSauce\(\)<\/em>/'
@ -746,7 +762,74 @@ class ExceptionRendererTest extends CakeTestCase {
$ExceptionRenderer->render();
$this->assertEquals('', $ExceptionRenderer->controller->layoutPath);
$this->assertEquals('', $ExceptionRenderer->controller->subDir);
$this->assertEquals('Errors/', $ExceptionRenderer->controller->viewPath);
$this->assertEquals('Errors', $ExceptionRenderer->controller->viewPath);
}
/**
* Test that missing plugin disables Controller::$plugin if the two are the same plugin.
*
* @return void
*/
public function testMissingPluginRenderSafe() {
$exception = new NotFoundException();
$ExceptionRenderer = new ExceptionRenderer($exception);
$ExceptionRenderer->controller = $this->getMock('Controller', array('render'));
$ExceptionRenderer->controller->plugin = 'TestPlugin';
$ExceptionRenderer->controller->request = $this->getMock('CakeRequest');
$exception = new MissingPluginException(array('plugin' => 'TestPlugin'));
$ExceptionRenderer->controller->expects($this->once())
->method('render')
->with('error400')
->will($this->throwException($exception));
$response = $this->getMock('CakeResponse');
$response->expects($this->once())
->method('body')
->with($this->logicalAnd(
$this->logicalNot($this->stringContains('test plugin error500')),
$this->stringContains('Not Found')
));
$ExceptionRenderer->controller->response = $response;
$ExceptionRenderer->render();
}
/**
* Test that missing plugin doesn't disable Controller::$plugin if the two aren't the same plugin.
*
* @return void
*/
public function testMissingPluginRenderSafeWithPlugin() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
), App::RESET);
CakePlugin::load('TestPlugin');
$exception = new NotFoundException();
$ExceptionRenderer = new ExceptionRenderer($exception);
$ExceptionRenderer->controller = $this->getMock('Controller', array('render'));
$ExceptionRenderer->controller->plugin = 'TestPlugin';
$ExceptionRenderer->controller->request = $this->getMock('CakeRequest');
$exception = new MissingPluginException(array('plugin' => 'TestPluginTwo'));
$ExceptionRenderer->controller->expects($this->once())
->method('render')
->with('error400')
->will($this->throwException($exception));
$response = $this->getMock('CakeResponse');
$response->expects($this->once())
->method('body')
->with($this->logicalAnd(
$this->stringContains('test plugin error500'),
$this->stringContains('Not Found')
));
$ExceptionRenderer->controller->response = $response;
$ExceptionRenderer->render();
CakePlugin::unload();
}
/**
@ -792,7 +875,33 @@ class ExceptionRendererTest extends CakeTestCase {
$this->assertContains('<h2>Database Error</h2>', $result);
$this->assertContains('There was an error in the SQL query', $result);
$this->assertContains('SELECT * from poo_query < 5 and :seven', $result);
$this->assertContains(h('SELECT * from poo_query < 5 and :seven'), $result);
$this->assertContains("'seven' => (int) 7", $result);
}
/**
* Test that rendering exceptions triggers shutdown events.
*
* @return void
*/
public function testRenderShutdownEvents() {
$fired = array();
$listener = function ($event) use (&$fired) {
$fired[] = $event->name();
};
$EventManager = CakeEventManager::instance();
$EventManager->attach($listener, 'Controller.shutdown');
$EventManager->attach($listener, 'Dispatcher.afterDispatch');
$exception = new Exception('Terrible');
$ExceptionRenderer = new ExceptionRenderer($exception);
ob_start();
$ExceptionRenderer->render();
ob_get_clean();
$expected = array('Controller.shutdown', 'Dispatcher.afterDispatch');
$this->assertEquals($expected, $fired);
}
}

View file

@ -1,22 +1,17 @@
<?php
/**
* ControllerTestCaseTest file
*
* Test Case for ControllerTestCase class
*
* PHP version 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Event
* @since CakePHP v 2.1
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeEvent', 'Event');
@ -67,7 +62,7 @@ class CakeEventTestListener {
*
* @package Cake.Test.Case.Event
*/
class CustomTestEventListerner extends CakeEventTestListener implements CakeEventListener {
class CustomTestEventListener extends CakeEventTestListener implements CakeEventListener {
public function implementedEvents() {
return array(
@ -93,7 +88,6 @@ class CustomTestEventListerner extends CakeEventTestListener implements CakeEven
/**
* Tests the CakeEventManager class functionality
*
*/
class CakeEventManagerTest extends CakeTestCase {
@ -103,7 +97,7 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testAttachListeners() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$manager->attach('fakeFunction', 'fake.event');
$expected = array(
array('callable' => 'fakeFunction', 'passParams' => false)
@ -135,7 +129,7 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testAttachMultipleEventKeys() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$manager->attach('fakeFunction', 'fake.event');
$manager->attach('fakeFunction2', 'another.event');
$manager->attach('fakeFunction3', 'another.event', array('priority' => 1, 'passParams' => true));
@ -157,7 +151,7 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDetach() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$manager->attach(array('AClass', 'aMethod'), 'fake.event');
$manager->attach(array('AClass', 'anotherMethod'), 'another.event');
$manager->attach('fakeFunction', 'another.event', array('priority' => 1));
@ -181,7 +175,7 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDetachFromAll() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$manager->attach(array('AClass', 'aMethod'), 'fake.event');
$manager->attach(array('AClass', 'aMethod'), 'another.event');
$manager->attach('fakeFunction', 'another.event', array('priority' => 1));
@ -198,9 +192,10 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests event dispatching
*
* @return void
* @triggers fake.event
*/
public function testDispatch() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
@ -218,8 +213,8 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDispatchWithKeyName() {
$manager = new CakeEventManager;
$listener = new CakeEventTestListener;
$manager = new CakeEventManager();
$listener = new CakeEventTestListener();
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
$event = 'fake.event';
$manager->dispatch($event);
@ -232,13 +227,14 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests event dispatching with a return value
*
* @return void
* @triggers fake.event
*/
public function testDispatchReturnValue() {
$this->skipIf(
version_compare(PHPUnit_Runner_Version::id(), '3.7', '<'),
'These tests fail in PHPUnit 3.6'
);
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
@ -259,6 +255,7 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests that returning false in a callback stops the event
*
* @return void
* @triggers fake.event
*/
public function testDispatchFalseStopsEvent() {
$this->skipIf(
@ -266,7 +263,7 @@ class CakeEventManagerTest extends CakeTestCase {
'These tests fail in PHPUnit 3.6'
);
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
@ -286,10 +283,11 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests event dispatching using priorities
*
* @return void
* @triggers fake.event
*/
public function testDispatchPrioritized() {
$manager = new CakeEventManager;
$listener = new CakeEventTestListener;
$manager = new CakeEventManager();
$listener = new CakeEventTestListener();
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
$manager->attach(array($listener, 'secondListenerFunction'), 'fake.event', array('priority' => 5));
$event = new CakeEvent('fake.event');
@ -303,9 +301,10 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests event dispatching with passed params
*
* @return void
* @triggers fake.event $this, array('some' => 'data')
*/
public function testDispatchPassingParams() {
$manager = new CakeEventManager;
$manager = new CakeEventManager();
$listener = $this->getMock('CakeEventTestListener');
$anotherListener = $this->getMock('CakeEventTestListener');
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
@ -321,10 +320,13 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests subscribing a listener object and firing the events it subscribed to
*
* @return void
* @triggers fake.event
* @triggers another.event $this, array('some' => 'data')
* @triggers multiple.handlers
*/
public function testAttachSubscriber() {
$manager = new CakeEventManager;
$listener = $this->getMock('CustomTestEventListerner', array('secondListenerFunction'));
$manager = new CakeEventManager();
$listener = $this->getMock('CustomTestEventListener', array('secondListenerFunction'));
$manager->attach($listener);
$event = new CakeEvent('fake.event');
@ -337,8 +339,8 @@ class CakeEventManagerTest extends CakeTestCase {
$event = new CakeEvent('another.event', $this, array('some' => 'data'));
$manager->dispatch($event);
$manager = new CakeEventManager;
$listener = $this->getMock('CustomTestEventListerner', array('listenerFunction', 'thirdListenerFunction'));
$manager = new CakeEventManager();
$listener = $this->getMock('CustomTestEventListener', array('listenerFunction', 'thirdListenerFunction'));
$manager->attach($listener);
$event = new CakeEvent('multiple.handlers');
$listener->expects($this->once())->method('listenerFunction')->with($event);
@ -352,8 +354,8 @@ class CakeEventManagerTest extends CakeTestCase {
* @return void
*/
public function testDetachSubscriber() {
$manager = new CakeEventManager;
$listener = $this->getMock('CustomTestEventListerner', array('secondListenerFunction'));
$manager = new CakeEventManager();
$listener = $this->getMock('CustomTestEventListener', array('secondListenerFunction'));
$manager->attach($listener);
$expected = array(
array('callable' => array($listener, 'secondListenerFunction'), 'passParams' => true)
@ -375,7 +377,7 @@ class CakeEventManagerTest extends CakeTestCase {
*/
public function testGlobalDispatcherGetter() {
$this->assertInstanceOf('CakeEventManager', CakeEventManager::instance());
$manager = new CakeEventManager;
$manager = new CakeEventManager();
CakeEventManager::instance($manager);
$this->assertSame($manager, CakeEventManager::instance());
@ -385,25 +387,36 @@ class CakeEventManagerTest extends CakeTestCase {
* Tests that the global event manager gets the event too from any other manager
*
* @return void
* @triggers fake.event
*/
public function testDispatchWithGlobal() {
$generalManager = $this->getMock('CakeEventManager', array('dispatch'));
$manager = new CakeEventManager;
$generalManager = $this->getMock('CakeEventManager', array('prioritisedListeners'));
$manager = new CakeEventManager();
$event = new CakeEvent('fake.event');
CakeEventManager::instance($generalManager);
$generalManager->expects($this->once())->method('dispatch')->with($event);
$generalManager->expects($this->once())->method('prioritisedListeners')->with('fake.event');
$manager->dispatch($event);
CakeEventManager::instance(new CakeEventManager());
}
/**
* Tests that stopping an event will not notify the rest of the listeners
*
* @return void
* @triggers fake.event
*/
public function testStopPropagation() {
$manager = new CakeEventManager;
$listener = new CakeEventTestListener;
$generalManager = $this->getMock('CakeEventManager');
$manager = new CakeEventManager();
$listener = new CakeEventTestListener();
CakeEventManager::instance($generalManager);
$generalManager->expects($this->any())
->method('prioritisedListeners')
->with('fake.event')
->will($this->returnValue(array()));
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
$manager->attach(array($listener, 'stopListener'), 'fake.event', array('priority' => 8));
$manager->attach(array($listener, 'secondListenerFunction'), 'fake.event', array('priority' => 5));
@ -412,5 +425,110 @@ class CakeEventManagerTest extends CakeTestCase {
$expected = array('secondListenerFunction');
$this->assertEquals($expected, $listener->callStack);
CakeEventManager::instance(new CakeEventManager());
}
/**
* Tests event dispatching using priorities
*
* @return void
* @triggers fake.event
*/
public function testDispatchPrioritizedWithGlobal() {
$generalManager = $this->getMock('CakeEventManager');
$manager = new CakeEventManager();
$listener = new CustomTestEventListener();
$event = new CakeEvent('fake.event');
CakeEventManager::instance($generalManager);
$generalManager->expects($this->any())
->method('prioritisedListeners')
->with('fake.event')
->will($this->returnValue(
array(11 => array(
array('callable' => array($listener, 'secondListenerFunction'), 'passParams' => false)
))
));
$manager->attach(array($listener, 'listenerFunction'), 'fake.event');
$manager->attach(array($listener, 'thirdListenerFunction'), 'fake.event', array('priority' => 15));
$manager->dispatch($event);
$expected = array('listenerFunction', 'secondListenerFunction', 'thirdListenerFunction');
$this->assertEquals($expected, $listener->callStack);
CakeEventManager::instance(new CakeEventManager());
}
/**
* Tests event dispatching using priorities
*
* @return void
* @triggers fake.event
*/
public function testDispatchGlobalBeforeLocal() {
$generalManager = $this->getMock('CakeEventManager');
$manager = new CakeEventManager();
$listener = new CustomTestEventListener();
$event = new CakeEvent('fake.event');
CakeEventManager::instance($generalManager);
$generalManager->expects($this->any())
->method('prioritisedListeners')
->with('fake.event')
->will($this->returnValue(
array(10 => array(
array('callable' => array($listener, 'listenerFunction'), 'passParams' => false)
))
));
$manager->attach(array($listener, 'secondListenerFunction'), 'fake.event');
$manager->dispatch($event);
$expected = array('listenerFunction', 'secondListenerFunction');
$this->assertEquals($expected, $listener->callStack);
CakeEventManager::instance(new CakeEventManager());
}
/**
* test callback
*/
public function onMyEvent($event) {
$event->data['callback'] = 'ok';
}
/**
* Tests events dispatched by a local manager can be handled by
* handler registered in the global event manager
* @triggers my_event $manager
*/
public function testDispatchLocalHandledByGlobal() {
$callback = array($this, 'onMyEvent');
CakeEventManager::instance()->attach($callback, 'my_event');
$manager = new CakeEventManager();
$event = new CakeEvent('my_event', $manager);
$manager->dispatch($event);
$this->assertEquals('ok', $event->data['callback']);
}
/**
* Test that events are dispatched properly when there are global and local
* listeners at the same priority.
*
* @return void
* @triggers fake.event $this
*/
public function testDispatchWithGlobalAndLocalEvents() {
$listener = new CustomTestEventListener();
CakeEventManager::instance()->attach($listener);
$listener2 = new CakeEventTestListener();
$manager = new CakeEventManager();
$manager->attach(array($listener2, 'listenerFunction'), 'fake.event');
$manager->dispatch(new CakeEvent('fake.event', $this));
$this->assertEquals(array('listenerFunction'), $listener->callStack);
$this->assertEquals(array('listenerFunction'), $listener2->callStack);
}
}

View file

@ -4,26 +4,24 @@
*
* Test Case for ControllerTestCase class
*
* PHP version 5
*
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc.
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.Event
* @since CakePHP v 2.1
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeEvent', 'Event');
/**
* Tests the CakeEvent class functionality
*
*/
class CakeEventTest extends CakeTestCase {
@ -31,6 +29,7 @@ class CakeEventTest extends CakeTestCase {
* Tests the name() method
*
* @return void
* @triggers fake.event
*/
public function testName() {
$event = new CakeEvent('fake.event');
@ -41,6 +40,8 @@ class CakeEventTest extends CakeTestCase {
* Tests the subject() method
*
* @return void
* @triggers fake.event $this
* @triggers fake.event
*/
public function testSubject() {
$event = new CakeEvent('fake.event', $this);
@ -54,6 +55,7 @@ class CakeEventTest extends CakeTestCase {
* Tests the event propagation stopping property
*
* @return void
* @triggers fake.event
*/
public function testPropagation() {
$event = new CakeEvent('fake.event');
@ -66,6 +68,7 @@ class CakeEventTest extends CakeTestCase {
* Tests that it is possible to get/set custom data in a event
*
* @return void
* @triggers fake.event $this, array('some' => 'data')
*/
public function testEventData() {
$event = new CakeEvent('fake.event', $this, array('some' => 'data'));
@ -76,10 +79,11 @@ class CakeEventTest extends CakeTestCase {
* Tests that it is possible to get the name and subject directly
*
* @return void
* @triggers fake.event $this
*/
public function testEventDirectPropertyAccess() {
$event = new CakeEvent('fake.event', $this);
$this->assertEquals($this, $event->subject);
$this->assertEquals('fake.event', $event->name);
}
}
}

View file

@ -2,21 +2,22 @@
/**
* I18nTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.I18n
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('I18n', 'I18n');
App::uses('CakeSession', 'Model/Datasource');
/**
* I18nTest class
@ -74,15 +75,15 @@ class I18nTest extends CakeTestCase {
$this->assertEquals('Dom 1 Foo', I18n::translate('dom1.foo', false, 'dom1'));
$this->assertEquals('Dom 1 Bar', I18n::translate('dom1.bar', false, 'dom1'));
$domains = I18n::domains();
$this->assertEquals('Dom 1 Foo', $domains['dom1']['cache_test_po']['LC_MESSAGES']['dom1.foo']);
$this->assertEquals('Dom 1 Foo', $domains['dom1']['cache_test_po']['LC_MESSAGES']['dom1.foo']['']);
// reset internally stored entries
I18n::clear();
// now only dom1 should be in cache
$cachedDom1 = Cache::read('dom1_' . $lang, '_cake_core_');
$this->assertEquals('Dom 1 Foo', $cachedDom1['LC_MESSAGES']['dom1.foo']);
$this->assertEquals('Dom 1 Bar', $cachedDom1['LC_MESSAGES']['dom1.bar']);
$this->assertEquals('Dom 1 Foo', $cachedDom1['LC_MESSAGES']['dom1.foo']['']);
$this->assertEquals('Dom 1 Bar', $cachedDom1['LC_MESSAGES']['dom1.bar']['']);
// dom2 not in cache
$this->assertFalse(Cache::read('dom2_' . $lang, '_cake_core_'));
@ -91,11 +92,11 @@ class I18nTest extends CakeTestCase {
// verify dom2 was cached through manual read from cache
$cachedDom2 = Cache::read('dom2_' . $lang, '_cake_core_');
$this->assertEquals('Dom 2 Foo', $cachedDom2['LC_MESSAGES']['dom2.foo']);
$this->assertEquals('Dom 2 Bar', $cachedDom2['LC_MESSAGES']['dom2.bar']);
$this->assertEquals('Dom 2 Foo', $cachedDom2['LC_MESSAGES']['dom2.foo']['']);
$this->assertEquals('Dom 2 Bar', $cachedDom2['LC_MESSAGES']['dom2.bar']['']);
// modify cache entry manually to verify that dom1 entries now will be read from cache
$cachedDom1['LC_MESSAGES']['dom1.foo'] = 'FOO';
$cachedDom1['LC_MESSAGES']['dom1.foo'][''] = 'FOO';
Cache::write('dom1_' . $lang, $cachedDom1, '_cake_core_');
$this->assertEquals('FOO', I18n::translate('dom1.foo', false, 'dom1'));
}
@ -106,10 +107,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function testDefaultStrings() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 1', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 = 0 or > 1', $plurals));
$this->assertTrue(in_array('1 = 1', $plurals));
$this->assertTrue(in_array('2 = 0 or > 1', $plurals));
@ -137,10 +138,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 = 0 or > 1', $plurals));
$this->assertTrue(in_array('25 = 0 or > 1', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 1 (from core)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 = 0 or > 1 (from core)', $corePlurals));
$this->assertTrue(in_array('1 = 1 (from core)', $corePlurals));
$this->assertTrue(in_array('2 = 0 or > 1 (from core)', $corePlurals));
@ -192,13 +193,13 @@ class I18nTest extends CakeTestCase {
/**
* Assertions for rules zero.
*
* @return
* @return void
*/
public function assertRulesZero() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 0 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 ends with any # (translated)', $plurals));
$this->assertTrue(in_array('1 ends with any # (translated)', $plurals));
$this->assertTrue(in_array('2 ends with any # (translated)', $plurals));
@ -226,10 +227,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 ends with any # (translated)', $plurals));
$this->assertTrue(in_array('25 ends with any # (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 0 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 ends with any # (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends with any # (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 ends with any # (from core translated)', $corePlurals));
@ -284,10 +285,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesOne() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 1 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 = 0 or > 1 (translated)', $plurals));
$this->assertTrue(in_array('1 = 1 (translated)', $plurals));
$this->assertTrue(in_array('2 = 0 or > 1 (translated)', $plurals));
@ -315,10 +316,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 = 0 or > 1 (translated)', $plurals));
$this->assertTrue(in_array('25 = 0 or > 1 (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 1 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 = 0 or > 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 = 0 or > 1 (from core translated)', $corePlurals));
@ -373,10 +374,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesTwo() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 2 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 = 0 or 1 (translated)', $plurals));
$this->assertTrue(in_array('1 = 0 or 1 (translated)', $plurals));
$this->assertTrue(in_array('2 > 1 (translated)', $plurals));
@ -404,10 +405,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 > 1 (translated)', $plurals));
$this->assertTrue(in_array('25 > 1 (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 2 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 = 0 or 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 = 0 or 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 > 1 (from core translated)', $corePlurals));
@ -462,10 +463,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesThree() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 3 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 = 0 (translated)', $plurals));
$this->assertTrue(in_array('1 ends 1 but not 11 (translated)', $plurals));
$this->assertTrue(in_array('2 everything else (translated)', $plurals));
@ -493,10 +494,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 3 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 = 0 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends 1 but not 11 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 everything else (from core translated)', $corePlurals));
@ -551,10 +552,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesFour() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 4 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 = 1 (translated)', $plurals));
$this->assertTrue(in_array('2 = 2 (translated)', $plurals));
@ -582,10 +583,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 4 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 = 2 (from core translated)', $corePlurals));
@ -640,10 +641,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesFive() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 5 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 = 0 or ends in 01-19 (translated)', $plurals));
$this->assertTrue(in_array('0 = 0 or ends in 01-19 (translated)', $plurals));
$this->assertTrue(in_array('1 = 1 (translated)', $plurals));
@ -672,10 +673,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 5 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 = 0 or ends in 01-19 (from core translated)', $corePlurals));
$this->assertTrue(in_array('0 = 0 or ends in 01-19 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 = 1 (from core translated)', $corePlurals));
@ -731,10 +732,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesSix() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 6 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 ends in 0 or ends in 10-20 (translated)', $plurals));
$this->assertTrue(in_array('1 ends in 1, not 11 (translated)', $plurals));
$this->assertTrue(in_array('2 everything else (translated)', $plurals));
@ -762,10 +763,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 6 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 ends in 0 or ends in 10-20 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends in 1, not 11 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 everything else (from core translated)', $corePlurals));
@ -820,10 +821,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesSeven() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 7 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 ends in 1, not 11 (translated)', $plurals));
$this->assertTrue(in_array('2 ends in 2-4, not 12-14 (translated)', $plurals));
@ -851,10 +852,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 ends in 2-4, not 12-14 (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 7 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends in 1, not 11 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 ends in 2-4, not 12-14 (from core translated)', $corePlurals));
@ -909,10 +910,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesEight() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 8 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
$this->assertTrue(in_array('2 is 2-4 (translated)', $plurals));
@ -940,10 +941,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 8 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 is 2-4 (from core translated)', $corePlurals));
@ -998,10 +999,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesNine() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 9 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
@ -1030,10 +1031,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 ends in 2-4, not 12-14 (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 9 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
@ -1090,10 +1091,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesTen() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 10 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 ends in 1 (translated)', $plurals));
@ -1122,10 +1123,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 10 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends in 1 (from core translated)', $corePlurals));
@ -1181,10 +1182,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesEleven() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 11 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
$this->assertTrue(in_array('2 is 2 (translated)', $plurals));
@ -1212,10 +1213,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 11 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 is 2 (from core translated)', $corePlurals));
@ -1270,10 +1271,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesTwelve() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 12 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 is 0 or 3-10 (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
$this->assertTrue(in_array('2 is 2 (translated)', $plurals));
@ -1301,10 +1302,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 12 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 is 0 or 3-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 is 2 (from core translated)', $corePlurals));
@ -1359,10 +1360,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesThirteen() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 13 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 is 0 or ends in 01-10 (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
$this->assertTrue(in_array('2 is 0 or ends in 01-10 (translated)', $plurals));
@ -1390,10 +1391,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 13 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 is 0 or ends in 01-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 is 0 or ends in 01-10 (from core translated)', $corePlurals));
@ -1448,10 +1449,10 @@ class I18nTest extends CakeTestCase {
* @return void
*/
public function assertRulesFourteen() {
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Plural Rule 14 (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (translated)', $plurals));
$this->assertTrue(in_array('1 ends in 1 (translated)', $plurals));
$this->assertTrue(in_array('2 ends in 2 (translated)', $plurals));
@ -1479,10 +1480,10 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('24 everything else (translated)', $plurals));
$this->assertTrue(in_array('25 everything else (translated)', $plurals));
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 14 (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertTrue(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 ends in 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 ends in 2 (from core translated)', $corePlurals));
@ -1511,17 +1512,138 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('25 everything else (from core translated)', $corePlurals));
}
/**
* testMoRulesFifteen method
*
* @return void
*/
public function testMoRulesFifteen() {
Configure::write('Config.language', 'rule_15_mo');
$this->assertRulesFifteen();
}
/**
* testPoRulesFifteen method
*
* @return void
*/
public function testPoRulesFifteen() {
Configure::write('Config.language', 'rule_15_po');
$this->assertRulesFifteen();
}
/**
* Assertions for plural rules fifteen
*
* @return void
*/
public function assertRulesFifteen() {
$singular = $this->_singular();
$this->assertEquals('Plural Rule 15 (translated)', $singular);
$plurals = $this->_plural(111);
$this->assertTrue(in_array('0 is 0 (translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (translated)', $plurals));
$this->assertTrue(in_array('2 is 2 (translated)', $plurals));
$this->assertTrue(in_array('3 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('4 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('5 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('6 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('7 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('8 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('9 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('10 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('11 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('12 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('13 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('14 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('15 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('16 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('17 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('18 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('19 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('20 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('31 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('42 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('53 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('64 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('75 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('86 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('97 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('98 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('99 ends with 11-99 (translated)', $plurals));
$this->assertTrue(in_array('100 everything else (translated)', $plurals));
$this->assertTrue(in_array('101 everything else (translated)', $plurals));
$this->assertTrue(in_array('102 everything else (translated)', $plurals));
$this->assertTrue(in_array('103 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('104 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('105 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('106 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('107 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('108 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('109 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('110 ends with 03-10 (translated)', $plurals));
$this->assertTrue(in_array('111 ends with 11-99 (translated)', $plurals));
$coreSingular = $this->_singularFromCore();
$this->assertEquals('Plural Rule 15 (from core translated)', $coreSingular);
$corePlurals = $this->_pluralFromCore(111);
$this->assertTrue(in_array('0 is 0 (from core translated)', $corePlurals));
$this->assertTrue(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertTrue(in_array('2 is 2 (from core translated)', $corePlurals));
$this->assertTrue(in_array('3 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('4 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('5 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('6 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('7 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('8 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('9 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('10 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('11 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('12 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('13 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('14 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('15 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('16 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('17 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('18 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('19 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('20 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('31 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('42 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('53 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('64 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('75 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('86 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('97 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('98 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('99 ends with 11-99 (from core translated)', $corePlurals));
$this->assertTrue(in_array('100 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('101 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('102 everything else (from core translated)', $corePlurals));
$this->assertTrue(in_array('103 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('104 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('105 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('106 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('107 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('108 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('109 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('110 ends with 03-10 (from core translated)', $corePlurals));
$this->assertTrue(in_array('111 ends with 11-99 (from core translated)', $corePlurals));
}
/**
* testSetLanguageWithSession method
*
* @return void
*/
public function testSetLanguageWithSession() {
$_SESSION['Config']['language'] = 'po';
$singular = $this->__singular();
CakeSession::write('Config.language', 'po');
$singular = $this->_singular();
$this->assertEquals('Po (translated)', $singular);
$plurals = $this->__plural();
$plurals = $this->_plural();
$this->assertTrue(in_array('0 everything else (po translated)', $plurals));
$this->assertTrue(in_array('1 is 1 (po translated)', $plurals));
$this->assertTrue(in_array('2 is 2-4 (po translated)', $plurals));
@ -1548,7 +1670,7 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('23 everything else (po translated)', $plurals));
$this->assertTrue(in_array('24 everything else (po translated)', $plurals));
$this->assertTrue(in_array('25 everything else (po translated)', $plurals));
unset($_SESSION['Config']['language']);
CakeSession::delete('Config.language');
}
/**
@ -1558,13 +1680,13 @@ class I18nTest extends CakeTestCase {
*/
public function testNoCoreTranslation() {
Configure::write('Config.language', 'po');
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Po (translated)', $singular);
$coreSingular = $this->__singularFromCore();
$coreSingular = $this->_singularFromCore();
$this->assertNotEquals('Po (from core translated)', $coreSingular);
$corePlurals = $this->__pluralFromCore();
$corePlurals = $this->_pluralFromCore();
$this->assertFalse(in_array('0 everything else (from core translated)', $corePlurals));
$this->assertFalse(in_array('1 is 1 (from core translated)', $corePlurals));
$this->assertFalse(in_array('2 is 2-4 (from core translated)', $corePlurals));
@ -1604,10 +1726,10 @@ class I18nTest extends CakeTestCase {
));
Configure::write('Config.language', 'po');
$singular = $this->__domainSingular();
$singular = $this->_domainSingular();
$this->assertEquals('Plural Rule 1 (from plugin)', $singular);
$plurals = $this->__domainPlural();
$plurals = $this->_domainPlural();
$this->assertTrue(in_array('0 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('1 = 1 (from plugin)', $plurals));
$this->assertTrue(in_array('2 = 0 or > 1 (from plugin)', $plurals));
@ -1636,6 +1758,30 @@ class I18nTest extends CakeTestCase {
$this->assertTrue(in_array('25 = 0 or > 1 (from plugin)', $plurals));
}
/**
* Test that Configure::read('I18n.preferApp') will prefer app.
*
* @return void
*/
public function testPluginTranslationPreferApp() {
// Reset internally stored entries
I18n::clear();
Cache::clear(false, '_cake_core_');
Configure::write('I18n.preferApp', true);
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
Configure::write('Config.language', 'po');
$singular = $this->_domainSingular();
$this->assertEquals('Plural Rule 1', $singular);
$plurals = $this->_domainPlural();
$this->assertTrue(in_array('0 = 0 or > 1', $plurals));
}
/**
* testPoMultipleLineTranslation method
*
@ -1759,7 +1905,11 @@ class I18nTest extends CakeTestCase {
*/
public function testCategory() {
Configure::write('Config.language', 'po');
$category = $this->__category();
// Test with default (I18n constant) category.
$category = $this->_category();
$this->assertEquals('Monetary Po (translated)', $category);
// Test with category number represenation.
$category = $this->_category(3);
$this->assertEquals('Monetary Po (translated)', $category);
}
@ -1771,10 +1921,10 @@ class I18nTest extends CakeTestCase {
public function testPluginCategory() {
Configure::write('Config.language', 'po');
$singular = $this->__domainCategorySingular();
$singular = $this->_domainCategorySingular();
$this->assertEquals('Monetary Plural Rule 1 (from plugin)', $singular);
$plurals = $this->__domainCategoryPlural();
$plurals = $this->_domainCategoryPlural();
$this->assertTrue(in_array('Monetary 0 = 0 or > 1 (from plugin)', $plurals));
$this->assertTrue(in_array('Monetary 1 = 1 (from plugin)', $plurals));
}
@ -1786,10 +1936,10 @@ class I18nTest extends CakeTestCase {
*/
public function testCategoryThenSingular() {
Configure::write('Config.language', 'po');
$category = $this->__category();
$category = $this->_category();
$this->assertEquals('Monetary Po (translated)', $category);
$singular = $this->__singular();
$singular = $this->_singular();
$this->assertEquals('Po (translated)', $singular);
}
@ -1843,21 +1993,78 @@ class I18nTest extends CakeTestCase {
public function testTranslateLanguageParam() {
Configure::write('Config.language', 'rule_0_po');
$result = I18n::translate('Plural Rule 1', null, null, 6);
$result = I18n::translate('Plural Rule 1', null, null, I18n::LC_MESSAGES);
$expected = 'Plural Rule 0 (translated)';
$this->assertEquals($expected, $result);
$result = I18n::translate('Plural Rule 1', null, null, 6, null, 'rule_1_po');
$result = I18n::translate('Plural Rule 1', null, null, I18n::LC_MESSAGES, null, 'rule_1_po');
$expected = 'Plural Rule 1 (translated)';
$this->assertEquals($expected, $result);
}
/**
* Test that the '' domain causes exceptions.
*
* @expectedException CakeException
* @return void
*/
public function testTranslateEmptyDomain() {
I18n::translate('Plural Rule 1', null, '');
}
/**
* testLoadLocaleDefinition method
*
* @return void
*/
public function testLoadLocaleDefinition() {
$path = current(App::path('locales'));
$result = I18n::loadLocaleDefinition($path . 'nld' . DS . 'LC_TIME');
$expected = array('zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag');
$this->assertSame($expected, $result['day']);
}
/**
* Test basic context support
*
* @return void
*/
public function testContext() {
Configure::write('Config.language', 'nld');
$this->assertSame("brief", __x('mail', 'letter'));
$this->assertSame("letter", __x('character', 'letter'));
$this->assertSame("bal", __x('spherical object', 'ball'));
$this->assertSame("danspartij", __x('social gathering', 'ball'));
$this->assertSame("balans", __('balance'));
$this->assertSame("saldo", __x('money', 'balance'));
}
/**
* Test basic context support using mo files.
*
* @return void
*/
public function testContextMoFile() {
Configure::write('Config.language', 'nld_mo');
$this->assertSame("brief", __x('mail', 'letter'));
$this->assertSame("letter", __x('character', 'letter'));
$this->assertSame("bal", __x('spherical object', 'ball'));
$this->assertSame("danspartij", __x('social gathering', 'ball'));
$this->assertSame("balans", __('balance'));
$this->assertSame("saldo", __x('money', 'balance'));
// MO file is sorted by msgid, 'zoo' should be last
$this->assertSame("dierentuin", __('zoo'));
}
/**
* Singular method
*
* @return void
*/
private function __domainCategorySingular($domain = 'test_plugin', $category = 3) {
protected function _domainCategorySingular($domain = 'test_plugin', $category = 3) {
$singular = __dc($domain, 'Plural Rule 1', $category);
return $singular;
}
@ -1867,7 +2074,7 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __domainCategoryPlural($domain = 'test_plugin', $category = 3) {
protected function _domainCategoryPlural($domain = 'test_plugin', $category = 3) {
$plurals = array();
for ($number = 0; $number <= 25; $number++) {
$plurals[] = sprintf(__dcn($domain, '%d = 1', '%d = 0 or > 1', (float)$number, $category), (float)$number);
@ -1880,7 +2087,7 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __domainSingular($domain = 'test_plugin') {
protected function _domainSingular($domain = 'test_plugin') {
$singular = __d($domain, 'Plural Rule 1');
return $singular;
}
@ -1890,10 +2097,10 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __domainPlural($domain = 'test_plugin') {
protected function _domainPlural($domain = 'test_plugin') {
$plurals = array();
for ($number = 0; $number <= 25; $number++) {
$plurals[] = sprintf(__dn($domain, '%d = 1', '%d = 0 or > 1', (float)$number), (float)$number );
$plurals[] = sprintf(__dn($domain, '%d = 1', '%d = 0 or > 1', (float)$number), (float)$number);
}
return $plurals;
}
@ -1903,7 +2110,7 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __category($category = 3) {
protected function _category($category = I18n::LC_MONETARY) {
$singular = __c('Plural Rule 1', $category);
return $singular;
}
@ -1913,7 +2120,7 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __singular() {
protected function _singular() {
$singular = __('Plural Rule 1');
return $singular;
}
@ -1921,11 +2128,12 @@ class I18nTest extends CakeTestCase {
/**
* Plural method
*
* @param int $upTo For numbers upto (default to 25)
* @return void
*/
private function __plural() {
protected function _plural($upTo = 25) {
$plurals = array();
for ($number = 0; $number <= 25; $number++) {
for ($number = 0; $number <= $upTo; $number++) {
$plurals[] = sprintf(__n('%d = 1', '%d = 0 or > 1', (float)$number), (float)$number);
}
return $plurals;
@ -1936,7 +2144,7 @@ class I18nTest extends CakeTestCase {
*
* @return void
*/
private function __singularFromCore() {
protected function _singularFromCore() {
$singular = __('Plural Rule 1 (from core)');
return $singular;
}
@ -1944,12 +2152,13 @@ class I18nTest extends CakeTestCase {
/**
* pluralFromCore method
*
* @param int $upTo For numbers upto (default to 25)
* @return void
*/
private function __pluralFromCore() {
protected function _pluralFromCore($upTo = 25) {
$plurals = array();
for ($number = 0; $number <= 25; $number++) {
$plurals[] = sprintf(__n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', (float)$number), (float)$number );
for ($number = 0; $number <= $upTo; $number++) {
$plurals[] = sprintf(__n('%d = 1 (from core)', '%d = 0 or > 1 (from core)', (float)$number), (float)$number);
}
return $plurals;
}

View file

@ -2,20 +2,20 @@
/**
* L10nTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.I18n
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('L10n', 'I18n');
/**
@ -25,6 +25,16 @@ App::uses('L10n', 'I18n');
*/
class L10nTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::delete('Config.language');
}
/**
* testGet method
*
@ -38,14 +48,14 @@ class L10nTest extends CakeTestCase {
$this->assertEquals('en', $lang);
$this->assertEquals('English', $localize->language);
$this->assertEquals(array('eng', 'eng'), $localize->languagePath);
$this->assertEquals(array('eng'), $localize->languagePath);
$this->assertEquals('eng', $localize->locale);
// Map Entry
$localize->get('eng');
$this->assertEquals('English', $localize->language);
$this->assertEquals(array('eng', 'eng'), $localize->languagePath);
$this->assertEquals(array('eng'), $localize->languagePath);
$this->assertEquals('eng', $localize->locale);
// Catalog Entry
@ -56,8 +66,7 @@ class L10nTest extends CakeTestCase {
$this->assertEquals('en_ca', $localize->locale);
// Default Entry
define('DEFAULT_LANGUAGE', 'en-us');
$localize->default = 'en-us';
$lang = $localize->get('use_default');
$this->assertEquals('en-us', $lang);
@ -68,14 +77,6 @@ class L10nTest extends CakeTestCase {
$localize->get('es');
$localize->get('');
$this->assertEquals('en-us', $localize->lang);
// Using $this->default
$localize = new L10n();
$localize->get('use_default');
$this->assertEquals('English (United States)', $localize->language);
$this->assertEquals(array('en_us', 'eng', 'eng'), $localize->languagePath);
$this->assertEquals('en_us', $localize->locale);
}
/**
@ -92,7 +93,7 @@ class L10nTest extends CakeTestCase {
$this->assertEquals('en-ca', $lang);
$this->assertEquals('English (Canadian)', $localize->language);
$this->assertEquals(array('en_ca', 'eng', 'eng'), $localize->languagePath);
$this->assertEquals(array('en_ca', 'eng'), $localize->languagePath);
$this->assertEquals('en_ca', $localize->locale);
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'es_mx';
@ -100,19 +101,52 @@ class L10nTest extends CakeTestCase {
$this->assertEquals('es-mx', $lang);
$this->assertEquals('Spanish (Mexican)', $localize->language);
$this->assertEquals(array('es_mx', 'spa', 'eng'), $localize->languagePath);
$this->assertEquals(array('es_mx', 'spa'), $localize->languagePath);
$this->assertEquals('es_mx', $localize->locale);
$localize = new L10n();
$localize->default = 'en-us';
$lang = $localize->get();
$this->assertEquals(array('es_mx', 'spa', 'eng'), $localize->languagePath);
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'en_xy,en_ca';
$localize->get();
$this->assertEquals('English', $localize->language);
$this->assertEquals(array('eng', 'eng', 'eng'), $localize->languagePath);
$this->assertEquals(array('eng'), $localize->languagePath);
$this->assertEquals('eng', $localize->locale);
$_SERVER = $serverBackup;
}
/**
* testGet method with deprecated constant DEFAULT_LANGUAGE
*
* @return void
*/
public function testGetWithDeprecatedConstant() {
$this->skipIf(defined('DEFAULT_LANGUAGE'), 'Cannot re-define already defined constant.');
define('DEFAULT_LANGUAGE', 'en-us');
$localize = new L10n();
$lang = $localize->get('use_default');
$this->assertEquals('en-us', $lang);
$this->assertEquals('English (United States)', $localize->language);
$this->assertEquals(array('en_us', 'eng'), $localize->languagePath);
$this->assertEquals('en_us', $localize->locale);
$localize = new L10n();
$lang = $localize->get();
$this->assertEquals('en-us', $lang);
$this->assertEquals('English (United States)', $localize->language);
$this->assertEquals(array('en_us', 'eng'), $localize->languagePath);
$this->assertEquals('en_us', $localize->locale);
}
/**
* testMap method
*
@ -125,8 +159,12 @@ class L10nTest extends CakeTestCase {
$expected = array('afr' => 'af', 'af' => 'afr');
$this->assertEquals($expected, $result);
$result = $localize->map(array('sqi', 'sq'));
$expected = array('sqi' => 'sq', 'sq' => 'sqi');
$this->assertEquals($expected, $result);
$result = $localize->map(array('alb', 'sq'));
$expected = array('alb' => 'sq', 'sq' => 'alb');
$expected = array('alb' => 'sq', 'sq' => 'sqi');
$this->assertEquals($expected, $result);
$result = $localize->map(array('ara', 'ar'));
@ -137,12 +175,12 @@ class L10nTest extends CakeTestCase {
$expected = array('hye' => 'hy', 'hy' => 'hye');
$this->assertEquals($expected, $result);
$result = $localize->map(array('baq', 'eu'));
$expected = array('baq' => 'eu', 'eu' => 'baq');
$result = $localize->map(array('eus', 'eu'));
$expected = array('eus' => 'eu', 'eu' => 'eus');
$this->assertEquals($expected, $result);
$result = $localize->map(array('baq', 'eu'));
$expected = array('baq' => 'eu', 'eu' => 'baq');
$expected = array('baq' => 'eu', 'eu' => 'eus');
$this->assertEquals($expected, $result);
$result = $localize->map(array('bos', 'bs'));
@ -162,11 +200,11 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('chi', 'zh'));
$expected = array('chi' => 'zh', 'zh' => 'chi');
$expected = array('chi' => 'zh', 'zh' => 'zho');
$this->assertEquals($expected, $result);
$result = $localize->map(array('zho', 'zh'));
$expected = array('zho' => 'zh', 'zh' => 'chi');
$expected = array('zho' => 'zh', 'zh' => 'zho');
$this->assertEquals($expected, $result);
$result = $localize->map(array('hrv', 'hr'));
@ -174,11 +212,11 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('ces', 'cs'));
$expected = array('ces' => 'cs', 'cs' => 'cze');
$expected = array('ces' => 'cs', 'cs' => 'ces');
$this->assertEquals($expected, $result);
$result = $localize->map(array('cze', 'cs'));
$expected = array('cze' => 'cs', 'cs' => 'cze');
$expected = array('cze' => 'cs', 'cs' => 'ces');
$this->assertEquals($expected, $result);
$result = $localize->map(array('dan', 'da'));
@ -186,17 +224,21 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('dut', 'nl'));
$expected = array('dut' => 'nl', 'nl' => 'dut');
$expected = array('dut' => 'nl', 'nl' => 'nld');
$this->assertEquals($expected, $result);
$result = $localize->map(array('nld', 'nl'));
$expected = array('nld' => 'nl', 'nl' => 'dut');
$expected = array('nld' => 'nl', 'nl' => 'nld');
$this->assertEquals($expected, $result);
$result = $localize->map(array('nld'));
$expected = array('nld' => 'nl');
$this->assertEquals($expected, $result);
$result = $localize->map(array('dut'));
$expected = array('dut' => 'nl');
$this->assertEquals($expected, $result);
$result = $localize->map(array('eng', 'en'));
$expected = array('eng' => 'en', 'en' => 'eng');
$this->assertEquals($expected, $result);
@ -222,11 +264,11 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('fra', 'fr'));
$expected = array('fra' => 'fr', 'fr' => 'fre');
$expected = array('fra' => 'fr', 'fr' => 'fra');
$this->assertEquals($expected, $result);
$result = $localize->map(array('fre', 'fr'));
$expected = array('fre' => 'fr', 'fr' => 'fre');
$expected = array('fre' => 'fr', 'fr' => 'fra');
$this->assertEquals($expected, $result);
$result = $localize->map(array('gla', 'gd'));
@ -266,11 +308,11 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('ice', 'is'));
$expected = array('ice' => 'is', 'is' => 'ice');
$expected = array('ice' => 'is', 'is' => 'isl');
$this->assertEquals($expected, $result);
$result = $localize->map(array('isl', 'is'));
$expected = array('isl' => 'is', 'is' => 'ice');
$expected = array('isl' => 'is', 'is' => 'isl');
$this->assertEquals($expected, $result);
$result = $localize->map(array('ind', 'id'));
@ -289,6 +331,10 @@ class L10nTest extends CakeTestCase {
$expected = array('jpn' => 'ja', 'ja' => 'jpn');
$this->assertEquals($expected, $result);
$result = $localize->map(array('kaz', 'kk'));
$expected = array('kaz' => 'kk', 'kk' => 'kaz');
$this->assertEquals($expected, $result);
$result = $localize->map(array('kor', 'ko'));
$expected = array('kor' => 'ko', 'ko' => 'kor');
$this->assertEquals($expected, $result);
@ -302,19 +348,19 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('mac', 'mk'));
$expected = array('mac' => 'mk', 'mk' => 'mac');
$expected = array('mac' => 'mk', 'mk' => 'mkd');
$this->assertEquals($expected, $result);
$result = $localize->map(array('mkd', 'mk'));
$expected = array('mkd' => 'mk', 'mk' => 'mac');
$expected = array('mkd' => 'mk', 'mk' => 'mkd');
$this->assertEquals($expected, $result);
$result = $localize->map(array('may', 'ms'));
$expected = array('may' => 'ms', 'ms' => 'may');
$expected = array('may' => 'ms', 'ms' => 'msa');
$this->assertEquals($expected, $result);
$result = $localize->map(array('msa', 'ms'));
$expected = array('msa' => 'ms', 'ms' => 'may');
$expected = array('msa' => 'ms', 'ms' => 'msa');
$this->assertEquals($expected, $result);
$result = $localize->map(array('mlt', 'mt'));
@ -346,35 +392,31 @@ class L10nTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $localize->map(array('ron', 'ro'));
$expected = array('ron' => 'ro', 'ro' => 'rum');
$expected = array('ron' => 'ro', 'ro' => 'ron');
$this->assertEquals($expected, $result);
$result = $localize->map(array('rum', 'ro'));
$expected = array('rum' => 'ro', 'ro' => 'rum');
$expected = array('rum' => 'ro', 'ro' => 'ron');
$this->assertEquals($expected, $result);
$result = $localize->map(array('rus', 'ru'));
$expected = array('rus' => 'ru', 'ru' => 'rus');
$this->assertEquals($expected, $result);
$result = $localize->map(array('smi', 'sz'));
$expected = array('smi' => 'sz', 'sz' => 'smi');
$this->assertEquals($expected, $result);
$result = $localize->map(array('scc', 'sr'));
$expected = array('scc' => 'sr', 'sr' => 'scc');
$result = $localize->map(array('sme', 'se'));
$expected = array('sme' => 'se', 'se' => 'sme');
$this->assertEquals($expected, $result);
$result = $localize->map(array('srp', 'sr'));
$expected = array('srp' => 'sr', 'sr' => 'scc');
$expected = array('srp' => 'sr', 'sr' => 'srp');
$this->assertEquals($expected, $result);
$result = $localize->map(array('slk', 'sk'));
$expected = array('slk' => 'sk', 'sk' => 'slo');
$expected = array('slk' => 'sk', 'sk' => 'slk');
$this->assertEquals($expected, $result);
$result = $localize->map(array('slo', 'sk'));
$expected = array('slo' => 'sk', 'sk' => 'slo');
$expected = array('slo' => 'sk', 'sk' => 'slk');
$this->assertEquals($expected, $result);
$result = $localize->map(array('slv', 'sl'));
@ -505,7 +547,7 @@ class L10nTest extends CakeTestCase {
$result = $localize->catalog(array('cs'));
$expected = array(
'cs' => array('language' => 'Czech', 'locale' => 'cze', 'localeFallback' => 'cze', 'charset' => 'utf-8', 'direction' => 'ltr')
'cs' => array('language' => 'Czech', 'locale' => 'ces', 'localeFallback' => 'ces', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -526,10 +568,9 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('e', 'el'));
$result = $localize->catalog(array('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')
'el' => array('language' => 'Greek', 'locale' => 'ell', 'localeFallback' => 'ell', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -583,13 +624,13 @@ class L10nTest extends CakeTestCase {
$result = $localize->catalog(array('eu'));
$expected = array(
'eu' => array('language' => 'Basque', 'locale' => 'baq', 'localeFallback' => 'baq', 'charset' => 'utf-8', 'direction' => 'ltr')
'eu' => array('language' => 'Basque', 'locale' => 'eus', 'localeFallback' => 'eus', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('fa'));
$expected = array(
'fa' => array('language' => 'Farsi', 'locale' => 'per', 'localeFallback' => 'per', 'charset' => 'utf-8', 'direction' => 'rtl')
'fa' => array('language' => 'Farsi', 'locale' => 'fas', 'localeFallback' => 'fas', 'charset' => 'utf-8', 'direction' => 'rtl')
);
$this->assertEquals($expected, $result);
@ -607,12 +648,12 @@ class L10nTest extends CakeTestCase {
$result = $localize->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')
'fr' => array('language' => 'French (Standard)', 'locale' => 'fra', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-be' => array('language' => 'French (Belgium)', 'locale' => 'fr_be', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-ca' => array('language' => 'French (Canadian)', 'locale' => 'fr_ca', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-ch' => array('language' => 'French (Swiss)', 'locale' => 'fr_ch', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-fr' => array('language' => 'French (France)', 'locale' => 'fr_fr', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr'),
'fr-lu' => array('language' => 'French (Luxembourg)', 'locale' => 'fr_lu', 'localeFallback' => 'fra', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -665,16 +706,15 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('id', 'in'));
$result = $localize->catalog(array('id'));
$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->assertEquals($expected, $result);
$result = $localize->catalog(array('is'));
$expected = array(
'is' => array('language' => 'Icelandic', 'locale' => 'ice', 'localeFallback' => 'ice', 'charset' => 'utf-8', 'direction' => 'ltr')
'is' => array('language' => 'Icelandic', 'locale' => 'isl', 'localeFallback' => 'isl', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -691,6 +731,12 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('kk'));
$expected = array(
'kk' => array('language' => 'Kazakh', 'locale' => 'kaz', 'localeFallback' => 'kaz', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('ko', 'ko-kp', 'ko-kr'));
$expected = array(
'ko' => array('language' => 'Korean', 'locale' => 'kor', 'localeFallback' => 'kor', 'charset' => 'kr', 'direction' => 'ltr'),
@ -721,14 +767,14 @@ class L10nTest extends CakeTestCase {
$result = $localize->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')
'mk' => array('language' => 'FYRO Macedonian', 'locale' => 'mkd', 'localeFallback' => 'mkd', 'charset' => 'utf-8', 'direction' => 'ltr'),
'mk-mk' => array('language' => 'Macedonian', 'locale' => 'mk_mk', 'localeFallback' => 'mkd', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('ms'));
$expected = array(
'ms' => array('language' => 'Malaysian', 'locale' => 'may', 'localeFallback' => 'may', 'charset' => 'utf-8', 'direction' => 'ltr')
'ms' => array('language' => 'Malaysian', 'locale' => 'msa', 'localeFallback' => 'msa', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -738,24 +784,23 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('n', 'nl', 'nl-be'));
$result = $localize->catalog(array('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')
'nl' => array('language' => 'Dutch (Standard)', 'locale' => 'nld', 'localeFallback' => 'nld', 'charset' => 'utf-8', 'direction' => 'ltr'),
'nl-be' => array('language' => 'Dutch (Belgium)', 'locale' => 'nl_be', 'localeFallback' => 'nld', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog('nl');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'nld', 'localeFallback' => 'nld', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEquals($expected, $result);
$result = $localize->catalog('nld');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'nld', 'localeFallback' => 'nld', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEquals($expected, $result);
$result = $localize->catalog('dut');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'dut', 'localeFallback' => 'dut', 'charset' => 'utf-8', 'direction' => 'ltr');
$expected = array('language' => 'Dutch (Standard)', 'locale' => 'nld', 'localeFallback' => 'nld', 'charset' => 'utf-8', 'direction' => 'ltr');
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('nb'));
@ -771,9 +816,8 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('p', 'pl'));
$result = $localize->catalog(array('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->assertEquals($expected, $result);
@ -793,8 +837,8 @@ class L10nTest extends CakeTestCase {
$result = $localize->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')
'ro' => array('language' => 'Romanian', 'locale' => 'ron', 'localeFallback' => 'ron', 'charset' => 'utf-8', 'direction' => 'ltr'),
'ro-mo' => array('language' => 'Romanian (Moldavia)', 'locale' => 'ro_mo', 'localeFallback' => 'ron', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -806,7 +850,7 @@ class L10nTest extends CakeTestCase {
$result = $localize->catalog(array('sk'));
$expected = array(
'sk' => array('language' => 'Slovak', 'locale' => 'slo', 'localeFallback' => 'slo', 'charset' => 'utf-8', 'direction' => 'ltr')
'sk' => array('language' => 'Slovak', 'locale' => 'slk', 'localeFallback' => 'slk', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -818,13 +862,13 @@ class L10nTest extends CakeTestCase {
$result = $localize->catalog(array('sq'));
$expected = array(
'sq' => array('language' => 'Albanian', 'locale' => 'alb', 'localeFallback' => 'alb', 'charset' => 'utf-8', 'direction' => 'ltr')
'sq' => array('language' => 'Albanian', 'locale' => 'sqi', 'localeFallback' => 'sqi', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('sr'));
$expected = array(
'sr' => array('language' => 'Serbian', 'locale' => 'scc', 'localeFallback' => 'scc', 'charset' => 'utf-8', 'direction' => 'ltr')
'sr' => array('language' => 'Serbian', 'locale' => 'srp', 'localeFallback' => 'srp', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -835,15 +879,9 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('sx'));
$result = $localize->catalog(array('se'));
$expected = array(
'sx' => array('language' => 'Sutu', 'locale' => 'sx', 'localeFallback' => 'sx', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('sz'));
$expected = array(
'sz' => array('language' => 'Sami (Lappish)', 'locale' => 'smi', 'localeFallback' => 'smi', 'charset' => 'utf-8', 'direction' => 'ltr')
'se' => array('language' => 'Sami', 'locale' => 'sme', 'localeFallback' => 'sme', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -916,11 +954,11 @@ class L10nTest extends CakeTestCase {
$result = $localize->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')
'zh' => array('language' => 'Chinese', 'locale' => 'zho', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-cn' => array('language' => 'Chinese (PRC)', 'locale' => 'zh_cn', 'localeFallback' => 'zho', 'charset' => 'GB2312', 'direction' => 'ltr'),
'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-sg' => array('language' => 'Chinese (Singapore)', 'locale' => 'zh_sg', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr'),
'zh-tw' => array('language' => 'Chinese (Taiwan)', 'locale' => 'zh_tw', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -930,13 +968,12 @@ class L10nTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$result = $localize->catalog(array('en-nz', 'es-do', 'sz', 'ar-lb', 'zh-hk', 'pt-br'));
$result = $localize->catalog(array('en-nz', 'es-do', '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'),
'zh-hk' => array('language' => 'Chinese (Hong Kong)', 'locale' => 'zh_hk', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr'),
'pt-br' => array('language' => 'Portuguese (Brazil)', 'locale' => 'pt_br', 'localeFallback' => 'por', 'charset' => 'utf-8', 'direction' => 'ltr')
);
$this->assertEquals($expected, $result);
@ -945,8 +982,8 @@ class L10nTest extends CakeTestCase {
$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'),
'zho' => array('language' => 'Chinese', 'locale' => 'zho', 'localeFallback' => 'zho', 'charset' => 'utf-8', 'direction' => 'ltr'),
'rum' => array('language' => 'Romanian', 'locale' => 'ron', 'localeFallback' => 'ron', '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')
);

View file

@ -2,20 +2,20 @@
/**
* MultibyteTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.I18n
* @since CakePHP(tm) v 1.2.0.6833
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Multibyte', 'I18n');
/**
@ -260,9 +260,9 @@ class MultibyteTest extends CakeTestCase {
7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750,
7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786,
7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822,
7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892,
7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
$this->assertEquals($expected, $result);
$string = 'ḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕẖẗẘẙẚạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹ';
@ -579,9 +579,9 @@ class MultibyteTest extends CakeTestCase {
7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734, 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750,
7752, 7754, 7756, 7758, 7760, 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786,
7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812, 7814, 7816, 7818, 7820, 7822,
7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
7824, 7826, 7828, 7830, 7831, 7832, 7833, 7834, 7840, 7842, 7844, 7846, 7848, 7850, 7852, 7854, 7856,
7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872, 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892,
7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
7894, 7896, 7898, 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924, 7926, 7928);
$result = Multibyte::ascii($input);
$expected = 'ḀḂḄḆḈḊḌḎḐḒḔḖḘḚḜḞḠḢḤḦḨḪḬḮḰḲḴḶḸḺḼḾṀṂṄṆṈṊṌṎṐṒṔṖṘṚṜṞṠṢṤṦṨṪṬṮṰṲṴṶṸṺṼṾẀẂẄẆẈẊẌẎẐẒẔẖẗẘẙẚẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼẾỀỂỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪỬỮỰỲỴỶỸ';
$this->assertEquals($expected, $result);

View file

@ -2,19 +2,18 @@
/**
* CakeLogTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Log
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeLog', 'Log');
@ -86,6 +85,18 @@ class CakeLogTest extends CakeTestCase {
* @return void
*/
public function testValidKeyName() {
CakeLog::config('valid', array('engine' => 'File'));
$stream = CakeLog::stream('valid');
$this->assertInstanceOf('FileLog', $stream);
CakeLog::drop('valid');
}
/**
* test config() with valid key name including the deprecated Log suffix
*
* @return void
*/
public function testValidKeyNameLogSuffix() {
CakeLog::config('valid', array('engine' => 'FileLog'));
$stream = CakeLog::stream('valid');
$this->assertInstanceOf('FileLog', $stream);
@ -99,7 +110,7 @@ class CakeLogTest extends CakeTestCase {
* @return void
*/
public function testInvalidKeyName() {
CakeLog::config('1nv', array('engine' => 'FileLog'));
CakeLog::config('1nv', array('engine' => 'File'));
}
/**
@ -113,27 +124,20 @@ class CakeLogTest extends CakeTestCase {
}
/**
* Test that CakeLog autoconfigures itself to use a FileLogger with the LOGS dir.
* When no streams are there.
* Test that CakeLog does not auto create logs when no streams are there to listen.
*
* @return void
*/
public function testAutoConfig() {
public function testNoStreamListenting() {
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertTrue(file_exists(LOGS . 'error.log'));
$res = CakeLog::write(LOG_WARNING, 'Test warning');
$this->assertFalse($res);
$this->assertFalse(file_exists(LOGS . 'error.log'));
$result = CakeLog::configured();
$this->assertEquals(array('default'), $result);
$testMessage = 'custom message';
CakeLog::write('custom', $testMessage);
$content = file_get_contents(LOGS . 'custom.log');
$this->assertContains($testMessage, $content);
unlink(LOGS . 'error.log');
unlink(LOGS . 'custom.log');
$this->assertEquals(array(), $result);
}
/**
@ -143,7 +147,7 @@ class CakeLogTest extends CakeTestCase {
*/
public function testConfig() {
CakeLog::config('file', array(
'engine' => 'FileLog',
'engine' => 'File',
'path' => LOGS
));
$result = CakeLog::configured();
@ -164,10 +168,10 @@ class CakeLogTest extends CakeTestCase {
* explicit tests for drop()
*
* @return void
**/
*/
public function testDrop() {
CakeLog::config('file', array(
'engine' => 'FileLog',
'engine' => 'File',
'path' => LOGS
));
$result = CakeLog::configured();
@ -184,6 +188,10 @@ class CakeLogTest extends CakeTestCase {
* @return void
*/
public function testLogFileWriting() {
CakeLog::config('file', array(
'engine' => 'File',
'path' => LOGS
));
if (file_exists(LOGS . 'error.log')) {
unlink(LOGS . 'error.log');
}
@ -213,12 +221,12 @@ class CakeLogTest extends CakeTestCase {
unlink(LOGS . 'eggs.log');
}
CakeLog::config('spam', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => 'debug',
'file' => 'spam',
));
CakeLog::config('eggs', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('eggs', 'debug', 'error', 'warning'),
'file' => 'eggs',
));
@ -249,10 +257,11 @@ class CakeLogTest extends CakeTestCase {
* test enable
*
* @expectedException CakeLogException
* @return void
*/
public function testStreamEnable() {
CakeLog::config('spam', array(
'engine' => 'FileLog',
'engine' => 'File',
'file' => 'spam',
));
$this->assertTrue(CakeLog::enabled('spam'));
@ -264,10 +273,11 @@ class CakeLogTest extends CakeTestCase {
* test disable
*
* @expectedException CakeLogException
* @return void
*/
public function testStreamDisable() {
CakeLog::config('spam', array(
'engine' => 'FileLog',
'engine' => 'File',
'file' => 'spam',
));
$this->assertTrue(CakeLog::enabled('spam'));
@ -281,6 +291,7 @@ class CakeLogTest extends CakeTestCase {
* test enabled() invalid stream
*
* @expectedException CakeLogException
* @return void
*/
public function testStreamEnabledInvalid() {
CakeLog::enabled('bogus_stream');
@ -290,24 +301,35 @@ class CakeLogTest extends CakeTestCase {
* test disable invalid stream
*
* @expectedException CakeLogException
* @return void
*/
public function testStreamDisableInvalid() {
CakeLog::disable('bogus_stream');
}
/**
* resets log config
*
* @return void
*/
protected function _resetLogConfig() {
CakeLog::config('debug', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
CakeLog::config('error', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('warning', 'error', 'critical', 'alert', 'emergency'),
'file' => 'error',
));
}
/**
* delete logs
*
* @return void
*/
protected function _deleteLogs() {
if (file_exists(LOGS . 'shops.log')) {
unlink(LOGS . 'shops.log');
@ -338,7 +360,7 @@ class CakeLogTest extends CakeTestCase {
$this->_resetLogConfig();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops',
@ -383,17 +405,22 @@ class CakeLogTest extends CakeTestCase {
CakeLog::drop('shops');
}
/**
* Test that scopes are exclusive and don't bleed.
*
* @return void
*/
public function testScopedLoggingExclusive() {
$this->_deleteLogs();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops.log',
));
CakeLog::config('eggs', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('eggs'),
'file' => 'eggs.log',
@ -418,8 +445,20 @@ class CakeLogTest extends CakeTestCase {
public function testScopedLogging() {
$this->_resetLogConfig();
$this->_deleteLogs();
CakeLog::config('string-scope', array(
'engine' => 'File',
'types' => array('info', 'notice', 'warning'),
'scopes' => 'string-scope',
'file' => 'string-scope.log'
));
CakeLog::write('info', 'info message', 'string-scope');
$this->assertTrue(file_exists(LOGS . 'string-scope.log'));
CakeLog::drop('string-scope');
CakeLog::config('shops', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('info', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops.log',
@ -468,11 +507,17 @@ class CakeLogTest extends CakeTestCase {
/**
* test bogus type and scope
*
* @return void
*/
public function testBogusTypeAndScope() {
$this->_resetLogConfig();
$this->_deleteLogs();
CakeLog::config('file', array(
'engine' => 'File',
'path' => LOGS
));
CakeLog::write('bogus', 'bogus message');
$this->assertTrue(file_exists(LOGS . 'bogus.log'));
$this->assertFalse(file_exists(LOGS . 'error.log'));
@ -494,6 +539,8 @@ class CakeLogTest extends CakeTestCase {
/**
* test scoped logging with convenience methods
*
* @return void
*/
public function testConvenienceScopedLogging() {
if (file_exists(LOGS . 'shops.log')) {
@ -508,7 +555,7 @@ class CakeLogTest extends CakeTestCase {
$this->_resetLogConfig();
CakeLog::config('shops', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('info', 'debug', 'notice', 'warning'),
'scopes' => array('transactions', 'orders'),
'file' => 'shops',
@ -540,17 +587,19 @@ class CakeLogTest extends CakeTestCase {
/**
* test convenience methods
*
* @return void
*/
public function testConvenienceMethods() {
$this->_deleteLogs();
CakeLog::config('debug', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
CakeLog::config('error', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('emergency', 'alert', 'critical', 'error', 'warning'),
'file' => 'error',
));
@ -614,6 +663,8 @@ class CakeLogTest extends CakeTestCase {
/**
* test levels customization
*
* @return void
*/
public function testLevelCustomization() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Log level tests not supported on Windows.');
@ -644,12 +695,14 @@ class CakeLogTest extends CakeTestCase {
/**
* Test writing log files with custom levels
*
* @return void
*/
public function testCustomLevelWrites() {
$this->_deleteLogs();
$this->_resetLogConfig();
$levels = CakeLog::levels(array('spam', 'eggs'));
CakeLog::levels(array('spam', 'eggs'));
$testMessage = 'error message';
CakeLog::write('error', $testMessage);
@ -659,12 +712,12 @@ class CakeLogTest extends CakeTestCase {
$this->assertContains('Error: ' . $testMessage, $contents);
CakeLog::config('spam', array(
'engine' => 'FileLog',
'engine' => 'File',
'file' => 'spam.log',
'types' => 'spam',
));
CakeLog::config('eggs', array(
'engine' => 'FileLog',
'engine' => 'File',
'file' => 'eggs.log',
'types' => array('spam', 'eggs'),
));

View file

@ -2,30 +2,40 @@
/**
* ConsoleLogTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Log.Engine
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ConsoleLog', 'Log/Engine');
/**
* TestConsoleLog
*
* @package Cake.Test.Case.Log.Engine
*/
class TestConsoleLog extends ConsoleLog {
}
/**
* TestCakeLog
*
* @package Cake.Test.Case.Log.Engine
*/
class TestCakeLog extends CakeLog {
public static function replace($key, &$engine) {
self::$_Collection->{$key} = $engine;
static::$_Collection->{$key} = $engine;
}
}
@ -40,12 +50,12 @@ class ConsoleLogTest extends CakeTestCase {
public function setUp() {
parent::setUp();
CakeLog::config('debug', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
CakeLog::config('error', array(
'engine' => 'FileLog',
'engine' => 'File',
'types' => array('error', 'warning'),
'file' => 'error',
));
@ -63,10 +73,12 @@ class ConsoleLogTest extends CakeTestCase {
/**
* Test writing to ConsoleOutput
*
* @return void
*/
public function testConsoleOutputWrites() {
TestCakeLog::config('test_console_log', array(
'engine' => 'TestConsoleLog',
'engine' => 'TestConsole',
));
$mock = $this->getMock('TestConsoleLog', array('write'), array(
@ -82,10 +94,12 @@ class ConsoleLogTest extends CakeTestCase {
/**
* Test logging to both ConsoleLog and FileLog
*
* @return void
*/
public function testCombinedLogWriting() {
TestCakeLog::config('test_console_log', array(
'engine' => 'TestConsoleLog',
'engine' => 'TestConsole',
));
$mock = $this->getMock('TestConsoleLog', array('write'), array(
array('types' => 'error'),
@ -118,12 +132,16 @@ class ConsoleLogTest extends CakeTestCase {
/**
* test default value of stream 'outputAs'
*
* @return void
*/
public function testDefaultOutputAs() {
TestCakeLog::config('test_console_log', array(
'engine' => 'TestConsoleLog',
'engine' => 'TestConsole',
));
if (DS == '\\' && !(bool)env('ANSICON')) {
if ((DS === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
(function_exists('posix_isatty') && !posix_isatty(null))
) {
$expected = ConsoleOutput::PLAIN;
} else {
$expected = ConsoleOutput::COLOR;

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