Backup of current cakephp version

This commit is contained in:
Brm Ko 2017-02-26 15:27:58 +01:00
parent b8f82da6f8
commit 5a580df460
925 changed files with 238041 additions and 1 deletions

View file

@ -0,0 +1,526 @@
<?php
/**
* CakeNumberTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('CakeNumber', 'Utility');
/**
* CakeNumberTest class
*
* @package Cake.Test.Case.Utility
*/
class CakeNumberTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Number = new CakeNumber();
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Number);
}
/**
* testFormatAndCurrency method
*
* @return void
*/
public function testFormat() {
$value = '100100100';
$result = $this->Number->format($value, '#');
$expected = '#100,100,100';
$this->assertEquals($expected, $result);
$result = $this->Number->format($value, 3);
$expected = '100,100,100.000';
$this->assertEquals($expected, $result);
$result = $this->Number->format($value);
$expected = '100,100,100';
$this->assertEquals($expected, $result);
$result = $this->Number->format($value, '-');
$expected = '100-100-100';
$this->assertEquals($expected, $result);
}
/**
* testMultibyteFormat
*
* @return void
*/
public function testMultibyteFormat() {
$value = '5199100.0006';
$result = $this->Number->format($value, array(
'thousands' => '&nbsp;',
'decimals' => '&amp;',
'places' => 3,
'escape' => false,
'before' => '',
));
$expected = '5&nbsp;199&nbsp;100&amp;001';
$this->assertEquals($expected, $result);
$value = 1000.45;
$result = $this->Number->format($value, array(
'thousands' => ',,',
'decimals' => '.a',
'escape' => false,
));
$expected = '$1,,000.a45';
$this->assertEquals($expected, $result);
$value = 519919827593784.00;
$this->Number->addFormat('RUR', array(
'thousands' => 'ø€ƒ‡™',
'decimals' => '(§.§)',
'escape' => false,
'wholeSymbol' => '€',
'wholePosition' => 'after',
));
$result = $this->Number->currency($value, 'RUR');
$expected = '519ø€ƒ‡™919ø€ƒ‡™827ø€ƒ‡™593ø€ƒ‡™784(§.§)00€';
$this->assertEquals($expected, $result);
$value = '13371337.1337';
$result = CakeNumber::format($value, array(
'thousands' => '- |-| /-\ >< () |2 -',
'decimals' => '- £€€† -',
'before' => ''
));
$expected = '13- |-| /-\ &gt;&lt; () |2 -371- |-| /-\ &gt;&lt; () |2 -337- £€€† -13';
$this->assertEquals($expected, $result);
}
/**
* Test currency method.
*
* @return void
*/
public function testCurrency() {
$value = '100100100';
$result = $this->Number->currency($value);
$expected = '$100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, '#');
$expected = '#100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, false);
$expected = '100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD');
$expected = '$100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, '', array('thousands' => ' ', 'wholeSymbol' => '€', 'wholePosition' => 'after', 'decimals' => ',', 'zero' => 'Gratuit'));
$expected = '100 100 100,00€';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(1000.45, null, array('after' => 'øre', 'before' => 'Kr. ', 'decimals' => ',', 'thousands' => '.'));
$expected = 'Kr. 1.000,45';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.5, 'USD');
$expected = '50c';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.5, null, array('after' => 'øre'));
$expected = '50øre';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(1, null, array('wholeSymbol' => '$ '));
$expected = '$ 1.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(1, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after'));
$expected = '1.00 $';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents'));
$expected = '20cents';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents', 'fractionPosition' => 'before'));
$expected = 'cents20';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(311, 'USD', array('wholePosition' => 'after'));
$expected = '311.00$';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, 'EUR');
$expected = '&#8364;0,20';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
$expected = '12.00 dollars';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
$expected = '12 cents';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.5, null, array('fractionSymbol' => false, 'fractionPosition' => 'before', 'wholeSymbol' => '$'));
$expected = '$0.50';
$this->assertEquals($expected, $result);
}
/**
* Test adding currency format options to the number helper
*
* @return void
*/
public function testCurrencyAddFormat() {
$this->Number->addFormat('NOK', array('before' => 'Kr. '));
$result = $this->Number->currency(1000, 'NOK');
$expected = 'Kr. 1,000.00';
$this->assertEquals($expected, $result);
$this->Number->addFormat('Other', array('before' => '$$ ', 'after' => 'c!'));
$result = $this->Number->currency(0.22, 'Other');
$expected = '22c!';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(-10, 'Other');
$expected = '($$ 10.00)';
$this->assertEquals($expected, $result);
$this->Number->addFormat('Other2', array('before' => '$ ', 'after' => false));
$result = $this->Number->currency(0.22, 'Other2');
$expected = '$ 0.22';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyPositive method
*
* @return void
*/
public function testCurrencyPositive() {
$value = '100100100';
$result = $this->Number->currency($value);
$expected = '$100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD', array('before' => '#'));
$expected = '#100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, false);
$expected = '100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD');
$expected = '$100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyNegative method
*
* @return void
*/
public function testCurrencyNegative() {
$value = '-100100100';
$result = $this->Number->currency($value);
$expected = '($100,100,100.00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;100.100.100,00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(&#163;100,100,100.00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD', array('negative' => '-'));
$expected = '-$100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
$expected = '-&#8364;100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
$expected = '-&#163;100,100,100.00';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyCentsPositive method
*
* @return void
*/
public function testCurrencyCentsPositive() {
$value = '0.99';
$result = $this->Number->currency($value, 'USD');
$expected = '99c';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,99';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '99p';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyCentsNegative method
*
* @return void
*/
public function testCurrencyCentsNegative() {
$value = '-0.99';
$result = $this->Number->currency($value, 'USD');
$expected = '(99c)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;0,99)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(99p)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD', array('negative' => '-'));
$expected = '-99c';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
$expected = '-&#8364;0,99';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
$expected = '-99p';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyZero method
*
* @return void
*/
public function testCurrencyZero() {
$value = '0';
$result = $this->Number->currency($value, 'USD');
$expected = '$0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('zero' => 'FREE!'));
$expected = 'FREE!';
$this->assertEquals($expected, $result);
}
/**
* testCurrencyOptions method
*
* @return void
*/
public function testCurrencyOptions() {
$value = '1234567.89';
$result = $this->Number->currency($value, null, array('before' => 'GBP'));
$expected = 'GBP1,234,567.89';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('places' => 0));
$expected = '&#163;1,234,568';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('1234567.8912345', null, array('before' => 'GBP', 'places' => 3));
$expected = 'GBP1,234,567.891';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('650.120001', null, array('before' => 'GBP', 'places' => 4));
$expected = 'GBP650.1200';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('escape' => true));
$expected = '&amp;#163;1,234,567.89';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.35', 'USD', array('after' => false));
$expected = '$0.35';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.35', 'GBP', array('after' => false));
$expected = '&#163;0.35';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.35', 'GBP');
$expected = '35p';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.35', 'EUR');
$expected = '&#8364;0,35';
$this->assertEquals($expected, $result);
}
/**
* testToReadableSize method
*
* @return void
*/
public function testToReadableSize() {
$result = $this->Number->toReadableSize(0);
$expected = '0 Bytes';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1);
$expected = '1 Byte';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(45);
$expected = '45 Bytes';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1023);
$expected = '1023 Bytes';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024);
$expected = '1 KB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 512);
$expected = '512 KB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 - 1);
$expected = '1.00 MB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 512);
$expected = '512.00 MB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 - 1);
$expected = '1.00 GB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
$expected = '512.00 GB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 - 1);
$expected = '1.00 TB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 512);
$expected = '512.00 TB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 1024 - 1);
$expected = '1024.00 TB';
$this->assertEquals($expected, $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 1024 * 1024 * 1024);
$expected = (1024 * 1024) . '.00 TB';
$this->assertEquals($expected, $result);
}
/**
* test toReadableSize() with locales
*
* @return void
*/
public function testReadableSizeLocalized() {
$restore = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, 'de_DE');
$result = $this->Number->toReadableSize(1321205);
$this->assertRegExp('/1[,.]26 MB/', $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
$this->assertRegExp('/512[,.]00 GB/', $result);
setlocale(LC_NUMERIC, $restore);
}
/**
* testToPercentage method
*
* @return void
*/
public function testToPercentage() {
$result = $this->Number->toPercentage(45, 0);
$expected = '45%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(45, 2);
$expected = '45.00%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0, 0);
$expected = '0%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0, 4);
$expected = '0.0000%';
$this->assertEquals($expected, $result);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,349 @@
<?php
/**
* ClassRegistryTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('ClassRegistry', 'Utility');
/**
* ClassRegisterModel class
*
* @package Cake.Test.Case.Utility
*/
class ClassRegisterModel extends CakeTestModel {
/**
* useTable property
*
* @var bool false
*/
public $useTable = false;
}
/**
* RegisterArticle class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticle extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticle'
*/
public $name = 'RegisterArticle';
}
/**
* RegisterArticleFeatured class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticleFeatured extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleFeatured'
*/
public $name = 'RegisterArticleFeatured';
}
/**
* RegisterArticleTag class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticleTag extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleTag'
*/
public $name = 'RegisterArticleTag';
}
/**
* RegistryPluginAppModel class
*
* @package Cake.Test.Case.Utility
*/
class RegistryPluginAppModel extends ClassRegisterModel {
/**
* tablePrefix property
*
* @var string 'something_'
*/
public $tablePrefix = 'something_';
}
/**
* TestRegistryPluginModel class
*
* @package Cake.Test.Case.Utility
*/
class TestRegistryPluginModel extends RegistryPluginAppModel {
/**
* name property
*
* @var string 'TestRegistryPluginModel'
*/
public $name = 'TestRegistryPluginModel';
}
/**
* RegisterCategory class
*
* @package Cake.Test.Case.Utility
*/
class RegisterCategory extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterCategory'
*/
public $name = 'RegisterCategory';
}
/**
* RegisterPrefixedDs class
*
* @package Cake.Test.Case.Utility
*/
class RegisterPrefixedDs extends ClassRegisterModel {
/**
* useDbConfig property
*
* @var string 'doesnotexist'
*/
public $useDbConfig = 'doesnotexist';
}
/**
* Abstract class for testing ClassRegistry.
*/
abstract class ClassRegistryAbstractModel extends ClassRegisterModel {
public abstract function doSomething();
}
/**
* Interface for testing ClassRegistry
*/
interface ClassRegistryInterfaceTest {
public function doSomething();
}
/**
* ClassRegistryTest class
*
* @package Cake.Test.Case.Utility
*/
class ClassRegistryTest extends CakeTestCase {
/**
* testAddModel method
*
* @return void
*/
public function testAddModel() {
$Tag = ClassRegistry::init('RegisterArticleTag');
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$TagCopy = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertTrue($TagCopy);
$Tag->name = 'SomeNewName';
$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
$this->assertTrue(is_a($TagCopy, 'RegisterArticleTag'));
$this->assertSame($Tag, $TagCopy);
$NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertNotSame($Tag, $NewTag);
$this->assertSame($NewTag, $NewTagCopy);
$NewTag->name = 'SomeOtherName';
$this->assertNotSame($Tag, $NewTag);
$this->assertSame($NewTag, $NewTagCopy);
$Tag->name = 'SomeOtherName';
$this->assertNotSame($Tag, $NewTag);
$this->assertTrue($TagCopy->name === 'SomeOtherName');
$User = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
$this->assertTrue(is_a($User, 'AppModel'));
$UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
$this->assertTrue(is_a($UserCopy, 'AppModel'));
$this->assertEquals($User, $UserCopy);
$Category = ClassRegistry::init(array('class' => 'RegisterCategory'));
$this->assertTrue(is_a($Category, 'RegisterCategory'));
$ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
$this->assertTrue(is_a($ParentCategory, 'RegisterCategory'));
$this->assertNotSame($Category, $ParentCategory);
$this->assertNotEquals($Category->alias, $ParentCategory->alias);
$this->assertEquals('RegisterCategory', $Category->alias);
$this->assertEquals('ParentCategory', $ParentCategory->alias);
}
/**
* testClassRegistryFlush method
*
* @return void
*/
public function testClassRegistryFlush() {
$Tag = ClassRegistry::init('RegisterArticleTag');
$ArticleTag = ClassRegistry::getObject('RegisterArticleTag');
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
ClassRegistry::flush();
$NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertFalse($NoArticleTag);
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
}
/**
* testAddMultipleModels method
*
* @return void
*/
public function testAddMultipleModels() {
$Article = ClassRegistry::isKeySet('Article');
$this->assertFalse($Article);
$Featured = ClassRegistry::isKeySet('Featured');
$this->assertFalse($Featured);
$Tag = ClassRegistry::isKeySet('Tag');
$this->assertFalse($Tag);
$models = array(array('class' => 'RegisterArticle', 'alias' => 'Article'),
array('class' => 'RegisterArticleFeatured', 'alias' => 'Featured'),
array('class' => 'RegisterArticleTag', 'alias' => 'Tag'));
$added = ClassRegistry::init($models);
$this->assertTrue($added);
$Article = ClassRegistry::isKeySet('Article');
$this->assertTrue($Article);
$Featured = ClassRegistry::isKeySet('Featured');
$this->assertTrue($Featured);
$Tag = ClassRegistry::isKeySet('Tag');
$this->assertTrue($Tag);
$Article = ClassRegistry::getObject('Article');
$this->assertTrue(is_a($Article, 'RegisterArticle'));
$Featured = ClassRegistry::getObject('Featured');
$this->assertTrue(is_a($Featured, 'RegisterArticleFeatured'));
$Tag = ClassRegistry::getObject('Tag');
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
}
/**
* testPluginAppModel method
*
* @return void
*/
public function testPluginAppModel() {
$TestRegistryPluginModel = ClassRegistry::isKeySet('TestRegistryPluginModel');
$this->assertFalse($TestRegistryPluginModel);
//Faking a plugin
CakePlugin::load('RegistryPlugin', array('path' => '/fake/path'));
$TestRegistryPluginModel = ClassRegistry::init('RegistryPlugin.TestRegistryPluginModel');
$this->assertTrue(is_a($TestRegistryPluginModel, 'TestRegistryPluginModel'));
$this->assertEquals('something_', $TestRegistryPluginModel->tablePrefix);
$PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
$this->assertTrue(is_a($PluginUser, 'RegistryPluginAppModel'));
$PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser');
$this->assertTrue(is_a($PluginUserCopy, 'RegistryPluginAppModel'));
$this->assertSame($PluginUser, $PluginUserCopy);
CakePlugin::unload();
}
/**
* Tests prefixed datasource names for test purposes
*
*/
public function testPrefixedTestDatasource() {
ClassRegistry::config(array('testing' => true));
$Model = ClassRegistry::init('RegisterPrefixedDs');
$this->assertEquals('test', $Model->useDbConfig);
ClassRegistry::removeObject('RegisterPrefixedDs');
$testConfig = ConnectionManager::getDataSource('test')->config;
ConnectionManager::create('test_doesnotexist', $testConfig);
$Model = ClassRegistry::init('RegisterArticle');
$this->assertEquals('test', $Model->useDbConfig);
$Model = ClassRegistry::init('RegisterPrefixedDs');
$this->assertEquals('test_doesnotexist', $Model->useDbConfig);
}
/**
* Tests that passing the string parameter to init() will return false if the model does not exists
*
*/
public function testInitStrict() {
$this->assertFalse(ClassRegistry::init('NonExistent', true));
}
/**
* Test that you cannot init() an abstract class. An exception will be raised.
*
* @expectedException CakeException
* @return void
*/
public function testInitAbstractClass() {
ClassRegistry::init('ClassRegistryAbstractModel');
}
/**
* Test that you cannot init() an abstract class. A exception will be raised.
*
* @expectedException CakeException
* @return void
*/
public function testInitInterface() {
ClassRegistry::init('ClassRegistryInterfaceTest');
}
}

View file

@ -0,0 +1,513 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Debugger', 'Utility');
/**
* DebugggerTestCaseDebuggger class
*
* @package Cake.Test.Case.Utility
*/
class DebuggerTestCaseDebugger extends Debugger {
}
/**
* DebuggerTest class
*
* !!! Be careful with changing code below as it may
* !!! change line numbers which are used in the tests
*
* @package Cake.Test.Case.Utility
*/
class DebuggerTest extends CakeTestCase {
protected $_restoreError = false;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('debug', 2);
Configure::write('log', false);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
Configure::write('log', true);
if ($this->_restoreError) {
restore_error_handler();
}
}
/**
* testDocRef method
*
* @return void
*/
public function testDocRef() {
ini_set('docref_root', '');
$this->assertEquals(ini_get('docref_root'), '');
$debugger = new Debugger();
$this->assertEquals(ini_get('docref_root'), 'http://php.net/');
}
/**
* test Excerpt writing
*
* @return void
*/
public function testExcerpt() {
$result = Debugger::excerpt(__FILE__, __LINE__, 2);
$this->assertTrue(is_array($result));
$this->assertEquals(5, count($result));
$this->assertRegExp('/function(.+)testExcerpt/', $result[1]);
$result = Debugger::excerpt(__FILE__, 2, 2);
$this->assertTrue(is_array($result));
$this->assertEquals(4, count($result));
$pattern = '/<code>.*?<span style\="color\: \#\d+">.*?&lt;\?php/';
$this->assertRegExp($pattern, $result[0]);
$result = Debugger::excerpt(__FILE__, 10, 2);
$this->assertEquals(5, count($result));
$pattern = '/<span style\="color\: \#\d{6}">\*<\/span>/';
$this->assertRegExp($pattern, $result[0]);
$return = Debugger::excerpt('[internal]', 2, 2);
$this->assertTrue(empty($return));
}
/**
* testOutput method
*
* @return void
*/
public function testOutput() {
set_error_handler('Debugger::showError');
$this->_restoreError = true;
$result = Debugger::output(false);
$this->assertEquals('', $result);
$out .= '';
$result = Debugger::output(true);
$this->assertEquals('Notice', $result[0]['error']);
$this->assertRegExp('/Undefined variable\:\s+out/', $result[0]['description']);
$this->assertRegExp('/DebuggerTest::testOutput/i', $result[0]['trace']);
ob_start();
Debugger::output('txt');
$other .= '';
$result = ob_get_clean();
$this->assertRegExp('/Undefined variable:\s+other/', $result);
$this->assertRegExp('/Context:/', $result);
$this->assertRegExp('/DebuggerTest::testOutput/i', $result);
ob_start();
Debugger::output('html');
$wrong .= '';
$result = ob_get_clean();
$this->assertRegExp('/<pre class="cake-error">.+<\/pre>/', $result);
$this->assertRegExp('/<b>Notice<\/b>/', $result);
$this->assertRegExp('/variable:\s+wrong/', $result);
ob_start();
Debugger::output('js');
$buzz .= '';
$result = explode('</a>', ob_get_clean());
$this->assertTags($result[0], array(
'pre' => array('class' => 'cake-error'),
'a' => array(
'href' => "javascript:void(0);",
'onclick' => "preg:/document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display = " .
"\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
" \? '' \: 'none'\);/"
),
'b' => array(), 'Notice', '/b', ' (8)',
));
$this->assertRegExp('/Undefined variable:\s+buzz/', $result[1]);
$this->assertRegExp('/<a[^>]+>Code/', $result[1]);
$this->assertRegExp('/<a[^>]+>Context/', $result[2]);
$this->assertContains('$wrong = &#039;&#039;', $result[3], 'Context should be HTML escaped.');
}
/**
* Tests that changes in output formats using Debugger::output() change the templates used.
*
* @return void
*/
public function testChangeOutputFormats() {
set_error_handler('Debugger::showError');
$this->_restoreError = true;
Debugger::output('js', array(
'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
'&line={:line}">{:path}</a>, line {:line}'
));
$result = Debugger::trace();
$this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
Debugger::output('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
'context' => "<context>{:context}</context>",
'trace' => "<stack>{:trace}</stack>",
));
Debugger::output('xml');
ob_start();
$foo .= '';
$result = ob_get_clean();
$data = array(
'error' => array(),
'code' => array(), '8', '/code',
'file' => array(), 'preg:/[^<]+/', '/file',
'line' => array(), '' . (intval(__LINE__) - 7), '/line',
'preg:/Undefined variable:\s+foo/',
'/error'
);
$this->assertTags($result, $data, true);
}
/**
* Test that outputAs works.
*
* @return void
*/
public function testOutputAs() {
Debugger::outputAs('html');
$this->assertEquals('html', Debugger::outputAs());
}
/**
* Test that choosing a non-existent format causes an exception
*
* @expectedException CakeException
* @return void
*/
public function testOutputAsException() {
Debugger::outputAs('Invalid junk');
}
/**
* Tests that changes in output formats using Debugger::output() change the templates used.
*
* @return void
*/
public function testAddFormat() {
set_error_handler('Debugger::showError');
$this->_restoreError = true;
Debugger::addFormat('js', array(
'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
'&line={:line}">{:path}</a>, line {:line}'
));
Debugger::outputAs('js');
$result = Debugger::trace();
$this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
Debugger::addFormat('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
));
Debugger::outputAs('xml');
ob_start();
$foo .= '';
$result = ob_get_clean();
$data = array(
'<error',
'<code', '8', '/code',
'<file', 'preg:/[^<]+/', '/file',
'<line', '' . (intval(__LINE__) - 7), '/line',
'preg:/Undefined variable:\s+foo/',
'/error'
);
$this->assertTags($result, $data, true);
}
/**
* Test adding a format that is handled by a callback.
*
* @return void
*/
public function testAddFormatCallback() {
set_error_handler('Debugger::showError');
$this->_restoreError = true;
Debugger::addFormat('callback', array('callback' => array($this, 'customFormat')));
Debugger::outputAs('callback');
ob_start();
$foo .= '';
$result = ob_get_clean();
$this->assertContains('Notice: I eated an error', $result);
$this->assertContains('DebuggerTest.php', $result);
}
/**
* Test method for testing addFormat with callbacks.
*/
public function customFormat($error, $strings) {
return $error['error'] . ': I eated an error ' . $error['file'];
}
/**
* testTrimPath method
*
* @return void
*/
public function testTrimPath() {
$this->assertEquals('APP' . DS, Debugger::trimPath(APP));
$this->assertEquals('CORE', Debugger::trimPath(CAKE_CORE_INCLUDE_PATH));
$this->assertEquals('ROOT', Debugger::trimPath(ROOT));
$this->assertEquals('CORE' . DS . 'Cake' . DS, Debugger::trimPath(CAKE));
$this->assertEquals('Some/Other/Path', Debugger::trimPath('Some/Other/Path'));
}
/**
* testExportVar method
*
* @return void
*/
public function testExportVar() {
App::uses('Controller', 'Controller');
$Controller = new Controller();
$Controller->helpers = array('Html', 'Form');
$View = new View($Controller);
$View->int = 2;
$View->float = 1.333;
$result = Debugger::exportVar($View);
$expected = <<<TEXT
object(View) {
Helpers => object(HelperCollection) {}
Blocks => object(ViewBlock) {}
plugin => null
name => ''
passedArgs => array()
helpers => array(
(int) 0 => 'Html',
(int) 1 => 'Form'
)
viewPath => ''
viewVars => array()
view => null
layout => 'default'
layoutPath => null
autoLayout => true
ext => '.ctp'
subDir => null
theme => null
cacheAction => false
validationErrors => array()
hasRendered => false
uuids => array()
request => object(CakeRequest) {}
response => object(CakeResponse) {}
elementCache => 'default'
int => (int) 2
float => (float) 1.333
}
TEXT;
$this->assertTextEquals($expected, $result);
$data = array(
1 => 'Index one',
5 => 'Index five'
);
$result = Debugger::exportVar($data);
$expected = <<<TEXT
array(
(int) 1 => 'Index one',
(int) 5 => 'Index five'
)
TEXT;
$this->assertTextEquals($expected, $result);
$data = array(
'key' => array(
'value'
)
);
$result = Debugger::exportVar($data, 1);
$expected = <<<TEXT
array(
'key' => array(
[maximum depth reached]
)
)
TEXT;
$this->assertTextEquals($expected, $result);
}
/**
* testLog method
*
* @return void
*/
public function testLog() {
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
Debugger::log('cool');
$result = file_get_contents(LOGS . 'debug.log');
$this->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
$this->assertRegExp("/'cool'/", $result);
unlink(LOGS . 'debug.log');
Debugger::log(array('whatever', 'here'));
$result = file_get_contents(LOGS . 'debug.log');
$this->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
$this->assertRegExp('/\[main\]/', $result);
$this->assertRegExp('/array/', $result);
$this->assertRegExp("/'whatever',/", $result);
$this->assertRegExp("/'here'/", $result);
}
/**
* testDump method
*
* @return void
*/
public function testDump() {
$var = array('People' => array(
array(
'name' => 'joeseph',
'coat' => 'technicolor',
'hair_color' => 'brown'
),
array(
'name' => 'Shaft',
'coat' => 'black',
'hair' => 'black'
)
));
ob_start();
Debugger::dump($var);
$result = ob_get_clean();
$expected = <<<TEXT
<pre>array(
'People' => array(
(int) 0 => array(
'name' => 'joeseph',
'coat' => 'technicolor',
'hair_color' => 'brown'
),
(int) 1 => array(
'name' => 'Shaft',
'coat' => 'black',
'hair' => 'black'
)
)
)</pre>
TEXT;
$this->assertTextEquals($expected, $result);
}
/**
* test getInstance.
*
* @return void
*/
public function testGetInstance() {
$result = Debugger::getInstance();
$this->assertInstanceOf('Debugger', $result);
$result = Debugger::getInstance('DebuggerTestCaseDebugger');
$this->assertInstanceOf('DebuggerTestCaseDebugger', $result);
$result = Debugger::getInstance();
$this->assertInstanceOf('DebuggerTestCaseDebugger', $result);
$result = Debugger::getInstance('Debugger');
$this->assertInstanceOf('Debugger', $result);
}
/**
* testNoDbCredentials
*
* If a connection error occurs, the config variable is passed through exportVar
* *** our database login credentials such that they are never visible
*
* @return void
*/
public function testNoDbCredentials() {
$config = array(
'datasource' => 'mysql',
'persistent' => false,
'host' => 'void.cakephp.org',
'login' => 'cakephp-user',
'password' => 'cakephp-password',
'database' => 'cakephp-database',
'prefix' => ''
);
$output = Debugger::exportVar($config);
$expectedArray = array(
'datasource' => 'mysql',
'persistent' => false,
'host' => '*****',
'login' => '*****',
'password' => '*****',
'database' => '*****',
'prefix' => ''
);
$expected = Debugger::exportVar($expectedArray);
$this->assertEquals($expected, $output);
}
/**
* Test that exportVar() doesn't loop through recursive structures.
*
* @return void
*/
public function testExportVarRecursion() {
$output = Debugger::exportVar($GLOBALS);
$this->assertContains("'GLOBALS' => [recursion]", $output);
}
/**
* test trace exclude
*
* @return void
*/
public function testTraceExclude() {
$result = Debugger::trace();
$this->assertRegExp('/^DebuggerTest::testTraceExclude/', $result);
$result = Debugger::trace(array(
'exclude' => array('DebuggerTest::testTraceExclude')
));
$this->assertNotRegExp('/^DebuggerTest::testTraceExclude/', $result);
}
}

View file

@ -0,0 +1,557 @@
<?php
/**
* FileTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
/**
* FileTest class
*
* @package Cake.Test.Case.Utility
*/
class FileTest extends CakeTestCase {
/**
* File property
*
* @var mixed null
*/
public $File = null;
/**
* setup the test case
*
* @return void
*/
public function setUp() {
parent::setUp();
$file = __FILE__;
$this->File = new File($file);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
$this->File->close();
unset($this->File);
$Folder = new Folder();
$Folder->delete(TMP . 'tests' . DS . 'permissions');
}
/**
* testBasic method
*
* @return void
*/
public function testBasic() {
$file = CAKE . DS . 'LICENSE.txt';
$this->File = new File($file, false);
$result = $this->File->name;
$expecting = basename($file);
$this->assertEquals($expecting, $result);
$result = $this->File->info();
$expecting = array(
'dirname' => dirname($file),
'basename' => basename($file),
'extension' => 'txt',
'filename' => 'LICENSE',
'filesize' => filesize($file),
'mime' => 'text/plain'
);
if (
!function_exists('finfo_open') &&
(!function_exists('mime_content_type') ||
function_exists('mime_content_type') &&
mime_content_type($this->File->pwd()) === false)
) {
$expecting['mime'] = false;
}
$this->assertEquals($expecting, $result);
$result = $this->File->ext();
$expecting = 'txt';
$this->assertEquals($expecting, $result);
$result = $this->File->name();
$expecting = 'LICENSE';
$this->assertEquals($expecting, $result);
$result = $this->File->md5();
$expecting = md5_file($file);
$this->assertEquals($expecting, $result);
$result = $this->File->md5(true);
$expecting = md5_file($file);
$this->assertEquals($expecting, $result);
$result = $this->File->size();
$expecting = filesize($file);
$this->assertEquals($expecting, $result);
$result = $this->File->owner();
$expecting = fileowner($file);
$this->assertEquals($expecting, $result);
$result = $this->File->group();
$expecting = filegroup($file);
$this->assertEquals($expecting, $result);
$result = $this->File->Folder();
$this->assertInstanceOf('Folder', $result);
}
/**
* testPermission method
*/
public function testPermission() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'File permissions tests not supported on Windows.');
$dir = TMP . 'tests' . DS . 'permissions' . DS;
$Folder = new Folder($dir);
$old = umask();
umask(0002);
$file = $dir . 'permission_' . uniqid();
$expecting = decoct(0664 & ~umask());
$File = new File($file, true);
$result = $File->perms();
$this->assertEquals($expecting, $result);
$File->delete();
umask(0022);
$file = $dir . 'permission_' . uniqid();
$expecting = decoct(0644 & ~umask());
$File = new File($file, true);
$result = $File->perms();
$this->assertEquals($expecting, $result);
$File->delete();
umask(0422);
$file = $dir . 'permission_' . uniqid();
$expecting = decoct(0244 & ~umask());
$File = new File($file, true);
$result = $File->perms();
$this->assertEquals($expecting, $result);
$File->delete();
umask(0444);
$file = $dir . 'permission_' . uniqid();
$expecting = decoct(0222 & ~umask());
$File = new File($file, true);
$result = $File->perms();
$this->assertEquals($expecting, $result);
$File->delete();
umask($old);
}
/**
* testRead method
*
* @return void
*/
public function testRead() {
$file = __FILE__;
$this->File = new File($file);
$result = $this->File->read();
$expecting = file_get_contents(__FILE__);
$this->assertEquals($expecting, $result);
$this->assertTrue(!is_resource($this->File->handle));
$this->File->lock = true;
$result = $this->File->read();
$expecting = file_get_contents(__FILE__);
$this->assertEquals(trim($expecting), $result);
$this->File->lock = null;
$data = $expecting;
$expecting = substr($data, 0, 3);
$result = $this->File->read(3);
$this->assertEquals($expecting, $result);
$this->assertTrue(is_resource($this->File->handle));
$expecting = substr($data, 3, 3);
$result = $this->File->read(3);
$this->assertEquals($expecting, $result);
}
/**
* testOffset method
*
* @return void
*/
public function testOffset() {
$this->File->close();
$result = $this->File->offset();
$this->assertFalse($result);
$this->assertFalse(is_resource($this->File->handle));
$success = $this->File->offset(0);
$this->assertTrue($success);
$this->assertTrue(is_resource($this->File->handle));
$result = $this->File->offset();
$expecting = 0;
$this->assertSame($result, $expecting);
$data = file_get_contents(__FILE__);
$success = $this->File->offset(5);
$expecting = substr($data, 5, 3);
$result = $this->File->read(3);
$this->assertTrue($success);
$this->assertEquals($expecting, $result);
$result = $this->File->offset();
$expecting = 5 + 3;
$this->assertSame($result, $expecting);
}
/**
* testOpen method
*
* @return void
*/
public function testOpen() {
$this->File->handle = null;
$r = $this->File->open();
$this->assertTrue(is_resource($this->File->handle));
$this->assertTrue($r);
$handle = $this->File->handle;
$r = $this->File->open();
$this->assertTrue($r);
$this->assertTrue($handle === $this->File->handle);
$this->assertTrue(is_resource($this->File->handle));
$r = $this->File->open('r', true);
$this->assertTrue($r);
$this->assertFalse($handle === $this->File->handle);
$this->assertTrue(is_resource($this->File->handle));
}
/**
* testClose method
*
* @return void
*/
public function testClose() {
$this->File->handle = null;
$this->assertFalse(is_resource($this->File->handle));
$this->assertTrue($this->File->close());
$this->assertFalse(is_resource($this->File->handle));
$this->File->handle = fopen(__FILE__, 'r');
$this->assertTrue(is_resource($this->File->handle));
$this->assertTrue($this->File->close());
$this->assertFalse(is_resource($this->File->handle));
}
/**
* testCreate method
*
* @return void
*/
public function testCreate() {
$tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
$File = new File($tmpFile, true, 0777);
$this->assertTrue($File->exists());
}
/**
* testOpeningNonExistentFileCreatesIt method
*
* @return void
*/
public function testOpeningNonExistentFileCreatesIt() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertEquals('', $someFile->read());
$someFile->close();
$someFile->delete();
}
/**
* testPrepare method
*
* @return void
*/
public function testPrepare() {
$string = "some\nvery\ncool\r\nteststring here\n\n\nfor\r\r\n\n\r\n\nhere";
if (DS == '\\') {
$expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n";
$expected .= "for\r\n\r\n\r\n\r\n\r\nhere";
} else {
$expected = "some\nvery\ncool\nteststring here\n\n\nfor\n\n\n\n\nhere";
}
$this->assertSame(File::prepare($string), $expected);
$expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n";
$expected .= "for\r\n\r\n\r\n\r\n\r\nhere";
$this->assertSame(File::prepare($string, true), $expected);
}
/**
* testReadable method
*
* @return void
*/
public function testReadable() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->readable());
$someFile->close();
$someFile->delete();
}
/**
* testWritable method
*
* @return void
*/
public function testWritable() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertTrue($someFile->writable());
$someFile->close();
$someFile->delete();
}
/**
* testExecutable method
*
* @return void
*/
public function testExecutable() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertTrue($someFile->open());
$this->assertFalse($someFile->executable());
$someFile->close();
$someFile->delete();
}
/**
* testLastAccess method
*
* @return void
*/
public function testLastAccess() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastAccess());
$this->assertTrue($someFile->open());
$this->assertWithinMargin($someFile->lastAccess(), time(), 2);
$someFile->close();
$someFile->delete();
}
/**
* testLastChange method
*
* @return void
*/
public function testLastChange() {
$someFile = new File(TMP . 'some_file.txt', false);
$this->assertFalse($someFile->lastChange());
$this->assertTrue($someFile->open('r+'));
$this->assertWithinMargin($someFile->lastChange(), time(), 2);
$someFile->write('something');
$this->assertWithinMargin($someFile->lastChange(), time(), 2);
$someFile->close();
$someFile->delete();
}
/**
* testWrite method
*
* @return void
*/
public function testWrite() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
$TmpFile = new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$this->assertFalse(is_resource($TmpFile->handle));
$testData = array('CakePHP\'s', ' test suite', ' was here ...', '');
foreach ($testData as $data) {
$r = $TmpFile->write($data);
$this->assertTrue($r);
$this->assertTrue(file_exists($tmpFile));
$this->assertEquals($data, file_get_contents($tmpFile));
$this->assertTrue(is_resource($TmpFile->handle));
$TmpFile->close();
}
unlink($tmpFile);
}
/**
* testAppend method
*
* @return void
*/
public function testAppend() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
$TmpFile = new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$fragments = array('CakePHP\'s', ' test suite', ' was here ...', '');
$data = null;
foreach ($fragments as $fragment) {
$r = $TmpFile->append($fragment);
$this->assertTrue($r);
$this->assertTrue(file_exists($tmpFile));
$data = $data . $fragment;
$this->assertEquals($data, file_get_contents($tmpFile));
$TmpFile->close();
}
}
/**
* testDelete method
*
* @return void
*/
public function testDelete() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
}
if (!file_exists($tmpFile)) {
touch($tmpFile);
}
$TmpFile = new File($tmpFile);
$this->assertTrue(file_exists($tmpFile));
$result = $TmpFile->delete();
$this->assertTrue($result);
$this->assertFalse(file_exists($tmpFile));
$TmpFile = new File('/this/does/not/exist');
$result = $TmpFile->delete();
$this->assertFalse($result);
}
/**
* Windows has issues unlinking files if there are
* active filehandles open.
*
* @return void
*/
public function testDeleteAfterRead() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
}
if (!file_exists($tmpFile)) {
touch($tmpFile);
}
$File = new File($tmpFile);
$File->read();
$this->assertTrue($File->delete());
}
/**
* testCopy method
*
* @return void
*/
public function testCopy() {
$dest = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
$file = __FILE__;
$this->File = new File($file);
$result = $this->File->copy($dest);
$this->assertTrue($result);
$result = $this->File->copy($dest, true);
$this->assertTrue($result);
$result = $this->File->copy($dest, false);
$this->assertFalse($result);
$this->File->close();
unlink($dest);
$TmpFile = new File('/this/does/not/exist');
$result = $TmpFile->copy($dest);
$this->assertFalse($result);
$TmpFile->close();
}
/**
* Test mime()
*
* @return void
*/
public function testMime() {
$this->skipIf(!function_exists('finfo_open') && !function_exists('mime_content_type'), 'Not able to read mime type');
$path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
$file = new File($path);
$expected = 'image/gif';
if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) {
$expected = false;
}
$this->assertEquals($expected, $file->mime());
}
/**
* getTmpFile method
*
* @param bool $paintSkip
* @return void
*/
protected function _getTmpFile($paintSkip = true) {
$tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
if (is_writable(dirname($tmpFile)) && (!file_exists($tmpFile) || is_writable($tmpFile))) {
return $tmpFile;
};
if ($paintSkip) {
$trace = debug_backtrace();
$caller = $trace[0]['function'];
$shortPath = dirname($tmpFile);
$message = __d('cake_dev', '[FileTest] Skipping %s because "%s" not writeable!', $caller, $shortPath);
$this->markTestSkipped($message);
}
return false;
}
}

View file

@ -0,0 +1,937 @@
<?php
/**
* FolderTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
/**
* FolderTest class
*
* @package Cake.Test.Case.Utility
*/
class FolderTest extends CakeTestCase {
protected static $_tmp = array();
/**
* Save the directory names in TMP
*
* @return void
*/
public static function setUpBeforeClass() {
foreach (scandir(TMP) as $file) {
if (is_dir(TMP . $file) && !in_array($file, array('.', '..'))) {
self::$_tmp[] = $file;
}
}
}
/**
* setUp clearstatcache() to flush file descriptors.
*
* @return void
*/
public function setUp() {
parent::setUp();
clearstatcache();
}
/**
* Restore the TMP directory to its original state.
*
* @return void
*/
public function tearDown() {
$exclude = array_merge(self::$_tmp, array('.', '..'));
foreach (scandir(TMP) as $dir) {
if (is_dir(TMP . $dir) && !in_array($dir, $exclude)) {
$iterator = new RecursiveDirectoryIterator(TMP . $dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
if ($file->isFile() || $file->isLink()) {
unlink($file->getPathname());
} elseif ($file->isDir() && !in_array($file->getFilename(), array('.', '..'))) {
rmdir($file->getPathname());
}
}
rmdir(TMP . $dir);
}
}
}
/**
* testBasic method
*
* @return void
*/
public function testBasic() {
$path = dirname(__FILE__);
$Folder = new Folder($path);
$result = $Folder->pwd();
$this->assertEquals($path, $result);
$result = Folder::addPathElement($path, 'test');
$expected = $path . DS . 'test';
$this->assertEquals($expected, $result);
$result = $Folder->cd(ROOT);
$expected = ROOT;
$this->assertEquals($expected, $result);
$result = $Folder->cd(ROOT . DS . 'non-existent');
$this->assertFalse($result);
}
/**
* testInPath method
*
* @return void
*/
public function testInPath() {
$path = dirname(dirname(__FILE__));
$inside = dirname($path) . DS;
$Folder = new Folder($path);
$result = $Folder->pwd();
$this->assertEquals($path, $result);
$result = Folder::isSlashTerm($inside);
$this->assertTrue($result);
$result = $Folder->realpath('Test/');
$this->assertEquals($path . DS . 'Test' . DS, $result);
$result = $Folder->inPath('Test' . DS);
$this->assertTrue($result);
$result = $Folder->inPath(DS . 'non-existing' . $inside);
$this->assertFalse($result);
$result = $Folder->inPath($path . DS . 'Model', true);
$this->assertTrue($result);
}
/**
* test creation of single and multiple paths.
*
* @return void
*/
public function testCreation() {
$Folder = new Folder(TMP . 'tests');
$result = $Folder->create(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third');
$this->assertTrue($result);
rmdir(TMP . 'tests' . DS . 'first' . DS . 'second' . DS . 'third');
rmdir(TMP . 'tests' . DS . 'first' . DS . 'second');
rmdir(TMP . 'tests' . DS . 'first');
$Folder = new Folder(TMP . 'tests');
$result = $Folder->create(TMP . 'tests' . DS . 'first');
$this->assertTrue($result);
rmdir(TMP . 'tests' . DS . 'first');
}
/**
* test that creation of folders with trailing ds works
*
* @return void
*/
public function testCreateWithTrailingDs() {
$Folder = new Folder(TMP);
$path = TMP . 'tests' . DS . 'trailing' . DS . 'dir' . DS;
$result = $Folder->create($path);
$this->assertTrue($result);
$this->assertTrue(is_dir($path), 'Folder was not made');
$Folder = new Folder(TMP . 'tests' . DS . 'trailing');
$this->assertTrue($Folder->delete());
}
/**
* test recursive directory create failure.
*
* @return void
*/
public function testRecursiveCreateFailure() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.');
$path = TMP . 'tests' . DS . 'one';
mkdir($path);
chmod($path, '0444');
try {
$Folder = new Folder($path);
$result = $Folder->create($path . DS . 'two' . DS . 'three');
$this->assertFalse($result);
} catch (PHPUnit_Framework_Error $e) {
$this->assertTrue(true);
}
chmod($path, '0777');
rmdir($path);
}
/**
* testOperations method
*
* @return void
*/
public function testOperations() {
$path = CAKE . 'Console' . DS . 'Templates' . DS . 'skel';
$Folder = new Folder($path);
$result = is_dir($Folder->pwd());
$this->assertTrue($result);
$new = TMP . 'test_folder_new';
$result = $Folder->create($new);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->copy($copy);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->copy($copy);
$this->assertTrue($result);
$copy = TMP . 'test_folder_copy';
$result = $Folder->chmod($copy, 0755, false);
$this->assertTrue($result);
$result = $Folder->cd($copy);
$this->assertTrue((bool)$result);
$mv = TMP . 'test_folder_mv';
$result = $Folder->move($mv);
$this->assertTrue($result);
$mv = TMP . 'test_folder_mv_2';
$result = $Folder->move($mv);
$this->assertTrue($result);
$result = $Folder->delete($new);
$this->assertTrue($result);
$result = $Folder->delete($mv);
$this->assertTrue($result);
$result = $Folder->delete($mv);
$this->assertTrue($result);
$new = APP . 'index.php';
$result = $Folder->create($new);
$this->assertFalse($result);
$expected = $new . ' is a file';
$result = $Folder->errors();
$this->assertEquals($expected, $result[0]);
$new = TMP . 'test_folder_new';
$result = $Folder->create($new);
$this->assertTrue($result);
$result = $Folder->cd($new);
$this->assertTrue((bool)$result);
$result = $Folder->delete();
$this->assertTrue($result);
$Folder = new Folder('non-existent');
$result = $Folder->pwd();
$this->assertNull($result);
}
/**
* testChmod method
*
* @return void
*/
public function testChmod() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Folder permissions tests not supported on Windows.');
$path = TMP;
$Folder = new Folder($path);
$subdir = 'test_folder_new';
$new = TMP . $subdir;
$this->assertTrue($Folder->create($new));
$this->assertTrue($Folder->create($new . DS . 'test1'));
$this->assertTrue($Folder->create($new . DS . 'test2'));
$filePath = $new . DS . 'test1.php';
$File = new File($filePath);
$this->assertTrue($File->create());
$filePath = $new . DS . 'skip_me.php';
$File = new File($filePath);
$this->assertTrue($File->create());
$this->assertTrue($Folder->chmod($new, 0755, true));
$perms = substr(sprintf('%o', fileperms($new . DS . 'test2')), -4);
$this->assertEquals('0755', $perms);
$this->assertTrue($Folder->chmod($new, 0744, true, array('skip_me.php', 'test2')));
$perms = substr(sprintf('%o', fileperms($new . DS . 'test2')), -4);
$this->assertEquals('0755', $perms);
$perms = substr(sprintf('%o', fileperms($new . DS . 'test1')), -4);
$this->assertEquals('0744', $perms);
$Folder->delete($new);
}
/**
* testRealPathForWebroot method
*
* @return void
*/
public function testRealPathForWebroot() {
$Folder = new Folder('files/');
$this->assertEquals(realpath('files/'), $Folder->path);
}
/**
* testZeroAsDirectory method
*
* @return void
*/
public function testZeroAsDirectory() {
$Folder = new Folder(TMP);
$new = TMP . '0';
$this->assertTrue($Folder->create($new));
$result = $Folder->read(true, true);
$expected = array('0', 'cache', 'logs', 'sessions', 'tests');
$this->assertEquals($expected, $result[0]);
$result = $Folder->read(true, array('logs'));
$expected = array('0', 'cache', 'sessions', 'tests');
$this->assertEquals($expected, $result[0]);
$result = $Folder->delete($new);
$this->assertTrue($result);
}
/**
* test Adding path elements to a path
*
* @return void
*/
public function testAddPathElement() {
$result = Folder::addPathElement(DS . 'some' . DS . 'dir', 'another_path');
$this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result);
$result = Folder::addPathElement(DS . 'some' . DS . 'dir' . DS, 'another_path');
$this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result);
}
/**
* testFolderRead method
*
* @return void
*/
public function testFolderRead() {
$Folder = new Folder(TMP);
$expected = array('cache', 'logs', 'sessions', 'tests');
$result = $Folder->read(true, true);
$this->assertEquals($expected, $result[0]);
$Folder->path = TMP . 'non-existent';
$expected = array(array(), array());
$result = $Folder->read(true, true);
$this->assertEquals($expected, $result);
}
/**
* testFolderReadWithHiddenFiles method
*
* @return void
*/
public function testFolderReadWithHiddenFiles() {
$this->skipIf(!is_writeable(TMP), 'Cant test Folder::read with hidden files unless the tmp folder is writable.');
$Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777);
mkdir($Folder->path . DS . '.svn');
mkdir($Folder->path . DS . 'some_folder');
touch($Folder->path . DS . 'not_hidden.txt');
touch($Folder->path . DS . '.hidden.txt');
$expected = array(
array('some_folder'),
array('not_hidden.txt'),
);
$result = $Folder->read(true, true);
$this->assertEquals($expected, $result);
$expected = array(
array(
'.svn',
'some_folder'
),
array(
'.hidden.txt',
'not_hidden.txt'
),
);
$result = $Folder->read(true);
$this->assertEquals($expected, $result);
}
/**
* testFolderTree method
*
* @return void
*/
public function testFolderTree() {
$Folder = new Folder();
$expected = array(
array(
CAKE . 'Config',
CAKE . 'Config' . DS . 'unicode',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding'
),
array(
CAKE . 'Config' . DS . 'config.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0080_00ff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0100_017f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0180_024F.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0250_02af.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0370_03ff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0400_04ff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0500_052f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '0530_058f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '1e00_1eff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '1f00_1fff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2100_214f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2150_218f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2460_24ff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c00_2c5f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c60_2c7f.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . '2c80_2cff.php',
CAKE . 'Config' . DS . 'unicode' . DS . 'casefolding' . DS . 'ff00_ffef.php'
)
);
$result = $Folder->tree(CAKE . 'Config', false);
$this->assertSame(array(), array_diff($expected[0], $result[0]));
$this->assertSame(array(), array_diff($result[0], $expected[0]));
$result = $Folder->tree(CAKE . 'Config', false, 'dir');
$this->assertSame(array(), array_diff($expected[0], $result));
$this->assertSame(array(), array_diff($expected[0], $result));
$result = $Folder->tree(CAKE . 'Config', false, 'files');
$this->assertSame(array(), array_diff($expected[1], $result));
$this->assertSame(array(), array_diff($expected[1], $result));
}
/**
* testFolderTreeWithHiddenFiles method
*
* @return void
*/
public function testFolderTreeWithHiddenFiles() {
$this->skipIf(!is_writeable(TMP), 'Can\'t test Folder::tree with hidden files unless the tmp folder is writable.');
$Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777);
mkdir($Folder->path . DS . '.svn', 0777, true);
touch($Folder->path . DS . '.svn' . DS . 'InHiddenFolder.php');
mkdir($Folder->path . DS . '.svn' . DS . 'inhiddenfolder');
touch($Folder->path . DS . '.svn' . DS . 'inhiddenfolder' . DS . 'NestedInHiddenFolder.php');
touch($Folder->path . DS . 'not_hidden.txt');
touch($Folder->path . DS . '.hidden.txt');
mkdir($Folder->path . DS . 'visible_folder' . DS . '.git', 0777, true);
$expected = array(
array(
$Folder->path,
$Folder->path . DS . 'visible_folder',
),
array(
$Folder->path . DS . 'not_hidden.txt',
),
);
$result = $Folder->tree(null, true);
$this->assertEquals($expected, $result);
$result = $Folder->tree(null, array('.'));
$this->assertEquals($expected, $result);
$expected = array(
array(
$Folder->path,
$Folder->path . DS . 'visible_folder',
$Folder->path . DS . 'visible_folder' . DS . '.git',
$Folder->path . DS . '.svn',
$Folder->path . DS . '.svn' . DS . 'inhiddenfolder',
),
array(
$Folder->path . DS . 'not_hidden.txt',
$Folder->path . DS . '.hidden.txt',
$Folder->path . DS . '.svn' . DS . 'inhiddenfolder' . DS . 'NestedInHiddenFolder.php',
$Folder->path . DS . '.svn' . DS . 'InHiddenFolder.php',
),
);
$result = $Folder->tree(null, false);
sort($result[0]);
sort($expected[0]);
sort($result[1]);
sort($expected[1]);
$this->assertEquals($expected, $result);
$Folder->delete();
}
/**
* testWindowsPath method
*
* @return void
*/
public function testWindowsPath() {
$this->assertFalse(Folder::isWindowsPath('0:\\cake\\is\\awesome'));
$this->assertTrue(Folder::isWindowsPath('C:\\cake\\is\\awesome'));
$this->assertTrue(Folder::isWindowsPath('d:\\cake\\is\\awesome'));
$this->assertTrue(Folder::isWindowsPath('\\\\vmware-host\\Shared Folders\\file'));
}
/**
* testIsAbsolute method
*
* @return void
*/
public function testIsAbsolute() {
$this->assertFalse(Folder::isAbsolute('path/to/file'));
$this->assertFalse(Folder::isAbsolute('cake/'));
$this->assertFalse(Folder::isAbsolute('path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('\\path/to/file'));
$this->assertFalse(Folder::isAbsolute('\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('/usr/local'));
$this->assertTrue(Folder::isAbsolute('//path/to/file'));
$this->assertTrue(Folder::isAbsolute('C:\\cake'));
$this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('\\\\vmware-host\\Shared Folders\\file'));
}
/**
* testIsSlashTerm method
*
* @return void
*/
public function testIsSlashTerm() {
$this->assertFalse(Folder::isSlashTerm('cake'));
$this->assertTrue(Folder::isSlashTerm('C:\\cake\\'));
$this->assertTrue(Folder::isSlashTerm('/usr/local/'));
}
/**
* testStatic method
*
* @return void
*/
public function testSlashTerm() {
$result = Folder::slashTerm('/path/to/file');
$this->assertEquals('/path/to/file/', $result);
}
/**
* testNormalizePath method
*
* @return void
*/
public function testNormalizePath() {
$path = '/path/to/file';
$result = Folder::normalizePath($path);
$this->assertEquals('/', $result);
$path = '\\path\\\to\\\file';
$result = Folder::normalizePath($path);
$this->assertEquals('/', $result);
$path = 'C:\\path\\to\\file';
$result = Folder::normalizePath($path);
$this->assertEquals('\\', $result);
}
/**
* correctSlashFor method
*
* @return void
*/
public function testCorrectSlashFor() {
$path = '/path/to/file';
$result = Folder::correctSlashFor($path);
$this->assertEquals('/', $result);
$path = '\\path\\to\\file';
$result = Folder::correctSlashFor($path);
$this->assertEquals('/', $result);
$path = 'C:\\path\to\\file';
$result = Folder::correctSlashFor($path);
$this->assertEquals('\\', $result);
}
/**
* testInCakePath method
*
* @return void
*/
public function testInCakePath() {
$Folder = new Folder();
$Folder->cd(ROOT);
$path = 'C:\\path\\to\\file';
$result = $Folder->inCakePath($path);
$this->assertFalse($result);
$path = ROOT;
$Folder->cd(ROOT);
$result = $Folder->inCakePath($path);
$this->assertFalse($result);
$path = DS . 'lib' . DS . 'Cake' . DS . 'Config';
$Folder->cd(ROOT . DS . 'lib' . DS . 'Cake' . DS . 'Config');
$result = $Folder->inCakePath($path);
$this->assertTrue($result);
}
/**
* testFind method
*
* @return void
*/
public function testFind() {
$Folder = new Folder();
$Folder->cd(CAKE . 'Config');
$result = $Folder->find();
$expected = array('config.php');
$this->assertSame(array_diff($expected, $result), array());
$this->assertSame(array_diff($expected, $result), array());
$result = $Folder->find('.*', true);
$expected = array('config.php', 'routes.php');
$this->assertSame($expected, $result);
$result = $Folder->find('.*\.php');
$expected = array('config.php');
$this->assertSame(array_diff($expected, $result), array());
$this->assertSame(array_diff($expected, $result), array());
$result = $Folder->find('.*\.php', true);
$expected = array('config.php', 'routes.php');
$this->assertSame($expected, $result);
$result = $Folder->find('.*ig\.php');
$expected = array('config.php');
$this->assertSame($expected, $result);
$result = $Folder->find('config\.php');
$expected = array('config.php');
$this->assertSame($expected, $result);
$Folder->cd(TMP);
$File = new File($Folder->pwd() . DS . 'paths.php', true);
$Folder->create($Folder->pwd() . DS . 'testme');
$Folder->cd('testme');
$result = $Folder->find('paths\.php');
$expected = array();
$this->assertSame($expected, $result);
$Folder->cd($Folder->pwd() . '/..');
$result = $Folder->find('paths\.php');
$expected = array('paths.php');
$this->assertSame($expected, $result);
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . DS . 'testme');
$File->delete();
}
/**
* testFindRecursive method
*
* @return void
*/
public function testFindRecursive() {
$Folder = new Folder();
$Folder->cd(CAKE);
$result = $Folder->findRecursive('(config|paths)\.php');
$expected = array(
CAKE . 'Config' . DS . 'config.php'
);
$this->assertSame(array_diff($expected, $result), array());
$this->assertSame(array_diff($expected, $result), array());
$result = $Folder->findRecursive('(config|paths)\.php', true);
$expected = array(
CAKE . 'Config' . DS . 'config.php'
);
$this->assertSame($expected, $result);
$Folder->cd(TMP);
$Folder->create($Folder->pwd() . DS . 'testme');
$Folder->cd('testme');
$File = new File($Folder->pwd() . DS . 'paths.php');
$File->create();
$Folder->cd(TMP . 'sessions');
$result = $Folder->findRecursive('paths\.php');
$expected = array();
$this->assertSame($expected, $result);
$Folder->cd(TMP . 'testme');
$File = new File($Folder->pwd() . DS . 'my.php');
$File->create();
$Folder->cd($Folder->pwd() . '/../..');
$result = $Folder->findRecursive('(paths|my)\.php');
$expected = array(
TMP . 'testme' . DS . 'my.php',
TMP . 'testme' . DS . 'paths.php'
);
$this->assertSame(array_diff($expected, $result), array());
$this->assertSame(array_diff($expected, $result), array());
$result = $Folder->findRecursive('(paths|my)\.php', true);
$expected = array(
TMP . 'testme' . DS . 'my.php',
TMP . 'testme' . DS . 'paths.php'
);
$this->assertSame($expected, $result);
$Folder->cd(CAKE . 'Config');
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . DS . 'testme');
$File->delete();
}
/**
* testConstructWithNonExistentPath method
*
* @return void
*/
public function testConstructWithNonExistentPath() {
$Folder = new Folder(TMP . 'config_non_existent', true);
$this->assertTrue(is_dir(TMP . 'config_non_existent'));
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . 'config_non_existent');
}
/**
* testDirSize method
*
* @return void
*/
public function testDirSize() {
$Folder = new Folder(TMP . 'config_non_existent', true);
$this->assertEquals(0, $Folder->dirSize());
$File = new File($Folder->pwd() . DS . 'my.php', true, 0777);
$File->create();
$File->write('something here');
$File->close();
$this->assertEquals(14, $Folder->dirSize());
$Folder->cd(TMP);
$Folder->delete($Folder->pwd() . 'config_non_existent');
}
/**
* testDelete method
*
* @return void
*/
public function testDelete() {
$path = TMP . 'folder_delete_test';
mkdir($path);
touch($path . DS . 'file_1');
mkdir($path . DS . 'level_1_1');
touch($path . DS . 'level_1_1' . DS . 'file_1_1');
mkdir($path . DS . 'level_1_1' . DS . 'level_2_1');
touch($path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_1');
touch($path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_2');
mkdir($path . DS . 'level_1_1' . DS . 'level_2_2');
$Folder = new Folder($path, true);
$return = $Folder->delete();
$this->assertTrue($return);
$messages = $Folder->messages();
$errors = $Folder->errors();
$this->assertEquals(array(), $errors);
$expected = array(
$path . DS . 'file_1 removed',
$path . DS . 'level_1_1' . DS . 'file_1_1 removed',
$path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_1 removed',
$path . DS . 'level_1_1' . DS . 'level_2_1' . DS . 'file_2_2 removed',
$path . DS . 'level_1_1' . DS . 'level_2_1 removed',
$path . DS . 'level_1_1' . DS . 'level_2_2 removed',
$path . DS . 'level_1_1 removed',
$path . ' removed'
);
sort($expected);
sort($messages);
$this->assertEquals($expected, $messages);
}
/**
* testCopy method
*
* Verify that directories and files are copied recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
*/
public function testCopy() {
$path = TMP . 'folder_test';
$folderOne = $path . DS . 'folder1';
$folderTwo = $folderOne . DS . 'folder2';
$folderThree = $path . DS . 'folder3';
$fileOne = $folderOne . DS . 'file1.php';
$fileTwo = $folderTwo . DS . 'file2.php';
new Folder($path, true);
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
touch($fileOne);
touch($fileTwo);
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$Folder = new Folder($folderThree);
$Folder->delete();
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$Folder = new Folder($folderThree);
$Folder->delete();
new Folder($folderThree, true);
new Folder($folderThree . DS . 'folder2', true);
file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php'));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* testMove method
*
* Verify that directories and files are moved recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
*/
public function testMove() {
$path = TMP . 'folder_test';
$folderOne = $path . DS . 'folder1';
$folderTwo = $folderOne . DS . 'folder2';
$folderThree = $path . DS . 'folder3';
$fileOne = $folderOne . DS . 'file1.php';
$fileTwo = $folderTwo . DS . 'file2.php';
new Folder($path, true);
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
touch($fileOne);
touch($fileTwo);
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(is_dir($folderThree . DS . 'folder2'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$Folder = new Folder($folderThree);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderTwo, true);
touch($fileOne);
touch($fileTwo);
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(is_dir($folderThree . DS . 'folder2'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$Folder = new Folder($folderThree);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
new Folder($folderThree . DS . 'folder2', true);
touch($fileOne);
touch($fileTwo);
file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched');
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$Folder = new Folder($path);
$Folder->delete();
}
}

File diff suppressed because it is too large Load diff

View file

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

View file

@ -0,0 +1,595 @@
<?php
/**
* ObjectCollectionTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('ObjectCollection', 'Utility');
App::uses('CakeEvent', 'Event');
/**
* A generic object class
*/
class GenericObject {
/**
* Constructor
*
* @param GenericObjectCollection $collection
* @param array $settings
*/
public function __construct(GenericObjectCollection $collection, $settings = array()) {
$this->_Collection = $collection;
$this->settings = $settings;
}
}
/**
* First Extension of Generic Object
*/
class FirstGenericObject extends GenericObject {
/**
* A generic callback
*/
public function callback() {
}
}
/**
* Second Extension of Generic Object
*/
class SecondGenericObject extends GenericObject {
public function callback() {
}
}
/**
* Third Extension of Generic Object
*/
class ThirdGenericObject extends GenericObject {
public function callback() {
}
}
/**
* A collection of Generic objects
*/
class GenericObjectCollection extends ObjectCollection {
/**
* Loads a generic object
*
* @param string $object Object name
* @param array $settings Settings array
* @return array List of loaded objects
*/
public function load($object, $settings = array()) {
list($plugin, $name) = pluginSplit($object);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
}
$objectClass = $name . 'GenericObject';
$this->_loaded[$name] = new $objectClass($this, $settings);
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->enable($name);
}
return $this->_loaded[$name];
}
}
class ObjectCollectionTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Objects = new GenericObjectCollection();
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Objects);
}
/**
* test triggering callbacks on loaded helpers
*
* @return void
*/
public function testLoad() {
$result = $this->Objects->load('First');
$this->assertInstanceOf('FirstGenericObject', $result);
$this->assertInstanceOf('FirstGenericObject', $this->Objects->First);
$result = $this->Objects->attached();
$this->assertEquals(array('First'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Objects->enabled('First'));
$result = $this->Objects->load('First');
$this->assertSame($result, $this->Objects->First);
}
/**
* test unload()
*
* @return void
*/
public function testUnload() {
$this->Objects->load('First');
$this->Objects->load('Second');
$result = $this->Objects->attached();
$this->assertEquals(array('First', 'Second'), $result, 'loaded objects are wrong');
$this->Objects->unload('First');
$this->assertFalse(isset($this->Objects->First));
$this->assertTrue(isset($this->Objects->Second));
$result = $this->Objects->attached();
$this->assertEquals(array('Second'), $result, 'loaded objects are wrong');
$result = $this->Objects->enabled();
$this->assertEquals(array('Second'), $result, 'enabled objects are wrong');
}
/**
* Tests set()
*
* @return void
*/
public function testSet() {
$this->Objects->load('First');
$result = $this->Objects->attached();
$this->assertEquals(array('First'), $result, 'loaded objects are wrong');
$result = $this->Objects->set('First', new SecondGenericObject($this->Objects));
$this->assertInstanceOf('SecondGenericObject', $result['First'], 'set failed');
$result = $this->Objects->set('Second', new SecondGenericObject($this->Objects));
$this->assertInstanceOf('SecondGenericObject', $result['Second'], 'set failed');
$this->assertEquals(2, count($result));
}
/**
* creates mock classes for testing
*
* @return void
*/
protected function _makeMockClasses() {
if (!class_exists('TriggerMockFirstGenericObject')) {
$this->getMock('FirstGenericObject', array(), array(), 'TriggerMockFirstGenericObject', false);
}
if (!class_exists('TriggerMockSecondGenericObject')) {
$this->getMock('SecondGenericObject', array(), array(), 'TriggerMockSecondGenericObject', false);
}
if (!class_exists('TriggerMockThirdGenericObject')) {
$this->getMock('ThirdGenericObject', array(), array(), 'TriggerMockThirdGenericObject', false);
}
}
/**
* test triggering callbacks.
*
* @return void
*/
public function testTrigger() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->will($this->returnValue(true));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->will($this->returnValue(true));
$this->assertTrue($this->Objects->trigger('callback'));
}
/**
* test trigger and disabled objects
*
* @return void
*/
public function testTriggerWithDisabledObjects() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->will($this->returnValue(true));
$this->Objects->TriggerMockSecond->expects($this->never())
->method('callback')
->will($this->returnValue(true));
$this->Objects->disable('TriggerMockSecond');
$this->assertTrue($this->Objects->trigger('callback', array()));
}
/**
* test that the collectReturn option works.
*
* @return void
*/
public function testTriggerWithCollectReturn() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->will($this->returnValue(array('one', 'two')));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->will($this->returnValue(array('three', 'four')));
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
array('one', 'two'),
array('three', 'four')
);
$this->assertEquals($expected, $result);
}
/**
* test that trigger with break & breakOn works.
*
* @return void
*/
public function testTriggerWithBreak() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->will($this->returnValue(false));
$this->Objects->TriggerMockSecond->expects($this->never())
->method('callback');
$result = $this->Objects->trigger(
'callback',
array(),
array('break' => true, 'breakOn' => false)
);
$this->assertFalse($result);
}
/**
* test that trigger with modParams works.
*
* @return void
*/
public function testTriggerWithModParams() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with(array('value'))
->will($this->returnValue(array('new value')));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->with(array('new value'))
->will($this->returnValue(array('newer value')));
$result = $this->Objects->trigger(
'callback',
array(array('value')),
array('modParams' => 0)
);
$this->assertEquals(array('newer value'), $result);
}
/**
* test that setting modParams to an index that doesn't exist doesn't cause errors.
*
* @expectedException CakeException
* @return void
*/
public function testTriggerModParamsInvalidIndex() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->never())
->method('callback');
$this->Objects->TriggerMockSecond->expects($this->never())
->method('callback');
$result = $this->Objects->trigger(
'callback',
array(array('value')),
array('modParams' => 2)
);
}
/**
* test that returning null doesn't modify parameters.
*
* @return void
*/
public function testTriggerModParamsNullIgnored() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with(array('value'))
->will($this->returnValue(null));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->with(array('value'))
->will($this->returnValue(array('new value')));
$result = $this->Objects->trigger(
'callback',
array(array('value')),
array('modParams' => 0)
);
$this->assertEquals(array('new value'), $result);
}
/**
* test order of callbacks triggering based on priority.
*
* @return void
*/
public function testTriggerPriority() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond', array('priority' => 5));
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->TriggerMockFirst->expects($this->any())
->method('callback')
->will($this->returnValue('1st'));
$this->Objects->TriggerMockSecond->expects($this->any())
->method('callback')
->will($this->returnValue('2nd'));
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->load('TriggerMockThird', array('priority' => 7));
$this->mockObjects[] = $this->Objects->TriggerMockThird;
$this->Objects->TriggerMockThird->expects($this->any())
->method('callback')
->will($this->returnValue('3rd'));
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'3rd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->disable('TriggerMockFirst');
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'3rd'
);
$this->assertEquals($expected, $result);
$this->Objects->enable('TriggerMockFirst');
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'3rd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->disable('TriggerMockThird');
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->enable('TriggerMockThird', false);
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st',
'3rd'
);
$this->assertEquals($expected, $result);
$this->Objects->setPriority('TriggerMockThird', 1);
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'3rd',
'2nd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->disable('TriggerMockThird');
$this->Objects->setPriority('TriggerMockThird', 11);
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st'
);
$this->assertEquals($expected, $result);
$this->Objects->enable('TriggerMockThird');
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st',
'3rd'
);
$this->assertEquals($expected, $result);
$this->Objects->setPriority('TriggerMockThird');
$result = $this->Objects->trigger('callback', array(), array('collectReturn' => true));
$expected = array(
'2nd',
'1st',
'3rd'
);
$this->assertEquals($expected, $result);
}
/**
* test normalizeObjectArray
*
* @return void
*/
public function testnormalizeObjectArray() {
$components = array(
'Html',
'Foo.Bar' => array('one', 'two'),
'Something',
'Banana.Apple' => array('foo' => 'bar')
);
$result = ObjectCollection::normalizeObjectArray($components);
$expected = array(
'Html' => array('class' => 'Html', 'settings' => array()),
'Bar' => array('class' => 'Foo.Bar', 'settings' => array('one', 'two')),
'Something' => array('class' => 'Something', 'settings' => array()),
'Apple' => array('class' => 'Banana.Apple', 'settings' => array('foo' => 'bar')),
);
$this->assertEquals($expected, $result);
// This is the result after Controller::_mergeVars
$components = array(
'Html' => null,
'Foo.Bar' => array('one', 'two'),
'Something' => null,
'Banana.Apple' => array('foo' => 'bar')
);
$result = ObjectCollection::normalizeObjectArray($components);
$this->assertEquals($expected, $result);
}
/**
* tests that passing an instance of CakeEvent to trigger will prepend the subject to the list of arguments
*
* @return void
*/
public function testDispatchEventWithSubject() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$subjectClass = new Object();
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with($subjectClass, 'first argument')
->will($this->returnValue(true));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->with($subjectClass, 'first argument')
->will($this->returnValue(true));
$event = new CakeEvent('callback', $subjectClass, array('first argument'));
$this->assertTrue($this->Objects->trigger($event));
}
/**
* tests that passing an instance of CakeEvent to trigger with omitSubject property
* will NOT prepend the subject to the list of arguments
*
* @return void
*/
public function testDispatchEventNoSubject() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$subjectClass = new Object();
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with('first argument')
->will($this->returnValue(true));
$this->Objects->TriggerMockSecond->expects($this->once())
->method('callback')
->with('first argument')
->will($this->returnValue(true));
$event = new CakeEvent('callback', $subjectClass, array('first argument'));
$event->omitSubject = true;
$this->assertTrue($this->Objects->trigger($event));
}
}

View file

@ -0,0 +1,462 @@
<?php
/**
* SanitizeTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.5428
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Sanitize', 'Utility');
/**
* DataTest class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeDataTest extends CakeTestModel {
/**
* name property
*
* @var string 'SanitizeDataTest'
*/
public $name = 'SanitizeDataTest';
/**
* useTable property
*
* @var string 'data_tests'
*/
public $useTable = 'data_tests';
}
/**
* Article class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeArticle extends CakeTestModel {
/**
* name property
*
* @var string 'Article'
*/
public $name = 'SanitizeArticle';
/**
* useTable property
*
* @var string 'articles'
*/
public $useTable = 'articles';
}
/**
* SanitizeTest class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
*/
public $autoFixtures = false;
/**
* fixtures property
*
* @var array
*/
public $fixtures = array('core.data_test', 'core.article');
/**
* testEscapeAlphaNumeric method
*
* @return void
*/
public function testEscapeAlphaNumeric() {
$resultAlpha = Sanitize::escape('abc', 'test');
$this->assertEquals('abc', $resultAlpha);
$resultNumeric = Sanitize::escape('123', 'test');
$this->assertEquals('123', $resultNumeric);
$resultNumeric = Sanitize::escape(1234, 'test');
$this->assertEquals(1234, $resultNumeric);
$resultNumeric = Sanitize::escape(1234.23, 'test');
$this->assertEquals(1234.23, $resultNumeric);
$resultNumeric = Sanitize::escape('#1234.23', 'test');
$this->assertEquals('#1234.23', $resultNumeric);
$resultNull = Sanitize::escape(null, 'test');
$this->assertEquals(null, $resultNull);
$resultNull = Sanitize::escape(false, 'test');
$this->assertEquals(false, $resultNull);
$resultNull = Sanitize::escape(true, 'test');
$this->assertEquals(true, $resultNull);
}
/**
* testClean method
*
* @return void
*/
public function testClean() {
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test &amp; &quot;quote&quot; &#039;other&#039; ;.$ symbol.another line';
$result = Sanitize::clean($string, array('connection' => 'test'));
$this->assertEquals($expected, $result);
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test & ' . Sanitize::escape('"quote"', 'test') . ' ' . Sanitize::escape('\'other\'', 'test') . ' ;.$ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ $ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$string = 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ \\$ symbol.another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'dollar' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$string = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$expected = 'test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line';
$result = Sanitize::clean($string, array('encode' => false, 'escape' => false, 'carriage' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$array = array(array('test & "quote" \'other\' ;.$ symbol.' . "\r" . 'another line'));
$expected = array(array('test &amp; &quot;quote&quot; &#039;other&#039; ;.$ symbol.another line'));
$result = Sanitize::clean($array, array('connection' => 'test'));
$this->assertEquals($expected, $result);
$array = array(array('test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line'));
$expected = array(array('test & "quote" \'other\' ;.$ $ symbol.another line'));
$result = Sanitize::clean($array, array('encode' => false, 'escape' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$array = array(array('test odd Ä spacesé'));
$expected = array(array('test odd &Auml; spaces&eacute;'));
$result = Sanitize::clean($array, array('odd_spaces' => false, 'escape' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$array = array(array('\\$', array('key' => 'test & "quote" \'other\' ;.$ \\$ symbol.' . "\r" . 'another line')));
$expected = array(array('$', array('key' => 'test & "quote" \'other\' ;.$ $ symbol.another line')));
$result = Sanitize::clean($array, array('encode' => false, 'escape' => false, 'connection' => 'test'));
$this->assertEquals($expected, $result);
$string = '';
$expected = '';
$result = Sanitize::clean($string, array('connection' => 'test'));
$this->assertEquals($expected, $string);
$data = array(
'Grant' => array(
'title' => '2 o clock grant',
'grant_peer_review_id' => 3,
'institution_id' => 5,
'created_by' => 1,
'modified_by' => 1,
'created' => '2010-07-15 14:11:00',
'modified' => '2010-07-19 10:45:41'
),
'GrantsMember' => array(
0 => array(
'id' => 68,
'grant_id' => 120,
'member_id' => 16,
'program_id' => 29,
'pi_percent_commitment' => 1
)
)
);
$result = Sanitize::clean($data, array('connection' => 'test'));
$this->assertEquals($data, $result);
}
/**
* testHtml method
*
* @return void
*/
public function testHtml() {
$string = '<p>This is a <em>test string</em> & so is this</p>';
$expected = 'This is a test string &amp; so is this';
$result = Sanitize::html($string, array('remove' => true));
$this->assertEquals($expected, $result);
$string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true';
$expected = 'The &quot;lazy&quot; dog &#039;jumped&#039; &amp; flew over the moon. If (1+1) = 2 &lt;em&gt;is&lt;/em&gt; true, (2-1) = 1 is also true';
$result = Sanitize::html($string);
$this->assertEquals($expected, $result);
$string = 'The "lazy" dog \'jumped\'';
$expected = 'The &quot;lazy&quot; dog \'jumped\'';
$result = Sanitize::html($string, array('quotes' => ENT_COMPAT));
$this->assertEquals($expected, $result);
$string = 'The "lazy" dog \'jumped\'';
$result = Sanitize::html($string, array('quotes' => ENT_NOQUOTES));
$this->assertEquals($string, $result);
$string = 'The "lazy" dog \'jumped\' & flew over the moon. If (1+1) = 2 <em>is</em> true, (2-1) = 1 is also true';
$expected = 'The &quot;lazy&quot; dog &#039;jumped&#039; &amp; flew over the moon. If (1+1) = 2 &lt;em&gt;is&lt;/em&gt; true, (2-1) = 1 is also true';
$result = Sanitize::html($string);
$this->assertEquals($expected, $result);
$string = 'The "lazy" dog & his friend Apple&reg; conquered the world';
$expected = 'The &quot;lazy&quot; dog &amp; his friend Apple&amp;reg; conquered the world';
$result = Sanitize::html($string);
$this->assertEquals($expected, $result);
$string = 'The "lazy" dog & his friend Apple&reg; conquered the world';
$expected = 'The &quot;lazy&quot; dog &amp; his friend Apple&reg; conquered the world';
$result = Sanitize::html($string, array('double' => false));
$this->assertEquals($expected, $result);
}
/**
* testStripWhitespace method
*
* @return void
*/
public function testStripWhitespace() {
$string = "This sentence \t\t\t has lots of \n\n white\nspace \rthat \r\n needs to be \t \n trimmed.";
$expected = "This sentence has lots of whitespace that needs to be trimmed.";
$result = Sanitize::stripWhitespace($string);
$this->assertEquals($expected, $result);
$text = 'I love ßá†ö√ letters.';
$result = Sanitize::stripWhitespace($text);
$expected = 'I love ßá†ö√ letters.';
$this->assertEquals($expected, $result);
}
/**
* testParanoid method
*
* @return void
*/
public function testParanoid() {
$string = 'I would like to !%@#% & dance & sing ^$&*()-+';
$expected = 'Iwouldliketodancesing';
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
$string = array('This |s th% s0ng that never ends it g*es',
'on and on my friends, b^ca#use it is the',
'so&g th===t never ends.');
$expected = array('This s th% s0ng that never ends it g*es',
'on and on my friends bcause it is the',
'sog tht never ends.');
$result = Sanitize::paranoid($string, array('%', '*', '.', ' '));
$this->assertEquals($expected, $result);
$string = "anything' OR 1 = 1";
$expected = 'anythingOR11';
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
$string = "x' AND email IS NULL; --";
$expected = 'xANDemailISNULL';
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
$string = "x' AND 1=(SELECT COUNT(*) FROM users); --";
$expected = "xAND1SELECTCOUNTFROMusers";
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
$string = "x'; DROP TABLE members; --";
$expected = "xDROPTABLEmembers";
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
}
/**
* testStripImages method
*
* @return void
*/
public function testStripImages() {
$string = '<img src="/img/test.jpg" alt="my image" />';
$expected = 'my image<br />';
$result = Sanitize::stripImages($string);
$this->assertEquals($expected, $result);
$string = '<img src="javascript:alert(\'XSS\');" />';
$expected = '';
$result = Sanitize::stripImages($string);
$this->assertEquals($expected, $result);
$string = '<a href="http://www.badsite.com/phising"><img src="/img/test.jpg" alt="test image alt" title="test image title" id="myImage" class="image-left"/></a>';
$expected = '<a href="http://www.badsite.com/phising">test image alt</a><br />';
$result = Sanitize::stripImages($string);
$this->assertEquals($expected, $result);
$string = '<a onclick="medium()" href="http://example.com"><img src="foobar.png" onclick="evilFunction(); return false;"/></a>';
$expected = '<a onclick="medium()" href="http://example.com"></a>';
$result = Sanitize::stripImages($string);
$this->assertEquals($expected, $result);
}
/**
* testStripScripts method
*
* @return void
*/
public function testStripScripts() {
$string = '<link href="/css/styles.css" media="screen" rel="stylesheet" />';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = '<link href="/css/styles.css" media="screen" rel="stylesheet" />' . "\n" .
'<link rel="icon" href="/favicon.ico" type="image/x-icon" />' . "\n" .
'<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />' . "\n" .
'<link rel="alternate" href="/feed.xml" title="RSS Feed" type="application/rss+xml" />';
$expected = "\n" . '<link rel="icon" href="/favicon.ico" type="image/x-icon" />' . "\n" .
'<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />' . "\n" .
'<link rel="alternate" href="/feed.xml" title="RSS Feed" type="application/rss+xml" />';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = '<script type="text/javascript"> alert("hacked!");</script>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = '<script> alert("hacked!");</script>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = '<style>#content { display:none; }</style>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = '<style type="text/css"><!-- #content { display:none; } --></style>';
$expected = '';
$result = Sanitize::stripScripts($string);
$this->assertEquals($expected, $result);
$string = <<<HTML
text
<style type="text/css">
<!--
#content { display:none; }
-->
</style>
text
HTML;
$expected = "text\n\ntext";
$result = Sanitize::stripScripts($string);
$this->assertTextEquals($expected, $result);
$string = <<<HTML
text
<script type="text/javascript">
<!--
alert('wooo');
-->
</script>
text
HTML;
$expected = "text\n\ntext";
$result = Sanitize::stripScripts($string);
$this->assertTextEquals($expected, $result);
}
/**
* testStripAll method
*
* @return void
*/
public function testStripAll() {
$string = '<img """><script>alert("xss")</script>"/>';
$expected = '"/>';
$result = Sanitize::stripAll($string);
$this->assertEquals($expected, $result);
$string = '<IMG SRC=&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058&#0000097&#0000108&#0000101&#0000114&#0000116&#0000040&#0000039&#0000088&#0000083&#0000083&#0000039&#0000041>';
$expected = '';
$result = Sanitize::stripAll($string);
$this->assertEquals($expected, $result);
$string = '<<script>alert("XSS");//<</script>';
$expected = '<';
$result = Sanitize::stripAll($string);
$this->assertEquals($expected, $result);
$string = '<img src="http://google.com/images/logo.gif" onload="window.location=\'http://sam.com/\'" />' . "\n" .
"<p>This is ok \t\n text</p>\n" .
'<link rel="stylesheet" href="/css/master.css" type="text/css" media="screen" title="my sheet" charset="utf-8">' . "\n" .
'<script src="xss.js" type="text/javascript" charset="utf-8"></script>';
$expected = '<p>This is ok text</p>';
$result = Sanitize::stripAll($string);
$this->assertEquals($expected, $result);
}
/**
* testStripTags method
*
* @return void
*/
public function testStripTags() {
$string = '<h2>Headline</h2><p><a href="http://example.com">My Link</a> could go to a bad site</p>';
$expected = 'Headline<p>My Link could go to a bad site</p>';
$result = Sanitize::stripTags($string, 'h2', 'a');
$this->assertEquals($expected, $result);
$string = '<script type="text/javascript" src="http://evildomain.com"> </script>';
$expected = ' ';
$result = Sanitize::stripTags($string, 'script');
$this->assertEquals($expected, $result);
$string = '<h2>Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here <img src="/img/test.png" />. Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a');
$this->assertEquals($expected, $result);
$string = '<h2>Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here . Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a', 'img');
$this->assertEquals($expected, $result);
$string = '<b>Important message!</b><br>This message will self destruct!';
$expected = 'Important message!<br>This message will self destruct!';
$result = Sanitize::stripTags($string, 'b');
$this->assertEquals($expected, $result);
$string = '<b>Important message!</b><br />This message will self destruct!';
$expected = 'Important message!<br />This message will self destruct!';
$result = Sanitize::stripTags($string, 'b');
$this->assertEquals($expected, $result);
$string = '<h2 onclick="alert(\'evil\'); onmouseover="badness()">Important</h2><p>Additional information here <a href="/about"><img src="/img/test.png" /></a>. Read even more here</p>';
$expected = 'Important<p>Additional information here . Read even more here</p>';
$result = Sanitize::stripTags($string, 'h2', 'a', 'img');
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,207 @@
<?php
/**
* SecurityTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Security', 'Utility');
/**
* SecurityTest class
*
* @package Cake.Test.Case.Utility
*/
class SecurityTest extends CakeTestCase {
/**
* sut property
*
* @var mixed null
*/
public $sut = null;
/**
* testInactiveMins method
*
* @return void
*/
public function testInactiveMins() {
Configure::write('Security.level', 'high');
$this->assertEquals(10, Security::inactiveMins());
Configure::write('Security.level', 'medium');
$this->assertEquals(100, Security::inactiveMins());
Configure::write('Security.level', 'low');
$this->assertEquals(300, Security::inactiveMins());
}
/**
* testGenerateAuthkey method
*
* @return void
*/
public function testGenerateAuthkey() {
$this->assertEquals(strlen(Security::generateAuthKey()), 40);
}
/**
* testValidateAuthKey method
*
* @return void
*/
public function testValidateAuthKey() {
$authKey = Security::generateAuthKey();
$this->assertTrue(Security::validateAuthKey($authKey));
}
/**
* testHash method
*
* @return void
*/
public function testHash() {
$_hashType = Security::$hashType;
$key = 'someKey';
$hash = 'someHash';
$this->assertSame(strlen(Security::hash($key, null, false)), 40);
$this->assertSame(strlen(Security::hash($key, 'sha1', false)), 40);
$this->assertSame(strlen(Security::hash($key, null, true)), 40);
$this->assertSame(strlen(Security::hash($key, 'sha1', true)), 40);
$result = Security::hash($key, null, $hash);
$this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1');
$result = Security::hash($key, 'sha1', $hash);
$this->assertSame($result, 'e38fcb877dccb6a94729a81523851c931a46efb1');
$hashType = 'sha1';
Security::setHash($hashType);
$this->assertSame(Security::$hashType, $hashType);
$this->assertSame(strlen(Security::hash($key, null, true)), 40);
$this->assertSame(strlen(Security::hash($key, null, false)), 40);
$this->assertSame(strlen(Security::hash($key, 'md5', false)), 32);
$this->assertSame(strlen(Security::hash($key, 'md5', true)), 32);
$hashType = 'md5';
Security::setHash($hashType);
$this->assertSame(Security::$hashType, $hashType);
$this->assertSame(strlen(Security::hash($key, null, false)), 32);
$this->assertSame(strlen(Security::hash($key, null, true)), 32);
if (!function_exists('hash') && !function_exists('mhash')) {
$this->assertSame(strlen(Security::hash($key, 'sha256', false)), 32);
$this->assertSame(strlen(Security::hash($key, 'sha256', true)), 32);
} else {
$this->assertSame(strlen(Security::hash($key, 'sha256', false)), 64);
$this->assertSame(strlen(Security::hash($key, 'sha256', true)), 64);
}
Security::setHash($_hashType);
}
/**
* testCipher method
*
* @return void
*/
public function testCipher() {
$length = 10;
$txt = '';
for ($i = 0; $i < $length; $i++) {
$txt .= mt_rand(0, 255);
}
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEquals($txt, Security::cipher($result, $key));
$txt = '';
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEquals($txt, Security::cipher($result, $key));
$txt = 123456;
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEquals($txt, Security::cipher($result, $key));
$txt = '123456';
$key = 'my_key';
$result = Security::cipher($txt, $key);
$this->assertEquals($txt, Security::cipher($result, $key));
}
/**
* testCipherEmptyKey method
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testCipherEmptyKey() {
$txt = 'some_text';
$key = '';
$result = Security::cipher($txt, $key);
}
/**
* testRijndael method
*
* @return void
*/
public function testRijndael() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
$result = Security::rijndael($txt, $key, 'encrypt');
$this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt'));
$result = Security::rijndael($key, $txt, 'encrypt');
$this->assertEquals($key, Security::rijndael($result, $txt, 'decrypt'));
$result = Security::rijndael('', $key, 'encrypt');
$this->assertEquals('', Security::rijndael($result, $key, 'decrypt'));
$result = Security::rijndael($txt, $key = 'this is my key of over 32 chars, yes it is', 'encrypt');
$this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt'));
}
/**
* testRijndaelInvalidOperation method
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testRijndaelInvalidOperation() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
$result = Security::rijndael($txt, $key, 'foo');
}
/**
* testRijndaelInvalidKey method
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testRijndaelInvalidKey() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'too small';
$result = Security::rijndael($txt, $key, 'encrypt');
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,650 @@
<?php
/**
* StringTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, 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.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('String', 'Utility');
/**
* StringTest class
*
* @package Cake.Test.Case.Utility
*/
class StringTest extends CakeTestCase {
public function setUp() {
parent::setUp();
$this->Text = new String();
}
public function tearDown() {
parent::tearDown();
unset($this->Text);
}
/**
* testUuidGeneration method
*
* @return void
*/
public function testUuidGeneration() {
$result = String::uuid();
$pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
$match = (bool)preg_match($pattern, $result);
$this->assertTrue($match);
}
/**
* testMultipleUuidGeneration method
*
* @return void
*/
public function testMultipleUuidGeneration() {
$check = array();
$count = mt_rand(10, 1000);
$pattern = "/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/";
for ($i = 0; $i < $count; $i++) {
$result = String::uuid();
$match = (bool)preg_match($pattern, $result);
$this->assertTrue($match);
$this->assertFalse(in_array($result, $check));
$check[] = $result;
}
}
/**
* testInsert method
*
* @return void
*/
public function testInsert() {
$string = 'some string';
$expected = 'some string';
$result = String::insert($string, array());
$this->assertEquals($expected, $result);
$string = '2 + 2 = :sum. Cake is :adjective.';
$expected = '2 + 2 = 4. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = %sum. Cake is %adjective.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = 2sum2. Cake is 9adjective9.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])%s\\1/'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = 12sum21. Cake is 23adjective45.';
$expected = '2 + 2 = 4. Cake is 23adjective45.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('format' => '/([\d])([\d])%s\\2\\1/'));
$this->assertEquals($expected, $result);
$string = ':web :web_site';
$expected = 'www http';
$result = String::insert($string, array('web' => 'www', 'web_site' => 'http'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = <sum. Cake is <adjective>.';
$expected = '2 + 2 = <sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '<', 'after' => '>'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = \:sum. Cake is :adjective.';
$expected = '2 + 2 = :sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = !:sum. Cake is :adjective.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('escape' => '!'));
$this->assertEquals($expected, $result);
$string = '2 + 2 = \%sum. Cake is %adjective.';
$expected = '2 + 2 = %sum. Cake is yummy.';
$result = String::insert($string, array('sum' => '4', 'adjective' => 'yummy'), array('before' => '%'));
$this->assertEquals($expected, $result);
$string = ':a :b \:a :a';
$expected = '1 2 :a 1';
$result = String::insert($string, array('a' => 1, 'b' => 2));
$this->assertEquals($expected, $result);
$string = ':a :b :c';
$expected = '2 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEquals($expected, $result);
$string = ':a :b :c';
$expected = '1 3';
$result = String::insert($string, array('a' => 1, 'c' => 3), array('clean' => true));
$this->assertEquals($expected, $result);
$string = ':a :b :c';
$expected = '2 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEquals($expected, $result);
$string = ':a, :b and :c';
$expected = '2 and 3';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEquals($expected, $result);
$string = '":a, :b and :c"';
$expected = '"1, 2"';
$result = String::insert($string, array('a' => 1, 'b' => 2), array('clean' => true));
$this->assertEquals($expected, $result);
$string = '"${a}, ${b} and ${c}"';
$expected = '"1, 2"';
$result = String::insert($string, array('a' => 1, 'b' => 2), array('before' => '${', 'after' => '}', 'clean' => true));
$this->assertEquals($expected, $result);
$string = '<img src=":src" alt=":alt" class="foo :extra bar"/>';
$expected = '<img src="foo" class="foo bar"/>';
$result = String::insert($string, array('src' => 'foo'), array('clean' => 'html'));
$this->assertEquals($expected, $result);
$string = '<img src=":src" class=":no :extra"/>';
$expected = '<img src="foo"/>';
$result = String::insert($string, array('src' => 'foo'), array('clean' => 'html'));
$this->assertEquals($expected, $result);
$string = '<img src=":src" class=":no :extra"/>';
$expected = '<img src="foo" class="bar"/>';
$result = String::insert($string, array('src' => 'foo', 'extra' => 'bar'), array('clean' => 'html'));
$this->assertEquals($expected, $result);
$result = String::insert("this is a ? string", "test");
$expected = "this is a test string";
$this->assertEquals($expected, $result);
$result = String::insert("this is a ? string with a ? ? ?", array('long', 'few?', 'params', 'you know'));
$expected = "this is a long string with a few? params you know";
$this->assertEquals($expected, $result);
$result = String::insert('update saved_urls set url = :url where id = :id', array('url' => 'http://www.testurl.com/param1:url/param2:id','id' => 1));
$expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
$this->assertEquals($expected, $result);
$result = String::insert('update saved_urls set url = :url where id = :id', array('id' => 1, 'url' => 'http://www.testurl.com/param1:url/param2:id'));
$expected = "update saved_urls set url = http://www.testurl.com/param1:url/param2:id where id = 1";
$this->assertEquals($expected, $result);
$result = String::insert(':me cake. :subject :verb fantastic.', array('me' => 'I :verb', 'subject' => 'cake', 'verb' => 'is'));
$expected = "I :verb cake. cake is fantastic.";
$this->assertEquals($expected, $result);
$result = String::insert(':I.am: :not.yet: passing.', array('I.am' => 'We are'), array('before' => ':', 'after' => ':', 'clean' => array('replacement' => ' of course', 'method' => 'text')));
$expected = "We are of course passing.";
$this->assertEquals($expected, $result);
$result = String::insert(
':I.am: :not.yet: passing.',
array('I.am' => 'We are'),
array('before' => ':', 'after' => ':', 'clean' => true)
);
$expected = "We are passing.";
$this->assertEquals($expected, $result);
$result = String::insert('?-pended result', array('Pre'));
$expected = "Pre-pended result";
$this->assertEquals($expected, $result);
$string = 'switching :timeout / :timeout_count';
$expected = 'switching 5 / 10';
$result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10));
$this->assertEquals($expected, $result);
$string = 'switching :timeout / :timeout_count';
$expected = 'switching 5 / 10';
$result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5));
$this->assertEquals($expected, $result);
$string = 'switching :timeout_count by :timeout';
$expected = 'switching 10 by 5';
$result = String::insert($string, array('timeout' => 5, 'timeout_count' => 10));
$this->assertEquals($expected, $result);
$string = 'switching :timeout_count by :timeout';
$expected = 'switching 10 by 5';
$result = String::insert($string, array('timeout_count' => 10, 'timeout' => 5));
$this->assertEquals($expected, $result);
}
/**
* test Clean Insert
*
* @return void
*/
public function testCleanInsert() {
$result = String::cleanInsert(':incomplete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('', $result);
$result = String::cleanInsert(':incomplete', array(
'clean' => array('method' => 'text', 'replacement' => 'complete'),
'before' => ':', 'after' => '')
);
$this->assertEquals('complete', $result);
$result = String::cleanInsert(':in.complete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('', $result);
$result = String::cleanInsert(':in.complete and', array(
'clean' => true, 'before' => ':', 'after' => '')
);
$this->assertEquals('', $result);
$result = String::cleanInsert(':in.complete or stuff', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('stuff', $result);
$result = String::cleanInsert(
'<p class=":missing" id=":missing">Text here</p>',
array('clean' => 'html', 'before' => ':', 'after' => '')
);
$this->assertEquals('<p>Text here</p>', $result);
}
/**
* Tests that non-insertable variables (i.e. arrays) are skipped when used as values in
* String::insert().
*
* @return void
*/
public function testAutoIgnoreBadInsertData() {
$data = array('foo' => 'alpha', 'bar' => 'beta', 'fale' => array());
$result = String::insert('(:foo > :bar || :fale!)', $data, array('clean' => 'text'));
$this->assertEquals('(alpha > beta || !)', $result);
}
/**
* testTokenize method
*
* @return void
*/
public function testTokenize() {
$result = String::tokenize('A,(short,boring test)');
$expected = array('A', '(short,boring test)');
$this->assertEquals($expected, $result);
$result = String::tokenize('A,(short,more interesting( test)');
$expected = array('A', '(short,more interesting( test)');
$this->assertEquals($expected, $result);
$result = String::tokenize('A,(short,very interesting( test))');
$expected = array('A', '(short,very interesting( test))');
$this->assertEquals($expected, $result);
$result = String::tokenize('"single tag"', ' ', '"', '"');
$expected = array('"single tag"');
$this->assertEquals($expected, $result);
$result = String::tokenize('tagA "single tag" tagB', ' ', '"', '"');
$expected = array('tagA', '"single tag"', 'tagB');
$this->assertEquals($expected, $result);
}
public function testReplaceWithQuestionMarkInString() {
$string = ':a, :b and :c?';
$expected = '2 and 3?';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$this->assertEquals($expected, $result);
}
/**
* test wrap method.
*
* @return void
*/
public function testWrap() {
$text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
$result = String::wrap($text, 33);
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$result = String::wrap($text, array('width' => 20, 'wordWrap' => false));
$expected = <<<TEXT
This is the song th
at never ends. This
is the song that n
ever ends. This is
the song that never
ends.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
/**
* test wrap() indenting
*
* @return void
*/
public function testWrapIndent() {
$text = 'This is the song that never ends. This is the song that never ends. This is the song that never ends.';
$result = String::wrap($text, array('width' => 33, 'indent' => "\t", 'indentAt' => 1));
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
This is the song that never ends.
TEXT;
$this->assertTextEquals($expected, $result);
}
/**
* testTruncate method
*
* @return void
*/
public function testTruncate() {
$text1 = 'The quick brown fox jumps over the lazy dog';
$text2 = 'Heiz&ouml;lr&uuml;cksto&szlig;abd&auml;mpfung';
$text3 = '<b>&copy; 2005-2007, Cake Software Foundation, Inc.</b><br />written by Alexander Wegener';
$text4 = '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Great, or?';
$text5 = '0<b>1<i>2<span class="myclass">3</span>4<u>5</u>6</i>7</b>8<b>9</b>0';
$text6 = '<p><strong>Extra dates have been announced for this year\'s tour.</strong></p><p>Tickets for the new shows in</p>';
$text7 = 'El moño está en el lugar correcto. Eso fue lo que dijo la niña, ¿habrá dicho la verdad?';
$text8 = 'Vive la R' . chr(195) . chr(169) . 'publique de France';
$text9 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь';
$text10 = 'http://example.com/something/foo:bar';
$this->assertSame($this->Text->truncate($text1, 15), 'The quick br...');
$this->assertSame($this->Text->truncate($text1, 15, array('exact' => false)), 'The quick...');
$this->assertSame($this->Text->truncate($text1, 100), 'The quick brown fox jumps over the lazy dog');
$this->assertSame($this->Text->truncate($text2, 10), 'Heiz&ou...');
$this->assertSame($this->Text->truncate($text2, 10, array('exact' => false)), '...');
$this->assertSame($this->Text->truncate($text3, 20), '<b>&copy; 2005-20...');
$this->assertSame($this->Text->truncate($text4, 15), '<img src="my...');
$this->assertSame($this->Text->truncate($text5, 6, array('ending' => '')), '0<b>1<');
$this->assertSame($this->Text->truncate($text1, 15, array('html' => true)), 'The quick br...');
$this->assertSame($this->Text->truncate($text1, 15, array('exact' => false, 'html' => true)), 'The quick...');
$this->assertSame($this->Text->truncate($text2, 10, array('html' => true)), 'Heiz&ouml;lr...');
$this->assertSame($this->Text->truncate($text2, 10, array('exact' => false, 'html' => true)), '...');
$this->assertSame($this->Text->truncate($text3, 20, array('html' => true)), '<b>&copy; 2005-2007, Cake...</b>');
$this->assertSame($this->Text->truncate($text4, 15, array('html' => true)), '<img src="mypic.jpg"> This image ...');
$this->assertSame($this->Text->truncate($text4, 45, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But t...</b>');
$this->assertSame($this->Text->truncate($text4, 90, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Grea...');
$this->assertSame($this->Text->truncate($text5, 6, array('ending' => '', 'html' => true)), '0<b>1<i>2<span class="myclass">3</span>4<u>5</u></i></b>');
$this->assertSame($this->Text->truncate($text5, 20, array('ending' => '', 'html' => true)), $text5);
$this->assertSame($this->Text->truncate($text6, 57, array('exact' => false, 'html' => true)), "<p><strong>Extra dates have been announced for this year's...</strong></p>");
$this->assertSame($this->Text->truncate($text7, 255), $text7);
$this->assertSame($this->Text->truncate($text7, 15), 'El moño está...');
$this->assertSame($this->Text->truncate($text8, 15), 'Vive la R' . chr(195) . chr(169) . 'pu...');
$this->assertSame($this->Text->truncate($text9, 10), 'НОПРСТУ...');
$this->assertSame($this->Text->truncate($text10, 30), 'http://example.com/somethin...');
$text = '<p><span style="font-size: medium;"><a>Iamatestwithnospacesandhtml</a></span></p>';
$result = $this->Text->truncate($text, 10, array(
'ending' => '...',
'exact' => false,
'html' => true
));
$expected = '<p><span style="font-size: medium;"><a>...</a></span></p>';
$this->assertEquals($expected, $result);
$text = '<p><span style="font-size: medium;">El biógrafo de Steve Jobs, Walter
Isaacson, explica porqué Jobs le pidió que le hiciera su biografía en
este artículo de El País.</span></p>
<p><span style="font-size: medium;"><span style="font-size:
large;">Por qué Steve era distinto.</span></span></p>
<p><span style="font-size: medium;"><a href="http://www.elpais.com/
articulo/primer/plano/Steve/era/distinto/elpepueconeg/
20111009elpneglse_4/Tes">http://www.elpais.com/articulo/primer/plano/
Steve/era/distinto/elpepueconeg/20111009elpneglse_4/Tes</a></span></p>
<p><span style="font-size: medium;">Ya se ha publicado la biografía de
Steve Jobs escrita por Walter Isaacson "<strong>Steve Jobs by Walter
Isaacson</strong>", aquí os dejamos la dirección de amazon donde
podeís adquirirla.</span></p>
<p><span style="font-size: medium;"><a>http://www.amazon.com/Steve-
Jobs-Walter-Isaacson/dp/1451648537</a></span></p>';
$result = $this->Text->truncate($text, 500, array(
'ending' => '... ',
'exact' => false,
'html' => true
));
$expected = '<p><span style="font-size: medium;">El biógrafo de Steve Jobs, Walter
Isaacson, explica porqué Jobs le pidió que le hiciera su biografía en
este artículo de El País.</span></p>
<p><span style="font-size: medium;"><span style="font-size:
large;">Por qué Steve era distinto.</span></span></p>
<p><span style="font-size: medium;"><a href="http://www.elpais.com/
articulo/primer/plano/Steve/era/distinto/elpepueconeg/
20111009elpneglse_4/Tes">http://www.elpais.com/articulo/primer/plano/
Steve/era/distinto/elpepueconeg/20111009elpneglse_4/Tes</a></span></p>
<p><span style="font-size: medium;">Ya se ha publicado la biografía de
Steve Jobs escrita por Walter Isaacson "<strong>Steve Jobs by Walter
Isaacson</strong>", aquí os dejamos la dirección de amazon donde
podeís adquirirla.</span></p>
<p><span style="font-size: medium;"><a>... </a></span></p>';
$this->assertEquals($expected, $result);
}
/**
* testHighlight method
*
* @return void
*/
public function testHighlight() {
$text = 'This is a test text';
$phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$expected = '<b>This</b> is a test <b>text</b>';
$this->assertEquals($expected, $result);
$phrases = array('is', 'text');
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>', 'regex' => "|\b%s\b|iu"));
$expected = 'This <b>is</b> a test <b>text</b>';
$this->assertEquals($expected, $result);
$text = 'This is a test text';
$phrases = null;
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEquals($text, $result);
$text = 'This is a (test) text';
$phrases = '(test';
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEquals('This is a <b>(test</b>) text', $result);
$text = 'Ich saß in einem Café am Übergang';
$expected = 'Ich <b>saß</b> in einem <b>Café</b> am <b>Übergang</b>';
$phrases = array('saß', 'café', 'übergang');
$result = $this->Text->highlight($text, $phrases, array('format' => '<b>\1</b>'));
$this->assertEquals($expected, $result);
}
/**
* testHighlightHtml method
*
* @return void
*/
public function testHighlightHtml() {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>';
$text2 = '<p>strongbow <strong>isn&rsquo;t</strong> real cider</p>';
$text3 = '<img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$text4 = 'What a strong mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$options = array('format' => '<b>\1</b>', 'html' => true);
$expected = '<p><b>strong</b>bow isn&rsquo;t real cider</p>';
$this->assertEquals($expected, $this->Text->highlight($text1, 'strong', $options));
$expected = '<p><b>strong</b>bow <strong>isn&rsquo;t</strong> real cider</p>';
$this->assertEquals($expected, $this->Text->highlight($text2, 'strong', $options));
$this->assertEquals($this->Text->highlight($text3, 'strong', $options), $text3);
$this->assertEquals($this->Text->highlight($text3, array('strong', 'what'), $options), $text3);
$expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEquals($this->Text->highlight($text4, array('strong', 'what'), $options), $expected);
}
/**
* testHighlightMulti method
*
* @return void
*/
public function testHighlightMulti() {
$text = 'This is a test text';
$phrases = array('This', 'text');
$result = $this->Text->highlight($text, $phrases, array('format' => array('<b>\1</b>', '<em>\1</em>')));
$expected = '<b>This</b> is a test <em>text</em>';
$this->assertEquals($expected, $result);
}
/**
* testStripLinks method
*
* @return void
*/
public function testStripLinks() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->stripLinks($text);
$this->assertEquals($expected, $result);
$text = 'This is a <a href="#">test</a> text';
$expected = 'This is a test text';
$result = $this->Text->stripLinks($text);
$this->assertEquals($expected, $result);
$text = 'This <strong>is</strong> a <a href="#">test</a> <a href="#">text</a>';
$expected = 'This <strong>is</strong> a test text';
$result = $this->Text->stripLinks($text);
$this->assertEquals($expected, $result);
$text = 'This <strong>is</strong> a <a href="#">test</a> and <abbr>some</abbr> other <a href="#">text</a>';
$expected = 'This <strong>is</strong> a test and <abbr>some</abbr> other text';
$result = $this->Text->stripLinks($text);
$this->assertEquals($expected, $result);
}
/**
* testHighlightCaseInsensitivity method
*
* @return void
*/
public function testHighlightCaseInsensitivity() {
$text = 'This is a Test text';
$expected = 'This is a <b>Test</b> text';
$result = $this->Text->highlight($text, 'test', array('format' => '<b>\1</b>'));
$this->assertEquals($expected, $result);
$result = $this->Text->highlight($text, array('test'), array('format' => '<b>\1</b>'));
$this->assertEquals($expected, $result);
}
/**
* testExcerpt method
*
* @return void
*/
public function testExcerpt() {
$text = 'This is a phrase with test text to play with';
$expected = '...ase with test text to ...';
$result = $this->Text->excerpt($text, 'test', 9, '...');
$this->assertEquals($expected, $result);
$expected = 'This is a...';
$result = $this->Text->excerpt($text, 'not_found', 9, '...');
$this->assertEquals($expected, $result);
$expected = 'This is a phras...';
$result = $this->Text->excerpt($text, null, 9, '...');
$this->assertEquals($expected, $result);
$expected = $text;
$result = $this->Text->excerpt($text, null, 200, '...');
$this->assertEquals($expected, $result);
$expected = '...a phrase w...';
$result = $this->Text->excerpt($text, 'phrase', 2, '...');
$this->assertEquals($expected, $result);
$phrase = 'This is a phrase with test text';
$expected = $text;
$result = $this->Text->excerpt($text, $phrase, 13, '...');
$this->assertEquals($expected, $result);
$text = 'aaaaaaaaaaaaaaaaaaaaaaaabbbbbbbbaaaaaaaaaaaaaaaaaaaaaaaa';
$phrase = 'bbbbbbbb';
$result = $this->Text->excerpt($text, $phrase, 10);
$expected = '...aaaaaaaaaabbbbbbbbaaaaaaaaaa...';
$this->assertEquals($expected, $result);
}
/**
* testExcerptCaseInsensitivity method
*
* @return void
*/
public function testExcerptCaseInsensitivity() {
$text = 'This is a phrase with test text to play with';
$expected = '...ase with test text to ...';
$result = $this->Text->excerpt($text, 'TEST', 9, '...');
$this->assertEquals($expected, $result);
$expected = 'This is a...';
$result = $this->Text->excerpt($text, 'NOT_FOUND', 9, '...');
$this->assertEquals($expected, $result);
}
/**
* testListGeneration method
*
* @return void
*/
public function testListGeneration() {
$result = $this->Text->toList(array());
$this->assertEquals('', $result);
$result = $this->Text->toList(array('One'));
$this->assertEquals('One', $result);
$result = $this->Text->toList(array('Larry', 'Curly', 'Moe'));
$this->assertEquals('Larry, Curly and Moe', $result);
$result = $this->Text->toList(array('Dusty', 'Lucky', 'Ned'), 'y');
$this->assertEquals('Dusty, Lucky y Ned', $result);
$result = $this->Text->toList(array(1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'y');
$this->assertEquals('Dusty, Lucky y Ned', $result);
$result = $this->Text->toList(array(1 => 'Dusty', 2 => 'Lucky', 3 => 'Ned'), 'and', ' + ');
$this->assertEquals('Dusty + Lucky and Ned', $result);
$result = $this->Text->toList(array('name1' => 'Dusty', 'name2' => 'Lucky'));
$this->assertEquals('Dusty and Lucky', $result);
$result = $this->Text->toList(array('test_0' => 'banana', 'test_1' => 'apple', 'test_2' => 'lemon'));
$this->assertEquals('banana, apple and lemon', $result);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff