Initial commit

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

View file

@ -0,0 +1,789 @@
<?php
/**
* CakeNumberTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
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);
$value = 0.00001;
$result = $this->Number->format($value, array('places' => 1));
$expected = '$0.0';
$this->assertEquals($expected, $result);
$value = -0.00001;
$result = $this->Number->format($value, array('places' => 1));
$expected = '$0.0';
$this->assertEquals($expected, $result);
$value = 1.23;
$options = array('decimals' => ',', 'thousands' => '.', 'before' => '', 'after' => ' €');
$result = $this->Number->format($value, $options);
$expected = '1,23 €';
$this->assertEquals($expected, $result);
}
/**
* testFormatDelta method
*
* @return void
*/
public function testFormatDelta() {
$value = '100100100';
$result = $this->Number->formatDelta($value);
$expected = '+100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->formatDelta($value, array('before' => '', 'after' => ''));
$expected = '+100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->formatDelta($value, array('before' => '[', 'after' => ']'));
$expected = '[+100,100,100.00]';
$this->assertEquals($expected, $result);
$result = $this->Number->formatDelta(-$value, array('before' => '[', 'after' => ']'));
$expected = '[-100,100,100.00]';
$this->assertEquals($expected, $result);
$result = $this->Number->formatDelta(-$value, array('before' => '[ ', 'after' => ' ]'));
$expected = '[ -100,100,100.00 ]';
$this->assertEquals($expected, $result);
$value = 0;
$result = $this->Number->formatDelta($value, array('places' => 1, 'before' => '[', 'after' => ']'));
$expected = '[0.0]';
$this->assertEquals($expected, $result);
$value = 0.0001;
$result = $this->Number->formatDelta($value, array('places' => 1, 'before' => '[', 'after' => ']'));
$expected = '[0.0]';
$this->assertEquals($expected, $result);
$value = 9876.1234;
$result = $this->Number->formatDelta($value, array('places' => 1, 'decimals' => ',', 'thousands' => '.'));
$expected = '+9.876,1';
$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 = '€100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '£100,100,100.00';
$this->assertEquals($expected, $result);
$options = array('thousands' => ' ', 'wholeSymbol' => 'EUR ', 'wholePosition' => 'before',
'decimals' => ',', 'zero' => 'Gratuit');
$result = $this->Number->currency($value, '', $options);
$expected = 'EUR 100 100 100,00';
$this->assertEquals($expected, $result);
$options = array('after' => 'øre', 'before' => 'Kr.', 'decimals' => ',', 'thousands' => '.');
$result = $this->Number->currency(1000.45, null, $options);
$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);
$options = array('wholeSymbol' => '$', 'wholePosition' => 'after', 'fractionSymbol' => ' cents');
$result = $this->Number->currency(0.2, null, $options);
$expected = '20 cents';
$this->assertEquals($expected, $result);
$options = array('wholeSymbol' => '$', 'wholePosition' => 'after', 'fractionSymbol' => 'cents ',
'fractionPosition' => 'before');
$result = $this->Number->currency(0.2, null, $options);
$expected = 'cents 20';
$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 = '€0,20';
$this->assertEquals($expected, $result);
$options = array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents',
'fractionPosition' => 'after');
$result = $this->Number->currency(12, null, $options);
$expected = '12.00 dollars';
$this->assertEquals($expected, $result);
$options = array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents',
'fractionPosition' => 'after');
$result = $this->Number->currency(0.12, null, $options);
$expected = '12 cents';
$this->assertEquals($expected, $result);
$options = array('fractionSymbol' => false, 'fractionPosition' => 'before', 'wholeSymbol' => '$');
$result = $this->Number->currency(0.5, null, $options);
$expected = '$0.50';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0, 'GBP');
$expected = '£0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.00000, 'GBP');
$expected = '£0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.00000', 'GBP');
$expected = '£0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('-2.23300', 'JPY');
$expected = '(¥2.23)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('22.389', 'CAD');
$expected = '$22.39';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('4.111', 'AUD');
$expected = '$4.11';
$this->assertEquals($expected, $result);
}
/**
* Test currency format with places and fraction exponents.
* Places should only matter for non fraction values and vice versa.
*
* @return void
*/
public function testCurrencyWithFractionAndPlaces() {
$result = $this->Number->currency('1.23', 'GBP', array('places' => 3));
$expected = '£1.230';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.23', 'GBP', array('places' => 3));
$expected = '23p';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.001', 'GBP', array('places' => 3));
$expected = '0p';
$this->assertEquals($expected, $result);
$this->Number->addFormat('BHD', array('before' => 'BD ', 'fractionSymbol' => ' fils',
'fractionExponent' => 3));
$result = $this->Number->currency('1.234', 'BHD', array('places' => 2));
$expected = 'BD 1.23';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.234', 'BHD', array('places' => 2));
$expected = '234 fils';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.001', 'BHD', array('places' => 2));
$expected = '1 fils';
$this->assertEquals($expected, $result);
}
/**
* Test that the default fraction handling does not cause issues.
*
* @return void
*/
public function testCurrencyFractionSymbol() {
$result = $this->Number->currency(0.2, '', array(
'places' => 2,
'decimal' => '.'
));
$this->assertEquals('0.2', $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);
}
/**
* Test default currency
*
* @return void
*/
public function testDefaultCurrency() {
$result = $this->Number->defaultCurrency();
$this->assertEquals('USD', $result);
$this->Number->addFormat('NOK', array('before' => 'Kr. '));
$this->Number->defaultCurrency('NOK');
$result = $this->Number->defaultCurrency();
$this->assertEquals('NOK', $result);
$result = $this->Number->currency(1000);
$expected = 'Kr. 1,000.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(2000);
$expected = 'Kr. 2,000.00';
$this->assertEquals($expected, $result);
$this->Number->defaultCurrency('EUR');
$result = $this->Number->currency(1000);
$expected = '€1.000,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(2000);
$expected = '€2.000,00';
$this->assertEquals($expected, $result);
$this->Number->defaultCurrency('USD');
}
/**
* 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 = '€100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '£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 = '(€100.100.100,00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(£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 = '-€100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
$expected = '-£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 = '€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 = '(€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 = '-€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 = '€0,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '£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 = '£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('before' => '&#163; ', '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('before' => '&#163;', 'after' => false, 'escape' => 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 = '€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);
$this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
$result = $this->Number->toReadableSize(1321205);
$this->assertEquals('1,26 MB', $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
$this->assertEquals('512,00 GB', $result);
setlocale(LC_NUMERIC, $restore);
}
/**
* test precision() with locales
*
* @return void
*/
public function testPrecisionLocalized() {
$restore = setlocale(LC_NUMERIC, 0);
$this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
$result = $this->Number->precision(1.234);
$this->assertEquals('1,234', $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);
$result = $this->Number->toPercentage(45, 0, array('multiply' => false));
$expected = '45%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(45, 2, array('multiply' => false));
$expected = '45.00%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0, 0, array('multiply' => false));
$expected = '0%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0, 4, array('multiply' => false));
$expected = '0.0000%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0.456, 0, array('multiply' => true));
$expected = '46%';
$this->assertEquals($expected, $result);
$result = $this->Number->toPercentage(0.456, 2, array('multiply' => true));
$expected = '45.60%';
$this->assertEquals($expected, $result);
}
/**
* testFromReadableSize
*
* @dataProvider filesizes
* @return void
*/
public function testFromReadableSize($params, $expected) {
$result = $this->Number->fromReadableSize($params['size'], $params['default']);
$this->assertEquals($expected, $result);
}
/**
* testFromReadableSize
*
* @expectedException CakeException
* @return void
*/
public function testFromReadableSizeException() {
$this->Number->fromReadableSize('bogus', false);
}
/**
* filesizes dataprovider
*
* @return array
*/
public function filesizes() {
return array(
array(array('size' => '512B', 'default' => false), 512),
array(array('size' => '1KB', 'default' => false), 1024),
array(array('size' => '1.5KB', 'default' => false), 1536),
array(array('size' => '1MB', 'default' => false), 1048576),
array(array('size' => '1mb', 'default' => false), 1048576),
array(array('size' => '1.5MB', 'default' => false), 1572864),
array(array('size' => '1GB', 'default' => false), 1073741824),
array(array('size' => '1.5GB', 'default' => false), 1610612736),
array(array('size' => '1K', 'default' => false), 1024),
array(array('size' => '1.5K', 'default' => false), 1536),
array(array('size' => '1M', 'default' => false), 1048576),
array(array('size' => '1m', 'default' => false), 1048576),
array(array('size' => '1.5M', 'default' => false), 1572864),
array(array('size' => '1G', 'default' => false), 1073741824),
array(array('size' => '1.5G', 'default' => false), 1610612736),
array(array('size' => '512', 'default' => 'Unknown type'), 512),
array(array('size' => '2VB', 'default' => 'Unknown type'), 'Unknown type')
);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,316 @@
<?php
/**
* ClassRegistryTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ClassRegistry', 'Utility');
/**
* ClassRegisterModel class
*
* @package Cake.Test.Case.Utility
*/
class ClassRegisterModel extends CakeTestModel {
/**
* useTable property
*
* @var bool
*/
public $useTable = false;
}
/**
* RegisterArticle class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticle extends ClassRegisterModel {
}
/**
* RegisterArticleFeatured class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticleFeatured extends ClassRegisterModel {
}
/**
* RegisterArticleTag class
*
* @package Cake.Test.Case.Utility
*/
class RegisterArticleTag extends ClassRegisterModel {
}
/**
* RegistryPluginAppModel class
*
* @package Cake.Test.Case.Utility
*/
class RegistryPluginAppModel extends ClassRegisterModel {
/**
* tablePrefix property
*
* @var string
*/
public $tablePrefix = 'something_';
}
/**
* TestRegistryPluginModel class
*
* @package Cake.Test.Case.Utility
*/
class TestRegistryPluginModel extends RegistryPluginAppModel {
}
/**
* RegisterCategory class
*
* @package Cake.Test.Case.Utility
*/
class RegisterCategory extends ClassRegisterModel {
}
/**
* RegisterPrefixedDs class
*
* @package Cake.Test.Case.Utility
*/
class RegisterPrefixedDs extends ClassRegisterModel {
/**
* useDbConfig property
*
* @var string
*/
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->assertInstanceOf('RegisterArticleTag', $Tag);
$TagCopy = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertTrue($TagCopy);
$Tag->name = 'SomeNewName';
$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
$this->assertInstanceOf('RegisterArticleTag', $TagCopy);
$this->assertSame($Tag, $TagCopy);
$NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertInstanceOf('RegisterArticleTag', $Tag);
$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->assertInstanceOf('AppModel', $User);
$UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
$this->assertInstanceOf('AppModel', $UserCopy);
$this->assertEquals($User, $UserCopy);
$Category = ClassRegistry::init(array('class' => 'RegisterCategory'));
$this->assertInstanceOf('RegisterCategory', $Category);
$ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
$this->assertInstanceOf('RegisterCategory', $ParentCategory);
$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() {
ClassRegistry::init('RegisterArticleTag');
$ArticleTag = ClassRegistry::getObject('RegisterArticleTag');
$this->assertInstanceOf('RegisterArticleTag', $ArticleTag);
ClassRegistry::flush();
$NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertFalse($NoArticleTag);
$this->assertInstanceOf('RegisterArticleTag', $ArticleTag);
}
/**
* 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->assertInstanceOf('RegisterArticle', $Article);
$Featured = ClassRegistry::getObject('Featured');
$this->assertInstanceOf('RegisterArticleFeatured', $Featured);
$Tag = ClassRegistry::getObject('Tag');
$this->assertInstanceOf('RegisterArticleTag', $Tag);
}
/**
* 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->assertInstanceOf('TestRegistryPluginModel', $TestRegistryPluginModel);
$this->assertEquals('something_', $TestRegistryPluginModel->tablePrefix);
$PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
$this->assertInstanceOf('RegistryPluginAppModel', $PluginUser);
$PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser');
$this->assertInstanceOf('RegistryPluginAppModel', $PluginUserCopy);
$this->assertSame($PluginUser, $PluginUserCopy);
CakePlugin::unload();
}
/**
* Tests prefixed datasource names for test purposes
*
* @return void
*/
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
*
* @return void
*/
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,633 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Debugger', 'Utility');
/**
* DebuggerTestCaseDebugger 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'), '');
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__, 11, 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.
*
* @return void
*/
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'
elementCacheSettings => array()
Html => object(HtmlHelper) {}
Form => object(FormHelper) {}
int => (int) 2
float => (float) 1.333
TEXT;
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
$expected .= <<<TEXT
[protected] _passedVars => array(
(int) 0 => 'viewVars',
(int) 1 => 'autoLayout',
(int) 2 => 'ext',
(int) 3 => 'helpers',
(int) 4 => 'view',
(int) 5 => 'layout',
(int) 6 => 'name',
(int) 7 => 'theme',
(int) 8 => 'layoutPath',
(int) 9 => 'viewPath',
(int) 10 => 'request',
(int) 11 => 'plugin',
(int) 12 => 'passedArgs',
(int) 13 => 'cacheAction'
)
[protected] _scripts => array()
[protected] _paths => array()
[protected] _pathsForPlugin => array()
[protected] _parents => array()
[protected] _current => null
[protected] _currentType => ''
[protected] _stack => array()
[protected] _eventManager => object(CakeEventManager) {}
[protected] _eventManagerConfigured => false
TEXT;
}
$expected .= <<<TEXT
}
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);
$data = false;
$result = Debugger::exportVar($data);
$expected = <<<TEXT
false
TEXT;
$this->assertTextEquals($expected, $result);
$file = fopen('php://output', 'w');
fclose($file);
$result = Debugger::exportVar($file);
$this->assertTextEquals('unknown', $result);
}
/**
* Test exporting various kinds of false.
*
* @return void
*/
public function testExportVarZero() {
$data = array(
'nothing' => '',
'null' => null,
'false' => false,
'szero' => '0',
'zero' => 0
);
$result = Debugger::exportVar($data);
$expected = <<<TEXT
array(
'nothing' => '',
'null' => null,
'false' => false,
'szero' => '0',
'zero' => (int) 0
)
TEXT;
$this->assertTextEquals($expected, $result);
}
/**
* testLog method
*
* @return void
*/
public function testLog() {
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
CakeLog::config('file', array('engine' => 'File', 'path' => TMP . 'logs' . DS));
Debugger::log('cool');
$result = file_get_contents(LOGS . 'debug.log');
$this->assertContains('DebuggerTest::testLog', $result);
$this->assertContains("'cool'", $result);
unlink(LOGS . 'debug.log');
Debugger::log(array('whatever', 'here'));
$result = file_get_contents(LOGS . 'debug.log');
$this->assertContains('DebuggerTest::testLog', $result);
$this->assertContains('[main]', $result);
$this->assertContains('array', $result);
$this->assertContains("'whatever',", $result);
$this->assertContains("'here'", $result);
}
/**
* test log() depth
*
* @return void
*/
public function testLogDepth() {
if (file_exists(LOGS . 'debug.log')) {
unlink(LOGS . 'debug.log');
}
CakeLog::config('file', array('engine' => 'File', 'path' => TMP . 'logs' . DS));
$val = array(
'test' => array('key' => 'val')
);
Debugger::log($val, LOG_DEBUG, 0);
$result = file_get_contents(LOGS . 'debug.log');
$this->assertContains('DebuggerTest::testLog', $result);
$this->assertNotContains("/'val'/", $result);
unlink(LOGS . 'debug.log');
}
/**
* 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();
$open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
$close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
$expected = <<<TEXT
{$open}array(
'People' => array(
(int) 0 => array(
'name' => 'joeseph',
'coat' => 'technicolor',
'hair_color' => 'brown'
),
(int) 1 => array(
'name' => 'Shaft',
'coat' => 'black',
'hair' => 'black'
)
)
){$close}
TEXT;
$this->assertTextEquals($expected, $result);
ob_start();
Debugger::dump($var, 1);
$result = ob_get_clean();
$open = php_sapi_name() == 'cli' ? "\n" : '<pre>';
$close = php_sapi_name() == 'cli' ? "\n" : '</pre>';
$expected = <<<TEXT
{$open}array(
'People' => array(
[maximum depth reached]
)
){$close}
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,601 @@
<?php
/**
* FileTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
/**
* FileTest class
*
* @package Cake.Test.Case.Utility
*/
class FileTest extends CakeTestCase {
/**
* File property
*
* @var mixed
*/
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
*
* @return void
*/
public function testPermission() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'File permissions tests not supported on Windows.');
$dir = TMP . 'tests' . DS . 'permissions' . DS;
$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();
$expected = 0;
$this->assertSame($expected, $result);
$data = file_get_contents(__FILE__);
$success = $this->File->offset(5);
$expected = substr($data, 5, 3);
$result = $this->File->read(3);
$this->assertTrue($success);
$this->assertEquals($expected, $result);
$result = $this->File->offset();
$expected = 5 + 3;
$this->assertSame($expected, $result);
}
/**
* 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($expected, File::prepare($string));
$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($expected, File::prepare($string, true));
}
/**
* 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;
$size = 0;
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));
$newSize = $TmpFile->size();
$this->assertTrue($newSize > $size);
$size = $newSize;
$TmpFile->close();
}
$TmpFile->append('');
$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') && mime_content_type($file->pwd()) === false) {
$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;
}
/**
* testReplaceText method
*
* @return void
*/
public function testReplaceText() {
$TestFile = new File(dirname(__FILE__) . '/../../test_app/Vendor/welcome.php');
$TmpFile = new File(TMP . 'tests' . DS . 'cakephp.file.test.tmp');
// Copy the test file to the temporary location
$TestFile->copy($TmpFile->path, true);
// Replace the contents of the tempory file
$result = $TmpFile->replaceText('welcome.php', 'welcome.tmp');
$this->assertTrue($result);
// Double check
$expected = 'This is the welcome.tmp file in vendors directory';
$contents = $TmpFile->read();
$this->assertContains($expected, $contents);
$search = array('This is the', 'welcome.php file', 'in tmp directory');
$replace = array('This should be a', 'welcome.tmp file', 'in the Lib directory');
// Replace the contents of the tempory file
$result = $TmpFile->replaceText($search, $replace);
$this->assertTrue($result);
// Double check
$expected = 'This should be a welcome.tmp file in vendors directory';
$contents = $TmpFile->read();
$this->assertContains($expected, $contents);
$TmpFile->delete();
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,539 @@
<?php
/**
* InflectorTest
*
* InflectorTest is used to test cases on the Inflector class
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Included libraries.
*/
App::uses('Inflector', 'Utility');
/**
* Short description for class.
*
* @package Cake.Test.Case.Utility
*/
class InflectorTest extends CakeTestCase {
/**
* A list of chars to test transliteration.
*
* @var array
*/
public static $maps = array (
'de' => array ( /* German */
'Ä' => 'Ae', 'Ö' => 'Oe', 'Ü' => 'Ue', 'ä' => 'ae', 'ö' => 'oe', 'ü' => 'ue', 'ß' => 'ss',
'ẞ' => 'SS'
),
'latin' => array (
'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Å' => 'A', 'Ă' => 'A', 'Æ' => 'AE', 'Ç' =>
'C', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I',
'Ï' => 'I', 'Ð' => 'D', 'Ñ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ő' => 'O', 'Ø' => 'O',
'Ș' => 'S', 'Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ű' => 'U',
'Ý' => 'Y', 'Þ' => 'TH', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
'å' => 'a', 'ă' => 'a', 'æ' => 'ae', 'ç' => 'c', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ð' => 'd', 'ñ' => 'n', 'ò' => 'o', 'ó' =>
'o', 'ô' => 'o', 'õ' => 'o', 'ő' => 'o', 'ø' => 'o', 'ș' => 's', 'ț' => 't', 'ù' => 'u', 'ú' => 'u',
'û' => 'u', 'ű' => 'u', 'ý' => 'y', 'þ' => 'th', 'ÿ' => 'y'
),
'tr' => array ( /* Turkish */
'ş' => 's', 'Ş' => 'S', 'ı' => 'i', 'İ' => 'I', 'ç' => 'c', 'Ç' => 'C', 'ğ' => 'g', 'Ğ' => 'G'
),
'uk' => array ( /* Ukrainian */
'Є' => 'Ye', 'І' => 'I', 'Ї' => 'Yi', 'Ґ' => 'G', 'є' => 'ye', 'і' => 'i', 'ї' => 'yi', 'ґ' => 'g'
),
'cs' => array ( /* Czech */
'č' => 'c', 'ď' => 'd', 'ě' => 'e', 'ň' => 'n', 'ř' => 'r', 'š' => 's', 'ť' => 't', 'ů' => 'u',
'ž' => 'z', 'Č' => 'C', 'Ď' => 'D', 'Ě' => 'E', 'Ň' => 'N', 'Ř' => 'R', 'Š' => 'S', 'Ť' => 'T',
'Ů' => 'U', 'Ž' => 'Z'
),
'pl' => array ( /* Polish */
'ą' => 'a', 'ć' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ś' => 's', 'ź' => 'z',
'ż' => 'z', 'Ą' => 'A', 'Ć' => 'C', 'Ł' => 'L', 'Ń' => 'N', 'Ó' => 'O', 'Ś' => 'S',
'Ź' => 'Z', 'Ż' => 'Z'
),
'ro' => array ( /* Romanian */
'ă' => 'a', 'â' => 'a', 'î' => 'i', 'ș' => 's', 'ț' => 't', 'Ţ' => 'T', 'ţ' => 't'
),
'lv' => array ( /* Latvian */
'ā' => 'a', 'č' => 'c', 'ē' => 'e', 'ģ' => 'g', 'ī' => 'i', 'ķ' => 'k', 'ļ' => 'l', 'ņ' => 'n',
'š' => 's', 'ū' => 'u', 'ž' => 'z', 'Ā' => 'A', 'Č' => 'C', 'Ē' => 'E', 'Ģ' => 'G', 'Ī' => 'I',
'Ķ' => 'K', 'Ļ' => 'L', 'Ņ' => 'N', 'Š' => 'S', 'Ū' => 'U', 'Ž' => 'Z'
),
'lt' => array ( /* Lithuanian */
'ą' => 'a', 'č' => 'c', 'ę' => 'e', 'ė' => 'e', 'į' => 'i', 'š' => 's', 'ų' => 'u', 'ū' => 'u', 'ž' => 'z',
'Ą' => 'A', 'Č' => 'C', 'Ę' => 'E', 'Ė' => 'E', 'Į' => 'I', 'Š' => 'S', 'Ų' => 'U', 'Ū' => 'U', 'Ž' => 'Z'
)
);
/**
* 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('caves'), 'cave');
$this->assertEquals(Inflector::singularize('graves'), 'grave');
$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('thieves'), 'thief');
$this->assertEquals(Inflector::singularize('potatoes'), 'potato');
$this->assertEquals(Inflector::singularize('heroes'), 'hero');
$this->assertEquals(Inflector::singularize('buffalos'), 'buffalo');
$this->assertEquals(Inflector::singularize('babies'), 'baby');
$this->assertEquals(Inflector::singularize('teeth'), 'tooth');
$this->assertEquals(Inflector::singularize('geese'), 'goose');
$this->assertEquals(Inflector::singularize('feet'), 'foot');
$this->assertEquals(Inflector::singularize('objectives'), 'objective');
$this->assertEquals(Inflector::singularize('archives'), 'archive');
$this->assertEquals(Inflector::singularize('briefs'), 'brief');
$this->assertEquals(Inflector::singularize('quotas'), 'quota');
$this->assertEquals(Inflector::singularize('curves'), 'curve');
$this->assertEquals(Inflector::singularize('body_curves'), 'body_curve');
$this->assertEquals(Inflector::singularize('metadata'), 'metadata');
$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('wolf'), 'wolves');
$this->assertEquals(Inflector::pluralize('thief'), 'thieves');
$this->assertEquals(Inflector::pluralize('potato'), 'potatoes');
$this->assertEquals(Inflector::pluralize('hero'), 'heroes');
$this->assertEquals(Inflector::pluralize('buffalo'), 'buffalo');
$this->assertEquals(Inflector::pluralize('tooth'), 'teeth');
$this->assertEquals(Inflector::pluralize('goose'), 'geese');
$this->assertEquals(Inflector::pluralize('foot'), 'feet');
$this->assertEquals(Inflector::pluralize('objective'), 'objectives');
$this->assertEquals(Inflector::pluralize('brief'), 'briefs');
$this->assertEquals(Inflector::pluralize('quota'), 'quotas');
$this->assertEquals(Inflector::pluralize('curve'), 'curves');
$this->assertEquals(Inflector::pluralize('body_curve'), 'body_curves');
$this->assertEquals(Inflector::pluralize('metadata'), 'metadata');
$this->assertEquals(Inflector::pluralize('stadia'), 'stadia');
$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);
$result = Inflector::slug("non\xc2\xa0breaking\xc2\xa0space");
$this->assertEquals('non_breaking_space', $result);
}
/**
* Test slug() with a complete list of special chars.
*
* @return void
*/
public function testInflectorSlugCharList() {
foreach (self::$maps as $language => $list) {
foreach ($list as $from => $to) {
$result = Inflector::slug($from);
$this->assertEquals($to, $result, $from . ' (' . $language . ') should be ' . $to . ' - but is ' . $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,584 @@
<?php
/**
* ObjectCollectionTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 2.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
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
*
* @return void
*/
public function callback() {
}
}
/**
* Second Extension of Generic Object
*/
class SecondGenericObject extends GenericObject {
/**
* @return void
*/
public function callback() {
}
}
/**
* Third Extension of Generic Object
*/
class ThirdGenericObject extends GenericObject {
/**
* @return void
*/
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(, $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];
}
/**
* Helper method for adding/overwriting enabled objects including
* settings
*
* @param string $name Name of the object
* @param Object $object The object to use
* @param array $settings Settings to apply for the object
* @return array Loaded objects
*/
public function setObject($name, $object, $settings = array()) {
$this->_loaded[$name] = $object;
if (isset($settings['priority'])) {
$this->setPriority($name, $settings['priority']);
}
$enable = isset($settings['enabled']) ? $settings['enabled'] : true;
if ($enable === true) {
$this->enable($name);
}
return $this->_loaded;
}
}
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->loaded();
$this->assertEquals(array('First'), $result, 'loaded() 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->loaded();
$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->loaded();
$this->assertEquals(array('Second'), $result, 'loaded objects are wrong');
$result = $this->Objects->loaded();
$this->assertEquals(array('Second'), $result, 'enabled objects are wrong');
}
/**
* Tests set()
*
* @return void
*/
public function testSet() {
$this->Objects->load('First');
$result = $this->Objects->loaded();
$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() {
$this->FirstGenericObject = $this->getMock('FirstGenericObject', array(), array(), '', false);
$this->SecondGenericObject = $this->getMock('SecondGenericObject', array(), array(), '', false);
$this->ThirdGenericObject = $this->getMock('ThirdGenericObject', array(), array(), '', false);
}
/**
* test triggering callbacks.
*
* @return void
*/
public function testTrigger() {
$this->_makeMockClasses();
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject, array('enabled' => false));
$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->assertTrue($this->Objects->trigger('callback', array()));
}
/**
* test that the collectReturn option works.
*
* @return void
*/
public function testTriggerWithCollectReturn() {
$this->_makeMockClasses();
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->never())
->method('callback');
$this->Objects->TriggerMockSecond->expects($this->never())
->method('callback');
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject, array('priority' => 5));
$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->setObject('TriggerMockThird', $this->ThirdGenericObject, array('priority' => 7));
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$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,448 @@
<?php
/**
* SanitizeTest file
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5428
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Sanitize', 'Utility');
/**
* DataTest class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeDataTest extends CakeTestModel {
/**
* useTable property
*
* @var string
*/
public $useTable = 'data_tests';
}
/**
* Article class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeArticle extends CakeTestModel {
/**
* useTable property
*
* @var string
*/
public $useTable = 'articles';
}
/**
* SanitizeTest class
*
* @package Cake.Test.Case.Utility
*/
class SanitizeTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool
*/
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,427 @@
<?php
/**
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Security', 'Utility');
/**
* SecurityTest class
*
* @package Cake.Test.Case.Utility
*/
class SecurityTest extends CakeTestCase {
/**
* sut property
*
* @var mixed
*/
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));
}
/**
* testHashInvalidSalt method
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testHashInvalidSalt() {
Security::hash('someKey', 'blowfish', true);
}
/**
* testHashAnotherInvalidSalt
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testHashAnotherInvalidSalt() {
Security::hash('someKey', 'blowfish', '$1$lksdjoijfaoijs');
}
/**
* testHashYetAnotherInvalidSalt
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testHashYetAnotherInvalidSalt() {
Security::hash('someKey', 'blowfish', '$2a$10$123');
}
/**
* testHashInvalidCost method
*
* @expectedException PHPUnit_Framework_Error
* @return void
*/
public function testHashInvalidCost() {
Security::setCost(1000);
}
/**
* testHash method
*
* @return void
*/
public function testHash() {
$_hashType = Security::$hashType;
$key = 'someKey';
$hash = 'someHash';
$this->assertSame(40, strlen(Security::hash($key, null, false)));
$this->assertSame(40, strlen(Security::hash($key, 'sha1', false)));
$this->assertSame(40, strlen(Security::hash($key, null, true)));
$this->assertSame(40, strlen(Security::hash($key, 'sha1', true)));
$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($hashType, Security::$hashType);
$this->assertSame(40, strlen(Security::hash($key, null, true)));
$this->assertSame(40, strlen(Security::hash($key, null, false)));
$this->assertSame(32, strlen(Security::hash($key, 'md5', false)));
$this->assertSame(32, strlen(Security::hash($key, 'md5', true)));
$hashType = 'md5';
Security::setHash($hashType);
$this->assertSame($hashType, Security::$hashType);
$this->assertSame(32, strlen(Security::hash($key, null, false)));
$this->assertSame(32, strlen(Security::hash($key, null, true)));
if (!function_exists('hash') && !function_exists('mhash')) {
$this->assertSame(32, strlen(Security::hash($key, 'sha256', false)));
$this->assertSame(32, strlen(Security::hash($key, 'sha256', true)));
} else {
$this->assertSame(64, strlen(Security::hash($key, 'sha256', false)));
$this->assertSame(64, strlen(Security::hash($key, 'sha256', true)));
}
Security::setHash($_hashType);
}
/**
* Test that hash() works with blowfish.
*
* @return void
*/
public function testHashBlowfish() {
Security::setCost(10);
$test = Security::hash('password', 'blowfish');
$this->skipIf(strpos($test, '$2a$') === false, 'Blowfish hashes are incorrect.');
$_hashType = Security::$hashType;
$key = 'someKey';
$hashType = 'blowfish';
Security::setHash($hashType);
$this->assertSame($hashType, Security::$hashType);
$this->assertSame(60, strlen(Security::hash($key, null, false)));
$password = $submittedPassword = $key;
$storedPassword = Security::hash($password);
$hashedPassword = Security::hash($submittedPassword, null, $storedPassword);
$this->assertSame($storedPassword, $hashedPassword);
$submittedPassword = 'someOtherKey';
$hashedPassword = Security::hash($submittedPassword, null, $storedPassword);
$this->assertNotSame($storedPassword, $hashedPassword);
$expected = sha1('customsaltsomevalue');
$result = Security::hash('somevalue', 'sha1', 'customsalt');
$this->assertSame($expected, $result);
$oldSalt = Configure::read('Security.salt');
Configure::write('Security.salt', 'customsalt');
$expected = sha1('customsaltsomevalue');
$result = Security::hash('somevalue', 'sha1', true);
$this->assertSame($expected, $result);
Configure::write('Security.salt', $oldSalt);
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 = '';
Security::cipher($txt, $key);
}
/**
* testRijndael method
*
* @return void
*/
public function testRijndael() {
$this->skipIf(!function_exists('mcrypt_encrypt'));
$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'));
$key = 'this is my key of over 32 chars, yes it is';
$result = Security::rijndael($txt, $key, 'encrypt');
$this->assertEquals($txt, Security::rijndael($result, $key, 'decrypt'));
}
/**
* Test that rijndael() can still decrypt values with a fixed iv.
*
* @return void
*/
public function testRijndaelBackwardCompatibility() {
$this->skipIf(!function_exists('mcrypt_encrypt'));
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
// Encrypted before random iv
$value = base64_decode('1WPjnq96LMzLGwNgmudHF+cAIqVUN5DaUZEpf5tm1EzSgt5iYY9o3d66iRI/fKJLTlTVGsa8HzW0jDNitmVXoQ==');
$this->assertEquals($txt, Security::rijndael($value, $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';
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';
Security::rijndael($txt, $key, 'encrypt');
}
/**
* Test encrypt/decrypt.
*
* @return void
*/
public function testEncryptDecrypt() {
$txt = 'The quick brown fox';
$key = 'This key is longer than 32 bytes long.';
$result = Security::encrypt($txt, $key);
$this->assertNotEquals($txt, $result, 'Should be encrypted.');
$this->assertNotEquals($result, Security::encrypt($txt, $key), 'Each result is unique.');
$this->assertEquals($txt, Security::decrypt($result, $key));
}
/**
* Test that changing the key causes decryption to fail.
*
* @return void
*/
public function testDecryptKeyFailure() {
$txt = 'The quick brown fox';
$key = 'This key is longer than 32 bytes long.';
$result = Security::encrypt($txt, $key);
$key = 'Not the same key. This one will fail';
$this->assertFalse(Security::decrypt($txt, $key), 'Modified key will fail.');
}
/**
* Test that decrypt fails when there is an hmac error.
*
* @return void
*/
public function testDecryptHmacFailure() {
$txt = 'The quick brown fox';
$key = 'This key is quite long and works well.';
$salt = 'this is a delicious salt!';
$result = Security::encrypt($txt, $key, $salt);
// Change one of the bytes in the hmac.
$result[10] = 'x';
$this->assertFalse(Security::decrypt($result, $key, $salt), 'Modified hmac causes failure.');
}
/**
* Test that changing the hmac salt will cause failures.
*
* @return void
*/
public function testDecryptHmacSaltFailure() {
$txt = 'The quick brown fox';
$key = 'This key is quite long and works well.';
$salt = 'this is a delicious salt!';
$result = Security::encrypt($txt, $key, $salt);
$salt = 'humpty dumpty had a great fall.';
$this->assertFalse(Security::decrypt($result, $key, $salt), 'Modified salt causes failure.');
}
/**
* Test that short keys cause errors
*
* @expectedException CakeException
* @expectedExceptionMessage Invalid key for encrypt(), key must be at least 256 bits (32 bytes) long.
* @return void
*/
public function testEncryptInvalidKey() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'this is too short';
Security::encrypt($txt, $key);
}
/**
* Test encrypting falsey data
*
* @return void
*/
public function testEncryptDecryptFalseyData() {
$key = 'This is a key that is long enough to be ok.';
$result = Security::encrypt('', $key);
$this->assertSame('', Security::decrypt($result, $key));
$result = Security::encrypt(false, $key);
$this->assertSame('', Security::decrypt($result, $key));
$result = Security::encrypt(null, $key);
$this->assertSame('', Security::decrypt($result, $key));
$result = Security::encrypt(0, $key);
$this->assertSame('0', Security::decrypt($result, $key));
$result = Security::encrypt('0', $key);
$this->assertSame('0', Security::decrypt($result, $key));
}
/**
* Test that short keys cause errors
*
* @expectedException CakeException
* @expectedExceptionMessage Invalid key for decrypt(), key must be at least 256 bits (32 bytes) long.
* @return void
*/
public function testDecryptInvalidKey() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'this is too short';
Security::decrypt($txt, $key);
}
/**
* Test that empty data cause errors
*
* @expectedException CakeException
* @expectedExceptionMessage The data to decrypt cannot be empty.
* @return void
*/
public function testDecryptInvalidData() {
$txt = '';
$key = 'This is a key that is long enough to be ok.';
Security::decrypt($txt, $key);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,806 @@
<?php
/**
* StringTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
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);
$result = String::tokenize('');
$expected = array();
$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 that wordWrap() works the same as built-in wordwrap function
*
* @dataProvider wordWrapProvider
* @return void
*/
public function testWordWrap($text, $width, $break = "\n", $cut = false) {
$result = String::wordWrap($text, $width, $break, $cut);
$expected = wordwrap($text, $width, $break, $cut);
$this->assertTextEquals($expected, $result, 'Text not wrapped same as built-in function.');
}
/**
* data provider for testWordWrap method
*
* @return array
*/
public function wordWrapProvider() {
return array(
array(
'The quick brown fox jumped over the lazy dog.',
33
),
array(
'A very long woooooooooooord.',
8
),
array(
'A very long woooooooooooord. Right.',
8
),
);
}
/**
* test that wordWrap() properly handle unicode strings.
*
* @return void
*/
public function testWordWrapUnicodeAware() {
$text = 'Но вим омниюм факёльиси элыктрам, мюнырэ лэгыры векж ыт. Выльёт квюандо нюмквуам ты кюм. Зыд эю рыбюм.';
$result = String::wordWrap($text, 33, "\n", true);
$expected = <<<TEXT
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт квю
андо нюмквуам ты кюм. Зыд эю рыбю
м.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$text = 'Но вим омниюм факёльиси элыктрам, мюнырэ лэгыры векж ыт. Выльёт квюандо нюмквуам ты кюм. Зыд эю рыбюм.';
$result = String::wordWrap($text, 33, "\n");
$expected = <<<TEXT
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт
квюандо нюмквуам ты кюм. Зыд эю
рыбюм.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
/**
* 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 = 'This is the song th' . "\n" .
'at never ends. This' . "\n" .
' is the song that n' . "\n" .
'ever ends. This is ' . "\n" .
'the song that never' . "\n" .
' ends.';
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$text = 'Но вим омниюм факёльиси элыктрам, мюнырэ лэгыры векж ыт. Выльёт квюандо нюмквуам ты кюм. Зыд эю рыбюм.';
$result = String::wrap($text, 33);
$expected = <<<TEXT
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт
квюандо нюмквуам ты кюм. Зыд эю
рыбюм.
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';
$elipsis = "\xe2\x80\xa6";
$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('ellipsis' => '')), '0<b>1<');
$this->assertSame($this->Text->truncate($text1, 15, array('html' => true)), 'The quick brow' . $elipsis);
$this->assertSame($this->Text->truncate($text1, 15, array('exact' => false, 'html' => true)), 'The quick' . $elipsis);
$this->assertSame($this->Text->truncate($text2, 10, array('html' => true)), 'Heiz&ouml;lr&uuml;c' . $elipsis);
$this->assertSame($this->Text->truncate($text2, 10, array('exact' => false, 'html' => true)), $elipsis);
$this->assertSame($this->Text->truncate($text3, 20, array('html' => true)), '<b>&copy; 2005-2007, Cake S' . $elipsis . '</b>');
$this->assertSame($this->Text->truncate($text4, 15, array('html' => true)), '<img src="mypic.jpg"> This image ta' . $elipsis);
$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 the' . $elipsis . '</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 />Great,' . $elipsis);
$this->assertSame($this->Text->truncate($text5, 6, array('ellipsis' => '', '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('ellipsis' => '', '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" . $elipsis . "</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(
'ellipsis' => '...',
'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(
'ellipsis' => '... ',
'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);
// test deprecated `ending` (`ellipsis` taking precedence if both are defined)
$result = $this->Text->truncate($text1, 31, array(
'ending' => '.',
'exact' => false,
));
$expected = 'The quick brown fox jumps.';
$this->assertEquals($expected, $result);
$result = $this->Text->truncate($text1, 31, array(
'ellipsis' => '..',
'ending' => '.',
'exact' => false,
));
$expected = 'The quick brown fox jumps..';
$this->assertEquals($expected, $result);
}
/**
* testTruncate method with non utf8 sites
*
* @return void
*/
public function testTruncateLegacy() {
Configure::write('App.encoding', 'ISO-8859-1');
$text = '<b>&copy; 2005-2007, Cake Software Foundation, Inc.</b><br />written by Alexander Wegener';
$result = $this->Text->truncate($text, 31, array(
'html' => true,
'exact' => false,
));
$expected = '<b>&copy; 2005-2007, Cake Software...</b>';
$this->assertEquals($expected, $result);
$result = $this->Text->truncate($text, 31, array(
'html' => true,
'exact' => true,
));
$expected = '<b>&copy; 2005-2007, Cake Software F...</b>';
$this->assertEquals($expected, $result);
}
/**
* testTail method
*
* @return void
*/
public function testTail() {
$text1 = 'The quick brown fox jumps over the lazy dog';
$text2 = 'Heiz&ouml;lr&uuml;cksto&szlig;abd&auml;mpfung';
$text3 = 'El moño está en el lugar correcto. Eso fue lo que dijo la niña, ¿habrá dicho la verdad?';
$text4 = 'Vive la R' . chr(195) . chr(169) . 'publique de France';
$text5 = 'НОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыь';
$result = $this->Text->tail($text1, 13);
$this->assertEquals('...e lazy dog', $result);
$result = $this->Text->tail($text1, 13, array('exact' => false));
$this->assertEquals('...lazy dog', $result);
$result = $this->Text->tail($text1, 100);
$this->assertEquals('The quick brown fox jumps over the lazy dog', $result);
$result = $this->Text->tail($text2, 10);
$this->assertEquals('...;mpfung', $result);
$result = $this->Text->tail($text2, 10, array('exact' => false));
$this->assertEquals('...', $result);
$result = $this->Text->tail($text3, 255);
$this->assertEquals($text3, $result);
$result = $this->Text->tail($text3, 21);
$this->assertEquals('...á dicho la verdad?', $result);
$result = $this->Text->tail($text4, 25);
$this->assertEquals('...a R' . chr(195) . chr(169) . 'publique de France', $result);
$result = $this->Text->tail($text5, 10);
$this->assertEquals('...цчшщъыь', $result);
$result = $this->Text->tail($text5, 6, array('ellipsis' => ''));
$this->assertEquals('чшщъыь', $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($expected, $this->Text->highlight($text4, array('strong', 'what'), $options));
}
/**
* 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