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,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());
}