Initial commit

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

View file

@ -0,0 +1,543 @@
<?php
/**
* DbAclTest 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.Acl
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ComponentCollection', 'Controller');
App::uses('AclComponent', 'Controller/Component');
App::uses('DbAcl', 'Controller/Component/Acl');
App::uses('AclNode', 'Model');
App::uses('Permission', 'Model');
require_once dirname(dirname(dirname(dirname(__FILE__)))) . DS . 'Model' . DS . 'models.php';
/**
* AclNodeTwoTestBase class
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class AclNodeTwoTestBase extends AclNode {
/**
* useDbConfig property
*
* @var string
*/
public $useDbConfig = 'test';
/**
* cacheSources property
*
* @var bool
*/
public $cacheSources = false;
}
/**
* AroTwoTest class
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class AroTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string
*/
public $name = 'AroTwoTest';
/**
* useTable property
*
* @var string
*/
public $useTable = 'aro_twos';
/**
* hasAndBelongsToMany property
*
* @var array
*/
public $hasAndBelongsToMany = array('AcoTwoTest' => array('with' => 'PermissionTwoTest'));
}
/**
* AcoTwoTest class
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class AcoTwoTest extends AclNodeTwoTestBase {
/**
* name property
*
* @var string
*/
public $name = 'AcoTwoTest';
/**
* useTable property
*
* @var string
*/
public $useTable = 'aco_twos';
/**
* hasAndBelongsToMany property
*
* @var array
*/
public $hasAndBelongsToMany = array('AroTwoTest' => array('with' => 'PermissionTwoTest'));
}
/**
* PermissionTwoTest class
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class PermissionTwoTest extends Permission {
/**
* name property
*
* @var string
*/
public $name = 'PermissionTwoTest';
/**
* useTable property
*
* @var string
*/
public $useTable = 'aros_aco_twos';
/**
* cacheQueries property
*
* @var bool
*/
public $cacheQueries = false;
/**
* belongsTo property
*
* @var array
*/
public $belongsTo = array('AroTwoTest' => array('foreignKey' => 'aro_id'), 'AcoTwoTest' => array('foreignKey' => 'aco_id'));
/**
* actsAs property
*
* @var mixed
*/
public $actsAs = null;
}
/**
* DbAclTwoTest class
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class DbAclTwoTest extends DbAcl {
/**
* construct method
*
*/
public function __construct() {
$this->Aro = new AroTwoTest();
$this->Aro->Permission = new PermissionTwoTest();
$this->Aco = new AcoTwoTest();
$this->Aro->Permission = new PermissionTwoTest();
$this->Permission = $this->Aro->Permission;
$this->Permission->Aro = $this->Aro;
$this->Permission->Aco = $this->Aco;
}
}
/**
* Test case for AclComponent using the DbAcl implementation.
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class DbAclTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
*/
public $fixtures = array('core.aro_two', 'core.aco_two', 'core.aros_aco_two');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Acl.classname', 'DbAclTwoTest');
Configure::write('Acl.database', 'test');
$Collection = new ComponentCollection();
$this->Acl = new AclComponent($Collection);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Acl);
}
/**
* testAclCreate method
*
* @return void
*/
public function testCreate() {
$this->Acl->Aro->create(array('alias' => 'Chotchkey'));
$this->assertTrue((bool)$this->Acl->Aro->save());
$parent = $this->Acl->Aro->id;
$this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Joanna'));
$this->assertTrue((bool)$this->Acl->Aro->save());
$this->Acl->Aro->create(array('parent_id' => $parent, 'alias' => 'Stapler'));
$this->assertTrue((bool)$this->Acl->Aro->save());
$root = $this->Acl->Aco->node('ROOT');
$parent = $root[0]['AcoTwoTest']['id'];
$this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'Drinks'));
$this->assertTrue((bool)$this->Acl->Aco->save());
$this->Acl->Aco->create(array('parent_id' => $parent, 'alias' => 'PiecesOfFlair'));
$this->assertTrue((bool)$this->Acl->Aco->save());
}
/**
* testAclCreateWithParent method
*
* @return void
*/
public function testCreateWithParent() {
$parent = $this->Acl->Aro->findByAlias('Peter', null, null, -1);
$this->Acl->Aro->create();
$this->Acl->Aro->save(array(
'alias' => 'Subordinate',
'model' => 'User',
'foreign_key' => 7,
'parent_id' => $parent['AroTwoTest']['id']
));
$result = $this->Acl->Aro->findByAlias('Subordinate', null, null, -1);
$this->assertEquals(16, $result['AroTwoTest']['lft']);
$this->assertEquals(17, $result['AroTwoTest']['rght']);
}
/**
* testDbAclAllow method
*
* @return void
*/
public function testAllow() {
$this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->allow('Micheal', 'tpsReports', array('read', 'delete', 'update')));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'update'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertFalse($this->Acl->check('Micheal', 'tpsReports', 'create'));
$this->assertTrue($this->Acl->allow('Micheal', 'ROOT/tpsReports', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->allow('Micheal', 'printers', 'create'));
// Michael no longer has his delete permission for tpsReports!
$this->assertTrue($this->Acl->check('Micheal', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->check('Micheal', 'printers', 'create'));
$this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view'));
$this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/view', '*'));
$this->assertTrue($this->Acl->check('Samir', 'view', 'read'));
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update'));
$this->assertFalse($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', '*'));
$this->assertTrue($this->Acl->allow('root/users/Samir', 'ROOT/tpsReports/update', '*'));
$this->assertTrue($this->Acl->check('Samir', 'update', 'read'));
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/update', 'update'));
// Samir should still have his tpsReports/view permissions, but does not
$this->assertTrue($this->Acl->check('root/users/Samir', 'ROOT/tpsReports/view', 'update'));
$this->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
*
* @return void
*/
public function testAllowInvalidNode() {
$this->assertFalse($this->Acl->allow('Homer', 'tpsReports', 'create'));
}
/**
* testDbAclCheck method
*
* @return void
*/
public function testCheck() {
$this->assertTrue($this->Acl->check('Samir', 'print', 'read'));
$this->assertTrue($this->Acl->check('Lumbergh', 'current', 'read'));
$this->assertFalse($this->Acl->check('Milton', 'smash', 'read'));
$this->assertFalse($this->Acl->check('Milton', 'current', 'update'));
$this->assertFalse($this->Acl->check(null, 'printers', 'create'));
$this->assertFalse($this->Acl->check('managers', null, 'read'));
$this->assertTrue($this->Acl->check('Bobs', 'ROOT/tpsReports/view/current', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'ROOT/tpsReports/update', 'read'));
$this->assertFalse($this->Acl->check('root/users/Milton', 'smash', 'delete'));
}
/**
* testCheckInvalidNode method
*
* @return void
*/
public function testCheckInvalidNode() {
$this->assertFalse($this->Acl->check('WRONG', 'tpsReports', 'read'));
}
/**
* testCheckInvalidPermission method
*
* @return void
*/
public function testCheckInvalidPermission() {
$this->assertFalse($this->Acl->check('Lumbergh', 'smash', 'foobar'));
}
/**
* testCheckMissingPermission method
*
* @return void
*/
public function testCheckMissingPermission() {
$this->assertFalse($this->Acl->check('users', 'NonExistent', 'read'));
}
/**
* testDbAclCascadingDeny function
*
* Setup the acl permissions such that Bobs inherits from admin.
* deny Admin delete access to a specific resource, check the permissions are inherited.
*
* @return void
*/
public function testAclCascadingDeny() {
$this->Acl->inherit('Bobs', 'ROOT', '*');
$this->assertTrue($this->Acl->check('admin', 'tpsReports', 'delete'));
$this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'delete'));
$this->Acl->deny('admin', 'tpsReports', 'delete');
$this->assertFalse($this->Acl->check('admin', 'tpsReports', 'delete'));
$this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'delete'));
}
/**
* testDbAclDeny method
*
* @return void
*/
public function testDeny() {
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'delete'));
$this->Acl->deny('Micheal', 'smash', 'delete');
$this->assertFalse($this->Acl->check('Micheal', 'smash', 'delete'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'smash', 'update'));
$this->assertFalse($this->Acl->check('Micheal', 'smash', '*'));
$this->assertTrue($this->Acl->check('Samir', 'refill', '*'));
$this->Acl->deny('Samir', 'refill', '*');
$this->assertFalse($this->Acl->check('Samir', 'refill', 'create'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'update'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'refill', 'delete'));
$result = $this->Acl->Aro->Permission->find('all', array('conditions' => array('AroTwoTest.alias' => 'Samir')));
$expected = '-1';
$this->assertEquals($expected, $result[0]['PermissionTwoTest']['_delete']);
$this->assertFalse($this->Acl->deny('Lumbergh', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
/**
* testAclNodeLookup method
*
* @return void
*/
public function testAclNodeLookup() {
$result = $this->Acl->Aro->node('root/users/Samir');
$expected = array(
array('AroTwoTest' => array('id' => '7', 'parent_id' => '4', 'model' => 'User', 'foreign_key' => 3, 'alias' => 'Samir')),
array('AroTwoTest' => array('id' => '4', 'parent_id' => '1', 'model' => 'Group', 'foreign_key' => 3, 'alias' => 'users')),
array('AroTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'root'))
);
$this->assertEquals($expected, $result);
$result = $this->Acl->Aco->node('ROOT/tpsReports/view/current');
$expected = array(
array('AcoTwoTest' => array('id' => '4', 'parent_id' => '3', 'model' => null, 'foreign_key' => null, 'alias' => 'current')),
array('AcoTwoTest' => array('id' => '3', 'parent_id' => '2', 'model' => null, 'foreign_key' => null, 'alias' => 'view')),
array('AcoTwoTest' => array('id' => '2', 'parent_id' => '1', 'model' => null, 'foreign_key' => null, 'alias' => 'tpsReports')),
array('AcoTwoTest' => array('id' => '1', 'parent_id' => null, 'model' => null, 'foreign_key' => null, 'alias' => 'ROOT')),
);
$this->assertEquals($expected, $result);
}
/**
* testDbInherit method
*
* @return void
*/
public function testInherit() {
//parent doesn't have access inherit should still deny
$this->assertFalse($this->Acl->check('Milton', 'smash', 'delete'));
$this->Acl->inherit('Milton', 'smash', 'delete');
$this->assertFalse($this->Acl->check('Milton', 'smash', 'delete'));
//inherit parent
$this->assertFalse($this->Acl->check('Milton', 'smash', 'read'));
$this->Acl->inherit('Milton', 'smash', 'read');
$this->assertTrue($this->Acl->check('Milton', 'smash', 'read'));
}
/**
* testDbGrant method
*
* @return void
*/
public function testGrant() {
$this->assertFalse($this->Acl->check('Samir', 'tpsReports', 'create'));
$this->Acl->allow('Samir', 'tpsReports', 'create');
$this->assertTrue($this->Acl->check('Samir', 'tpsReports', 'create'));
$this->assertFalse($this->Acl->check('Micheal', 'view', 'read'));
$this->Acl->allow('Micheal', 'view', array('read', 'create', 'update'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'read'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'create'));
$this->assertTrue($this->Acl->check('Micheal', 'view', 'update'));
$this->assertFalse($this->Acl->check('Micheal', 'view', 'delete'));
$this->assertFalse($this->Acl->allow('Peter', 'ROOT/tpsReports/DoesNotExist', 'create'));
}
/**
* testDbRevoke method
*
* @return void
*/
public function testRevoke() {
$this->assertTrue($this->Acl->check('Bobs', 'tpsReports', 'read'));
$this->Acl->deny('Bobs', 'tpsReports', 'read');
$this->assertFalse($this->Acl->check('Bobs', 'tpsReports', 'read'));
$this->assertTrue($this->Acl->check('users', 'printers', 'read'));
$this->Acl->deny('users', 'printers', 'read');
$this->assertFalse($this->Acl->check('users', 'printers', 'read'));
$this->assertFalse($this->Acl->check('Samir', 'printers', 'read'));
$this->assertFalse($this->Acl->check('Peter', 'printers', 'read'));
$this->Acl->deny('Bobs', 'ROOT/printers/DoesNotExist', 'create');
}
/**
* debug function - to help editing/creating test cases for the ACL component
*
* To check the overall ACL status at any time call $this->_debug();
* Generates a list of the current aro and aco structures and a grid dump of the permissions that are defined
* Only designed to work with the db based ACL
*
* @param bool $treesToo
* @return void
*/
protected function _debug($printTreesToo = false) {
$this->Acl->Aro->displayField = 'alias';
$this->Acl->Aco->displayField = 'alias';
$aros = $this->Acl->Aro->find('list', array('order' => 'lft'));
$acos = $this->Acl->Aco->find('list', array('order' => 'lft'));
$rights = array('*', 'create', 'read', 'update', 'delete');
$permissions['Aros v Acos >'] = $acos;
foreach ($aros as $aro) {
$row = array();
foreach ($acos as $aco) {
$perms = '';
foreach ($rights as $right) {
if ($this->Acl->check($aro, $aco, $right)) {
if ($right === '*') {
$perms .= '****';
break;
}
$perms .= $right[0];
} elseif ($right !== '*') {
$perms .= ' ';
}
}
$row[] = $perms;
}
$permissions[$aro] = $row;
}
foreach ($permissions as $key => $values) {
array_unshift($values, $key);
$values = array_map(array(&$this, '_pad'), $values);
$permissions[$key] = implode(' ', $values);
}
$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()));
}
debug(implode("\r\n", $permissions));
}
/**
* pad function
* Used by debug to format strings used in the data dump
*
* @param string $string
* @param int $len
* @return void
*/
protected function _pad($string = '', $len = 14) {
return str_pad($string, $len);
}
}

View file

@ -0,0 +1,68 @@
<?php
/**
* IniAclTest 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.Acl
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('IniAcl', 'Controller/Component/Acl');
/**
* Test case for the IniAcl implementation
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class IniAclTest extends CakeTestCase {
/**
* testIniCheck method
*
* @return void
*/
public function testCheck() {
$iniFile = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'acl.ini.php';
$Ini = new IniAcl();
$Ini->config = $Ini->readConfigFile($iniFile);
$this->assertFalse($Ini->check('admin', 'ads'));
$this->assertTrue($Ini->check('admin', 'posts'));
$this->assertTrue($Ini->check('jenny', 'posts'));
$this->assertTrue($Ini->check('jenny', 'ads'));
$this->assertTrue($Ini->check('paul', 'posts'));
$this->assertFalse($Ini->check('paul', 'ads'));
$this->assertFalse($Ini->check('nobody', 'comments'));
}
/**
* check should accept a user array.
*
* @return void
*/
public function testCheckArray() {
$iniFile = CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'acl.ini.php';
$Ini = new IniAcl();
$Ini->config = $Ini->readConfigFile($iniFile);
$Ini->userPath = 'User.username';
$user = array(
'User' => array('username' => 'admin')
);
$this->assertTrue($Ini->check($user, 'posts'));
}
}

View file

@ -0,0 +1,374 @@
<?php
/**
* PhpAclTest 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.Acl
* @since CakePHP(tm) v 2.1
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclComponent', 'Controller/Component');
App::uses('PhpAcl', 'Controller/Component/Acl');
class_exists('AclComponent');
/**
* Test case for the PhpAcl implementation
*
* @package Cake.Test.Case.Controller.Component.Acl
*/
class PhpAclTest extends CakeTestCase {
/**
* Setup
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Acl.classname', 'PhpAcl');
$Collection = new ComponentCollection();
$this->PhpAcl = new PhpAcl();
$this->Acl = new AclComponent($Collection, array(
'adapter' => array(
'config' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS . 'acl.php',
),
));
}
/**
* Test role inheritance
*
* @return void
*/
public function testRoleInheritance() {
$roles = $this->Acl->Aro->roles('User/peter');
$this->assertEquals(array('Role/accounting'), $roles[0]);
$this->assertEquals(array('User/peter'), $roles[1]);
$roles = $this->Acl->Aro->roles('hardy');
$this->assertEquals(array('Role/database_manager', 'Role/data_acquirer'), $roles[0]);
$this->assertEquals(array('Role/accounting', 'Role/data_analyst'), $roles[1]);
$this->assertEquals(array('Role/accounting_manager', 'Role/reports'), $roles[2]);
$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() {
$this->Acl->Aro->map = array(
'User' => 'FooModel/nickname',
'Role' => 'FooModel/role',
);
$this->assertEquals('Role/default', $this->Acl->Aro->resolve('Foo.bar'));
$this->assertEquals('User/hardy', $this->Acl->Aro->resolve('FooModel/hardy'));
$this->assertEquals('User/hardy', $this->Acl->Aro->resolve('hardy'));
$this->assertEquals('User/hardy', $this->Acl->Aro->resolve(array('FooModel' => array('nickname' => 'hardy'))));
$this->assertEquals('Role/admin', $this->Acl->Aro->resolve(array('FooModel' => array('role' => 'admin'))));
$this->assertEquals('Role/admin', $this->Acl->Aro->resolve('Role/admin'));
$this->assertEquals('Role/admin', $this->Acl->Aro->resolve('admin'));
$this->assertEquals('Role/admin', $this->Acl->Aro->resolve('FooModel/admin'));
$this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('accounting'));
$this->assertEquals(PhpAro::DEFAULT_ROLE, $this->Acl->Aro->resolve('bla'));
$this->assertEquals(PhpAro::DEFAULT_ROLE, $this->Acl->Aro->resolve(array('FooModel' => array('role' => 'hardy'))));
}
/**
* test correct resolution of defined aliases
*
* @return void
*/
public function testAroAliases() {
$this->Acl->Aro->map = array(
'User' => 'User/username',
'Role' => 'User/group_id',
);
$this->Acl->Aro->aliases = array(
'Role/1' => 'Role/admin',
'Role/24' => 'Role/accounting',
);
$user = array(
'User' => array(
'username' => 'unknown_user',
'group_id' => '1',
),
);
// group/1
$this->assertEquals('Role/admin', $this->Acl->Aro->resolve($user));
// group/24
$this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('Role/24'));
$this->assertEquals('Role/accounting', $this->Acl->Aro->resolve('24'));
// check department
$user = array(
'User' => array(
'username' => 'foo',
'group_id' => '25',
),
);
$this->Acl->Aro->addRole(array('Role/IT' => null));
$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->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
$this->assertFalse($this->Acl->check($user, '/controllers/users/dashboard'));
$this->assertFalse($this->Acl->check($user, '/controllers/invoices/send'));
// wee add an more specific entry for user foo to also inherit from Role/accounting
$this->Acl->Aro->addRole(array('User/foo' => 'Role/IT, Role/accounting'));
$this->assertTrue($this->Acl->check($user, '/controllers/invoices/send'));
}
/**
* test check method
*
* @return void
*/
public function testCheck() {
$this->assertTrue($this->Acl->check('jan', '/controllers/users/Dashboard'));
$this->assertTrue($this->Acl->check('some_unknown_role', '/controllers/users/Dashboard'));
$this->assertTrue($this->Acl->check('Role/admin', 'foo/bar'));
$this->assertTrue($this->Acl->check('role/admin', '/foo/bar'));
$this->assertTrue($this->Acl->check('jan', 'foo/bar'));
$this->assertTrue($this->Acl->check('user/jan', 'foo/bar'));
$this->assertTrue($this->Acl->check('Role/admin', 'controllers/bar'));
$this->assertTrue($this->Acl->check(array('User' => array('username' => 'jan')), '/controllers/bar/bll'));
$this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/create'));
$this->assertTrue($this->Acl->check('User/db_manager_2', 'controllers/db/create'));
$this->assertFalse($this->Acl->check('db_manager_2', '/controllers/users/Dashboard'));
// inheritance: hardy -> reports -> data_analyst -> database_manager
$this->assertTrue($this->Acl->check('User/hardy', 'controllers/db/create'));
$this->assertFalse($this->Acl->check('User/jeff', 'controllers/db/create'));
$this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/select'));
$this->assertTrue($this->Acl->check('User/db_manager_2', 'controllers/db/select'));
$this->assertFalse($this->Acl->check('User/jeff', 'controllers/db/select'));
$this->assertTrue($this->Acl->check('Role/database_manager', 'controllers/db/drop'));
$this->assertTrue($this->Acl->check('User/db_manager_1', 'controllers/db/drop'));
$this->assertFalse($this->Acl->check('db_manager_2', 'controllers/db/drop'));
$this->assertTrue($this->Acl->check('db_manager_2', 'controllers/invoices/edit'));
$this->assertFalse($this->Acl->check('database_manager', 'controllers/invoices/edit'));
$this->assertFalse($this->Acl->check('db_manager_1', 'controllers/invoices/edit'));
// Role/manager is allowed /controllers/*/*_manager
$this->assertTrue($this->Acl->check('stan', 'controllers/invoices/manager_edit'));
$this->assertTrue($this->Acl->check('Role/manager', 'controllers/baz/manager_foo'));
$this->assertFalse($this->Acl->check('User/stan', 'custom/foo/manager_edit'));
$this->assertFalse($this->Acl->check('stan', 'bar/baz/manager_foo'));
$this->assertFalse($this->Acl->check('Role/accounting', 'bar/baz/manager_foo'));
$this->assertFalse($this->Acl->check('accounting', 'controllers/baz/manager_foo'));
$this->assertTrue($this->Acl->check('User/stan', 'controllers/articles/edit'));
$this->assertTrue($this->Acl->check('stan', 'controllers/articles/add'));
$this->assertTrue($this->Acl->check('stan', 'controllers/articles/publish'));
$this->assertFalse($this->Acl->check('User/stan', 'controllers/articles/delete'));
$this->assertFalse($this->Acl->check('accounting', 'controllers/articles/edit'));
$this->assertFalse($this->Acl->check('accounting', 'controllers/articles/add'));
$this->assertFalse($this->Acl->check('role/accounting', 'controllers/articles/publish'));
}
/**
* lhs of defined rules are case insensitive
*
* @return void
*/
public function testCheckIsCaseInsensitive() {
$this->assertTrue($this->Acl->check('hardy', 'controllers/forms/new'));
$this->assertTrue($this->Acl->check('Role/data_acquirer', 'controllers/forms/new'));
$this->assertTrue($this->Acl->check('hardy', 'controllers/FORMS/NEW'));
$this->assertTrue($this->Acl->check('Role/data_acquirer', 'controllers/FORMS/NEW'));
}
/**
* allow should work in-memory
*
* @return void
*/
public function testAllow() {
$this->assertFalse($this->Acl->check('jeff', 'foo/bar'));
$this->Acl->allow('jeff', 'foo/bar');
$this->assertTrue($this->Acl->check('jeff', 'foo/bar'));
$this->assertFalse($this->Acl->check('peter', 'foo/bar'));
$this->assertFalse($this->Acl->check('hardy', 'foo/bar'));
$this->Acl->allow('Role/accounting', 'foo/bar');
$this->assertTrue($this->Acl->check('peter', 'foo/bar'));
$this->assertTrue($this->Acl->check('hardy', 'foo/bar'));
$this->assertFalse($this->Acl->check('Role/reports', 'foo/bar'));
}
/**
* deny should work in-memory
*
* @return void
*/
public function testDeny() {
$this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_foo'));
$this->Acl->deny('stan', 'controllers/baz/manager_foo');
$this->assertFalse($this->Acl->check('stan', 'controllers/baz/manager_foo'));
$this->assertTrue($this->Acl->check('Role/manager', 'controllers/baz/manager_foo'));
$this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_bar'));
$this->assertTrue($this->Acl->check('stan', 'controllers/baz/manager_foooooo'));
}
/**
* 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'));
$this->Acl->allow('peter', 'baz/bam');
$this->assertTrue($this->Acl->check('peter', 'baz/bam'));
$this->Acl->deny('peter', 'baz/bam');
$this->assertFalse($this->Acl->check('peter', 'baz/bam'));
$this->assertTrue($this->Acl->check('stan', 'controllers/reports/foo'));
// stan is denied as he's sales and sales is denied /controllers/*/delete
$this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete'));
$this->Acl->allow('stan', 'controllers/reports/delete');
$this->assertFalse($this->Acl->check('Role/sales', 'controllers/reports/delete'));
$this->assertTrue($this->Acl->check('stan', 'controllers/reports/delete'));
$this->Acl->deny('stan', 'controllers/reports/delete');
$this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete'));
// there is already an equally specific deny rule that will win
$this->Acl->allow('stan', 'controllers/reports/delete');
$this->assertFalse($this->Acl->check('stan', 'controllers/reports/delete'));
}
/**
* test that an invalid configuration throws exception
*
* @return void
*/
public function testInvalidConfigWithAroMissing() {
$this->setExpectedException(
'AclException',
'"roles" section not found in configuration'
);
$config = array('aco' => array('allow' => array('foo' => '')));
$this->PhpAcl->build($config);
}
public function testInvalidConfigWithAcosMissing() {
$this->setExpectedException(
'AclException',
'Neither "allow" nor "deny" rules were provided in configuration.'
);
$config = array(
'roles' => array('Role/foo' => null),
);
$this->PhpAcl->build($config);
}
/**
* test resolving of ACOs
*
* @return void
*/
public function testAcoResolve() {
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo/bar'));
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo/bar'));
$this->assertEquals(array('foo', 'bar', 'baz'), $this->Acl->Aco->resolve('foo/bar/baz'));
$this->assertEquals(array('foo', '*-bar', '?-baz'), $this->Acl->Aco->resolve('foo/*-bar/?-baz'));
$this->assertEquals(array('foo', 'bar', '[a-f0-9]{24}', '*_bla', 'bla'), $this->Acl->Aco->resolve('foo/bar/[a-f0-9]{24}/*_bla/bla'));
// multiple slashes will be squashed to a single, trimmed and then exploded
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('foo//bar'));
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('//foo///bar/'));
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('/foo//bar//'));
$this->assertEquals(array('foo', 'bar'), $this->Acl->Aco->resolve('/foo // bar'));
$this->assertEquals(array(), $this->Acl->Aco->resolve('/////'));
}
/**
* test that declaring cyclic dependencies should give an error when building the tree
*
* @return void
*/
public function testAroDeclarationContainsCycles() {
$config = array(
'roles' => array(
'Role/a' => null,
'Role/b' => 'User/b',
'User/a' => 'Role/a, Role/b',
'User/b' => 'User/a',
),
'rules' => array(
'allow' => array(
'*' => 'Role/a',
),
),
);
$this->expectError('PHPUnit_Framework_Error', 'cycle detected' /* ... */);
$this->PhpAcl->build($config);
}
/**
* test that with policy allow, only denies count
*
* @return void
*/
public function testPolicy() {
// allow by default
$this->Acl->settings['adapter']['policy'] = PhpAcl::ALLOW;
$this->Acl->adapter($this->PhpAcl);
$this->assertTrue($this->Acl->check('Role/sales', 'foo'));
$this->assertTrue($this->Acl->check('Role/sales', 'controllers/bla/create'));
$this->assertTrue($this->Acl->check('Role/default', 'foo'));
// undefined user, undefined aco
$this->assertTrue($this->Acl->check('foobar', 'foo/bar'));
// deny rule: Role.sales -> controllers.*.delete
$this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar/delete'));
$this->assertFalse($this->Acl->check('Role/sales', 'controllers/bar', 'delete'));
}
}

View file

@ -0,0 +1,91 @@
<?php
/**
* AclComponentTest file
*
* 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 1.2.0.5435
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AclComponent', 'Controller/Component');
class_exists('AclComponent');
/**
* Test Case for AclComponent
*
* @package Cake.Test.Case.Controller.Component
*/
class AclComponentTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
if (!class_exists('MockAclImplementation', false)) {
$this->getMock('AclInterface', array(), array(), 'MockAclImplementation');
}
Configure::write('Acl.classname', 'MockAclImplementation');
$Collection = new ComponentCollection();
$this->Acl = new AclComponent($Collection);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Acl);
}
/**
* test that constructor throws an exception when Acl.classname is a
* non-existent class
*
* @expectedException CakeException
* @return void
*/
public function testConstrutorException() {
Configure::write('Acl.classname', 'AclClassNameThatDoesNotExist');
$Collection = new ComponentCollection();
new AclComponent($Collection);
}
/**
* test that adapter() allows control of the internal implementation AclComponent uses.
*
* @return void
*/
public function testAdapter() {
$Adapter = $this->getMock('AclInterface');
$Adapter->expects($this->once())->method('initialize')->with($this->Acl);
$this->assertNull($this->Acl->adapter($Adapter));
$this->assertEquals($this->Acl->adapter(), $Adapter, 'Returned object is different %s');
}
/**
* test that adapter() whines when the class does not implement AclInterface
*
* @expectedException CakeException
* @return void
*/
public function testAdapterException() {
$thing = new StdClass();
$this->Acl->adapter($thing);
}
}

View file

@ -0,0 +1,197 @@
<?php
/**
* ActionsAuthorizeTest 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.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ActionsAuthorize', 'Controller/Component/Auth');
App::uses('ComponentCollection', 'Controller');
App::uses('AclComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* Class ActionsAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class ActionsAuthorizeTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->controller = $this->getMock('Controller', array(), array(), '', false);
$this->Acl = $this->getMock('AclComponent', array(), array(), '', false);
$this->Collection = $this->getMock('ComponentCollection');
$this->auth = new ActionsAuthorize($this->Collection);
$this->auth->settings['actionPath'] = '/controllers';
}
/**
* setup the mock acl.
*
* @return void
*/
protected function _mockAcl() {
$this->Collection->expects($this->any())
->method('load')
->with('Acl')
->will($this->returnValue($this->Acl));
}
/**
* test failure
*
* @return void
*/
public function testAuthorizeFailure() {
$user = array(
'User' => array(
'id' => 1,
'user' => 'mariano'
)
);
$request = new CakeRequest('/posts/index', false);
$request->addParams(array(
'plugin' => null,
'controller' => 'posts',
'action' => 'index'
));
$this->_mockAcl();
$this->Acl->expects($this->once())
->method('check')
->with($user, 'controllers/Posts/index')
->will($this->returnValue(false));
$this->assertFalse($this->auth->authorize($user['User'], $request));
}
/**
* test isAuthorized working.
*
* @return void
*/
public function testAuthorizeSuccess() {
$user = array(
'User' => array(
'id' => 1,
'user' => 'mariano'
)
);
$request = new CakeRequest('/posts/index', false);
$request->addParams(array(
'plugin' => null,
'controller' => 'posts',
'action' => 'index'
));
$this->_mockAcl();
$this->Acl->expects($this->once())
->method('check')
->with($user, 'controllers/Posts/index')
->will($this->returnValue(true));
$this->assertTrue($this->auth->authorize($user['User'], $request));
}
/**
* testAuthorizeSettings
*
* @return void
*/
public function testAuthorizeSettings() {
$request = new CakeRequest('/posts/index', false);
$request->addParams(array(
'plugin' => null,
'controller' => 'posts',
'action' => 'index'
));
$this->_mockAcl();
$this->auth->settings['userModel'] = 'TestPlugin.TestPluginAuthUser';
$user = array(
'id' => 1,
'user' => 'mariano'
);
$expected = array('TestPlugin.TestPluginAuthUser' => array('id' => 1, 'user' => 'mariano'));
$this->Acl->expects($this->once())
->method('check')
->with($expected, 'controllers/Posts/index')
->will($this->returnValue(true));
$this->assertTrue($this->auth->authorize($user, $request));
}
/**
* test action()
*
* @return void
*/
public function testActionMethod() {
$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);
}
/**
* Make sure that action() doesn't create double slashes anywhere.
*
* @return void
*/
public function testActionNoDoubleSlash() {
$this->auth->settings['actionPath'] = '/controllers/';
$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);
}
/**
* test action() and plugins
*
* @return void
*/
public function testActionWithPlugin() {
$request = new CakeRequest('/debug_kit/posts/index', false);
$request->addParams(array(
'plugin' => 'debug_kit',
'controller' => 'posts',
'action' => 'index'
));
$result = $this->auth->action($request);
$this->assertEquals('controllers/DebugKit/Posts/index', $result);
}
}

View file

@ -0,0 +1,251 @@
<?php
/**
* BasicAuthenticateTest 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.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AuthComponent', 'Controller/Component');
App::uses('BasicAuthenticate', 'Controller/Component/Auth');
App::uses('AppModel', 'Model');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
/**
* Test case for BasicAuthentication
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class BasicAuthenticateTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user');
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Collection = $this->getMock('ComponentCollection');
$this->auth = new BasicAuthenticate($this->Collection, array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User',
'realm' => 'localhost',
'recursive' => 0
));
$password = Security::hash('password', null, true);
$User = ClassRegistry::init('User');
$User->updateAll(array('password' => $User->getDataSource()->value($password)));
$this->response = $this->getMock('CakeResponse');
}
/**
* test applying settings in the constructor
*
* @return void
*/
public function testConstructor() {
$object = new BasicAuthenticate($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']);
$this->assertEquals(env('SERVER_NAME'), $object->settings['realm']);
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$this->response->expects($this->never())
->method('header');
$this->assertFalse($this->auth->getUser($request));
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateNoUsername() {
$request = new CakeRequest('posts/index', false);
$_SERVER['PHP_AUTH_PW'] = 'foobar';
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateNoPassword() {
$request = new CakeRequest('posts/index', false);
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = null;
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateInjection() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_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.
*
* @return void
*/
public function testAuthenticateChallenge() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
try {
$this->auth->unauthenticated($request, $this->response);
} catch (UnauthorizedException $e) {
}
$this->assertNotEmpty($e);
$expected = array('WWW-Authenticate: Basic realm="localhost"');
$this->assertEquals($expected, $e->responseHeader());
}
/**
* test authenticate success
*
* @return void
*/
public function testAuthenticateSuccess() {
$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',
'created' => '2007-03-17 01:16:23',
'updated' => '2007-03-17 01:18:31'
);
$this->assertEquals($expected, $result);
}
/**
* test scope failure.
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateFailReChallenge() {
$this->auth->settings['scope'] = array('user' => 'nate');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_USER'] = 'mariano';
$_SERVER['PHP_AUTH_PW'] = 'password';
$this->auth->unauthenticated($request, $this->response);
}
/**
* 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');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_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(self::date(), $result['updated']);
unset($result['updated']);
$this->assertEquals($expected, $result);
CakePlugin::unload();
}
}

View file

@ -0,0 +1,91 @@
<?php
/**
* ControllerAuthorizeTest 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.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('ControllerAuthorize', 'Controller/Component/Auth');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* Class ControllerAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class ControllerAuthorizeTest extends CakeTestCase {
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->controller = $this->getMock('Controller', array('isAuthorized'), array(), '', false);
$this->components = $this->getMock('ComponentCollection');
$this->components->expects($this->any())
->method('getController')
->will($this->returnValue($this->controller));
$this->auth = new ControllerAuthorize($this->components);
}
/**
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testControllerTypeError() {
$this->auth->controller(new StdClass());
}
/**
* @expectedException CakeException
* @return void
*/
public function testControllerErrorOnMissingMethod() {
$this->auth->controller(new Controller());
}
/**
* test failure
*
* @return void
*/
public function testAuthorizeFailure() {
$user = array();
$request = new CakeRequest('/posts/index', false);
$this->assertFalse($this->auth->authorize($user, $request));
}
/**
* test isAuthorized working.
*
* @return void
*/
public function testAuthorizeSuccess() {
$user = array('User' => array('username' => 'mark'));
$request = new CakeRequest('/posts/index', false);
$this->controller->expects($this->once())
->method('isAuthorized')
->with($user)
->will($this->returnValue(true));
$this->assertTrue($this->auth->authorize($user, $request));
}
}

View file

@ -0,0 +1,189 @@
<?php
/**
* CrudAuthorizeTest 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.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CrudAuthorize', 'Controller/Component/Auth');
App::uses('ComponentCollection', 'Controller');
App::uses('AclComponent', 'Controller/Component');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
/**
* Class CrudAuthorizeTest
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class CrudAuthorizeTest extends CakeTestCase {
/**
* setup
*
* @return void
*/
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');
$this->auth = new CrudAuthorize($this->Components);
}
/**
* setup the mock acl.
*
* @return void
*/
protected function _mockAcl() {
$this->Components->expects($this->any())
->method('load')
->with('Acl')
->will($this->returnValue($this->Acl));
}
/**
* test authorize() without a mapped action, ensure an error is generated.
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testAuthorizeNoMappedAction() {
$request = new CakeRequest('/posts/foobar', false);
$request->addParams(array(
'controller' => 'posts',
'action' => 'foobar'
));
$user = array('User' => array('user' => 'mark'));
$this->auth->authorize($user, $request);
}
/**
* test check() passing
*
* @return void
*/
public function testAuthorizeCheckSuccess() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array(
'controller' => 'posts',
'action' => 'index'
));
$user = array('User' => array('user' => 'mark'));
$this->_mockAcl();
$this->Acl->expects($this->once())
->method('check')
->with($user, 'Posts', 'read')
->will($this->returnValue(true));
$this->assertTrue($this->auth->authorize($user['User'], $request));
}
/**
* test check() failing
*
* @return void
*/
public function testAuthorizeCheckFailure() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array(
'controller' => 'posts',
'action' => 'index'
));
$user = array('User' => array('user' => 'mark'));
$this->_mockAcl();
$this->Acl->expects($this->once())
->method('check')
->with($user, 'Posts', 'read')
->will($this->returnValue(false));
$this->assertFalse($this->auth->authorize($user['User'], $request));
}
/**
* test getting actionMap
*
* @return void
*/
public function testMapActionsGet() {
$result = $this->auth->mapActions();
$expected = array(
'create' => 'create',
'read' => 'read',
'update' => 'update',
'delete' => 'delete',
'index' => 'read',
'add' => 'create',
'edit' => 'update',
'view' => 'read',
'remove' => 'delete'
);
$this->assertEquals($expected, $result);
}
/**
* test adding into mapActions
*
* @return void
*/
public function testMapActionsSet() {
$map = array(
'create' => array('generate'),
'read' => array('listing', 'show'),
'update' => array('update'),
'random' => 'custom'
);
$result = $this->auth->mapActions($map);
$this->assertNull($result);
$result = $this->auth->mapActions();
$expected = array(
'add' => 'create',
'create' => 'create',
'read' => 'read',
'index' => 'read',
'edit' => 'update',
'view' => 'read',
'delete' => 'delete',
'remove' => 'delete',
'generate' => 'create',
'listing' => 'read',
'show' => 'read',
'update' => 'update',
'random' => 'custom',
);
$this->assertEquals($expected, $result);
}
/**
* test prefix routes getting auto mapped.
*
* @return void
*/
public function testAutoPrefixMapActions() {
Configure::write('Routing.prefixes', array('admin', 'manager'));
Router::reload();
$auth = new CrudAuthorize($this->Components);
$this->assertTrue(isset($auth->settings['actionMap']['admin_index']));
}
}

View file

@ -0,0 +1,310 @@
<?php
/**
* DigestAuthenticateTest 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.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('DigestAuthenticate', 'Controller/Component/Auth');
App::uses('AppModel', 'Model');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
/**
* Test case for DigestAuthentication
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class DigestAuthenticateTest extends CakeTestCase {
/**
* Fixtures
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user');
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Collection = $this->getMock('ComponentCollection');
$this->server = $_SERVER;
$this->auth = new DigestAuthenticate($this->Collection, array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User',
'realm' => 'localhost',
'nonce' => 123,
'opaque' => '123abc'
));
$password = DigestAuthenticate::password('mariano', 'cake', 'localhost');
$User = ClassRegistry::init('User');
$User->updateAll(array('password' => $User->getDataSource()->value($password)));
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->response = $this->getMock('CakeResponse');
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
$_SERVER = $this->server;
}
/**
* test applying settings in the constructor
*
* @return void
*/
public function testConstructor() {
$object = new DigestAuthenticate($this->Collection, array(
'userModel' => 'AuthUser',
'fields' => array('username' => 'user', 'password' => 'password'),
'nonce' => 123456
));
$this->assertEquals('AuthUser', $object->settings['userModel']);
$this->assertEquals(array('username' => 'user', 'password' => 'password'), $object->settings['fields']);
$this->assertEquals(123456, $object->settings['nonce']);
$this->assertEquals(env('SERVER_NAME'), $object->settings['realm']);
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$this->response->expects($this->never())
->method('header');
$this->assertFalse($this->auth->getUser($request, $this->response));
}
/**
* test the authenticate method
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateWrongUsername() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_DIGEST'] = <<<DIGEST
Digest username="incorrect_user",
realm="localhost",
nonce="123456",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="123abc"
DIGEST;
$this->auth->unauthenticated($request, $this->response);
}
/**
* test that challenge headers are sent when no credentials are found.
*
* @return void
*/
public function testAuthenticateChallenge() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
try {
$this->auth->unauthenticated($request, $this->response);
} catch (UnauthorizedException $e) {
}
$this->assertNotEmpty($e);
$expected = array('WWW-Authenticate: Digest realm="localhost",qop="auth",nonce="123",opaque="123abc"');
$this->assertEquals($expected, $e->responseHeader());
}
/**
* test authenticate success
*
* @return void
*/
public function testAuthenticateSuccess() {
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_DIGEST'] = <<<DIGEST
Digest username="mariano",
realm="localhost",
nonce="123",
uri="/dir/index.html",
qop=auth,
nc=1,
cnonce="123",
response="06b257a54befa2ddfb9bfa134224aa29",
opaque="123abc"
DIGEST;
$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);
}
/**
* test scope failure.
*
* @expectedException UnauthorizedException
* @expectedExceptionCode 401
* @return void
*/
public function testAuthenticateFailReChallenge() {
$this->auth->settings['scope'] = array('user' => 'nate');
$request = new CakeRequest('posts/index', false);
$request->addParams(array('pass' => array(), 'named' => array()));
$_SERVER['PHP_AUTH_DIGEST'] = <<<DIGEST
Digest username="mariano",
realm="localhost",
nonce="123",
uri="/dir/index.html",
qop=auth,
nc=1,
cnonce="123",
response="6629fae49393a05397450978507c4ef1",
opaque="123abc"
DIGEST;
$this->auth->unauthenticated($request, $this->response);
}
/**
* testParseDigestAuthData method
*
* @return void
*/
public function testParseAuthData() {
$digest = <<<DIGEST
Digest username="Mufasa",
realm="testrealm@host.com",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"
DIGEST;
$expected = array(
'username' => 'Mufasa',
'realm' => 'testrealm@host.com',
'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
'uri' => '/dir/index.html',
'qop' => 'auth',
'nc' => '00000001',
'cnonce' => '0a4f113b',
'response' => '6629fae49393a05397450978507c4ef1',
'opaque' => '5ccc069c403ebaf9f0171e9517f40e41'
);
$result = $this->auth->parseAuthData($digest);
$this->assertSame($expected, $result);
$result = $this->auth->parseAuthData('');
$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
*
* @return void
*/
public function testParseAuthEmailAddress() {
$digest = <<<DIGEST
Digest username="mark@example.com",
realm="testrealm@host.com",
nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
uri="/dir/index.html",
qop=auth,
nc=00000001,
cnonce="0a4f113b",
response="6629fae49393a05397450978507c4ef1",
opaque="5ccc069c403ebaf9f0171e9517f40e41"
DIGEST;
$expected = array(
'username' => 'mark@example.com',
'realm' => 'testrealm@host.com',
'nonce' => 'dcd98b7102dd2f0e8b11d0f600bfb0c093',
'uri' => '/dir/index.html',
'qop' => 'auth',
'nc' => '00000001',
'cnonce' => '0a4f113b',
'response' => '6629fae49393a05397450978507c4ef1',
'opaque' => '5ccc069c403ebaf9f0171e9517f40e41'
);
$result = $this->auth->parseAuthData($digest);
$this->assertSame($expected, $result);
}
/**
* test password hashing
*
* @return void
*/
public function testPassword() {
$result = DigestAuthenticate::password('mark', 'password', 'localhost');
$expected = md5('mark:localhost:password');
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,345 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Test.Case.Controller.Component.Auth
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('AuthComponent', 'Controller/Component');
App::uses('FormAuthenticate', 'Controller/Component/Auth');
App::uses('AppModel', 'Model');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
require_once CAKE . 'Test' . DS . 'Case' . DS . 'Model' . DS . 'models.php';
/**
* Test case for FormAuthentication
*
* @package Cake.Test.Case.Controller.Component.Auth
*/
class FormAuthenticateTest extends CakeTestCase {
/**
* Fixtrues
*
* @var array
*/
public $fixtures = array('core.user', 'core.auth_user');
/**
* setup
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Collection = $this->getMock('ComponentCollection');
$this->auth = new FormAuthenticate($this->Collection, array(
'fields' => array('username' => 'user', 'password' => 'password'),
'userModel' => 'User'
));
$password = Security::hash('password', null, true);
$User = ClassRegistry::init('User');
$User->updateAll(array('password' => $User->getDataSource()->value($password)));
$this->response = $this->getMock('CakeResponse');
}
/**
* test applying settings in the constructor
*
* @return void
*/
public function testConstructor() {
$object = new FormAuthenticate($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']);
}
/**
* test the authenticate method
*
* @return void
*/
public function testAuthenticateNoData() {
$request = new CakeRequest('posts/index', false);
$request->data = array();
$this->assertFalse($this->auth->authenticate($request, $this->response));
}
/**
* test the authenticate 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));
}
/**
* test the authenticate 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));
}
/**
* 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
*
* @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));
}
/**
* test authenticate success
*
* @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);
}
/**
* test scope failure.
*
* @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));
}
/**
* 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.
*
* @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(Configure::read('Security.salt') . 'cake');
$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' => 'cake'
));
$result = $this->auth->authenticate($request, $this->response);
$expected = array(
'id' => 1,
'username' => 'gwoo',
'created' => '2007-03-17 01:16:23'
);
$this->assertEquals(self::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

@ -0,0 +1,777 @@
<?php
/**
* CookieComponentTest file
*
* 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 1.2.0.5435
* @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
*
* @package Cake.Test.Case.Controller.Component
*/
class CookieComponentTestController extends Controller {
/**
* components property
*
* @var array
*/
public $components = array('Cookie');
/**
* beforeFilter method
*
* @return void
*/
public function beforeFilter() {
$this->Cookie->name = 'CakeTestCookie';
$this->Cookie->time = 10;
$this->Cookie->path = '/';
$this->Cookie->domain = '';
$this->Cookie->secure = false;
$this->Cookie->key = 'somerandomhaskey';
}
}
/**
* CookieComponentTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class CookieComponentTest extends CakeTestCase {
/**
* Controller property
*
* @var CookieComponentTestController
*/
public $Controller;
/**
* start
*
* @return void
*/
public function setUp() {
parent::setUp();
$_COOKIE = array();
$this->Controller = new CookieComponentTestController(new CakeRequest(), new CakeResponse());
$this->Controller->constructClasses();
$this->Cookie = $this->Controller->Cookie;
$this->Cookie->name = 'CakeTestCookie';
$this->Cookie->time = 10;
$this->Cookie->path = '/';
$this->Cookie->domain = '';
$this->Cookie->secure = false;
$this->Cookie->key = 'somerandomhaskey';
$this->Cookie->startup($this->Controller);
}
/**
* end
*
* @return void
*/
public function tearDown() {
parent::tearDown();
$this->Cookie->destroy();
}
/**
* sets up some default cookie data.
*
* @return void
*/
protected function _setCookieData() {
$this->Cookie->write(array('Encrytped_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')));
$this->Cookie->write(array('Encrytped_multi_cookies.name' => 'CakePHP'));
$this->Cookie->write(array('Encrytped_multi_cookies.version' => '1.2.0.x'));
$this->Cookie->write(array('Encrytped_multi_cookies.tag' => 'CakePHP Rocks!'));
$this->Cookie->write(array('Plain_array' => array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')), null, false);
$this->Cookie->write(array('Plain_multi_cookies.name' => 'CakePHP'), null, false);
$this->Cookie->write(array('Plain_multi_cookies.version' => '1.2.0.x'), null, false);
$this->Cookie->write(array('Plain_multi_cookies.tag' => 'CakePHP Rocks!'), null, false);
}
/**
* test that initialize sets settings from components array
*
* @return void
*/
public function testSettings() {
$settings = array(
'time' => '5 days',
'path' => '/'
);
$Cookie = new CookieComponent(new ComponentCollection(), $settings);
$this->assertEquals($Cookie->time, $settings['time']);
$this->assertEquals($Cookie->path, $settings['path']);
}
/**
* testCookieName
*
* @return void
*/
public function testCookieName() {
$this->assertEquals('CakeTestCookie', $this->Cookie->name);
}
/**
* testReadEncryptedCookieData
*
* @return void
*/
public function testReadEncryptedCookieData() {
$this->_setCookieData();
$data = $this->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
}
/**
* testReadPlainCookieData
*
* @return void
*/
public function testReadPlainCookieData() {
$this->_setCookieData();
$data = $this->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
}
/**
* test read() after switching the cookie name.
*
* @return void
*/
public function testReadWithNameSwitch() {
$_COOKIE = array(
'CakeTestCookie' => array(
'key' => 'value'
),
'OtherTestCookie' => array(
'key' => 'other value'
)
);
$this->assertEquals('value', $this->Cookie->read('key'));
$this->Cookie->name = 'OtherTestCookie';
$this->assertEquals('other value', $this->Cookie->read('key'));
}
/**
* test a simple write()
*
* @return void
*/
public function testWriteSimple() {
$this->Cookie->write('Testing', 'value');
$result = $this->Cookie->read('Testing');
$this->assertEquals('value', $result);
}
/**
* test write() encrypted data with falsey value
*
* @return void
*/
public function testWriteWithFalseyValue() {
$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
*
* @return void
*/
public function testWriteHttpOnly() {
$this->Cookie->httpOnly = true;
$this->Cookie->secure = false;
$this->Cookie->write('Testing', 'value', false);
$expected = array(
'name' => $this->Cookie->name . '[Testing]',
'value' => 'value',
'expire' => time() + 10,
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => true);
$result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]');
$this->assertEquals($expected, $result);
}
/**
* test delete with httpOnly
*
* @return void
*/
public function testDeleteHttpOnly() {
$this->Cookie->httpOnly = true;
$this->Cookie->secure = false;
$this->Cookie->delete('Testing', false);
$expected = array(
'name' => $this->Cookie->name . '[Testing]',
'value' => '',
'expire' => time() - 42000,
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => true);
$result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]');
$this->assertEquals($expected, $result);
}
/**
* testWritePlainCookieArray
*
* @return void
*/
public function testWritePlainCookieArray() {
$this->Cookie->write(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!'), null, false);
$this->assertEquals('CakePHP', $this->Cookie->read('name'));
$this->assertEquals('1.2.0.x', $this->Cookie->read('version'));
$this->assertEquals('CakePHP Rocks!', $this->Cookie->read('tag'));
$this->Cookie->delete('name');
$this->Cookie->delete('version');
$this->Cookie->delete('tag');
}
/**
* test writing values that are not scalars
*
* @return void
*/
public function testWriteArrayValues() {
$this->Cookie->secure = false;
$this->Cookie->write('Testing', array(1, 2, 3), false);
$expected = array(
'name' => $this->Cookie->name . '[Testing]',
'value' => '[1,2,3]',
'path' => '/',
'domain' => '',
'secure' => false,
'httpOnly' => false);
$result = $this->Controller->response->cookie($this->Cookie->name . '[Testing]');
$this->assertWithinMargin($result['expire'], time() + 10, 1);
unset($result['expire']);
$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
*
* @return void
*/
public function testReadingCookieValue() {
$this->_setCookieData();
$data = $this->Cookie->read();
$expected = array(
'Encrytped_array' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Encrytped_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Plain_array' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'),
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$this->assertEquals($expected, $data);
}
/**
* testDeleteCookieValue
*
* @return void
*/
public function testDeleteCookieValue() {
$this->_setCookieData();
$this->Cookie->delete('Encrytped_multi_cookies.name');
$data = $this->Cookie->read('Encrytped_multi_cookies');
$expected = array('version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$this->Cookie->delete('Encrytped_array');
$data = $this->Cookie->read('Encrytped_array');
$this->assertNull($data);
$this->Cookie->delete('Plain_multi_cookies.name');
$data = $this->Cookie->read('Plain_multi_cookies');
$expected = array('version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$this->Cookie->delete('Plain_array');
$data = $this->Cookie->read('Plain_array');
$this->assertNull($data);
}
/**
* testReadingCookieArray
*
* @return void
*/
public function testReadingCookieArray() {
$this->_setCookieData();
$data = $this->Cookie->read('Encrytped_array.name');
$expected = 'CakePHP';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_array.version');
$expected = '1.2.0.x';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_array.tag');
$expected = 'CakePHP Rocks!';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies.name');
$expected = 'CakePHP';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies.version');
$expected = '1.2.0.x';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies.tag');
$expected = 'CakePHP Rocks!';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array.name');
$expected = 'CakePHP';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array.version');
$expected = '1.2.0.x';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array.tag');
$expected = 'CakePHP Rocks!';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies.name');
$expected = 'CakePHP';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies.version');
$expected = '1.2.0.x';
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies.tag');
$expected = 'CakePHP Rocks!';
$this->assertEquals($expected, $data);
}
/**
* testReadingCookieDataOnStartup
*
* @return void
*/
public function testReadingCookieDataOnStartup() {
$data = $this->Cookie->read('Encrytped_array');
$this->assertNull($data);
$data = $this->Cookie->read('Encrytped_multi_cookies');
$this->assertNull($data);
$data = $this->Cookie->read('Plain_array');
$this->assertNull($data);
$data = $this->Cookie->read('Plain_multi_cookies');
$this->assertNull($data);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->_encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->_encrypt('CakePHP'),
'version' => $this->_encrypt('1.2.0.x'),
'tag' => $this->_encrypt('CakePHP Rocks!')),
'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$this->Cookie->startup(new CookieComponentTestController());
$data = $this->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$this->Cookie->destroy();
unset($_COOKIE['CakeTestCookie']);
}
/**
* testReadingCookieDataWithoutStartup
*
* @return void
*/
public function testReadingCookieDataWithoutStartup() {
$data = $this->Cookie->read('Encrytped_array');
$expected = null;
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies');
$expected = null;
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array');
$expected = null;
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies');
$expected = null;
$this->assertEquals($expected, $data);
$_COOKIE['CakeTestCookie'] = array(
'Encrytped_array' => $this->_encrypt(array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!')),
'Encrytped_multi_cookies' => array(
'name' => $this->_encrypt('CakePHP'),
'version' => $this->_encrypt('1.2.0.x'),
'tag' => $this->_encrypt('CakePHP Rocks!')),
'Plain_array' => '{"name":"CakePHP","version":"1.2.0.x","tag":"CakePHP Rocks!"}',
'Plain_multi_cookies' => array(
'name' => 'CakePHP',
'version' => '1.2.0.x',
'tag' => 'CakePHP Rocks!'));
$data = $this->Cookie->read('Encrytped_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Encrytped_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_array');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$data = $this->Cookie->read('Plain_multi_cookies');
$expected = array('name' => 'CakePHP', 'version' => '1.2.0.x', 'tag' => 'CakePHP Rocks!');
$this->assertEquals($expected, $data);
$this->Cookie->destroy();
unset($_COOKIE['CakeTestCookie']);
}
/**
* Test Reading legacy cookie values.
*
* @return void
*/
public function testReadLegacyCookieValue() {
$_COOKIE['CakeTestCookie'] = array(
'Legacy' => array('value' => $this->_oldImplode(array(1, 2, 3)))
);
$result = $this->Cookie->read('Legacy.value');
$expected = array(1, 2, 3);
$this->assertEquals($expected, $result);
}
/**
* Test reading empty values.
*
* @return void
*/
public function testReadEmpty() {
$_COOKIE['CakeTestCookie'] = array(
'JSON' => '{"name":"value"}',
'Empty' => '',
'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'));
}
/**
* test that no error is issued for non array data.
*
* @return void
*/
public function testNoErrorOnNonArrayData() {
$this->Cookie->destroy();
$_COOKIE['CakeTestCookie'] = 'kaboom';
$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.
*
* @return void
*/
public function testDeleteRemovesChildren() {
$_COOKIE['CakeTestCookie'] = array(
'User' => array('email' => 'example@example.com', 'name' => 'mark'),
'other' => 'value'
);
$this->assertEquals('mark', $this->Cookie->read('User.name'));
$this->Cookie->delete('User');
$this->assertNull($this->Cookie->read('User.email'));
$this->Cookie->destroy();
}
/**
* Test deleting recursively with keys that don't exist.
*
* @return void
*/
public function testDeleteChildrenNotExist() {
$this->assertNull($this->Cookie->delete('NotFound'));
$this->assertNull($this->Cookie->delete('Not.Found'));
}
/**
* Helper method for generating old style encoded cookie values.
*
* @return string.
*/
protected function _oldImplode(array $array) {
$string = '';
foreach ($array as $key => $value) {
$string .= ',' . $key . '|' . $value;
}
return substr($string, 1);
}
/**
* Implode method to keep keys are multidimensional arrays
*
* @param array $array Map of key and values
* @return string String in the form key1|value1,key2|value2
*/
protected function _implode(array $array) {
return json_encode($array);
}
/**
* encrypt method
*
* @param array|string $value
* @return string
*/
protected function _encrypt($value) {
if (is_array($value)) {
$value = $this->_implode($value);
}
return "Q2FrZQ==." . base64_encode(Security::cipher($value, $this->Cookie->key));
}
}

View file

@ -0,0 +1,881 @@
<?php
/**
* EmailComponentTest file
*
* Series of tests for email 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 1.2.0.5347
* @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');
/**
* EmailTestComponent class
*
* @package Cake.Test.Case.Controller.Component
*/
class EmailTestComponent extends EmailComponent {
/**
* Convenience method for testing.
*
* @return string
*/
public function strip($content, $message = false) {
return parent::_strip($content, $message);
}
}
/**
* DebugCompTransport class
*
* @package Cake.Test.Case.Controller.Component
*/
class DebugCompTransport extends AbstractTransport {
/**
* Last email
*
* @var string
*/
public static $lastEmail = null;
/**
* Send mail
*
* @params object $email CakeEmail
* @return bool
*/
public function send(CakeEmail $email) {
$email->addHeaders(array('Date' => EmailComponentTest::$sentDate));
$headers = $email->getHeaders(array_fill_keys(array('from', 'replyTo', 'readReceipt', 'returnPath', 'to', 'cc', 'bcc', 'subject'), true));
$to = $headers['To'];
$subject = $headers['Subject'];
unset($headers['To'], $headers['Subject']);
$message = implode("\n", $email->message());
$last = '<pre>';
$last .= sprintf("%s %s\n", 'To:', $to);
$last .= sprintf("%s %s\n", 'From:', $headers['From']);
$last .= sprintf("%s %s\n", 'Subject:', $subject);
$last .= sprintf("%s\n\n%s", 'Header:', $this->_headersToString($headers, "\n"));
$last .= sprintf("%s\n\n%s", 'Message:', $message);
$last .= '</pre>';
self::$lastEmail = $last;
return true;
}
}
/**
* EmailTestController class
*
* @package Cake.Test.Case.Controller.Component
*/
class EmailTestController extends Controller {
/**
* uses property
*
* @var mixed
*/
public $uses = null;
/**
* components property
*
* @var array
*/
public $components = array('Session', 'EmailTest');
}
/**
* EmailTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class EmailComponentTest extends CakeTestCase {
/**
* Controller property
*
* @var EmailTestController
*/
public $Controller;
/**
* name property
*
* @var string
*/
public $name = 'Email';
/**
* sentDate
*
* @var string
*/
public static $sentDate = null;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('App.encoding', 'UTF-8');
$this->Controller = new EmailTestController();
$this->Controller->Components->init($this->Controller);
$this->Controller->EmailTest->initialize($this->Controller, array());
self::$sentDate = date(DATE_RFC2822);
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
}
/**
* testSendFormats method
*
* @return void
*/
public function testSendFormats() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->messageId = false;
$date = self::$sentDate;
$message = <<<MSGBLOC
<pre>To: postmaster@example.com
From: noreply@example.com
Subject: Cake SMTP test
Header:
From: noreply@example.com
Reply-To: noreply@example.com
X-Mailer: CakePHP Email Component
Date: $date
MIME-Version: 1.0
Content-Type: {CONTENTTYPE}
Content-Transfer-Encoding: 8bitMessage:
This is the body of the message
</pre>
MSGBLOC;
$this->Controller->EmailTest->sendAs = 'text';
$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($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'html';
$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($expected, DebugCompTransport::$lastEmail);
}
/**
* testTemplates method
*
* @return void
*/
public function testTemplates() {
ClassRegistry::flush();
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->messageId = false;
$date = self::$sentDate;
$header = <<<HEADBLOC
To: postmaster@example.com
From: noreply@example.com
Subject: Cake SMTP test
Header:
From: noreply@example.com
Reply-To: noreply@example.com
X-Mailer: CakePHP Email Component
Date: $date
MIME-Version: 1.0
Content-Type: {CONTENTTYPE}
Content-Transfer-Encoding: 8bitMessage:
HEADBLOC;
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = 'default';
$this->Controller->set('title_for_layout', 'Email Test');
$text = <<<TEXTBLOC
This is the body of the message
This email was sent using the CakePHP Framework, http://cakephp.org.
TEXTBLOC;
$html = <<<HTMLBLOC
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Email Test</title>
</head>
<body>
<p> This is the body of the message</p><p> </p>
<p>This email was sent using the <a href="http://cakephp.org">CakePHP Framework</a></p>
</body>
</html>
HTMLBLOC;
$this->Controller->EmailTest->sendAs = 'text';
$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($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'html';
$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($expected, DebugCompTransport::$lastEmail);
$this->Controller->EmailTest->sendAs = 'both';
$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" .
'--{boundary}' . "\n" .
'Content-Type: text/html; charset=UTF-8' . "\n" .
'Content-Transfer-Encoding: 8bit' . "\n\n" .
$html .
"\n\n\n" .
'--{boundary}--' . "\n";
$expected = '<pre>' . $expected . '</pre>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals(
$expected,
preg_replace('/[a-z0-9]{32}/i', '{boundary}', DebugCompTransport::$lastEmail)
);
$html = <<<HTMLBLOC
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Email Test</title>
</head>
<body>
<p> This is the body of the message</p><p> </p>
<p>This email was sent using the CakePHP Framework</p>
</body>
</html>
HTMLBLOC;
$this->Controller->EmailTest->sendAs = 'html';
$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($expected, DebugCompTransport::$lastEmail);
}
/**
* test that elements used in email templates get helpers.
*
* @return void
*/
public function testTemplateNestedElements() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake SMTP test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->messageId = false;
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = 'nested_element';
$this->Controller->EmailTest->sendAs = 'html';
$this->Controller->helpers = array('Html');
$this->Controller->EmailTest->send();
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/Test/', $result);
$this->assertRegExp('/http\:\/\/example\.com/', $result);
}
/**
* testSendDebug method
*
* @return void
*/
public function testSendDebug() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->cc = 'cc@example.com';
$this->Controller->EmailTest->bcc = 'bcc@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/To: postmaster@example.com\n/', $result);
$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('/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('/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);
$this->assertRegExp('/This is the body of the message/', $result);
}
/**
* test send with delivery = debug and not using sessions.
*
* @return void
*/
public function testSendDebugWithNoSessions() {
$session = $this->Controller->Session;
unset($this->Controller->Session);
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->send('This is the body of the message');
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/To: postmaster@example.com\n/', $result);
$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('/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);
$this->assertRegExp('/This is the body of the message/', $result);
$this->Controller->Session = $session;
}
/**
* testMessageRetrievalWithoutTemplate method
*
* @return void
*/
public function testMessageRetrievalWithoutTemplate() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$text = $html = "This is the body of the message\n";
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals($this->Controller->EmailTest->textMessage, $text);
$this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html);
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertTextEquals($this->Controller->EmailTest->textMessage, $text);
$this->assertNull($this->Controller->EmailTest->htmlMessage);
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$this->assertNull($this->Controller->EmailTest->textMessage);
$this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html);
}
/**
* testMessageRetrievalWithTemplate method
*
* @return void
*/
public function testMessageRetrievalWithTemplate() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$this->Controller->set('value', 22091985);
$this->Controller->set('title_for_layout', 'EmailTest');
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = 'custom';
$this->Controller->EmailTest->delivery = 'DebugComp';
$text = <<<TEXTBLOC
Here is your value: 22091985
This email was sent using the CakePHP Framework, http://cakephp.org.
TEXTBLOC;
$html = <<<HTMLBLOC
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>EmailTest</title>
</head>
<body>
<p>Here is your value: <b>22091985</b></p>
<p>This email was sent using the <a href="http://cakephp.org">CakePHP Framework</a></p>
</body>
</html>
HTMLBLOC;
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send());
$this->assertTextEquals($this->Controller->EmailTest->textMessage, $text);
$this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html);
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send());
$this->assertTextEquals($this->Controller->EmailTest->textMessage, $text);
$this->assertNull($this->Controller->EmailTest->htmlMessage);
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send());
$this->assertNull($this->Controller->EmailTest->textMessage);
$this->assertTextEquals($this->Controller->EmailTest->htmlMessage, $html);
}
/**
* testMessageRetrievalWithHelper method
*
* @return void
*/
public function testMessageRetrievalWithHelper() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$timestamp = time();
$this->Controller->set('time', $timestamp);
$this->Controller->set('title_for_layout', 'EmailTest');
$this->Controller->helpers = array('Time');
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->layout = 'default';
$this->Controller->EmailTest->template = 'custom_helper';
$this->Controller->EmailTest->sendAs = 'text';
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send());
$this->assertTrue((bool)strpos($this->Controller->EmailTest->textMessage, 'Right now: ' . date('Y-m-d\TH:i:s\Z', $timestamp)));
}
/**
* testContentArray method
*
* @return void
*/
public function testSendContentArray() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$content = array('First line', 'Second line', 'Third line');
$this->assertTrue($this->Controller->EmailTest->send($content));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/To: postmaster@example.com\n/', $result);
$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('/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);
$this->assertRegExp('/First line\n/', $result);
$this->assertRegExp('/Second line\n/', $result);
$this->assertRegExp('/Third line\n/', $result);
}
/**
* test setting a custom date.
*
* @return void
*/
public function testDateProperty() {
$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->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send('test message'));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/Date: Today!\n/', $result);
}
/**
* testContentStripping method
*
* @return void
*/
public function testContentStripping() {
$content = "Previous content\n--alt-\nContent-TypeContent-Type:: text/html; charsetcharset==utf-8\nContent-Transfer-Encoding: 8bit";
$content .= "\n\n<p>My own html content</p>";
$result = $this->Controller->EmailTest->strip($content, true);
$expected = "Previous content\n--alt-\n text/html; utf-8\n 8bit\n\n<p>My own html content</p>";
$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);
$expected = $content;
$this->assertEquals($expected, $result);
$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);
$expected = $content;
$this->assertEquals($expected, $result);
}
/**
* test that the _encode() will set mb_internal_encoding.
*
* @return void
*/
public function testEncodeSettingInternalCharset() {
$this->skipIf(!function_exists('mb_internal_encoding'), 'Missing mb_* functions, cannot run test.');
$restore = mb_internal_encoding();
mb_internal_encoding('ISO-8859-1');
$this->Controller->charset = 'UTF-8';
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$subject = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches);
$this->assertEquals(trim($matches[1]), $subject);
$result = mb_internal_encoding();
$this->assertEquals('ISO-8859-1', $result);
mb_internal_encoding($restore);
}
/**
* testMultibyte method
*
* @return void
*/
public function testMultibyte() {
$this->Controller->charset = 'UTF-8';
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'هذه رسالة بعنوان طويل مرسل للمستلم';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$subject = '=?UTF-8?B?2YfYsNmHINix2LPYp9mE2Kkg2KjYudmG2YjYp9mGINi32YjZitmEINmF2LE=?=' . "\r\n" . ' =?UTF-8?B?2LPZhCDZhNmE2YXYs9iq2YTZhQ==?=';
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches);
$this->assertEquals(trim($matches[1]), $subject);
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches);
$this->assertEquals(trim($matches[1]), $subject);
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
preg_match('/Subject: (.*)Header:/s', DebugCompTransport::$lastEmail, $matches);
$this->assertEquals(trim($matches[1]), $subject);
}
/**
* undocumented function
*
* @return void
*/
public function testSendWithAttachments() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Attachment Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->attachments = array(
__FILE__,
'some-name.php' => __FILE__
);
$body = '<p>This is the body of the message</p>';
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = DebugCompTransport::$lastEmail;
$this->assertRegExp('/' . preg_quote('Content-Disposition: attachment; filename="EmailComponentTest.php"') . '/', $msg);
$this->assertRegExp('/' . preg_quote('Content-Disposition: attachment; filename="some-name.php"') . '/', $msg);
}
/**
* testSendAsIsNotIgnoredIfAttachmentsPresent method
*
* @return void
*/
public function testSendAsIsNotIgnoredIfAttachmentsPresent() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Attachment Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->Controller->EmailTest->attachments = array(__FILE__);
$body = '<p>This is the body of the message</p>';
$this->Controller->EmailTest->sendAs = 'html';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = DebugCompTransport::$lastEmail;
$this->assertNotRegExp('/text\/plain/', $msg);
$this->assertRegExp('/text\/html/', $msg);
$this->Controller->EmailTest->sendAs = 'text';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = DebugCompTransport::$lastEmail;
$this->assertRegExp('/text\/plain/', $msg);
$this->assertNotRegExp('/text\/html/', $msg);
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = DebugCompTransport::$lastEmail;
$this->assertRegExp('/text\/plain/', $msg);
$this->assertRegExp('/text\/html/', $msg);
$this->assertRegExp('/multipart\/alternative/', $msg);
}
/**
* testNoDoubleNewlinesInHeaders function
*
* @return void
*/
public function testNoDoubleNewlinesInHeaders() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Attachment Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$body = '<p>This is the body of the message</p>';
$this->Controller->EmailTest->sendAs = 'both';
$this->assertTrue($this->Controller->EmailTest->send($body));
$msg = DebugCompTransport::$lastEmail;
$this->assertNotRegExp('/\n\nContent-Transfer-Encoding/', $msg);
$this->assertRegExp('/\nContent-Transfer-Encoding/', $msg);
}
/**
* testReset method
*
* @return void
*/
public function testReset() {
$this->Controller->EmailTest->template = 'default';
$this->Controller->EmailTest->to = 'test.recipient@example.com';
$this->Controller->EmailTest->from = 'test.sender@example.com';
$this->Controller->EmailTest->replyTo = 'test.replyto@example.com';
$this->Controller->EmailTest->return = 'test.return@example.com';
$this->Controller->EmailTest->cc = array('cc1@example.com', 'cc2@example.com');
$this->Controller->EmailTest->bcc = array('bcc1@example.com', 'bcc2@example.com');
$this->Controller->EmailTest->date = 'Today!';
$this->Controller->EmailTest->subject = 'Test subject';
$this->Controller->EmailTest->additionalParams = 'X-additional-header';
$this->Controller->EmailTest->delivery = 'smtp';
$this->Controller->EmailTest->smtpOptions['host'] = 'blah';
$this->Controller->EmailTest->smtpOptions['timeout'] = 0.2;
$this->Controller->EmailTest->attachments = array('attachment1', 'attachment2');
$this->Controller->EmailTest->textMessage = 'This is the body of the message';
$this->Controller->EmailTest->htmlMessage = 'This is the body of the message';
$this->Controller->EmailTest->messageId = false;
try {
$this->Controller->EmailTest->send('Should not work');
$this->fail('No exception');
} catch (SocketException $e) {
$this->assertTrue(true, 'SocketException raised');
}
$this->Controller->EmailTest->reset();
$this->assertNull($this->Controller->EmailTest->template);
$this->assertSame($this->Controller->EmailTest->to, array());
$this->assertNull($this->Controller->EmailTest->from);
$this->assertNull($this->Controller->EmailTest->replyTo);
$this->assertNull($this->Controller->EmailTest->return);
$this->assertSame($this->Controller->EmailTest->cc, array());
$this->assertSame($this->Controller->EmailTest->bcc, array());
$this->assertNull($this->Controller->EmailTest->date);
$this->assertNull($this->Controller->EmailTest->subject);
$this->assertNull($this->Controller->EmailTest->additionalParams);
$this->assertNull($this->Controller->EmailTest->smtpError);
$this->assertSame($this->Controller->EmailTest->attachments, array());
$this->assertNull($this->Controller->EmailTest->textMessage);
$this->assertTrue($this->Controller->EmailTest->messageId);
$this->assertEquals('mail', $this->Controller->EmailTest->delivery);
}
public function testPluginCustomViewClass() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$this->Controller->view = 'TestPlugin.Email';
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'CustomViewClass test';
$this->Controller->EmailTest->delivery = 'DebugComp';
$body = 'Body of message';
$this->assertTrue($this->Controller->EmailTest->send($body));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/Body of message/', $result);
}
/**
* testStartup method
*
* @return void
*/
public function testStartup() {
$this->assertNull($this->Controller->EmailTest->startup($this->Controller));
}
/**
* testMessageId method
*
* @return void
*/
public function testMessageId() {
$this->Controller->EmailTest->to = 'postmaster@example.com';
$this->Controller->EmailTest->from = 'noreply@example.com';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$result = DebugCompTransport::$lastEmail;
$host = env('HTTP_HOST') ? env('HTTP_HOST') : php_uname('n');
$this->assertRegExp('/Message-ID: \<[a-f0-9]{8}[a-f0-9]{4}[a-f0-9]{4}[a-f0-9]{4}[a-f0-9]{12}@' . $host . '\>\n/', $result);
$this->Controller->EmailTest->messageId = '<22091985.998877@example.com>';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$result = DebugCompTransport::$lastEmail;
$this->assertRegExp('/Message-ID: <22091985.998877@example.com>\n/', $result);
$this->Controller->EmailTest->messageId = false;
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$result = DebugCompTransport::$lastEmail;
$this->assertNotRegExp('/Message-ID:/', $result);
}
/**
* 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>';
$this->Controller->EmailTest->from = 'Teßt <test@example.com>';
$this->Controller->EmailTest->subject = 'Cake Debug Test';
$this->Controller->EmailTest->replyTo = 'noreply@example.com';
$this->Controller->EmailTest->template = null;
$this->Controller->EmailTest->delivery = 'DebugComp';
$this->assertTrue($this->Controller->EmailTest->send('This is the body of the message'));
$result = DebugCompTransport::$lastEmail;
$this->assertContains('From: =?UTF-8?B?VGXDn3Qg?= <test@example.com>', $result);
$this->assertContains('To: =?UTF-8?B?VGXDn3Qg?= <test@example.com>', $result);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,967 @@
<?php
/**
* RequestHandlerComponentTest file
*
* 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 1.2.0.5435
* @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
*
* @package Cake.Test.Case.Controller.Component
*/
class RequestHandlerTestController extends Controller {
/**
* uses property
*
* @var mixed
*/
public $uses = null;
/**
* test method for ajax redirection
*
* @return void
*/
public function destination() {
$this->viewPath = 'Posts';
$this->render('index');
}
/**
* test method for ajax redirection + parameter parsing
*
* @return void
*/
public function param_method($one = null, $two = null) {
echo "one: $one two: $two";
$this->autoRender = false;
}
/**
* test method for testing layout rendering when isAjax()
*
* @return void
*/
public function ajax2_layout() {
if ($this->autoLayout) {
$this->layout = 'ajax2';
}
$this->destination();
}
}
/**
* CustomJsonView class
*
* @package Cake.Test.Case.Controller.Component
*/
class CustomJsonView extends JsonView {
}
/**
* RequestHandlerComponentTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class RequestHandlerComponentTest extends CakeTestCase {
/**
* Controller property
*
* @var RequestHandlerTestController
*/
public $Controller;
/**
* RequestHandler property
*
* @var RequestHandlerComponent
*/
public $RequestHandler;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->_init();
}
/**
* init method
*
* @return void
*/
protected function _init() {
$request = new CakeRequest('controller_posts/index');
$response = new CakeResponse();
$this->Controller = new RequestHandlerTestController($request, $response);
$this->Controller->constructClasses();
$this->RequestHandler = new RequestHandlerComponent($this->Controller->Components);
$this->_extensions = Router::extensions();
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->RequestHandler, $this->Controller);
if (!headers_sent()) {
header('Content-type: text/html'); //reset content type.
}
call_user_func_array('Router::parseExtensions', $this->_extensions);
}
/**
* Test that the constructor sets the settings.
*
* @return void
*/
public function testConstructorSettings() {
$settings = array(
'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']);
}
/**
* testInitializeCallback method
*
* @return void
*/
public function testInitializeCallback() {
$this->assertNull($this->RequestHandler->ext);
$this->Controller->request->params['ext'] = 'rss';
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('rss', $this->RequestHandler->ext);
}
/**
* test that a mapped Accept-type header will set $this->ext correctly.
*
* @return void
*/
public function testInitializeContentTypeSettingExt() {
$this->assertNull($this->RequestHandler->ext);
$_SERVER['HTTP_ACCEPT'] = 'application/json';
Router::parseExtensions('json');
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $this->RequestHandler->ext);
}
/**
* Test that RequestHandler sets $this->ext when jQuery sends its wonky-ish headers.
*
* @return void
*/
public function testInitializeContentTypeWithjQueryAccept() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, application/javascript, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('json');
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $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
*
* @return void
*/
public function testInitializeContentTypeWithjQueryAcceptAndMultiplesExtensions() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, application/javascript, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('rss', 'json');
$this->RequestHandler->initialize($this->Controller);
$this->assertEquals('json', $this->RequestHandler->ext);
}
/**
* Test that RequestHandler does not set $this->ext when multiple accepts are sent.
*
* @return void
*/
public function testInitializeNoContentTypeWithSingleAccept() {
$_SERVER['HTTP_ACCEPT'] = 'application/json, text/html, */*; q=0.01';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('json');
$this->RequestHandler->initialize($this->Controller);
$this->assertNull($this->RequestHandler->ext);
}
/**
* 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, 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);
}
/**
* Test that ext is not set with confusing android accepts headers.
*
* @return void
*/
public function testInitializeAmbiguousAndroidAccepts() {
$_SERVER['HTTP_ACCEPT'] = 'application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->assertNull($this->RequestHandler->ext);
Router::parseExtensions('html', 'xml');
$this->RequestHandler->initialize($this->Controller);
$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
*
* @return void
*/
public function testInitializeContentTypeAndExtensionMismatch() {
$this->assertNull($this->RequestHandler->ext);
$extensions = Router::extensions();
Router::parseExtensions('xml');
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->request->expects($this->any())
->method('accepts')
->will($this->returnValue(array('application/json')));
$this->RequestHandler->initialize($this->Controller);
$this->assertNull($this->RequestHandler->ext);
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
*
* @return void
*/
public function testDisabling() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->_init();
$this->RequestHandler->initialize($this->Controller);
$this->Controller->beforeFilter();
$this->RequestHandler->startup($this->Controller);
$this->assertEquals(true, $this->Controller->params['isAjax']);
}
/**
* testAutoAjaxLayout method
*
* @return void
*/
public function testAutoAjaxLayout() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->RequestHandler->startup($this->Controller);
$this->assertEquals($this->Controller->layout, $this->RequestHandler->ajaxLayout);
$this->_init();
$this->Controller->request->params['ext'] = 'js';
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$this->assertNotEquals('ajax', $this->Controller->layout);
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
}
/**
* testStartupCallback method
*
* @return void
*/
public function testStartupCallback() {
$_SERVER['REQUEST_METHOD'] = 'PUT';
$_SERVER['CONTENT_TYPE'] = 'application/xml';
$this->Controller->request = $this->getMock('CakeRequest', array('_readInput'));
$this->RequestHandler->startup($this->Controller);
$this->assertTrue(is_array($this->Controller->data));
$this->assertFalse(is_object($this->Controller->data));
}
/**
* testStartupCallback with charset.
*
* @return void
*/
public function testStartupCallbackCharset() {
$_SERVER['REQUEST_METHOD'] = 'PUT';
$_SERVER['CONTENT_TYPE'] = 'application/xml; charset=UTF-8';
$this->Controller->request = $this->getMock('CakeRequest', array('_readInput'));
$this->RequestHandler->startup($this->Controller);
$this->assertTrue(is_array($this->Controller->data));
$this->assertFalse(is_object($this->Controller->data));
}
/**
* Test mapping a new type and having startup process it.
*
* @return void
*/
public function testStartupCustomTypeProcess() {
if (!function_exists('str_getcsv')) {
$this->markTestSkipped('Need "str_getcsv" for this test.');
}
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['CONTENT_TYPE'] = 'text/csv';
$this->Controller->request = $this->getMock('CakeRequest', array('_readInput'));
$this->Controller->request->expects($this->once())
->method('_readInput')
->will($this->returnValue('"A","csv","string"'));
$this->RequestHandler->addInputType('csv', array('str_getcsv'));
$this->RequestHandler->startup($this->Controller);
$expected = array(
'A', 'csv', 'string'
);
$this->assertEquals($expected, $this->Controller->request->data);
}
/**
* testNonAjaxRedirect method
*
* @return void
*/
public function testNonAjaxRedirect() {
$this->RequestHandler->initialize($this->Controller);
$this->RequestHandler->startup($this->Controller);
$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
*
* @return void
*/
public function testRenderAs() {
$this->assertFalse(in_array('Rss', $this->Controller->helpers));
$this->RequestHandler->renderAs($this->Controller, 'rss');
$this->assertTrue(in_array('Rss', $this->Controller->helpers));
$this->Controller->viewPath = 'request_handler_test\\rss';
$this->RequestHandler->renderAs($this->Controller, 'js');
$this->assertEquals('request_handler_test' . DS . 'js', $this->Controller->viewPath);
}
/**
* test that attachment headers work with renderAs
*
* @return void
*/
public function testRenderAsWithAttachment() {
$this->RequestHandler->request = $this->getMock('CakeRequest');
$this->RequestHandler->request->expects($this->any())
->method('parseAccept')
->will($this->returnValue(array('1.0' => array('application/xml'))));
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download', 'charset'));
$this->RequestHandler->response->expects($this->at(0))
->method('type')
->with('application/xml');
$this->RequestHandler->response->expects($this->at(1))
->method('charset')
->with('UTF-8');
$this->RequestHandler->response->expects($this->at(2))
->method('download')
->with('myfile.xml');
$this->RequestHandler->renderAs($this->Controller, 'xml', array('attachment' => 'myfile.xml'));
$this->assertEquals('Xml', $this->Controller->viewClass);
}
/**
* test that respondAs works as expected.
*
* @return void
*/
public function testRespondAs() {
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type'));
$this->RequestHandler->response->expects($this->at(0))->method('type')
->with('application/json');
$this->RequestHandler->response->expects($this->at(1))->method('type')
->with('text/xml');
$result = $this->RequestHandler->respondAs('json');
$this->assertTrue($result);
$result = $this->RequestHandler->respondAs('text/xml');
$this->assertTrue($result);
}
/**
* test that attachment headers work with respondAs
*
* @return void
*/
public function testRespondAsWithAttachment() {
$this->RequestHandler = $this->getMock(
'RequestHandlerComponent',
array('_header'),
array(&$this->Controller->Components)
);
$this->RequestHandler->response = $this->getMock('CakeResponse', array('type', 'download'));
$this->RequestHandler->request = $this->getMock('CakeRequest');
$this->RequestHandler->request->expects($this->once())
->method('parseAccept')
->will($this->returnValue(array('1.0' => array('application/xml'))));
$this->RequestHandler->response->expects($this->once())->method('download')
->with('myfile.xml');
$this->RequestHandler->response->expects($this->once())->method('type')
->with('application/xml');
$result = $this->RequestHandler->respondAs('xml', array('attachment' => 'myfile.xml'));
$this->assertTrue($result);
}
/**
* test that calling renderAs() more than once continues to work.
*
* @link #6466
* @return void
*/
public function testRenderAsCalledTwice() {
$this->RequestHandler->renderAs($this->Controller, 'print');
$this->assertEquals('RequestHandlerTest' . DS . 'print', $this->Controller->viewPath);
$this->assertEquals('print', $this->Controller->layoutPath);
$this->RequestHandler->renderAs($this->Controller, 'js');
$this->assertEquals('RequestHandlerTest' . DS . 'js', $this->Controller->viewPath);
$this->assertEquals('js', $this->Controller->layoutPath);
$this->assertTrue(in_array('Js', $this->Controller->helpers));
}
/**
* testRequestClientTypes method
*
* @return void
*/
public function testRequestClientTypes() {
$_SERVER['HTTP_X_PROTOTYPE_VERSION'] = '1.5';
$this->assertEquals('1.5', $this->RequestHandler->getAjaxVersion());
unset($_SERVER['HTTP_X_REQUESTED_WITH'], $_SERVER['HTTP_X_PROTOTYPE_VERSION']);
$this->assertFalse($this->RequestHandler->getAjaxVersion());
}
/**
* Tests the detection of various Flash versions
*
* @return void
*/
public function testFlashDetection() {
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('flash')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isFlash());
}
/**
* testRequestContentTypes method
*
* @return void
*/
public function testRequestContentTypes() {
$_SERVER['REQUEST_METHOD'] = 'GET';
$this->assertNull($this->RequestHandler->requestedWith());
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['CONTENT_TYPE'] = 'application/json';
$this->assertEquals('json', $this->RequestHandler->requestedWith());
$result = $this->RequestHandler->requestedWith(array('json', 'xml'));
$this->assertEquals('json', $result);
$result = $this->RequestHandler->requestedWith(array('rss', 'atom'));
$this->assertFalse($result);
$_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());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/atom+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->assertTrue($this->RequestHandler->isAtom());
$this->assertFalse($this->RequestHandler->isRSS());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->assertFalse($this->RequestHandler->isAtom());
$this->assertTrue($this->RequestHandler->isRSS());
$this->assertFalse($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'text/vnd.wap.wml,text/html,text/plain,image/png,*/*';
$this->assertTrue($this->RequestHandler->isWap());
$_SERVER['HTTP_ACCEPT'] = 'application/rss+xml,text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
}
/**
* testResponseContentType method
*
* @return void
*/
public function testResponseContentType() {
$this->assertEquals('html', $this->RequestHandler->responseType());
$this->assertTrue($this->RequestHandler->respondAs('atom'));
$this->assertEquals('atom', $this->RequestHandler->responseType());
}
/**
* testMobileDeviceDetection method
*
* @return void
*/
public function testMobileDeviceDetection() {
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('mobile')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isMobile());
}
/**
* testRequestProperties method
*
* @return void
*/
public function testRequestProperties() {
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('is')
->with('ssl')
->will($this->returnValue(true));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isSsl());
}
/**
* testRequestMethod method
*
* @return void
*/
public function testRequestMethod() {
$request = $this->getMock('CakeRequest');
$request->expects($this->at(0))->method('is')
->with('get')
->will($this->returnValue(true));
$request->expects($this->at(1))->method('is')
->with('post')
->will($this->returnValue(false));
$request->expects($this->at(2))->method('is')
->with('delete')
->will($this->returnValue(true));
$request->expects($this->at(3))->method('is')
->with('put')
->will($this->returnValue(false));
$this->RequestHandler->request = $request;
$this->assertTrue($this->RequestHandler->isGet());
$this->assertFalse($this->RequestHandler->isPost());
$this->assertTrue($this->RequestHandler->isDelete());
$this->assertFalse($this->RequestHandler->isPut());
}
/**
* test that map alias converts aliases to content types.
*
* @return void
*/
public function testMapAlias() {
$result = $this->RequestHandler->mapAlias('xml');
$this->assertEquals('application/xml', $result);
$result = $this->RequestHandler->mapAlias('text/html');
$this->assertNull($result);
$result = $this->RequestHandler->mapAlias('wap');
$this->assertEquals('text/vnd.wap.wml', $result);
$result = $this->RequestHandler->mapAlias(array('xml', 'js', 'json'));
$expected = array('application/xml', 'application/javascript', 'application/json');
$this->assertEquals($expected, $result);
}
/**
* test accepts() on the component
*
* @return void
*/
public function testAccepts() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->assertTrue($this->RequestHandler->accepts(array('js', 'xml', 'html')));
$this->assertFalse($this->RequestHandler->accepts(array('gif', 'jpeg', 'foo')));
$_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5';
$this->assertFalse($this->RequestHandler->accepts('rss'));
}
/**
* test accepts and prefers methods.
*
* @return void
*/
public function testPrefers() {
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html,text/plain,image/png,*/*';
$this->assertNotEquals('rss', $this->RequestHandler->prefers());
$this->RequestHandler->ext = 'rss';
$this->assertEquals('rss', $this->RequestHandler->prefers());
$this->assertFalse($this->RequestHandler->prefers('xml'));
$this->assertEquals('xml', $this->RequestHandler->prefers(array('js', 'xml', 'xhtml')));
$this->assertFalse($this->RequestHandler->prefers(array('red', 'blue')));
$this->assertEquals('xhtml', $this->RequestHandler->prefers(array('js', 'json', 'xhtml')));
$this->assertTrue($this->RequestHandler->prefers(array('rss')), 'Should return true if input matches ext.');
$this->assertFalse($this->RequestHandler->prefers(array('html')), 'No match with ext, return false.');
$_SERVER['HTTP_ACCEPT'] = 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$this->_init();
$this->assertEquals('xml', $this->RequestHandler->prefers());
$_SERVER['HTTP_ACCEPT'] = '*/*;q=0.5';
$this->assertEquals('html', $this->RequestHandler->prefers());
$this->assertFalse($this->RequestHandler->prefers('rss'));
}
/**
* testCustomContent method
*
* @return void
*/
public function testCustomContent() {
$_SERVER['HTTP_ACCEPT'] = 'text/x-mobile,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5';
$this->RequestHandler->setContent('mobile', 'text/x-mobile');
$this->RequestHandler->startup($this->Controller);
$this->assertEquals('mobile', $this->RequestHandler->prefers());
}
/**
* testClientProperties method
*
* @return void
*/
public function testClientProperties() {
$request = $this->getMock('CakeRequest');
$request->expects($this->once())->method('referer');
$request->expects($this->once())->method('clientIp')->will($this->returnValue(false));
$this->RequestHandler->request = $request;
$this->RequestHandler->getReferer();
$this->RequestHandler->getClientIP(false);
}
/**
* test that ajax requests involving redirects trigger requestAction instead.
*
* @return void
*/
public function testAjaxRedirectAsRequestAction() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
), App::RESET);
$this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$this->Controller->RequestHandler->request = $this->Controller->request;
$this->Controller->RequestHandler->response = $this->Controller->response;
$this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
$this->Controller->RequestHandler->expects($this->once())->method('_stop');
ob_start();
$this->Controller->RequestHandler->beforeRedirect(
$this->Controller, array('controller' => 'request_handler_test', 'action' => 'destination')
);
$result = ob_get_clean();
$this->assertRegExp('/posts index/', $result, 'RequestAction redirect failed.');
App::build();
}
/**
* test that ajax requests involving redirects don't force no layout
* this would cause the ajax layout to not be rendered.
*
* @return void
*/
public function testAjaxRedirectAsRequestActionStillRenderingLayout() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
), App::RESET);
$this->Controller->RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$this->Controller->request = $this->getMock('CakeRequest');
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$this->Controller->RequestHandler->request = $this->Controller->request;
$this->Controller->RequestHandler->response = $this->Controller->response;
$this->Controller->request->expects($this->any())->method('is')->will($this->returnValue(true));
$this->Controller->RequestHandler->expects($this->once())->method('_stop');
ob_start();
$this->Controller->RequestHandler->beforeRedirect(
$this->Controller, array('controller' => 'request_handler_test', 'action' => 'ajax2_layout')
);
$result = ob_get_clean();
$this->assertRegExp('/posts index/', $result, 'RequestAction redirect failed.');
$this->assertRegExp('/Ajax!/', $result, 'Layout was not rendered.');
App::build();
}
/**
* test that the beforeRedirect callback properly converts
* array URLs into their correct string ones, and adds base => false so
* the correct URLs are generated.
*
* @link https://cakephp.lighthouseapp.com/projects/42648-cakephp-1x/tickets/276
* @return void
*/
public function testBeforeRedirectCallbackWithArrayUrl() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
Router::setRequestInfo(array(
array('plugin' => null, 'controller' => 'accounts', 'action' => 'index', 'pass' => array(), 'named' => array(), 'form' => array(), 'url' => array('url' => 'accounts/')),
array('base' => '/officespace', 'here' => '/officespace/accounts/', 'webroot' => '/officespace/')
));
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader'));
$RequestHandler->request = new CakeRequest('posts/index');
$RequestHandler->response = $this->getMock('CakeResponse', array('_sendHeader'));
ob_start();
$RequestHandler->beforeRedirect(
$this->Controller,
array('controller' => 'request_handler_test', 'action' => 'param_method', 'first', 'second')
);
$result = ob_get_clean();
$this->assertEquals('one: first two: second', $result);
}
/**
* assure that beforeRedirect with a status code will correctly set the status header
*
* @return void
*/
public function testBeforeRedirectCallingHeader() {
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$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->request = $this->getMock('CakeRequest');
$RequestHandler->request->expects($this->once())->method('is')
->with('ajax')
->will($this->returnValue(true));
$RequestHandler->response->expects($this->once())->method('statusCode')->with(403);
ob_start();
$RequestHandler->beforeRedirect($controller, 'request_handler_test/param_method/first/second', 403);
ob_get_clean();
}
/**
* @expectedException CakeException
* @return void
*/
public function testAddInputTypeException() {
$this->RequestHandler->addInputType('csv', array('I am not callable'));
}
/**
* Test checkNotModified method
*
* @return void
*/
public function testCheckNotModifiedByEtagStar() {
$_SERVER['HTTP_IF_NONE_MATCH'] = '*';
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('notModified'));
$RequestHandler->response->etag('something');
$RequestHandler->response->expects($this->once())->method('notModified');
$this->assertFalse($RequestHandler->beforeRender($this->Controller));
}
/**
* 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));
$RequestHandler->response = $this->getMock('CakeResponse', array('notModified'));
$RequestHandler->response->etag('something', true);
$RequestHandler->response->expects($this->once())->method('notModified');
$this->assertFalse($RequestHandler->beforeRender($this->Controller));
}
/**
* 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';
$RequestHandler = $this->getMock('RequestHandlerComponent', array('_stop'), array(&$this->Controller->Components));
$RequestHandler->response = $this->getMock('CakeResponse', array('notModified'));
$RequestHandler->response->etag('something', true);
$RequestHandler->response->modified('2012-01-01 00:00:00');
$RequestHandler->response->expects($this->once())->method('notModified');
$this->assertFalse($RequestHandler->beforeRender($this->Controller));
}
/**
* 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'));
$RequestHandler->response->expects($this->never())->method('notModified');
$this->assertNull($RequestHandler->beforeRender($this->Controller));
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,291 @@
<?php
/**
* SessionComponentTest file
*
* 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 1.2.0.5436
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('SessionComponent', 'Controller/Component');
/**
* SessionTestController class
*
* @package Cake.Test.Case.Controller.Component
*/
class SessionTestController extends Controller {
/**
* uses property
*
* @var array
*/
public $uses = array();
/**
* sessionId method
*
* @return string
*/
public function sessionId() {
return $this->Session->id();
}
}
/**
* OrangeSessionTestController class
*
* @package Cake.Test.Case.Controller.Component
*/
class OrangeSessionTestController extends Controller {
/**
* uses property
*
* @var array
*/
public $uses = array();
/**
* sessionId method
*
* @return string
*/
public function sessionId() {
return $this->Session->id();
}
}
/**
* SessionComponentTest class
*
* @package Cake.Test.Case.Controller.Component
*/
class SessionComponentTest extends CakeTestCase {
protected static $_sessionBackup;
/**
* fixtures
*
* @var string
*/
public $fixtures = array('core.session');
/**
* test case startup
*
* @return void
*/
public static function setupBeforeClass() {
self::$_sessionBackup = Configure::read('Session');
Configure::write('Session', array(
'defaults' => 'php',
'timeout' => 100,
'cookie' => 'test'
));
}
/**
* cleanup after test case.
*
* @return void
*/
public static function teardownAfterClass() {
Configure::write('Session', self::$_sessionBackup);
}
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$_SESSION = null;
$this->ComponentCollection = new ComponentCollection();
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
CakeSession::destroy();
}
/**
* ensure that session ids don't change when request action is called.
*
* @return void
*/
public function testSessionIdConsistentAcrossRequestAction() {
$Object = new Object();
$Session = new SessionComponent($this->ComponentCollection);
$expected = $Session->id();
$result = $Object->requestAction('/session_test/sessionId');
$this->assertEquals($expected, $result);
$result = $Object->requestAction('/orange_session_test/sessionId');
$this->assertEquals($expected, $result);
}
/**
* testSessionValid method
*
* @return void
*/
public function testSessionValid() {
$Session = new SessionComponent($this->ComponentCollection);
$this->assertTrue($Session->valid());
Configure::write('Session.checkAgent', true);
$Session->userAgent('rweerw');
$this->assertFalse($Session->valid());
$Session = new SessionComponent($this->ComponentCollection);
$Session->time = $Session->read('Config.time') + 1;
$this->assertFalse($Session->valid());
}
/**
* testSessionError method
*
* @return void
*/
public function testSessionError() {
CakeSession::$lastError = null;
$Session = new SessionComponent($this->ComponentCollection);
$this->assertFalse($Session->error());
}
/**
* testSessionReadWrite method
*
* @return void
*/
public function testSessionReadWrite() {
$Session = new SessionComponent($this->ComponentCollection);
$this->assertNull($Session->read('Test'));
$this->assertTrue($Session->write('Test', 'some value'));
$this->assertEquals('some value', $Session->read('Test'));
$Session->delete('Test');
$this->assertTrue($Session->write('Test.key.path', 'some value'));
$this->assertEquals('some value', $Session->read('Test.key.path'));
$this->assertEquals(array('path' => 'some value'), $Session->read('Test.key'));
$this->assertTrue($Session->write('Test.key.path2', 'another value'));
$this->assertEquals(array('path' => 'some value', 'path2' => 'another value'), $Session->read('Test.key'));
$Session->delete('Test');
$array = array('key1' => 'val1', 'key2' => 'val2', 'key3' => 'val3');
$this->assertTrue($Session->write('Test', $array));
$this->assertEquals($Session->read('Test'), $array);
$Session->delete('Test');
$this->assertTrue($Session->write(array('Test'), 'some value'));
$this->assertTrue($Session->write(array('Test' => 'some value')));
$this->assertEquals('some value', $Session->read('Test'));
$Session->delete('Test');
}
/**
* testSessionDelete method
*
* @return void
*/
public function testSessionDelete() {
$Session = new SessionComponent($this->ComponentCollection);
$this->assertFalse($Session->delete('Test'));
$Session->write('Test', 'some value');
$this->assertTrue($Session->delete('Test'));
}
/**
* testSessionCheck method
*
* @return void
*/
public function testSessionCheck() {
$Session = new SessionComponent($this->ComponentCollection);
$this->assertFalse($Session->check('Test'));
$Session->write('Test', 'some value');
$this->assertTrue($Session->check('Test'));
$Session->delete('Test');
}
/**
* testSessionFlash method
*
* @return void
*/
public function testSessionFlash() {
$Session = new SessionComponent($this->ComponentCollection);
$this->assertNull($Session->read('Message.flash'));
$Session->setFlash('This is a test message');
$this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.flash'));
$Session->setFlash('This is a test message', 'test', array('name' => 'Joel Moss'));
$this->assertEquals(array('message' => 'This is a test message', 'element' => 'test', 'params' => array('name' => 'Joel Moss')), $Session->read('Message.flash'));
$Session->setFlash('This is a test message', 'default', array(), 'myFlash');
$this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.myFlash'));
$Session->setFlash('This is a test message', 'non_existing_layout');
$this->assertEquals(array('message' => 'This is a test message', 'element' => 'default', 'params' => array()), $Session->read('Message.myFlash'));
$Session->delete('Message');
}
/**
* testSessionId method
*
* @return void
*/
public function testSessionId() {
unset($_SESSION);
$Session = new SessionComponent($this->ComponentCollection);
CakeSession::start();
$this->assertEquals(session_id(), $Session->id());
}
/**
* testSessionDestroy method
*
* @return void
*/
public function testSessionDestroy() {
$Session = new SessionComponent($this->ComponentCollection);
$Session->write('Test', 'some value');
$this->assertEquals('some value', $Session->read('Test'));
$Session->destroy('Test');
$this->assertNull($Session->read('Test'));
}
}

View file

@ -0,0 +1,178 @@
<?php
/**
* ComponentCollectionTest 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://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeResponse', 'Network');
App::uses('CookieComponent', 'Controller/Component');
App::uses('SecurityComponent', 'Controller/Component');
App::uses('ComponentCollection', 'Controller');
/**
* Extended CookieComponent
*/
class CookieAliasComponent extends CookieComponent {
}
class ComponentCollectionTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Components = new ComponentCollection();
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Components);
}
/**
* test triggering callbacks on loaded helpers
*
* @return void
*/
public function testLoad() {
$result = $this->Components->load('Cookie');
$this->assertInstanceOf('CookieComponent', $result);
$this->assertInstanceOf('CookieComponent', $this->Components->Cookie);
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie'), $result, 'loaded() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
$result = $this->Components->load('Cookie');
$this->assertSame($result, $this->Components->Cookie);
}
/**
* Tests loading as an alias
*
* @return void
*/
public function testLoadWithAlias() {
$result = $this->Components->load('Cookie', array('className' => 'CookieAlias', 'somesetting' => true));
$this->assertInstanceOf('CookieAliasComponent', $result);
$this->assertInstanceOf('CookieAliasComponent', $this->Components->Cookie);
$this->assertTrue($this->Components->Cookie->settings['somesetting']);
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie'), $result, 'loaded() results are wrong.');
$this->assertTrue($this->Components->enabled('Cookie'));
$result = $this->Components->load('Cookie');
$this->assertInstanceOf('CookieAliasComponent', $result);
App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)));
CakePlugin::load('TestPlugin');
$result = $this->Components->load('SomeOther', array('className' => 'TestPlugin.Other'));
$this->assertInstanceOf('OtherComponent', $result);
$this->assertInstanceOf('OtherComponent', $this->Components->SomeOther);
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie', 'SomeOther'), $result, 'loaded() results are wrong.');
App::build();
CakePlugin::unload();
}
/**
* test load and enable = false
*
* @return void
*/
public function testLoadWithEnableFalse() {
$result = $this->Components->load('Cookie', array('enabled' => false));
$this->assertInstanceOf('CookieComponent', $result);
$this->assertInstanceOf('CookieComponent', $this->Components->Cookie);
$this->assertFalse($this->Components->enabled('Cookie'), 'Cookie should be disabled');
}
/**
* test missingcomponent exception
*
* @expectedException MissingComponentException
* @return void
*/
public function testLoadMissingComponent() {
$this->Components->load('ThisComponentShouldAlwaysBeMissing');
}
/**
* test loading a plugin component.
*
* @return void
*/
public function testLoadPluginComponent() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
));
CakePlugin::load('TestPlugin');
$result = $this->Components->load('TestPlugin.Other');
$this->assertInstanceOf('OtherComponent', $result, 'Component class is wrong.');
$this->assertInstanceOf('OtherComponent', $this->Components->Other, 'Class is wrong');
App::build();
CakePlugin::unload();
}
/**
* test unload()
*
* @return void
*/
public function testUnload() {
$this->Components->load('Cookie');
$this->Components->load('Security');
$result = $this->Components->loaded();
$this->assertEquals(array('Cookie', 'Security'), $result, 'loaded components is wrong');
$this->Components->unload('Cookie');
$this->assertFalse(isset($this->Components->Cookie));
$this->assertTrue(isset($this->Components->Security));
$result = $this->Components->loaded();
$this->assertEquals(array('Security'), $result, 'loaded components is wrong');
$result = $this->Components->enabled();
$this->assertEquals(array('Security'), $result, 'enabled components is wrong');
}
/**
* test getting the controller out of the collection
*
* @return void
*/
public function testGetController() {
$controller = $this->getMock('Controller');
$controller->components = array('Security');
$this->Components->init($controller);
$result = $this->Components->getController();
$this->assertSame($controller, $result);
}
}

View file

@ -0,0 +1,289 @@
<?php
/**
* ComponentTest file
*
* 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
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
App::uses('Component', 'Controller');
/**
* ParamTestComponent
*
* @package Cake.Test.Case.Controller
*/
class ParamTestComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('Banana' => array('config' => 'value'));
}
/**
* ComponentTestController class
*
* @package Cake.Test.Case.Controller
*/
class ComponentTestController extends Controller {
/**
* uses property
*
* @var array
*/
public $uses = array();
}
/**
* AppleComponent class
*
* @package Cake.Test.Case.Controller
*/
class AppleComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('Orange');
/**
* testName property
*
* @var mixed
*/
public $testName = null;
/**
* startup method
*
* @param Controller $controller
* @return void
*/
public function startup(Controller $controller) {
$this->testName = $controller->name;
}
}
/**
* OrangeComponent class
*
* @package Cake.Test.Case.Controller
*/
class OrangeComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('Banana');
/**
* initialize method
*
* @param Controller $controller
* @return void
*/
public function initialize(Controller $controller) {
$this->Controller = $controller;
$this->Banana->testField = 'OrangeField';
}
/**
* startup method
*
* @param Controller $controller
* @return string
*/
public function startup(Controller $controller) {
$controller->foo = 'pass';
}
}
/**
* BananaComponent class
*
* @package Cake.Test.Case.Controller
*/
class BananaComponent extends Component {
/**
* testField property
*
* @var string
*/
public $testField = 'BananaField';
/**
* startup method
*
* @param Controller $controller
* @return string
*/
public function startup(Controller $controller) {
$controller->bar = 'fail';
}
}
/**
* MutuallyReferencingOneComponent class
*
* @package Cake.Test.Case.Controller
*/
class MutuallyReferencingOneComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('MutuallyReferencingTwo');
}
/**
* MutuallyReferencingTwoComponent class
*
* @package Cake.Test.Case.Controller
*/
class MutuallyReferencingTwoComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('MutuallyReferencingOne');
}
/**
* SomethingWithEmailComponent class
*
* @package Cake.Test.Case.Controller
*/
class SomethingWithEmailComponent extends Component {
/**
* components property
*
* @var array
*/
public $components = array('Email');
}
/**
* ComponentTest class
*
* @package Cake.Test.Case.Controller
*/
class ComponentTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->_pluginPaths = App::path('plugins');
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
}
/**
* test accessing inner components.
*
* @return void
*/
public function testInnerComponentConstruction() {
$Collection = new ComponentCollection();
$Component = new AppleComponent($Collection);
$this->assertInstanceOf('OrangeComponent', $Component->Orange, 'class is wrong');
}
/**
* test component loading
*
* @return void
*/
public function testNestedComponentLoading() {
$Collection = new ComponentCollection();
$Apple = new AppleComponent($Collection);
$this->assertInstanceOf('OrangeComponent', $Apple->Orange, 'class is wrong');
$this->assertInstanceOf('BananaComponent', $Apple->Orange->Banana, 'class is wrong');
$this->assertTrue(empty($Apple->Session));
$this->assertTrue(empty($Apple->Orange->Session));
}
/**
* test that component components are not enabled in the collection.
*
* @return void
*/
public function testInnerComponentsAreNotEnabled() {
$Collection = new ComponentCollection();
$Apple = $Collection->load('Apple');
$this->assertInstanceOf('OrangeComponent', $Apple->Orange, 'class is wrong');
$result = $Collection->enabled();
$this->assertEquals(array('Apple'), $result, 'Too many components enabled.');
}
/**
* test a component being used more than once.
*
* @return void
*/
public function testMultipleComponentInitialize() {
$Collection = new ComponentCollection();
$Banana = $Collection->load('Banana');
$Orange = $Collection->load('Orange');
$this->assertSame($Banana, $Orange->Banana, 'Should be references');
$Banana->testField = 'OrangeField';
$this->assertSame($Banana->testField, $Orange->Banana->testField, 'References are broken');
}
/**
* Test mutually referencing components.
*
* @return void
*/
public function testSomethingReferencingEmailComponent() {
$Controller = new ComponentTestController();
$Controller->components = array('SomethingWithEmail');
$Controller->uses = false;
$Controller->constructClasses();
$Controller->Components->trigger('initialize', array(&$Controller));
$Controller->beforeFilter();
$Controller->Components->trigger('startup', array(&$Controller));
$this->assertInstanceOf('SomethingWithEmailComponent', $Controller->SomethingWithEmail);
$this->assertInstanceOf('EmailComponent', $Controller->SomethingWithEmail->Email);
}
}

View file

@ -0,0 +1,250 @@
<?php
/**
* Controller Merge vars Test file
*
* Isolated from the Controller and Component test as to not pollute their AppController class
*
* 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
* @since CakePHP(tm) v 1.2.3
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Controller', 'Controller');
/**
* Test case AppController
*
* @package Cake.Test.Case.Controller
*/
class MergeVarsAppController extends Controller {
/**
* components
*
* @var array
*/
public $components = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
/**
* helpers
*
* @var array
*/
public $helpers = array('MergeVar' => array('format' => 'html', 'terse'));
}
/**
* MergeVar Component
*
* @package Cake.Test.Case.Controller
*/
class MergeVarComponent extends Object {
}
/**
* Additional controller for testing
*
* @package Cake.Test.Case.Controller
*/
class MergeVariablesController extends MergeVarsAppController {
/**
* uses
*
* @var arrays
*/
public $uses = array();
/**
* parent for mergeVars
*
* @var string
*/
protected $_mergeParent = 'MergeVarsAppController';
}
/**
* MergeVarPlugin App Controller
*
* @package Cake.Test.Case.Controller
*/
class MergeVarPluginAppController extends MergeVarsAppController {
/**
* components
*
* @var array
*/
public $components = array('Auth' => array('setting' => 'val', 'otherVal'));
/**
* helpers
*
* @var array
*/
public $helpers = array('Js');
/**
* parent for mergeVars
*
* @var string
*/
protected $_mergeParent = 'MergeVarsAppController';
}
/**
* MergePostsController
*
* @package Cake.Test.Case.Controller
*/
class MergePostsController extends MergeVarPluginAppController {
/**
* uses
*
* @var array
*/
public $uses = array();
}
/**
* Test Case for Controller Merging of Vars.
*
* @package Cake.Test.Case.Controller
*/
class ControllerMergeVarsTest extends CakeTestCase {
/**
* test that component settings are not duplicated when merging component settings
*
* @return void
*/
public function testComponentParamMergingNoDuplication() {
$Controller = new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => false));
$this->assertEquals($expected, $Controller->components, 'Duplication of settings occurred. %s');
}
/**
* test component merges with redeclared components
*
* @return void
*/
public function testComponentMergingWithRedeclarations() {
$Controller = new MergeVariablesController();
$Controller->components['MergeVar'] = array('remote', 'redirect' => true);
$Controller->constructClasses();
$expected = array('MergeVar' => array('flag', 'otherFlag', 'redirect' => true, 'remote'));
$this->assertEquals($expected, $Controller->components, 'Merging of settings is wrong. %s');
}
/**
* test merging of helpers array, ensure no duplication occurs
*
* @return void
*/
public function testHelperSettingMergingNoDuplication() {
$Controller = new MergeVariablesController();
$Controller->constructClasses();
$expected = array('MergeVar' => array('format' => 'html', 'terse'));
$this->assertEquals($expected, $Controller->helpers, 'Duplication of settings occurred. %s');
}
/**
* Test that helpers declared in appcontroller come before those in the subclass
* orderwise
*
* @return void
*/
public function testHelperOrderPrecedence() {
$Controller = new MergeVariablesController();
$Controller->helpers = array('Custom', 'Foo' => array('something'));
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('format' => 'html', 'terse'),
'Custom' => null,
'Foo' => array('something')
);
$this->assertSame($expected, $Controller->helpers, 'Order is incorrect.');
}
/**
* test merging of vars with plugin
*
* @return void
*/
public function testMergeVarsWithPlugin() {
$Controller = new MergePostsController();
$Controller->components = array('Email' => array('ports' => 'open'));
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
'Email' => array('ports' => 'open')
);
$this->assertEquals($expected, $Controller->components, 'Components are unexpected.');
$expected = array(
'MergeVar' => array('format' => 'html', 'terse'),
'Js' => null
);
$this->assertEquals($expected, $Controller->helpers, 'Helpers are unexpected.');
$Controller = new MergePostsController();
$Controller->components = array();
$Controller->plugin = 'MergeVarPlugin';
$Controller->constructClasses();
$expected = array(
'MergeVar' => array('flag', 'otherFlag', 'redirect' => false),
'Auth' => array('setting' => 'val', 'otherVal'),
);
$this->assertEquals($expected, $Controller->components, 'Components are unexpected.');
}
/**
* Ensure that _mergeControllerVars is not being greedy and merging with
* AppController when you make an instance of Controller
*
* @return void
*/
public function testMergeVarsNotGreedy() {
$Controller = new Controller();
$Controller->components = array();
$Controller->uses = array();
$Controller->constructClasses();
$this->assertFalse(isset($Controller->Session));
}
/**
* Ensure that $modelClass is correct even when Controller::$uses
* has been iterated, eg: by a Component, or event handlers.
*
* @return void
*/
public function testMergeVarsModelClass() {
$Controller = new MergeVariablescontroller();
$Controller->uses = array('Test', 'TestAlias');
$Controller->constructClasses();
$this->assertEquals($Controller->uses[0], $Controller->modelClass);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,78 @@
<?php
/**
* PagesControllerTest file
*
* 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
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('PagesController', 'Controller');
/**
* PagesControllerTest class
*
* @package Cake.Test.Case.Controller
*/
class PagesControllerTest extends CakeTestCase {
/**
* testDisplay method
*
* @return void
*/
public function testDisplay() {
App::build(array(
'View' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
)
));
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->viewPath = 'Posts';
$Pages->display('index');
$this->assertRegExp('/posts index/', $Pages->response->body());
$this->assertEquals('index', $Pages->viewVars['page']);
$Pages->viewPath = 'Themed';
$Pages->display('TestTheme', 'Posts', 'index');
$this->assertRegExp('/posts index themed view/', $Pages->response->body());
$this->assertEquals('TestTheme', $Pages->viewVars['page']);
$this->assertEquals('Posts', $Pages->viewVars['subpage']);
}
/**
* Test that missing view renders 404 page in production
*
* @expectedException NotFoundException
* @expectedExceptionCode 404
* @return void
*/
public function testMissingView() {
Configure::write('debug', 0);
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->display('non_existing_page');
}
/**
* Test that missing view in debug mode renders missing_view error page
*
* @expectedException MissingViewException
* @expectedExceptionCode 500
* @return void
*/
public function testMissingViewInDebug() {
Configure::write('debug', 1);
$Pages = new PagesController(new CakeRequest(null, false), new CakeResponse());
$Pages->display('non_existing_page');
}
}

View file

@ -0,0 +1,347 @@
<?php
/**
* ScaffoldTest file
*
* 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
* @since CakePHP(tm) v 1.2.0.5436
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Router', 'Routing');
App::uses('Controller', 'Controller');
App::uses('Scaffold', 'Controller');
App::uses('ScaffoldView', 'View');
App::uses('AppModel', 'Model');
require_once dirname(dirname(__FILE__)) . DS . 'Model' . DS . 'models.php';
/**
* ScaffoldMockController class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldMockController extends Controller {
/**
* scaffold property
*
* @var mixed
*/
public $scaffold;
}
/**
* ScaffoldMockControllerWithFields class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldMockControllerWithFields extends Controller {
/**
* name property
*
* @var string
*/
public $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
*/
public $scaffold;
/**
* function beforeScaffold
*
* @param string method
* @return bool true
*/
public function beforeScaffold($method) {
$this->set('scaffoldFields', array('title'));
return true;
}
}
/**
* TestScaffoldMock class
*
* @package Cake.Test.Case.Controller
*/
class TestScaffoldMock extends Scaffold {
/**
* Overload _scaffold
*
* @param CakeRequest $request
* @return void
*/
protected function _scaffold(CakeRequest $request) {
$this->_params = $request;
}
/**
* Get Params from the Controller.
*
* @return unknown
*/
public function getParams() {
return $this->_params;
}
}
/**
* Scaffold Test class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldTest extends CakeTestCase {
/**
* Controller property
*
* @var SecurityTestController
*/
public $Controller;
/**
* fixtures property
*
* @var array
*/
public $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Config.language', 'eng');
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockController($request);
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Controller);
}
/**
* Test the correct Generation of Scaffold Params.
* This ensures that the correct action and view will be generated
*
* @return void
*/
public function testScaffoldParams() {
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' => 'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => true,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
$Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request);
$result = $Scaffold->getParams();
$this->assertEquals('admin_edit', $result['action']);
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
*/
public function testScaffoldVariableSetting() {
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' => 'admin/scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => true,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
$Scaffold = new TestScaffoldMock($this->Controller, $this->Controller->request);
$result = $Scaffold->controller->viewVars;
$this->assertEquals('Scaffold :: Admin Edit :: Scaffold Mock', $result['title_for_layout']);
$this->assertEquals('Scaffold Mock', $result['singularHumanName']);
$this->assertEquals('Scaffold Mock', $result['pluralHumanName']);
$this->assertEquals('ScaffoldMock', $result['modelClass']);
$this->assertEquals('id', $result['primaryKey']);
$this->assertEquals('title', $result['displayField']);
$this->assertEquals('scaffoldMock', $result['singularVar']);
$this->assertEquals('scaffoldMock', $result['pluralVar']);
$this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated'), $result['scaffoldFields']);
$this->assertArrayHasKey('plugin', $result['associations']['belongsTo']['User']);
}
/**
* test that Scaffold overrides the view property even if its set to 'Theme'
*
* @return void
*/
public function testScaffoldChangingViewProperty() {
$this->Controller->action = 'edit';
$this->Controller->theme = 'TestTheme';
$this->Controller->viewClass = 'Theme';
$this->Controller->constructClasses();
new TestScaffoldMock($this->Controller, $this->Controller->request);
$this->assertEquals('Scaffold', $this->Controller->viewClass);
}
/**
* test that scaffold outputs flash messages when sessions are unset.
*
* @return void
*/
public function testScaffoldFlashMessages() {
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->request->data = array(
'ScaffoldMock' => array(
'id' => 1,
'title' => 'New title',
'body' => 'new body'
)
);
$this->Controller->constructClasses();
unset($this->Controller->Session);
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/Scaffold Mock has been updated/', $result);
}
/**
* test that habtm relationship keys get added to scaffoldFields.
*
* @return void
*/
public function testHabtmFieldAdditionWithScaffoldForm() {
CakePlugin::unload();
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/name="data\[ScaffoldTag\]\[ScaffoldTag\]"/', $result);
$result = $Scaffold->controller->viewVars;
$this->assertEquals(array('id', 'user_id', 'title', 'body', 'published', 'created', 'updated', 'ScaffoldTag'), $result['scaffoldFields']);
}
/**
* test that the proper names and variable values are set by Scaffold
*
* @return void
*/
public function testEditScaffoldWithScaffoldFields() {
$request = new CakeRequest(null, false);
$this->Controller = new ScaffoldMockControllerWithFields($request);
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock/edit'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit';
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertNotRegExp('/textarea name="data\[ScaffoldMock\]\[body\]" cols="30" rows="6" id="ScaffoldMockBody"/', $result);
}
}