Upgrade CakePHP from 2.2.5 to 2.9.5

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

View file

@ -2,19 +2,18 @@
/**
* CakeNumberTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('View', 'View');
@ -70,6 +69,66 @@ class CakeNumberTest extends CakeTestCase {
$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);
}
/**
@ -80,31 +139,31 @@ class CakeNumberTest extends CakeTestCase {
public function testMultibyteFormat() {
$value = '5199100.0006';
$result = $this->Number->format($value, array(
'thousands' => '&nbsp;',
'decimals' => '&amp;',
'places' => 3,
'escape' => false,
'before' => '',
'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,
'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',
'thousands' => 'ø€ƒ‡™',
'decimals' => '(§.§)',
'escape' => false,
'wholeSymbol' => '€',
'wholePosition' => 'after',
));
$result = $this->Number->currency($value, 'RUR');
$expected = '519ø€ƒ‡™919ø€ƒ‡™827ø€ƒ‡™593ø€ƒ‡™784(§.§)00€';
@ -112,9 +171,9 @@ class CakeNumberTest extends CakeTestCase {
$value = '13371337.1337';
$result = CakeNumber::format($value, array(
'thousands' => '- |-| /-\ >< () |2 -',
'decimals' => '- £€€† -',
'before' => ''
'thousands' => '- |-| /-\ >< () |2 -',
'decimals' => '- £€€† -',
'before' => ''
));
$expected = '13- |-| /-\ &gt;&lt; () |2 -371- |-| /-\ &gt;&lt; () |2 -337- £€€† -13';
$this->assertEquals($expected, $result);
@ -145,19 +204,22 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$expected = '100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$expected = '£100,100,100.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, '', array('thousands' => ' ', 'wholeSymbol' => '€', 'wholePosition' => 'after', 'decimals' => ',', 'zero' => 'Gratuit'));
$expected = '100 100 100,00€';
$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);
$result = $this->Number->currency(1000.45, null, array('after' => 'øre', 'before' => 'Kr. ', 'decimals' => ',', 'thousands' => '.'));
$expected = 'Kr. 1.000,45';
$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');
@ -176,12 +238,15 @@ class CakeNumberTest extends CakeTestCase {
$expected = '1.00 $';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents'));
$expected = '20cents';
$options = array('wholeSymbol' => '$', 'wholePosition' => 'after', 'fractionSymbol' => ' cents');
$result = $this->Number->currency(0.2, null, $options);
$expected = '20 cents';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, null, array('wholeSymbol' => ' $', 'wholePosition' => 'after', 'fractionSymbol' => 'cents', 'fractionPosition' => 'before'));
$expected = 'cents20';
$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'));
@ -189,20 +254,96 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency(0.2, 'EUR');
$expected = '&#8364;0,20';
$expected = '0,20';
$this->assertEquals($expected, $result);
$result = $this->Number->currency(12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
$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);
$result = $this->Number->currency(0.12, null, array('wholeSymbol' => ' dollars', 'wholePosition' => 'after', 'fractionSymbol' => ' cents', 'fractionPosition' => 'after'));
$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);
$result = $this->Number->currency(0.5, null, array('fractionSymbol' => false, 'fractionPosition' => 'before', 'wholeSymbol' => '$'));
$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);
}
/**
@ -231,6 +372,39 @@ class CakeNumberTest extends CakeTestCase {
$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
*
@ -256,11 +430,11 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;100.100.100,00';
$expected = '100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;100,100,100.00';
$expected = '£100,100,100.00';
$this->assertEquals($expected, $result);
}
@ -277,11 +451,11 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;100.100.100,00)';
$expected = '(100.100.100,00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '(&#163;100,100,100.00)';
$expected = '(£100,100,100.00)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'USD', array('negative' => '-'));
@ -289,11 +463,11 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
$expected = '-&#8364;100.100.100,00';
$expected = '-100.100.100,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
$expected = '-&#163;100,100,100.00';
$expected = '-£100,100,100.00';
$this->assertEquals($expected, $result);
}
@ -310,7 +484,7 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,99';
$expected = '0,99';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
@ -331,7 +505,7 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '(&#8364;0,99)';
$expected = '(0,99)';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
@ -343,7 +517,7 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR', array('negative' => '-'));
$expected = '-&#8364;0,99';
$expected = '-0,99';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('negative' => '-'));
@ -364,11 +538,11 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'EUR');
$expected = '&#8364;0,00';
$expected = '0,00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP');
$expected = '&#163;0.00';
$expected = '£0.00';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('zero' => 'FREE!'));
@ -389,7 +563,7 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('places' => 0));
$expected = '&#163;1,234,568';
$expected = '£1,234,568';
$this->assertEquals($expected, $result);
$result = $this->Number->currency('1234567.8912345', null, array('before' => 'GBP', 'places' => 3));
@ -400,15 +574,15 @@ class CakeNumberTest extends CakeTestCase {
$expected = 'GBP650.1200';
$this->assertEquals($expected, $result);
$result = $this->Number->currency($value, 'GBP', array('escape' => true));
$expected = '&amp;#163;1,234,567.89';
$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('after' => false));
$result = $this->Number->currency('0.35', 'GBP', array('before' => '&#163;', 'after' => false, 'escape' => false));
$expected = '&#163;0.35';
$this->assertEquals($expected, $result);
@ -417,7 +591,7 @@ class CakeNumberTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$result = $this->Number->currency('0.35', 'EUR');
$expected = '&#8364;0,35';
$expected = '0,35';
$this->assertEquals($expected, $result);
}
@ -491,12 +665,29 @@ class CakeNumberTest extends CakeTestCase {
*/
public function testReadableSizeLocalized() {
$restore = setlocale(LC_NUMERIC, 0);
setlocale(LC_NUMERIC, 'de_DE');
$this->skipIf(setlocale(LC_NUMERIC, 'de_DE') === false, "The German locale isn't available.");
$result = $this->Number->toReadableSize(1321205);
$this->assertRegExp('/1[,.]26 MB/', $result);
$this->assertEquals('1,26 MB', $result);
$result = $this->Number->toReadableSize(1024 * 1024 * 1024 * 512);
$this->assertRegExp('/512[,.]00 GB/', $result);
$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);
}
@ -521,6 +712,78 @@ class CakeNumberTest extends CakeTestCase {
$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')
);
}
}

View file

@ -1,35 +1,46 @@
<?php
/**
* StringTest file
*
* PHP 5
* CakeTextTest file
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('String', 'Utility');
App::uses('CakeText', 'Utility');
/**
* StringTest class
* CakeText Tests
*
* @package Cake.Test.Case.Utility
* @package Cake.Test.Case.Utility
* @coversDefaultClass CakeText
*/
class StringTest extends CakeTestCase {
class CakeTextTest extends CakeTestCase {
/**
* Setup object under test
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->Text = new String();
$this->Text = new CakeText();
}
/**
* Tear down object under test
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Text);
@ -39,9 +50,10 @@ class StringTest extends CakeTestCase {
* testUuidGeneration method
*
* @return void
* @covers ::uuid
*/
public function testUuidGeneration() {
$result = String::uuid();
$result = CakeText::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);
@ -51,6 +63,7 @@ class StringTest extends CakeTestCase {
* testMultipleUuidGeneration method
*
* @return void
* @covers ::uuid
*/
public function testMultipleUuidGeneration() {
$check = array();
@ -58,7 +71,7 @@ class StringTest extends CakeTestCase {
$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();
$result = CakeText::uuid();
$match = (bool)preg_match($pattern, $result);
$this->assertTrue($match);
$this->assertFalse(in_array($result, $check));
@ -70,131 +83,132 @@ class StringTest extends CakeTestCase {
* testInsert method
*
* @return void
* @covers ::insert
*/
public function testInsert() {
$string = 'some string';
$expected = 'some string';
$result = String::insert($string, array());
$result = CakeText::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'));
$result = CakeText::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' => '%'));
$result = CakeText::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/'));
$result = CakeText::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/'));
$result = CakeText::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'));
$result = CakeText::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' => '>'));
$result = CakeText::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'));
$result = CakeText::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' => '!'));
$result = CakeText::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' => '%'));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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'));
$result = CakeText::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'));
$result = CakeText::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'));
$result = CakeText::insert($string, array('src' => 'foo', 'extra' => 'bar'), array('clean' => 'html'));
$this->assertEquals($expected, $result);
$result = String::insert("this is a ? string", "test");
$result = CakeText::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'));
$result = CakeText::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));
$result = CakeText::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'));
$result = CakeText::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'));
$result = CakeText::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')));
$result = CakeText::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(
$result = CakeText::insert(
':I.am: :not.yet: passing.',
array('I.am' => 'We are'),
array('before' => ':', 'after' => ':', 'clean' => true)
@ -202,28 +216,28 @@ class StringTest extends CakeTestCase {
$expected = "We are passing.";
$this->assertEquals($expected, $result);
$result = String::insert('?-pended result', array('Pre'));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::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));
$result = CakeText::insert($string, array('timeout_count' => 10, 'timeout' => 5));
$this->assertEquals($expected, $result);
}
@ -231,35 +245,36 @@ class StringTest extends CakeTestCase {
* test Clean Insert
*
* @return void
* @covers ::cleanInsert
*/
public function testCleanInsert() {
$result = String::cleanInsert(':incomplete', array(
$result = CakeText::cleanInsert(':incomplete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('', $result);
$result = String::cleanInsert(':incomplete', array(
$result = CakeText::cleanInsert(':incomplete', array(
'clean' => array('method' => 'text', 'replacement' => 'complete'),
'before' => ':', 'after' => '')
);
$this->assertEquals('complete', $result);
$result = String::cleanInsert(':in.complete', array(
$result = CakeText::cleanInsert(':in.complete', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('', $result);
$result = String::cleanInsert(':in.complete and', array(
$result = CakeText::cleanInsert(':in.complete and', array(
'clean' => true, 'before' => ':', 'after' => '')
);
$this->assertEquals('', $result);
$result = String::cleanInsert(':in.complete or stuff', array(
$result = CakeText::cleanInsert(':in.complete or stuff', array(
'clean' => true, 'before' => ':', 'after' => ''
));
$this->assertEquals('stuff', $result);
$result = String::cleanInsert(
$result = CakeText::cleanInsert(
'<p class=":missing" id=":missing">Text here</p>',
array('clean' => 'html', 'before' => ':', 'after' => '')
);
@ -268,13 +283,14 @@ class StringTest extends CakeTestCase {
/**
* Tests that non-insertable variables (i.e. arrays) are skipped when used as values in
* String::insert().
* CakeText::insert().
*
* @return void
* @covers ::insert
*/
public function testAutoIgnoreBadInsertData() {
$data = array('foo' => 'alpha', 'bar' => 'beta', 'fale' => array());
$result = String::insert('(:foo > :bar || :fale!)', $data, array('clean' => 'text'));
$result = CakeText::insert('(:foo > :bar || :fale!)', $data, array('clean' => 'text'));
$this->assertEquals('(alpha > beta || !)', $result);
}
@ -282,44 +298,147 @@ class StringTest extends CakeTestCase {
* testTokenize method
*
* @return void
* @covers ::tokenize
*/
public function testTokenize() {
$result = String::tokenize('A,(short,boring test)');
$result = CakeText::tokenize('A,(short,boring test)');
$expected = array('A', '(short,boring test)');
$this->assertEquals($expected, $result);
$result = String::tokenize('A,(short,more interesting( test)');
$result = CakeText::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))');
$result = CakeText::tokenize('A,(short,very interesting( test))');
$expected = array('A', '(short,very interesting( test))');
$this->assertEquals($expected, $result);
$result = String::tokenize('"single tag"', ' ', '"', '"');
$result = CakeText::tokenize('"single tag"', ' ', '"', '"');
$expected = array('"single tag"');
$this->assertEquals($expected, $result);
$result = String::tokenize('tagA "single tag" tagB', ' ', '"', '"');
$result = CakeText::tokenize('tagA "single tag" tagB', ' ', '"', '"');
$expected = array('tagA', '"single tag"', 'tagB');
$this->assertEquals($expected, $result);
// Ideographic width space.
$result = CakeText::tokenize("tagA\xe3\x80\x80\"single\xe3\x80\x80tag\"\xe3\x80\x80tagB", "\xe3\x80\x80", '"', '"');
$expected = array('tagA', '"single tag"', 'tagB');
$this->assertEquals($expected, $result);
$result = CakeText::tokenize('');
$expected = array();
$this->assertEquals($expected, $result);
}
/**
* testReplaceWithQuestionMarkInString method
*
* @return void
* @covers ::insert
*/
public function testReplaceWithQuestionMarkInString() {
$string = ':a, :b and :c?';
$expected = '2 and 3?';
$result = String::insert($string, array('b' => 2, 'c' => 3), array('clean' => true));
$result = CakeText::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
* @covers ::wordWrap
* @covers ::_wordWrap
*/
public function testWordWrap($text, $width, $break = "\n", $cut = false) {
$result = CakeText::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
* @covers ::wordWrap
* @covers ::_wordWrap
*/
public function testWordWrapUnicodeAware() {
$text = 'Но вим омниюм факёльиси элыктрам, мюнырэ лэгыры векж ыт. Выльёт квюандо нюмквуам ты кюм. Зыд эю рыбюм.';
$result = CakeText::wordWrap($text, 33, "\n", true);
$expected = <<<TEXT
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт квю
андо нюмквуам ты кюм. Зыд эю рыбю
м.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$text = 'Но вим омниюм факёльиси элыктрам, мюнырэ лэгыры векж ыт. Выльёт квюандо нюмквуам ты кюм. Зыд эю рыбюм.';
$result = CakeText::wordWrap($text, 33, "\n");
$expected = <<<TEXT
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт
квюандо нюмквуам ты кюм. Зыд эю
рыбюм.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
/**
* test that wordWrap() properly handle newline characters.
*
* @return void
* @covers ::wordWrap
* @covers ::_wordWrap
*/
public function testWordWrapNewlineAware() {
$text = 'This is a line that is almost the 55 chars long.
This is a new sentence which is manually newlined, but is so long it needs two lines.';
$result = CakeText::wordWrap($text, 55);
$expected = <<<TEXT
This is a line that is almost the 55 chars long.
This is a new sentence which is manually newlined, but
is so long it needs two lines.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
/**
* test wrap method.
*
* @return void
* @covers ::wrap
* @covers ::wordWrap
* @covers ::_wordWrap
*/
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);
$result = CakeText::wrap($text, 33);
$expected = <<<TEXT
This is the song that never ends.
This is the song that never ends.
@ -327,14 +446,22 @@ This is the song that never ends.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
$result = String::wrap($text, array('width' => 20, 'wordWrap' => false));
$result = CakeText::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 = CakeText::wrap($text, 33);
$expected = <<<TEXT
This is the song th
at never ends. This
is the song that n
ever ends. This is
the song that never
ends.
Но вим омниюм факёльиси элыктрам,
мюнырэ лэгыры векж ыт. Выльёт
квюандо нюмквуам ты кюм. Зыд эю
рыбюм.
TEXT;
$this->assertTextEquals($expected, $result, 'Text not wrapped.');
}
@ -343,10 +470,13 @@ TEXT;
* test wrap() indenting
*
* @return void
* @covers ::wrap
* @covers ::wordWrap
* @covers ::_wordWrap
*/
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));
$result = CakeText::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.
@ -359,6 +489,7 @@ TEXT;
* testTruncate method
*
* @return void
* @covers ::truncate
*/
public function testTruncate() {
$text1 = 'The quick brown fox jumps over the lazy dog';
@ -372,6 +503,7 @@ TEXT;
$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');
@ -379,18 +511,18 @@ TEXT;
$this->assertSame($this->Text->truncate($text2, 10, array('exact' => false)), '...');
$this->assertSame($this->Text->truncate($text3, 20), '<b>&copy; 2005-20...');
$this->assertSame($this->Text->truncate($text4, 15), '<img src="my...');
$this->assertSame($this->Text->truncate($text5, 6, array('ending' => '')), '0<b>1<');
$this->assertSame($this->Text->truncate($text1, 15, array('html' => true)), 'The quick br...');
$this->assertSame($this->Text->truncate($text1, 15, array('exact' => false, 'html' => true)), 'The quick...');
$this->assertSame($this->Text->truncate($text2, 10, array('html' => true)), 'Heiz&ouml;lr...');
$this->assertSame($this->Text->truncate($text2, 10, array('exact' => false, 'html' => true)), '...');
$this->assertSame($this->Text->truncate($text3, 20, array('html' => true)), '<b>&copy; 2005-2007, Cake...</b>');
$this->assertSame($this->Text->truncate($text4, 15, array('html' => true)), '<img src="mypic.jpg"> This image ...');
$this->assertSame($this->Text->truncate($text4, 45, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But t...</b>');
$this->assertSame($this->Text->truncate($text4, 90, array('html' => true)), '<img src="mypic.jpg"> This image tag is not XHTML conform!<br><hr/><b>But the following image tag should be conform <img src="mypic.jpg" alt="Me, myself and I" /></b><br />Grea...');
$this->assertSame($this->Text->truncate($text5, 6, array('ending' => '', 'html' => true)), '0<b>1<i>2<span class="myclass">3</span>4<u>5</u></i></b>');
$this->assertSame($this->Text->truncate($text5, 20, array('ending' => '', 'html' => true)), $text5);
$this->assertSame($this->Text->truncate($text6, 57, array('exact' => false, 'html' => true)), "<p><strong>Extra dates have been announced for this year's...</strong></p>");
$this->assertSame($this->Text->truncate($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...');
@ -399,7 +531,7 @@ TEXT;
$text = '<p><span style="font-size: medium;"><a>Iamatestwithnospacesandhtml</a></span></p>';
$result = $this->Text->truncate($text, 10, array(
'ending' => '...',
'ellipsis' => '...',
'exact' => false,
'html' => true
));
@ -422,7 +554,7 @@ podeís adquirirla.</span></p>
<p><span style="font-size: medium;"><a>http://www.amazon.com/Steve-
Jobs-Walter-Isaacson/dp/1451648537</a></span></p>';
$result = $this->Text->truncate($text, 500, array(
'ending' => '... ',
'ellipsis' => '... ',
'exact' => false,
'html' => true
));
@ -441,12 +573,97 @@ 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
* @covers ::truncate
*/
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
* @covers ::tail
*/
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
* @covers ::highlight
*/
public function testHighlight() {
$text = 'This is a test text';
@ -481,6 +698,7 @@ podeís adquirirla.</span></p>
* testHighlightHtml method
*
* @return void
* @covers ::highlight
*/
public function testHighlightHtml() {
$text1 = '<p>strongbow isn&rsquo;t real cider</p>';
@ -500,13 +718,14 @@ podeís adquirirla.</span></p>
$this->assertEquals($this->Text->highlight($text3, array('strong', 'what'), $options), $text3);
$expected = '<b>What</b> a <b>strong</b> mouse: <img src="what-a-strong-mouse.png" alt="What a strong mouse!" />';
$this->assertEquals($this->Text->highlight($text4, array('strong', 'what'), $options), $expected);
$this->assertEquals($expected, $this->Text->highlight($text4, array('strong', 'what'), $options));
}
/**
* testHighlightMulti method
*
* @return void
* @covers ::highlight
*/
public function testHighlightMulti() {
$text = 'This is a test text';
@ -520,6 +739,7 @@ podeís adquirirla.</span></p>
* testStripLinks method
*
* @return void
* @covers ::stripLinks
*/
public function testStripLinks() {
$text = 'This is a test text';
@ -547,6 +767,7 @@ podeís adquirirla.</span></p>
* testHighlightCaseInsensitivity method
*
* @return void
* @covers ::highlight
*/
public function testHighlightCaseInsensitivity() {
$text = 'This is a Test text';
@ -563,6 +784,7 @@ podeís adquirirla.</span></p>
* testExcerpt method
*
* @return void
* @covers ::excerpt
*/
public function testExcerpt() {
$text = 'This is a phrase with test text to play with';
@ -603,6 +825,7 @@ podeís adquirirla.</span></p>
* testExcerptCaseInsensitivity method
*
* @return void
* @covers ::excerpt
*/
public function testExcerptCaseInsensitivity() {
$text = 'This is a phrase with test text to play with';
@ -620,6 +843,7 @@ podeís adquirirla.</span></p>
* testListGeneration method
*
* @return void
* @covers ::toList
*/
public function testListGeneration() {
$result = $this->Text->toList(array());

View file

@ -2,20 +2,20 @@
/**
* CakeTimeTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('CakeTime', 'Utility');
/**
@ -38,8 +38,10 @@ class CakeTimeTest extends CakeTestCase {
* @return void
*/
public function setUp() {
parent::setUp();
$this->Time = new CakeTime();
$this->_systemTimezoneIdentifier = date_default_timezone_get();
Configure::write('Config.language', 'eng');
}
/**
@ -48,6 +50,7 @@ class CakeTimeTest extends CakeTestCase {
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Time);
$this->_restoreSystemTimezone();
}
@ -69,13 +72,13 @@ class CakeTimeTest extends CakeTestCase {
*/
public function testToQuarter() {
$result = $this->Time->toQuarter('2007-12-25');
$this->assertEquals(4, $result);
$this->assertSame(4, $result);
$result = $this->Time->toQuarter('2007-9-25');
$this->assertEquals(3, $result);
$this->assertSame(3, $result);
$result = $this->Time->toQuarter('2007-3-25');
$this->assertEquals(1, $result);
$this->assertSame(1, $result);
$result = $this->Time->toQuarter('2007-3-25', true);
$this->assertEquals(array('2007-01-01', '2007-03-31'), $result);
@ -105,9 +108,9 @@ class CakeTimeTest extends CakeTestCase {
array('-2 days -3 hours', '2 days, 3 hours ago'),
array('-1 week', '1 week ago'),
array('-2 weeks -2 days', '2 weeks, 2 days ago'),
array('+1 week', '1 week'),
array('+1 week 1 day', '1 week, 1 day'),
array('+2 weeks 2 day', '2 weeks, 2 days'),
array('+1 week', 'in 1 week'),
array('+1 week 1 day', 'in 1 week, 1 day'),
array('+2 weeks 2 day', 'in 2 weeks, 2 days'),
array('2007-9-24', 'on 24/9/07'),
array('now', 'just now'),
);
@ -133,37 +136,37 @@ class CakeTimeTest extends CakeTestCase {
return array(
array(
'+4 months +2 weeks +3 days',
'4 months, 2 weeks, 3 days',
'in 4 months, 2 weeks, 3 days',
'8 years'
),
array(
'+4 months +2 weeks +1 day',
'4 months, 2 weeks, 1 day',
'in 4 months, 2 weeks, 1 day',
'8 years'
),
array(
'+3 months +2 weeks',
'3 months, 2 weeks',
'in 3 months, 2 weeks',
'8 years'
),
array(
'+3 months +2 weeks +1 day',
'3 months, 2 weeks, 1 day',
'in 3 months, 2 weeks, 1 day',
'8 years'
),
array(
'+1 months +1 week +1 day',
'1 month, 1 week, 1 day',
'in 1 month, 1 week, 1 day',
'8 years'
),
array(
'+2 months +2 days',
'2 months, 2 days',
'in 2 months, 2 days',
'on ' . date('j/n/y', strtotime('+2 months +2 days'))
),
array(
'+2 months +12 days',
'2 months, 1 week, 5 days',
'in 2 months, 1 week, 5 days',
'3 months'
),
);
@ -182,6 +185,34 @@ class CakeTimeTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test the custom string options for timeAgoInWords
*
* @return void
*/
public function testTimeAgoInWordsCustomStrings() {
$result = $this->Time->timeAgoInWords(
strtotime('-8 years -4 months -2 weeks -3 days'),
array('relativeString' => 'at least %s ago', 'accuracy' => array('year' => 'year'), 'end' => '+10 years')
);
$expected = 'at least 8 years ago';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+8 years +4 months +2 weeks +3 days'),
array('relativeStringFuture' => 'not in the next %s', 'accuracy' => array('year' => 'year'), 'end' => '+10 years')
);
$expected = 'not in the next 8 years';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+4 months +2 weeks +3 days'),
array('absoluteString' => 'exactly on %s', 'accuracy' => array('year' => 'year'), 'end' => '+2 months')
);
$expected = 'exactly on ' . date('j/n/y', strtotime('+4 months +2 weeks +3 days'));
$this->assertEquals($expected, $result);
}
/**
* Test the accuracy option for timeAgoInWords()
*
@ -192,40 +223,54 @@ class CakeTimeTest extends CakeTestCase {
strtotime('+8 years +4 months +2 weeks +3 days'),
array('accuracy' => array('year' => 'year'), 'end' => '+10 years')
);
$expected = '8 years';
$expected = 'in 8 years';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+8 years +4 months +2 weeks +3 days'),
array('accuracy' => array('year' => 'month'), 'end' => '+10 years')
);
$expected = '8 years, 4 months';
$expected = 'in 8 years, 4 months';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+8 years +4 months +2 weeks +3 days'),
array('accuracy' => array('year' => 'week'), 'end' => '+10 years')
);
$expected = '8 years, 4 months, 2 weeks';
$expected = 'in 8 years, 4 months, 2 weeks';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+8 years +4 months +2 weeks +3 days'),
array('accuracy' => array('year' => 'day'), 'end' => '+10 years')
);
$expected = '8 years, 4 months, 2 weeks, 3 days';
$expected = 'in 8 years, 4 months, 2 weeks, 3 days';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+1 years +5 weeks'),
array('accuracy' => array('year' => 'year'), 'end' => '+10 years')
);
$expected = '1 year';
$expected = 'in 1 year';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+58 minutes'),
array('accuracy' => 'hour')
);
$expected = 'in about an hour';
$this->assertEquals($expected, $result);
$result = $this->Time->timeAgoInWords(
strtotime('+23 hours'),
array('accuracy' => 'day')
);
$expected = 'in about a day';
$this->assertEquals($expected, $result);
}
/**
* Test the format option of timeAgoInWords()
* Test the format option of timeAgoInWords() with date() and strftime compatible strings
*
* @return void
*/
@ -233,20 +278,32 @@ class CakeTimeTest extends CakeTestCase {
$result = $this->Time->timeAgoInWords('2007-9-25', 'Y-m-d');
$this->assertEquals('on 2007-09-25', $result);
$result = $this->Time->timeAgoInWords('2007-9-25', 'Y-m-d');
$this->assertEquals('on 2007-09-25', $result);
$result = $this->Time->timeAgoInWords('2007-9-25', '%x');
$this->assertEquals('on ' . strftime('%x', strtotime('2007-9-25')), $result);
$result = $this->Time->timeAgoInWords(
strtotime('+2 weeks +2 days'),
'Y-m-d'
);
$this->assertRegExp('/^2 weeks, [1|2] day(s)?$/', $result);
$this->assertRegExp('/^in 2 weeks, [1|2] day(s)?$/', $result);
$result = $this->Time->timeAgoInWords(
strtotime('+2 weeks +2 days'),
'%x'
);
$this->assertRegExp('/^in 2 weeks, [1|2] day(s)?$/', $result);
$result = $this->Time->timeAgoInWords(
strtotime('+2 months +2 days'),
array('end' => '1 month', 'format' => 'Y-m-d')
);
$this->assertEquals('on ' . date('Y-m-d', strtotime('+2 months +2 days')), $result);
$result = $this->Time->timeAgoInWords(
strtotime('+2 months +2 days'),
array('end' => '1 month', 'format' => '%x')
);
$this->assertEquals('on ' . strftime('%x', strtotime('+2 months +2 days')), $result);
}
/**
@ -309,6 +366,18 @@ class CakeTimeTest extends CakeTestCase {
array('end' => '2 years')
);
$this->assertEquals('1 year, 1 month, 5 days ago', $result);
$result = $this->Time->timeAgoInWords(
strtotime('-58 minutes'),
array('accuracy' => 'hour')
);
$this->assertEquals('about an hour ago', $result);
$result = $this->Time->timeAgoInWords(
strtotime('-23 hours'),
array('accuracy' => 'day')
);
$this->assertEquals('about a day ago', $result);
}
/**
@ -367,6 +436,12 @@ class CakeTimeTest extends CakeTestCase {
$time = time() + DAY;
$this->assertEquals('Tomorrow, ' . date('H:i', $time), $this->Time->niceShort($time));
$time = strtotime('+6 days');
$this->assertEquals('On ' . date('l F d, H:i', $time), $this->Time->niceShort($time));
$time = strtotime('-6 days');
$this->assertEquals(date('l F d, H:i', $time), $this->Time->niceShort($time));
date_default_timezone_set('Europe/London');
$result = $this->Time->niceShort('2005-01-15 10:00:00', new DateTimeZone('Europe/Brussels'));
$this->assertEquals('Jan 15th 2005, 11:00', $result);
@ -379,6 +454,19 @@ class CakeTimeTest extends CakeTestCase {
$this->_restoreSystemTimezone();
}
/**
* testNiceShort translations
*
* @return void
*/
public function testNiceShortI18n() {
$restore = setlocale(LC_ALL, 0);
setlocale(LC_ALL, 'es_ES');
$time = strtotime('2015-01-07 03:05:00');
$this->assertEquals('ene 7th 2015, 03:05', $this->Time->niceShort($time));
setlocale(LC_ALL, $restore);
}
/**
* testDaysAsSql method
*
@ -470,7 +558,7 @@ class CakeTimeTest extends CakeTestCase {
$expected = date('l jS \of F Y h:i:s A', $time);
$this->assertEquals($expected, $result);
$this->assertFalse($this->Time->toServer(time(), new Object()));
$this->assertFalse($this->Time->toServer(time(), new CakeObject()));
date_default_timezone_set('UTC');
@ -541,11 +629,20 @@ class CakeTimeTest extends CakeTestCase {
$result = $this->Time->format('Y-m-d', null, 'never');
$this->assertEquals('never', $result);
$result = $this->Time->format('Y-m-d', '');
$this->assertSame('', $result);
$result = $this->Time->format('Y-m-d', false);
$this->assertSame('', $result);
$result = $this->Time->format('2012-01-13', '%d-%m-%Y', 'invalid');
$this->assertEquals('13-01-2012', $result);
$result = $this->Time->format('nonsense', '%d-%m-%Y', 'invalid', 'UTC');
$this->assertEquals('invalid', $result);
$result = $this->Time->format('0000-00-00', '%d-%m-%Y', 'invalid');
$this->assertEquals('invalid', $result);
}
/**
@ -590,6 +687,40 @@ class CakeTimeTest extends CakeTestCase {
$this->assertFalse($result);
}
/**
* testIsFuture method
*
* @return void
*/
public function testIsFuture() {
$this->assertTrue($this->Time->isFuture('+1 month'));
$this->assertTrue($this->Time->isFuture('+1 days'));
$this->assertTrue($this->Time->isFuture('+1 minute'));
$this->assertTrue($this->Time->isFuture('+1 second'));
$this->assertFalse($this->Time->isFuture('-1 second'));
$this->assertFalse($this->Time->isFuture('-1 day'));
$this->assertFalse($this->Time->isFuture('-1 week'));
$this->assertFalse($this->Time->isFuture('-1 month'));
}
/**
* testIsPast method
*
* @return void
*/
public function testIsPast() {
$this->assertFalse($this->Time->isPast('+1 month'));
$this->assertFalse($this->Time->isPast('+1 days'));
$this->assertFalse($this->Time->isPast('+1 minute'));
$this->assertFalse($this->Time->isPast('+1 second'));
$this->assertTrue($this->Time->isPast('-1 second'));
$this->assertTrue($this->Time->isPast('-1 day'));
$this->assertTrue($this->Time->isPast('-1 week'));
$this->assertTrue($this->Time->isPast('-1 month'));
}
/**
* testIsThisWeek method
*
@ -847,6 +978,7 @@ class CakeTimeTest extends CakeTestCase {
$date = new DateTime('+1 hour', new DateTimeZone('America/New_York'));
$result = $this->Time->fromString($date, 'Asia/Kuwait');
$date->setTimezone(new DateTimeZone('Asia/Kuwait'));
$expected = $date->format('U') + $date->getOffset();
$this->assertWithinMargin($expected, $result, 1);
@ -854,6 +986,18 @@ class CakeTimeTest extends CakeTestCase {
$this->_restoreSystemTimezone();
}
/**
* Test that datetimes in the default timezone are not modified.
*
* @return void
*/
public function testFromStringWithDateTimeNoConversion() {
Configure::write('Config.timezone', date_default_timezone_get());
$date = new DateTime('2013-04-09');
$result = $this->Time->fromString($date);
$this->assertEquals($result, $date->format('U'));
}
/**
* test converting time specifiers using a time definition localfe file
*
@ -944,12 +1088,12 @@ class CakeTimeTest extends CakeTestCase {
}
/**
* test convert %e on windows.
* test convert %e on Windows.
*
* @return void
*/
public function testConvertPercentE() {
$this->skipIf(DIRECTORY_SEPARATOR !== '\\', 'Cannot run windows tests on non-windows OS.');
$this->skipIf(DIRECTORY_SEPARATOR !== '\\', 'Cannot run Windows tests on non-Windows OS.');
$time = strtotime('Thu Jan 14 11:43:39 2010');
$result = $this->Time->convertSpecifiers('%e', $time);
@ -1022,6 +1166,10 @@ class CakeTimeTest extends CakeTestCase {
* @return void
*/
public function testListTimezones() {
$this->skipIf(
version_compare(PHP_VERSION, '5.4.0', '<='),
'This test requires newer libicu which is in php5.4+'
);
$return = CakeTime::listTimezones();
$this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
$this->assertEquals('Bangkok', $return['Asia']['Asia/Bangkok']);
@ -1035,6 +1183,19 @@ class CakeTimeTest extends CakeTestCase {
$this->assertTrue(isset($return['Asia']['Asia/Bangkok']));
$this->assertFalse(isset($return['Pacific']));
$return = CakeTime::listTimezones(null, null, array('abbr' => true));
$this->assertTrue(isset($return['Asia']['Asia/Jakarta']));
$this->assertEquals('Jakarta - WIB', $return['Asia']['Asia/Jakarta']);
$this->assertEquals('Regina - CST', $return['America']['America/Regina']);
$return = CakeTime::listTimezones(null, null, array(
'abbr' => true,
'before' => ' (',
'after' => ')',
));
$this->assertEquals('Jayapura (WIT)', $return['Asia']['Asia/Jayapura']);
$this->assertEquals('Regina (CST)', $return['America']['America/Regina']);
$return = CakeTime::listTimezones('#^(America|Pacific)/#', null, false);
$this->assertTrue(isset($return['America/Argentina/Buenos_Aires']));
$this->assertTrue(isset($return['Pacific/Tahiti']));
@ -1055,7 +1216,7 @@ class CakeTimeTest extends CakeTestCase {
* from one timezone to the other correctly
*
* @return void
**/
*/
public function testCorrectTimezoneConversion() {
date_default_timezone_set('UTC');
$date = '2012-01-01 10:00:00';

View file

@ -2,20 +2,20 @@
/**
* ClassRegistryTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ClassRegistry', 'Utility');
/**
@ -28,7 +28,7 @@ class ClassRegisterModel extends CakeTestModel {
/**
* useTable property
*
* @var bool false
* @var bool
*/
public $useTable = false;
}
@ -39,13 +39,6 @@ class ClassRegisterModel extends CakeTestModel {
* @package Cake.Test.Case.Utility
*/
class RegisterArticle extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticle'
*/
public $name = 'RegisterArticle';
}
/**
@ -54,13 +47,6 @@ class RegisterArticle extends ClassRegisterModel {
* @package Cake.Test.Case.Utility
*/
class RegisterArticleFeatured extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleFeatured'
*/
public $name = 'RegisterArticleFeatured';
}
/**
@ -69,13 +55,6 @@ class RegisterArticleFeatured extends ClassRegisterModel {
* @package Cake.Test.Case.Utility
*/
class RegisterArticleTag extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterArticleTag'
*/
public $name = 'RegisterArticleTag';
}
/**
@ -88,7 +67,7 @@ class RegistryPluginAppModel extends ClassRegisterModel {
/**
* tablePrefix property
*
* @var string 'something_'
* @var string
*/
public $tablePrefix = 'something_';
}
@ -99,13 +78,6 @@ class RegistryPluginAppModel extends ClassRegisterModel {
* @package Cake.Test.Case.Utility
*/
class TestRegistryPluginModel extends RegistryPluginAppModel {
/**
* name property
*
* @var string 'TestRegistryPluginModel'
*/
public $name = 'TestRegistryPluginModel';
}
/**
@ -114,13 +86,6 @@ class TestRegistryPluginModel extends RegistryPluginAppModel {
* @package Cake.Test.Case.Utility
*/
class RegisterCategory extends ClassRegisterModel {
/**
* name property
*
* @var string 'RegisterCategory'
*/
public $name = 'RegisterCategory';
}
/**
* RegisterPrefixedDs class
@ -132,7 +97,7 @@ class RegisterPrefixedDs extends ClassRegisterModel {
/**
* useDbConfig property
*
* @var string 'doesnotexist'
* @var string
*/
public $useDbConfig = 'doesnotexist';
}
@ -169,7 +134,7 @@ class ClassRegistryTest extends CakeTestCase {
*/
public function testAddModel() {
$Tag = ClassRegistry::init('RegisterArticleTag');
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $Tag);
$TagCopy = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertTrue($TagCopy);
@ -178,11 +143,11 @@ class ClassRegistryTest extends CakeTestCase {
$TagCopy = ClassRegistry::getObject('RegisterArticleTag');
$this->assertTrue(is_a($TagCopy, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $TagCopy);
$this->assertSame($Tag, $TagCopy);
$NewTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $NewTag);
$NewTagCopy = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
@ -199,17 +164,17 @@ class ClassRegistryTest extends CakeTestCase {
$this->assertTrue($TagCopy->name === 'SomeOtherName');
$User = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
$this->assertTrue(is_a($User, 'AppModel'));
$this->assertInstanceOf('AppModel', $User);
$UserCopy = ClassRegistry::init(array('class' => 'RegisterUser', 'alias' => 'User', 'table' => false));
$this->assertTrue(is_a($UserCopy, 'AppModel'));
$this->assertInstanceOf('AppModel', $UserCopy);
$this->assertEquals($User, $UserCopy);
$Category = ClassRegistry::init(array('class' => 'RegisterCategory'));
$this->assertTrue(is_a($Category, 'RegisterCategory'));
$this->assertInstanceOf('RegisterCategory', $Category);
$ParentCategory = ClassRegistry::init(array('class' => 'RegisterCategory', 'alias' => 'ParentCategory'));
$this->assertTrue(is_a($ParentCategory, 'RegisterCategory'));
$this->assertInstanceOf('RegisterCategory', $ParentCategory);
$this->assertNotSame($Category, $ParentCategory);
$this->assertNotEquals($Category->alias, $ParentCategory->alias);
@ -217,21 +182,50 @@ class ClassRegistryTest extends CakeTestCase {
$this->assertEquals('ParentCategory', $ParentCategory->alias);
}
/**
* Test that init() can make models with alias set properly
*
* @return void
*/
public function testAddModelWithAlias() {
$tag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'NewTag'));
$this->assertInstanceOf('RegisterArticleTag', $tag);
$this->assertSame('NewTag', $tag->alias);
$this->assertSame('RegisterArticleTag', $tag->name);
$newTag = ClassRegistry::init(array('class' => 'RegisterArticleTag', 'alias' => 'OtherTag'));
$this->assertInstanceOf('RegisterArticleTag', $tag);
$this->assertSame('OtherTag', $newTag->alias);
$this->assertSame('RegisterArticleTag', $newTag->name);
}
/**
* Test that init() can make the Aco models with alias set properly
*
* @return void
*/
public function testAddModelWithAliasAco() {
$aco = ClassRegistry::init(array('class' => 'Aco', 'alias' => 'CustomAco'));
$this->assertInstanceOf('Aco', $aco);
$this->assertSame('Aco', $aco->name);
$this->assertSame('CustomAco', $aco->alias);
}
/**
* testClassRegistryFlush method
*
* @return void
*/
public function testClassRegistryFlush() {
$Tag = ClassRegistry::init('RegisterArticleTag');
ClassRegistry::init('RegisterArticleTag');
$ArticleTag = ClassRegistry::getObject('RegisterArticleTag');
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $ArticleTag);
ClassRegistry::flush();
$NoArticleTag = ClassRegistry::isKeySet('RegisterArticleTag');
$this->assertFalse($NoArticleTag);
$this->assertTrue(is_a($ArticleTag, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $ArticleTag);
}
/**
@ -266,13 +260,13 @@ class ClassRegistryTest extends CakeTestCase {
$this->assertTrue($Tag);
$Article = ClassRegistry::getObject('Article');
$this->assertTrue(is_a($Article, 'RegisterArticle'));
$this->assertInstanceOf('RegisterArticle', $Article);
$Featured = ClassRegistry::getObject('Featured');
$this->assertTrue(is_a($Featured, 'RegisterArticleFeatured'));
$this->assertInstanceOf('RegisterArticleFeatured', $Featured);
$Tag = ClassRegistry::getObject('Tag');
$this->assertTrue(is_a($Tag, 'RegisterArticleTag'));
$this->assertInstanceOf('RegisterArticleTag', $Tag);
}
/**
@ -287,15 +281,15 @@ class ClassRegistryTest extends CakeTestCase {
//Faking a plugin
CakePlugin::load('RegistryPlugin', array('path' => '/fake/path'));
$TestRegistryPluginModel = ClassRegistry::init('RegistryPlugin.TestRegistryPluginModel');
$this->assertTrue(is_a($TestRegistryPluginModel, 'TestRegistryPluginModel'));
$this->assertInstanceOf('TestRegistryPluginModel', $TestRegistryPluginModel);
$this->assertEquals('something_', $TestRegistryPluginModel->tablePrefix);
$PluginUser = ClassRegistry::init(array('class' => 'RegistryPlugin.RegisterUser', 'alias' => 'RegistryPluginUser', 'table' => false));
$this->assertTrue(is_a($PluginUser, 'RegistryPluginAppModel'));
$this->assertInstanceOf('RegistryPluginAppModel', $PluginUser);
$PluginUserCopy = ClassRegistry::getObject('RegistryPluginUser');
$this->assertTrue(is_a($PluginUserCopy, 'RegistryPluginAppModel'));
$this->assertInstanceOf('RegistryPluginAppModel', $PluginUserCopy);
$this->assertSame($PluginUser, $PluginUserCopy);
CakePlugin::unload();
}
@ -303,6 +297,7 @@ class ClassRegistryTest extends CakeTestCase {
/**
* Tests prefixed datasource names for test purposes
*
* @return void
*/
public function testPrefixedTestDatasource() {
ClassRegistry::config(array('testing' => true));
@ -322,6 +317,7 @@ class ClassRegistryTest extends CakeTestCase {
/**
* 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));

View file

@ -1,20 +1,22 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Debugger', 'Utility');
/**
* DebugggerTestCaseDebuggger class
* DebuggerTestCaseDebugger class
*
* @package Cake.Test.Case.Utility
*/
@ -65,7 +67,7 @@ class DebuggerTest extends CakeTestCase {
public function testDocRef() {
ini_set('docref_root', '');
$this->assertEquals(ini_get('docref_root'), '');
$debugger = new Debugger();
new Debugger();
$this->assertEquals(ini_get('docref_root'), 'http://php.net/');
}
@ -87,7 +89,7 @@ class DebuggerTest extends CakeTestCase {
$pattern = '/<code>.*?<span style\="color\: \#\d+">.*?&lt;\?php/';
$this->assertRegExp($pattern, $result[0]);
$result = Debugger::excerpt(__FILE__, 10, 2);
$result = Debugger::excerpt(__FILE__, 11, 2);
$this->assertEquals(5, count($result));
$pattern = '/<span style\="color\: \#\d{6}">\*<\/span>/';
@ -141,8 +143,8 @@ class DebuggerTest extends CakeTestCase {
'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'\);/"
"\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
" \? '' \: 'none'\);/"
),
'b' => array(), 'Notice', '/b', ' (8)',
));
@ -153,6 +155,24 @@ class DebuggerTest extends CakeTestCase {
$this->assertContains('$wrong = &#039;&#039;', $result[3], 'Context should be HTML escaped.');
}
/**
* test encodes error messages
*
* @return void
*/
public function testOutputEncodeDescription() {
set_error_handler('Debugger::showError');
$this->_restoreError = true;
ob_start();
$a = array();
$b = $a['<script>alert(1)</script>'];
$result = ob_get_clean();
$this->assertNotContains('<script>alert(1)', $result);
$this->assertContains('&lt;script&gt;alert(1)', $result);
}
/**
* Tests that changes in output formats using Debugger::output() change the templates used.
*
@ -171,7 +191,7 @@ class DebuggerTest extends CakeTestCase {
Debugger::output('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
'{:description}</error>',
'context' => "<context>{:context}</context>",
'trace' => "<stack>{:trace}</stack>",
));
@ -185,7 +205,7 @@ class DebuggerTest extends CakeTestCase {
'error' => array(),
'code' => array(), '8', '/code',
'file' => array(), 'preg:/[^<]+/', '/file',
'line' => array(), '' . (intval(__LINE__) - 7), '/line',
'line' => array(), '' . ((int)__LINE__ - 7), '/line',
'preg:/Undefined variable:\s+foo/',
'/error'
);
@ -223,7 +243,7 @@ class DebuggerTest extends CakeTestCase {
Debugger::addFormat('js', array(
'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
'&line={:line}">{:path}</a>, line {:line}'
'&line={:line}">{:path}</a>, line {:line}'
));
Debugger::outputAs('js');
@ -232,7 +252,7 @@ class DebuggerTest extends CakeTestCase {
Debugger::addFormat('xml', array(
'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
'{:description}</error>',
'{:description}</error>',
));
Debugger::outputAs('xml');
@ -244,7 +264,7 @@ class DebuggerTest extends CakeTestCase {
'<error',
'<code', '8', '/code',
'<file', 'preg:/[^<]+/', '/file',
'<line', '' . (intval(__LINE__) - 7), '/line',
'<line', '' . ((int)__LINE__ - 7), '/line',
'preg:/Undefined variable:\s+foo/',
'/error'
);
@ -272,6 +292,8 @@ class DebuggerTest extends CakeTestCase {
/**
* Test method for testing addFormat with callbacks.
*
* @return void
*/
public function customFormat($error, $strings) {
return $error['error'] . ': I eated an error ' . $error['file'];
@ -331,10 +353,47 @@ object(View) {
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(
@ -362,6 +421,44 @@ 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);
}
@ -375,21 +472,44 @@ TEXT;
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->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
$this->assertRegExp("/'cool'/", $result);
$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->assertRegExp('/DebuggerTest\:\:testLog/i', $result);
$this->assertRegExp('/\[main\]/', $result);
$this->assertRegExp('/array/', $result);
$this->assertRegExp("/'whatever',/", $result);
$this->assertRegExp("/'here'/", $result);
$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');
}
/**
@ -413,8 +533,11 @@ TEXT;
ob_start();
Debugger::dump($var);
$result = ob_get_clean();
$open = PHP_SAPI === 'cli' ? "\n" : '<pre>';
$close = PHP_SAPI === 'cli' ? "\n" : '</pre>';
$expected = <<<TEXT
<pre>array(
{$open}array(
'People' => array(
(int) 0 => array(
'name' => 'joeseph',
@ -427,7 +550,22 @@ TEXT;
'hair' => 'black'
)
)
)</pre>
){$close}
TEXT;
$this->assertTextEquals($expected, $result);
ob_start();
Debugger::dump($var, 1);
$result = ob_get_clean();
$open = PHP_SAPI === 'cli' ? "\n" : '<pre>';
$close = PHP_SAPI === 'cli' ? "\n" : '</pre>';
$expected = <<<TEXT
{$open}array(
'People' => array(
[maximum depth reached]
)
){$close}
TEXT;
$this->assertTextEquals($expected, $result);
}

View file

@ -2,20 +2,20 @@
/**
* FileTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('File', 'Utility');
App::uses('Folder', 'Utility');
@ -23,13 +23,14 @@ App::uses('Folder', 'Utility');
* FileTest class
*
* @package Cake.Test.Case.Utility
* @coversDefaultClass File
*/
class FileTest extends CakeTestCase {
/**
* File property
*
* @var mixed null
* @var mixed
*/
public $File = null;
@ -62,6 +63,15 @@ class FileTest extends CakeTestCase {
* testBasic method
*
* @return void
* @covers ::__construct
* @covers ::info
* @covers ::ext
* @covers ::name
* @covers ::md5
* @covers ::size
* @covers ::owner
* @covers ::group
* @covers ::Folder
*/
public function testBasic() {
$file = CAKE . DS . 'LICENSE.txt';
@ -81,8 +91,7 @@ class FileTest extends CakeTestCase {
'filesize' => filesize($file),
'mime' => 'text/plain'
);
if (
!function_exists('finfo_open') &&
if (!function_exists('finfo_open') &&
(!function_exists('mime_content_type') ||
function_exists('mime_content_type') &&
mime_content_type($this->File->pwd()) === false)
@ -125,13 +134,14 @@ class FileTest extends CakeTestCase {
/**
* testPermission method
*
* @return void
* @covers ::perms
*/
public function testPermission() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'File permissions tests not supported on Windows.');
$dir = TMP . 'tests' . DS . 'permissions' . DS;
$Folder = new Folder($dir);
$old = umask();
umask(0002);
@ -173,6 +183,7 @@ class FileTest extends CakeTestCase {
* testRead method
*
* @return void
* @covers ::read
*/
public function testRead() {
$file = __FILE__;
@ -204,6 +215,7 @@ class FileTest extends CakeTestCase {
* testOffset method
*
* @return void
* @covers ::offset
*/
public function testOffset() {
$this->File->close();
@ -217,25 +229,26 @@ class FileTest extends CakeTestCase {
$this->assertTrue(is_resource($this->File->handle));
$result = $this->File->offset();
$expecting = 0;
$this->assertSame($result, $expecting);
$expected = 0;
$this->assertSame($expected, $result);
$data = file_get_contents(__FILE__);
$success = $this->File->offset(5);
$expecting = substr($data, 5, 3);
$expected = substr($data, 5, 3);
$result = $this->File->read(3);
$this->assertTrue($success);
$this->assertEquals($expecting, $result);
$this->assertEquals($expected, $result);
$result = $this->File->offset();
$expecting = 5 + 3;
$this->assertSame($result, $expecting);
$expected = 5 + 3;
$this->assertSame($expected, $result);
}
/**
* testOpen method
*
* @return void
* @covers ::open
*/
public function testOpen() {
$this->File->handle = null;
@ -260,6 +273,7 @@ class FileTest extends CakeTestCase {
* testClose method
*
* @return void
* @covers ::close
*/
public function testClose() {
$this->File->handle = null;
@ -277,6 +291,9 @@ class FileTest extends CakeTestCase {
* testCreate method
*
* @return void
* @covers ::create
* @covers ::exists
* @covers ::clearStatCache
*/
public function testCreate() {
$tmpFile = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
@ -284,10 +301,29 @@ class FileTest extends CakeTestCase {
$this->assertTrue($File->exists());
}
/**
* Tests the exists() method.
*
* @return void
*/
public function testExists() {
$tmpFile = TMP . 'tests/cakephp.file.test.tmp';
$file = new File($tmpFile, true, 0777);
$this->assertTrue($file->exists(), 'absolute path should exist');
$file = new File('file://' . $tmpFile, false);
$this->assertTrue($file->exists(), 'file:// should exist.');
$file = new File('/something/bad', false);
$this->assertFalse($file->exists(), 'missing file should not exist.');
}
/**
* testOpeningNonExistentFileCreatesIt method
*
* @return void
* @covers ::open
* @covers ::create
*/
public function testOpeningNonExistentFileCreatesIt() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -301,26 +337,28 @@ class FileTest extends CakeTestCase {
* testPrepare method
*
* @return void
* @covers ::prepare
*/
public function testPrepare() {
$string = "some\nvery\ncool\r\nteststring here\n\n\nfor\r\r\n\n\r\n\nhere";
if (DS == '\\') {
if (DS === '\\') {
$expected = "some\r\nvery\r\ncool\r\nteststring here\r\n\r\n\r\n";
$expected .= "for\r\n\r\n\r\n\r\n\r\nhere";
} else {
$expected = "some\nvery\ncool\nteststring here\n\n\nfor\n\n\n\n\nhere";
}
$this->assertSame(File::prepare($string), $expected);
$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(File::prepare($string, true), $expected);
$this->assertSame($expected, File::prepare($string, true));
}
/**
* testReadable method
*
* @return void
* @covers ::readable
*/
public function testReadable() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -334,6 +372,7 @@ class FileTest extends CakeTestCase {
* testWritable method
*
* @return void
* @covers ::writable
*/
public function testWritable() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -347,6 +386,7 @@ class FileTest extends CakeTestCase {
* testExecutable method
*
* @return void
* @covers ::executable
*/
public function testExecutable() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -360,6 +400,7 @@ class FileTest extends CakeTestCase {
* testLastAccess method
*
* @return void
* @covers ::lastAccess
*/
public function testLastAccess() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -374,6 +415,7 @@ class FileTest extends CakeTestCase {
* testLastChange method
*
* @return void
* @covers ::lastChange
*/
public function testLastChange() {
$someFile = new File(TMP . 'some_file.txt', false);
@ -392,11 +434,12 @@ class FileTest extends CakeTestCase {
* testWrite method
*
* @return void
* @covers ::write
*/
public function testWrite() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
}
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
@ -422,11 +465,12 @@ class FileTest extends CakeTestCase {
* testAppend method
*
* @return void
* @covers ::append
*/
public function testAppend() {
if (!$tmpFile = $this->_getTmpFile()) {
return false;
};
}
if (file_exists($tmpFile)) {
unlink($tmpFile);
}
@ -434,22 +478,31 @@ class FileTest extends CakeTestCase {
$TmpFile = new File($tmpFile);
$this->assertFalse(file_exists($tmpFile));
$fragments = array('CakePHP\'s', ' test suite', ' was here ...', '');
$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
* @covers ::delete
*/
public function testDelete() {
if (!$tmpFile = $this->_getTmpFile()) {
@ -475,6 +528,7 @@ class FileTest extends CakeTestCase {
* active filehandles open.
*
* @return void
* @covers ::delete
*/
public function testDeleteAfterRead() {
if (!$tmpFile = $this->_getTmpFile()) {
@ -492,6 +546,7 @@ class FileTest extends CakeTestCase {
* testCopy method
*
* @return void
* @covers ::copy
*/
public function testCopy() {
$dest = TMP . 'tests' . DS . 'cakephp.file.test.tmp';
@ -520,13 +575,14 @@ class FileTest extends CakeTestCase {
* Test mime()
*
* @return void
* @covers ::mime
*/
public function testMime() {
$this->skipIf(!function_exists('finfo_open') && !function_exists('mime_content_type'), 'Not able to read mime type');
$path = CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
$file = new File($path);
$expected = 'image/gif';
if (function_exists('mime_content_type') && false === mime_content_type($file->pwd())) {
if (function_exists('mime_content_type') && mime_content_type($file->pwd()) === false) {
$expected = false;
}
$this->assertEquals($expected, $file->mime());
@ -542,7 +598,7 @@ class FileTest extends CakeTestCase {
$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();
@ -554,4 +610,54 @@ class FileTest extends CakeTestCase {
}
return false;
}
/**
* testReplaceText method
*
* @return void
* @covers ::replaceText
*/
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();
}
/**
* Tests that no path is being set for passed file paths that
* do not exist.
*
* @return void
* @covers ::pwd
*/
public function testNoPartialPathBeingSetForNonExistentPath() {
$tmpFile = new File('/non/existent/file');
$this->assertNull($tmpFile->pwd());
$this->assertNull($tmpFile->path);
}
}

View file

@ -2,20 +2,20 @@
/**
* FolderTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Folder', 'Utility');
App::uses('File', 'Utility');
@ -29,14 +29,19 @@ class FolderTest extends CakeTestCase {
protected static $_tmp = array();
/**
* Save the directory names in TMP
* Save the directory names in TMP and make sure default directories exist
*
* @return void
*/
public static function setUpBeforeClass() {
$dirs = array('cache', 'logs', 'sessions', 'tests');
foreach ($dirs as $dir) {
new Folder(TMP . $dir, true);
}
foreach (scandir(TMP) as $file) {
if (is_dir(TMP . $file) && !in_array($file, array('.', '..'))) {
self::$_tmp[] = $file;
static::$_tmp[] = $file;
}
}
}
@ -57,7 +62,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
public function tearDown() {
$exclude = array_merge(self::$_tmp, array('.', '..'));
$exclude = array_merge(static::$_tmp, array('.', '..'));
foreach (scandir(TMP) as $dir) {
if (is_dir(TMP . $dir) && !in_array($dir, $exclude)) {
$iterator = new RecursiveDirectoryIterator(TMP . $dir);
@ -71,6 +76,7 @@ class FolderTest extends CakeTestCase {
rmdir(TMP . $dir);
}
}
parent::tearDown();
}
/**
@ -103,28 +109,86 @@ class FolderTest extends CakeTestCase {
* @return void
*/
public function testInPath() {
$path = dirname(dirname(__FILE__));
$inside = dirname($path) . DS;
// "/Test/test_app/"
$basePath = CAKE . 'Test' . DS . 'test_app' . DS;
$Base = new Folder($basePath);
$Folder = new Folder($path);
$result = $Base->pwd();
$this->assertEquals($basePath, $result);
$result = $Folder->pwd();
$this->assertEquals($path, $result);
// is "/" in "/Test/test_app/"
$result = $Base->inPath(realpath(DS), true);
$this->assertFalse($result, true);
$result = Folder::isSlashTerm($inside);
// is "/Test/test_app/" in "/Test/test_app/"
$result = $Base->inPath($basePath, true);
$this->assertTrue($result);
$result = $Folder->realpath('Test/');
$this->assertEquals($path . DS . 'Test' . DS, $result);
$result = $Folder->inPath('Test' . DS);
// is "/Test/test_app" in "/Test/test_app/"
$result = $Base->inPath(mb_substr($basePath, 0, -1), true);
$this->assertTrue($result);
$result = $Folder->inPath(DS . 'non-existing' . $inside);
// is "/Test/test_app/sub" in "/Test/test_app/"
$result = $Base->inPath($basePath . 'sub', true);
$this->assertTrue($result);
// is "/Test" in "/Test/test_app/"
$result = $Base->inPath(dirname($basePath), true);
$this->assertFalse($result);
$result = $Folder->inPath($path . DS . 'Model', true);
// is "/Test/other/(...)Test/test_app" in "/Test/test_app/"
$result = $Base->inPath(TMP . 'tests' . DS . 'other' . DS . $basePath, true);
$this->assertFalse($result);
// is "/Test/test_app/" in "/"
$result = $Base->inPath(realpath(DS));
$this->assertTrue($result);
// is "/Test/test_app/" in "/Test/test_app/"
$result = $Base->inPath($basePath);
$this->assertTrue($result);
// is "/Test/test_app/" in "/Test/test_app"
$result = $Base->inPath(mb_substr($basePath, 0, -1));
$this->assertTrue($result);
// is "/Test/test_app/" in "/Test"
$result = $Base->inPath(dirname($basePath));
$this->assertTrue($result);
// is "/Test/test_app/" in "/Test/test_app/sub"
$result = $Base->inPath($basePath . 'sub');
$this->assertFalse($result);
// is "/other/Test/test_app/" in "/Test/test_app/"
$VirtualBase = new Folder();
$VirtualBase->path = '/other/Test/test_app';
$result = $VirtualBase->inPath('/Test/test_app/');
$this->assertFalse($result);
}
/**
* Data provider for the testInPathInvalidPathArgument test
*
* @return array
*/
public function inPathInvalidPathArgumentDataProvider() {
return array(
array(''),
array('relative/path/'),
array('unknown://stream-wrapper')
);
}
/**
* @dataProvider inPathInvalidPathArgumentDataProvider
* @param string $path
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage The $path argument is expected to be an absolute path.
*/
public function testInPathInvalidPathArgument($path) {
$Folder = new Folder();
$Folder->inPath($path);
}
/**
@ -164,13 +228,29 @@ class FolderTest extends CakeTestCase {
$this->assertTrue($Folder->delete());
}
/**
* Test that relative paths to create() are added to cwd.
*
* @return void
*/
public function testCreateRelative() {
$folder = new Folder(TMP);
$path = TMP . 'tests' . DS . 'relative-test';
$result = $folder->create('tests' . DS . 'relative-test');
$this->assertTrue($result, 'should create');
$this->assertTrue(is_dir($path), 'Folder was not made');
$folder = new Folder($path);
$folder->delete();
}
/**
* test recursive directory create failure.
*
* @return void
*/
public function testRecursiveCreateFailure() {
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on windows.');
$this->skipIf(DIRECTORY_SEPARATOR === '\\', 'Cant perform operations using permissions on Windows.');
$path = TMP . 'tests' . DS . 'one';
mkdir($path);
@ -338,11 +418,24 @@ class FolderTest extends CakeTestCase {
* @return void
*/
public function testAddPathElement() {
$expected = DS . 'some' . DS . 'dir' . DS . 'another_path';
$result = Folder::addPathElement(DS . 'some' . DS . 'dir', 'another_path');
$this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result);
$this->assertEquals($expected, $result);
$result = Folder::addPathElement(DS . 'some' . DS . 'dir' . DS, 'another_path');
$this->assertEquals(DS . 'some' . DS . 'dir' . DS . 'another_path', $result);
$this->assertEquals($expected, $result);
$result = Folder::addPathElement(DS . 'some' . DS . 'dir', array('another_path'));
$this->assertEquals($expected, $result);
$result = Folder::addPathElement(DS . 'some' . DS . 'dir' . DS, array('another_path'));
$this->assertEquals($expected, $result);
$expected = DS . 'some' . DS . 'dir' . DS . 'another_path' . DS . 'and' . DS . 'another';
$result = Folder::addPathElement(DS . 'some' . DS . 'dir', array('another_path', 'and', 'another'));
$this->assertEquals($expected, $result);
}
/**
@ -369,7 +462,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
public function testFolderReadWithHiddenFiles() {
$this->skipIf(!is_writeable(TMP), 'Cant test Folder::read with hidden files unless the tmp folder is writable.');
$this->skipIf(!is_writable(TMP), 'Cant test Folder::read with hidden files unless the tmp folder is writable.');
$Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777);
mkdir($Folder->path . DS . '.svn');
@ -452,7 +545,7 @@ class FolderTest extends CakeTestCase {
* @return void
*/
public function testFolderTreeWithHiddenFiles() {
$this->skipIf(!is_writeable(TMP), 'Can\'t test Folder::tree with hidden files unless the tmp folder is writable.');
$this->skipIf(!is_writable(TMP), 'Can\'t test Folder::tree with hidden files unless the tmp folder is writable.');
$Folder = new Folder(TMP . 'folder_tree_hidden', true, 0777);
mkdir($Folder->path . DS . '.svn', 0777, true);
@ -529,6 +622,8 @@ class FolderTest extends CakeTestCase {
$this->assertFalse(Folder::isAbsolute('0:\\path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('\\path/to/file'));
$this->assertFalse(Folder::isAbsolute('\\path\\to\\file'));
$this->assertFalse(Folder::isAbsolute('notRegisteredStreamWrapper://example'));
$this->assertFalse(Folder::isAbsolute('://example'));
$this->assertTrue(Folder::isAbsolute('/usr/local'));
$this->assertTrue(Folder::isAbsolute('//path/to/file'));
@ -536,6 +631,7 @@ class FolderTest extends CakeTestCase {
$this->assertTrue(Folder::isAbsolute('C:\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('d:\\path\\to\\file'));
$this->assertTrue(Folder::isAbsolute('\\\\vmware-host\\Shared Folders\\file'));
$this->assertTrue(Folder::isAbsolute('http://www.example.com'));
}
/**
@ -635,7 +731,7 @@ class FolderTest extends CakeTestCase {
$this->assertSame(array_diff($expected, $result), array());
$result = $Folder->find('.*', true);
$expected = array('config.php', 'routes.php');
$expected = array('cacert.pem', 'config.php', 'routes.php');
$this->assertSame($expected, $result);
$result = $Folder->find('.*\.php');
@ -761,6 +857,55 @@ class FolderTest extends CakeTestCase {
$Folder->delete($Folder->pwd() . 'config_non_existent');
}
/**
* test that errors and messages can be resetted
*
* @return void
*/
public function testReset() {
$path = TMP . 'folder_delete_test';
mkdir($path);
$folder = $path . DS . 'sub';
mkdir($folder);
$file = $folder . DS . 'file';
touch($file);
chmod($folder, 0555);
chmod($file, 0444);
$Folder = new Folder($folder);
$return = $Folder->delete();
$this->assertFalse($return);
$messages = $Folder->messages();
$errors = $Folder->errors();
$expected = array(
$file . ' NOT removed',
$folder . ' NOT removed',
);
sort($expected);
sort($errors);
$this->assertEmpty($messages);
$this->assertEquals($expected, $errors);
chmod($file, 0644);
chmod($folder, 0755);
$return = $Folder->delete();
$this->assertTrue($return);
$messages = $Folder->messages();
$errors = $Folder->errors();
$expected = array(
$file . ' removed',
$folder . ' removed',
);
sort($expected);
sort($messages);
$this->assertEmpty($errors);
$this->assertEquals($expected, $messages);
}
/**
* testDelete method
*
@ -803,6 +948,64 @@ class FolderTest extends CakeTestCase {
/**
* testCopy method
*
* Verify that subdirectories existing in both destination and source directory
* are merged recursively.
*
* @return void
*/
public function testCopy() {
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderTwo);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'file2.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderB' . DS . 'fileB.php'));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* testCopyWithMerge method
*
* Verify that subdirectories existing in both destination and source directory
* are merged recursively.
*
* @return void
*/
public function testCopyWithMerge() {
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderTwo);
$result = $Folder->copy(array('to' => $folderThree, 'scheme' => Folder::MERGE));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'file2.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderB' . DS . 'fileB.php'));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* testCopyWithSkip method
*
* Verify that directories and files are copied recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
@ -810,128 +1013,357 @@ class FolderTest extends CakeTestCase {
*
* @return void
*/
public function testCopy() {
public function testCopyWithSkip() {
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->copy(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(file_exists($folderTwo . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderTwo);
$Folder->delete();
$Folder = new Folder($folderOne);
$result = $Folder->copy(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(file_exists($folderTwo . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderTwo);
$Folder->delete();
new Folder($folderTwo, true);
new Folder($folderTwo . DS . 'folderB', true);
file_put_contents($folderTwo . DS . 'file2.php', 'touched');
file_put_contents($folderTwo . DS . 'folderB' . DS . 'fileB.php', 'untouched');
$Folder = new Folder($folderTwo);
$result = $Folder->copy(array('to' => $folderThree, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file2.php'));
$this->assertEquals('touched', file_get_contents($folderThree . DS . 'file2.php'));
$this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folderB' . DS . 'fileB.php'));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* Test that SKIP mode skips files too.
*
* @return void
*/
public function testCopyWithSkipFileSkipped() {
$path = TMP . 'folder_test';
$folderOne = $path . DS . 'folder1';
$folderTwo = $folderOne . DS . 'folder2';
$folderThree = $path . DS . 'folder3';
$fileOne = $folderOne . DS . 'file1.php';
$fileTwo = $folderTwo . DS . 'file2.php';
$folderTwo = $path . DS . 'folder2';
new Folder($path, true);
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
touch($fileOne);
touch($fileTwo);
file_put_contents($folderOne . DS . 'fileA.txt', 'Folder One File');
file_put_contents($folderTwo . DS . 'fileA.txt', 'Folder Two File');
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$result = $Folder->copy(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertEquals('Folder Two File', file_get_contents($folderTwo . DS . 'fileA.txt'));
}
$Folder = new Folder($folderThree);
$Folder->delete();
/**
* testCopyWithOverwrite
*
* Verify that subdirectories existing in both destination and source directory
* are overwritten/replaced recursively.
*
* @return void
*/
public function testCopyWithOverwrite() {
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
$this->assertTrue($result);
$Folder->copy(array('to' => $folderThree, 'scheme' => Folder::OVERWRITE));
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderThree);
$Folder->delete();
$Folder = new Folder($folderTwo);
$result = $Folder->copy(array('to' => $folderThree, 'scheme' => Folder::OVERWRITE));
$this->assertTrue($result);
new Folder($folderThree, true);
new Folder($folderThree . DS . 'folder2', true);
file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched');
$this->assertTrue(file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$Folder = new Folder($folderOne);
$result = $Folder->copy($folderThree);
unlink($fileOneA);
$result = $Folder->copy(array('to' => $folderThree, 'scheme' => Folder::OVERWRITE));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertTrue(file_exists($folderThree . DS . 'file2.php'));
$this->assertTrue(!file_exists($folderThree . DS . 'folderA' . DS . 'fileA.php'));
$this->assertTrue(file_exists($folderThree . DS . 'folderB' . DS . 'fileB.php'));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* Setup filesystem for copy tests
* $path: folder_test/
* - folder1/file1.php
* - folder1/folderA/fileA.php
* - folder2/file2.php
* - folder2/folderB/fileB.php
* - folder3/
*
* @return array Filenames to extract in the test methods
*/
protected function _setupFilesystem() {
$path = TMP . 'folder_test';
$folderOne = $path . DS . 'folder1';
$folderOneA = $folderOne . DS . 'folderA';
$folderTwo = $path . DS . 'folder2';
$folderTwoB = $folderTwo . DS . 'folderB';
$folderThree = $path . DS . 'folder3';
$fileOne = $folderOne . DS . 'file1.php';
$fileTwo = $folderTwo . DS . 'file2.php';
$fileOneA = $folderOneA . DS . 'fileA.php';
$fileTwoB = $folderTwoB . DS . 'fileB.php';
new Folder($path, true);
new Folder($folderOne, true);
new Folder($folderOneA, true);
new Folder($folderTwo, true);
new Folder($folderTwoB, true);
new Folder($folderThree, true);
touch($fileOne);
touch($fileTwo);
touch($fileOneA);
touch($fileTwoB);
return compact(
'path',
'folderOne', 'folderOneA', 'folderTwo', 'folderTwoB', 'folderThree',
'fileOne', 'fileOneA', 'fileTwo', 'fileTwoB');
}
/**
* testMove method
*
* Verify that directories and files are moved recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
* are merged recursively.
*
* @return void
*/
public function testMove() {
$path = TMP . 'folder_test';
$folderOne = $path . DS . 'folder1';
$folderTwo = $folderOne . DS . 'folder2';
$folderThree = $path . DS . 'folder3';
$fileOne = $folderOne . DS . 'file1.php';
$fileTwo = $folderTwo . DS . 'file2.php';
new Folder($path, true);
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
touch($fileOne);
touch($fileTwo);
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$result = $Folder->move($folderTwo);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(is_dir($folderThree . DS . 'folder2'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(is_dir($folderTwo . DS . 'folderB'));
$this->assertTrue(file_exists($folderTwo . DS . 'folderB' . DS . 'fileB.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$this->assertTrue(file_exists($folderTwo . DS . 'folderA'));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($folderThree);
$Folder = new Folder($folderTwo);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderTwo, true);
new Folder($folderOneA, true);
touch($fileOne);
touch($fileTwo);
touch($fileOneA);
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$result = $Folder->move($folderTwo);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertTrue(is_dir($folderThree . DS . 'folder2'));
$this->assertTrue(file_exists($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(is_dir($folderTwo . DS . 'folderA'));
$this->assertTrue(file_exists($folderTwo . DS . 'folderA' . DS . 'fileA.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($folderThree);
$Folder = new Folder($folderTwo);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderOneA, true);
new Folder($folderTwo, true);
new Folder($folderThree, true);
new Folder($folderThree . DS . 'folder2', true);
new Folder($folderTwoB, true);
touch($fileOne);
touch($fileTwo);
file_put_contents($folderThree . DS . 'folder2' . DS . 'file2.php', 'untouched');
touch($fileOneA);
new Folder($folderOne . DS . 'folderB', true);
touch($folderOne . DS . 'folderB' . DS . 'fileB.php');
file_put_contents($folderTwoB . DS . 'fileB.php', 'untouched');
$Folder = new Folder($folderOne);
$result = $Folder->move($folderThree);
$result = $Folder->move($folderTwo);
$this->assertTrue($result);
$this->assertTrue(file_exists($folderThree . DS . 'file1.php'));
$this->assertEquals('untouched', file_get_contents($folderThree . DS . 'folder2' . DS . 'file2.php'));
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertEquals('', file_get_contents($folderTwoB . DS . 'fileB.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderTwo));
$this->assertFalse(file_exists($fileTwo));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* testMoveWithSkip method
*
* Verify that directories and files are moved recursively
* even if the destination directory already exists.
* Subdirectories existing in both destination and source directory
* are skipped and not merged or overwritten.
*
* @return void
*/
public function testMoveWithSkip() {
extract($this->_setupFilesystem());
$Folder = new Folder($folderOne);
$result = $Folder->move(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(is_dir($folderTwo . DS . 'folderB'));
$this->assertTrue(file_exists($folderTwoB . DS . 'fileB.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($folderTwo);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderOneA, true);
new Folder($folderTwo, true);
touch($fileOne);
touch($fileOneA);
$Folder = new Folder($folderOne);
$result = $Folder->move(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertTrue(is_dir($folderTwo . DS . 'folderA'));
$this->assertTrue(file_exists($folderTwo . DS . 'folderA' . DS . 'fileA.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($folderTwo);
$Folder->delete();
new Folder($folderOne, true);
new Folder($folderOneA, true);
new Folder($folderTwo, true);
new Folder($folderTwoB, true);
touch($fileOne);
touch($fileOneA);
file_put_contents($folderTwoB . DS . 'fileB.php', 'untouched');
$Folder = new Folder($folderOne);
$result = $Folder->move(array('to' => $folderTwo, 'scheme' => Folder::SKIP));
$this->assertTrue($result);
$this->assertTrue(file_exists($folderTwo . DS . 'file1.php'));
$this->assertEquals('untouched', file_get_contents($folderTwoB . DS . 'fileB.php'));
$this->assertFalse(file_exists($fileOne));
$this->assertFalse(file_exists($folderOneA));
$this->assertFalse(file_exists($fileOneA));
$Folder = new Folder($path);
$Folder->delete();
}
/**
* testSortByTime method
*
* Verify that the order using modified time is correct.
*
* @return void
*/
public function testSortByTime() {
$Folder = new Folder(TMP . 'test_sort_by_time', true);
$file2 = new File($Folder->pwd() . DS . 'file_2.tmp');
$file2->create();
sleep(1);
$file1 = new File($Folder->pwd() . DS . 'file_1.tmp');
$file1->create();
$expected = array('file_2.tmp', 'file_1.tmp');
$result = $Folder->find('.*', Folder::SORT_TIME);
$this->assertSame($expected, $result);
$Folder->delete();
}
/**
* testSortByTime2 method
*
* Verify that the sort order using modified time is correct.
*
* @return void
*/
public function testSortByTime2() {
$Folder = new Folder(TMP . 'test_sort_by_time2', true);
$fileC = new File($Folder->pwd() . DS . 'c.txt');
$fileC->create();
sleep(1);
$fileA = new File($Folder->pwd() . DS . 'a.txt');
$fileA->create();
sleep(1);
$fileB = new File($Folder->pwd() . DS . 'b.txt');
$fileB->create();
$expected = array('c.txt', 'a.txt', 'b.txt');
$result = $Folder->find('.*', Folder::SORT_TIME);
$this->assertSame($expected, $result);
$Folder->delete();
}
/**
* Verify that the sort order using name is correct.
*
* @return void
*/
public function testSortByName() {
$Folder = new Folder(TMP . 'test_sort_by_name', true);
$fileA = new File($Folder->pwd() . DS . 'a.txt');
$fileA->create();
$fileC = new File($Folder->pwd() . DS . 'c.txt');
$fileC->create();
sleep(1);
$fileB = new File($Folder->pwd() . DS . 'b.txt');
$fileB->create();
$expected = array('a.txt', 'b.txt', 'c.txt');
$result = $Folder->find('.*', Folder::SORT_NAME);
$this->assertSame($expected, $result);
$Folder->delete();
}
}

View file

@ -1,21 +1,33 @@
<?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package Cake.Utility
* @since CakePHP(tm) v 2.2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Hash', 'Utility');
/**
* HashTest
*
* @package Cake.Utility
*/
class HashTest extends CakeTestCase {
/**
* Data provider
*
* @return array
*/
public static function articleData() {
return array(
array(
@ -129,6 +141,11 @@ class HashTest extends CakeTestCase {
);
}
/**
* Data provider
*
* @return array
*/
public static function userData() {
return array(
array(
@ -167,10 +184,21 @@ class HashTest extends CakeTestCase {
/**
* Test get()
*
* return void
* @return void
*/
public function testGet() {
$data = self::articleData();
$data = array('abc', 'def');
$result = Hash::get($data, '0');
$this->assertEquals('abc', $result);
$result = Hash::get($data, 0);
$this->assertEquals('abc', $result);
$result = Hash::get($data, '1');
$this->assertEquals('def', $result);
$data = static::articleData();
$result = Hash::get(array(), '1.Article.title');
$this->assertNull($result);
@ -187,6 +215,10 @@ class HashTest extends CakeTestCase {
$result = Hash::get($data, '5.Article.title');
$this->assertNull($result);
$default = array('empty');
$this->assertEquals($default, Hash::get($data, '5.Article.title', $default));
$this->assertEquals($default, Hash::get(array(), '5.Article.title', $default));
$result = Hash::get($data, '1.Article.title.not_there');
$this->assertNull($result);
@ -197,6 +229,42 @@ class HashTest extends CakeTestCase {
$this->assertEquals($data[1]['Article'], $result);
}
/**
* Test that get() can extract '' key data.
*
* @return void
*/
public function testGetEmptyKey() {
$data = array(
'' => 'some value'
);
$result = Hash::get($data, '');
$this->assertSame($data[''], $result);
}
/**
* Test get() with an invalid path
*
* @expectedException InvalidArgumentException
* @return void
*/
public function testGetInvalidPath() {
Hash::get(array('one' => 'two'), true);
}
/**
* Test testGetNullPath()
*
* @return void
*/
public function testGetNullPath() {
$result = Hash::get(array('one' => 'two'), null, '-');
$this->assertEquals('-', $result);
$result = Hash::get(array('one' => 'two'), '', '-');
$this->assertEquals('-', $result);
}
/**
* Test dimensions.
*
@ -233,42 +301,37 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testMaxDimensions() {
$data = array();
$result = Hash::maxDimensions($data);
$this->assertEquals(0, $result);
$data = array('a', 'b');
$result = Hash::maxDimensions($data);
$this->assertEquals(1, $result);
$data = array('1' => '1.1', '2', '3' => array('3.1' => '3.1.1'));
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 2);
$data = array('1' => array('1.1' => '1.1.1'), '2', '3' => array('3.1' => array('3.1.1' => '3.1.1.1')));
$data = array(
'1' => array('1.1' => '1.1.1'),
'2',
'3' => array('3.1' => array('3.1.1' => '3.1.1.1'))
);
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 3);
$data = array(
'1' => array('1.1' => '1.1.1'),
array('2' => array('2.1' => array('2.1.1' => '2.1.1.1'))),
'3' => array('3.1' => array('3.1.1' => '3.1.1.1'))
);
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 4);
$data = array(
'1' => array('1.1' => '1.1.1'),
array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1')))),
'3' => array('3.1' => array('3.1.1' => '3.1.1.1'))
);
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 5);
$data = array(
'1' => array('1.1' => '1.1.1'),
array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))),
'3' => array('3.1' => array('3.1.1' => '3.1.1.1'))
);
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 5);
$data = array(
'1' => array('1.1' => '1.1.1'),
array('2' => array('2.1' => array('2.1.1' => array('2.1.1.1' => '2.1.1.1.1')))),
'3' => array('3.1' => array('3.1.1' => '3.1.1.1'))
'1' => array(
'1.1' => '1.1.1',
'1.2' => array(
'1.2.1' => array(
'1.2.1.1',
array('1.2.2.1')
)
)
),
'2' => array('2.1' => '2.1.1')
);
$result = Hash::maxDimensions($data);
$this->assertEquals($result, 5);
@ -509,7 +572,7 @@ class HashTest extends CakeTestCase {
'Validator',
'Transactional'
);
$this->assertEquals(Hash::merge($a, $b), $expected);
$this->assertEquals($expected, Hash::merge($a, $b));
}
/**
@ -575,6 +638,12 @@ class HashTest extends CakeTestCase {
);
$this->assertTrue(Hash::contains($b, $a));
$this->assertFalse(Hash::contains($a, $b));
$a = array(0 => 'test', 'string' => null);
$this->assertTrue(Hash::contains($a, array('string' => null)));
$a = array(0 => 'test', 'string' => null);
$this->assertTrue(Hash::contains($a, array('test')));
}
/**
@ -641,6 +710,9 @@ class HashTest extends CakeTestCase {
$data = array('one', 2 => 'two', 3 => 'three', 4 => 'four', 'a' => 'five');
$this->assertFalse(Hash::numeric(array_keys($data)));
$data = array(2.4, 1, 0, -1, -2);
$this->assertTrue(Hash::numeric($data));
}
/**
@ -649,7 +721,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractBasic() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '');
$this->assertEquals($data, $result);
@ -659,6 +731,9 @@ class HashTest extends CakeTestCase {
$result = Hash::extract($data, '1.Article.title');
$this->assertEquals(array('Second Article'), $result);
$result = Hash::extract(array(false), '{n}.Something.another_thing');
$this->assertEquals(array(), $result);
}
/**
@ -667,7 +742,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractNumericKey() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Article.title');
$expected = array(
'First Article', 'Second Article',
@ -746,7 +821,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractStringKey() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.{s}.user');
$expected = array(
'mariano',
@ -761,13 +836,39 @@ class HashTest extends CakeTestCase {
$this->assertEquals(array('foo'), $result);
}
/**
* Test wildcard matcher
*
* @return void
*/
public function testExtractWildcard() {
$data = array(
'02000009C5560001' => array('name' => 'Mr. Alphanumeric'),
'2300000918020101' => array('name' => 'Mr. Numeric'),
'390000096AB30001' => array('name' => 'Mrs. Alphanumeric'),
'stuff' => array('name' => 'Ms. Word'),
123 => array('name' => 'Mr. Number'),
true => array('name' => 'Ms. Bool'),
);
$result = Hash::extract($data, '{*}.name');
$expected = array(
'Mr. Alphanumeric',
'Mr. Numeric',
'Mrs. Alphanumeric',
'Ms. Word',
'Mr. Number',
'Ms. Bool',
);
$this->assertEquals($expected, $result);
}
/**
* Test the attribute presense selector.
*
* @return void
*/
public function testExtractAttributePresence() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Article[published]');
$expected = array($data[1]['Article']);
@ -784,7 +885,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractAttributeEquality() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Article[id=3]');
$expected = array($data[2]['Article']);
@ -801,13 +902,75 @@ class HashTest extends CakeTestCase {
$this->assertEquals(5, $result[3]['id']);
}
/**
* Test extracting based on attributes with boolean values.
*
* @return void
*/
public function testExtractAttributeBoolean() {
$users = array(
array(
'id' => 2,
'username' => 'johndoe',
'active' => true
),
array(
'id' => 5,
'username' => 'kevin',
'active' => true
),
array(
'id' => 9,
'username' => 'samantha',
'active' => false
),
);
$result = Hash::extract($users, '{n}[active=0]');
$this->assertCount(1, $result);
$this->assertEquals($users[2], $result[0]);
$result = Hash::extract($users, '{n}[active=false]');
$this->assertCount(1, $result);
$this->assertEquals($users[2], $result[0]);
$result = Hash::extract($users, '{n}[active=1]');
$this->assertCount(2, $result);
$this->assertEquals($users[0], $result[0]);
$this->assertEquals($users[1], $result[1]);
$result = Hash::extract($users, '{n}[active=true]');
$this->assertCount(2, $result);
$this->assertEquals($users[0], $result[0]);
$this->assertEquals($users[1], $result[1]);
}
/**
* Test that attribute matchers don't cause errors on scalar data.
*
* @return void
*/
public function testExtractAttributeEqualityOnScalarValue() {
$data = array(
'Entity' => array(
'id' => 1,
'data1' => 'value',
)
);
$result = Hash::extract($data, 'Entity[id=1].data1');
$this->assertEquals(array('value'), $result);
$data = array('Entity' => false );
$result = Hash::extract($data, 'Entity[id=1].data1');
$this->assertEquals(array(), $result);
}
/**
* Test comparison operators.
*
* @return void
*/
public function testExtractAttributeComparison() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Comment.{n}[user_id > 2]');
$expected = array($data[0]['Comment'][1]);
@ -836,7 +999,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractAttributeMultiple() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Comment.{n}[user_id > 2][id=1]');
$this->assertEmpty($result);
@ -853,15 +1016,21 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testExtractAttributePattern() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::extract($data, '{n}.Article[title=/^First/]');
$expected = array($data[0]['Article']);
$this->assertEquals($expected, $result);
$result = Hash::extract($data, '{n}.Article[title=/^Fir[a-z]+/]');
$expected = array($data[0]['Article']);
$this->assertEquals($expected, $result);
}
/**
* Test that extract() + matching can hit null things.
*
* @return void
*/
public function testExtractMatchesNull() {
$data = array(
@ -928,7 +1097,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testSort() {
$result = Hash::sort(array(), '{n}.name', 'asc');
$result = Hash::sort(array(), '{n}.name');
$this->assertEquals(array(), $result);
$a = array(
@ -951,7 +1120,7 @@ class HashTest extends CakeTestCase {
'Friend' => array(array('name' => 'Nate'))
)
);
$a = Hash::sort($a, '{n}.Friend.{n}.name', 'asc');
$a = Hash::sort($a, '{n}.Friend.{n}.name');
$this->assertEquals($a, $b);
$b = array(
@ -1017,7 +1186,7 @@ class HashTest extends CakeTestCase {
1 => array('Person' => array('name' => 'Jeff')),
);
$a = Hash::sort($a, '{n}.Person.name', 'ASC', 'STRING');
$this->assertEquals($a, $b);
$this->assertSame($a, $b);
$names = array(
array('employees' => array(
@ -1040,7 +1209,38 @@ class HashTest extends CakeTestCase {
array('employees' => array(array('name' => array()))),
array('employees' => array(array('name' => array())))
);
$this->assertEquals($expected, $result);
$this->assertSame($expected, $result);
$a = array(
'SU' => array(
'total_fulfillable' => 2
),
'AA' => array(
'total_fulfillable' => 1
),
'LX' => array(
'total_fulfillable' => 0
),
'BL' => array(
'total_fulfillable' => 3
),
);
$expected = array(
'LX' => array(
'total_fulfillable' => 0
),
'AA' => array(
'total_fulfillable' => 1
),
'SU' => array(
'total_fulfillable' => 2
),
'BL' => array(
'total_fulfillable' => 3
),
);
$result = Hash::sort($a, '{s}.total_fulfillable', 'asc');
$this->assertSame($expected, $result);
}
/**
@ -1114,6 +1314,97 @@ class HashTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* Test natural sorting ignoring case.
*
* @return void
*/
public function testSortNaturalIgnoreCase() {
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$this->markTestSkipped('SORT_NATURAL is available since PHP 5.4.');
}
$items = array(
array('Item' => array('image' => 'img1.jpg')),
array('Item' => array('image' => 'img99.jpg')),
array('Item' => array('image' => 'Img12.jpg')),
array('Item' => array('image' => 'Img10.jpg')),
array('Item' => array('image' => 'img2.jpg')),
);
$result = Hash::sort($items, '{n}.Item.image', 'desc', array('type' => 'natural', 'ignoreCase' => true));
$expected = array(
array('Item' => array('image' => 'img99.jpg')),
array('Item' => array('image' => 'Img12.jpg')),
array('Item' => array('image' => 'Img10.jpg')),
array('Item' => array('image' => 'img2.jpg')),
array('Item' => array('image' => 'img1.jpg')),
);
$this->assertEquals($expected, $result);
$result = Hash::sort($items, '{n}.Item.image', 'asc', array('type' => 'natural', 'ignoreCase' => true));
$expected = array(
array('Item' => array('image' => 'img1.jpg')),
array('Item' => array('image' => 'img2.jpg')),
array('Item' => array('image' => 'Img10.jpg')),
array('Item' => array('image' => 'Img12.jpg')),
array('Item' => array('image' => 'img99.jpg')),
);
$this->assertEquals($expected, $result);
}
/**
* Test that sort() with 'natural' type will fallback to 'regular' as SORT_NATURAL is introduced in PHP 5.4
*
* @return void
*/
public function testSortNaturalFallbackToRegular() {
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
$this->markTestSkipped('Skipping SORT_NATURAL fallback test on PHP >= 5.4');
}
$a = array(
0 => array('Person' => array('name' => 'Jeff')),
1 => array('Shirt' => array('color' => 'black'))
);
$b = array(
0 => array('Shirt' => array('color' => 'black')),
1 => array('Person' => array('name' => 'Jeff')),
);
$sorted = Hash::sort($a, '{n}.Person.name', 'asc', 'natural');
$this->assertEquals($sorted, $b);
}
/**
* Test sort() with locale option.
*
* @return void
*/
public function testSortLocale() {
// get the current locale
$oldLocale = setlocale(LC_COLLATE, '0');
$updated = setlocale(LC_COLLATE, 'de_DE.utf8');
$this->skipIf($updated === false, 'Could not set locale to de_DE.utf8, skipping test.');
$items = array(
array('Item' => array('entry' => 'Übergabe')),
array('Item' => array('entry' => 'Ostfriesland')),
array('Item' => array('entry' => 'Äpfel')),
array('Item' => array('entry' => 'Apfel')),
);
$result = Hash::sort($items, '{n}.Item.entry', 'asc', 'locale');
$expected = array(
array('Item' => array('entry' => 'Apfel')),
array('Item' => array('entry' => 'Äpfel')),
array('Item' => array('entry' => 'Ostfriesland')),
array('Item' => array('entry' => 'Übergabe')),
);
$this->assertEquals($expected, $result);
// change to the original locale
setlocale(LC_COLLATE, $oldLocale);
}
/**
* test sorting with out of order keys.
*
@ -1146,7 +1437,7 @@ class HashTest extends CakeTestCase {
*
* @return void
*/
public function testSortString() {
public function testSortStringKeys() {
$toSort = array(
'four' => array('number' => 4, 'some' => 'foursome'),
'six' => array('number' => 6, 'some' => 'sixsome'),
@ -1178,6 +1469,50 @@ class HashTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test sorting with string ignoring case.
*
* @return void
*/
public function testSortStringIgnoreCase() {
$toSort = array(
array('Item' => array('name' => 'bar')),
array('Item' => array('name' => 'Baby')),
array('Item' => array('name' => 'Baz')),
array('Item' => array('name' => 'bat')),
);
$sorted = Hash::sort($toSort, '{n}.Item.name', 'asc', array('type' => 'string', 'ignoreCase' => true));
$expected = array(
array('Item' => array('name' => 'Baby')),
array('Item' => array('name' => 'bar')),
array('Item' => array('name' => 'bat')),
array('Item' => array('name' => 'Baz')),
);
$this->assertEquals($expected, $sorted);
}
/**
* test regular sorting ignoring case.
*
* @return void
*/
public function testSortRegularIgnoreCase() {
$toSort = array(
array('Item' => array('name' => 'bar')),
array('Item' => array('name' => 'Baby')),
array('Item' => array('name' => 'Baz')),
array('Item' => array('name' => 'bat')),
);
$sorted = Hash::sort($toSort, '{n}.Item.name', 'asc', array('type' => 'regular', 'ignoreCase' => true));
$expected = array(
array('Item' => array('name' => 'Baby')),
array('Item' => array('name' => 'bar')),
array('Item' => array('name' => 'bat')),
array('Item' => array('name' => 'Baz')),
);
$this->assertEquals($expected, $sorted);
}
/**
* Test insert()
*
@ -1202,6 +1537,13 @@ class HashTest extends CakeTestCase {
'pages' => array('name' => array()),
);
$this->assertEquals($expected, $result);
$a = array(
'foo' => array('bar' => 'baz')
);
$result = Hash::insert($a, 'some.0123.path', array('foo' => array('bar' => 'baz')));
$expected = array('foo' => array('bar' => 'baz'));
$this->assertEquals($expected, Hash::get($result, 'some.0123.path'));
}
/**
@ -1210,7 +1552,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testInsertMulti() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::insert($data, '{n}.Article.insert', 'value');
$this->assertEquals('value', $result[0]['Article']['insert']);
@ -1219,6 +1561,23 @@ class HashTest extends CakeTestCase {
$result = Hash::insert($data, '{n}.Comment.{n}.insert', 'value');
$this->assertEquals('value', $result[0]['Comment'][0]['insert']);
$this->assertEquals('value', $result[0]['Comment'][1]['insert']);
$data = array(
0 => array('Item' => array('id' => 1, 'title' => 'first')),
1 => array('Item' => array('id' => 2, 'title' => 'second')),
2 => array('Item' => array('id' => 3, 'title' => 'third')),
3 => array('Item' => array('id' => 4, 'title' => 'fourth')),
4 => array('Item' => array('id' => 5, 'title' => 'fifth')),
);
$result = Hash::insert($data, '{n}.Item[id=/\b2|\b4/]', array('test' => 2));
$expected = array(
0 => array('Item' => array('id' => 1, 'title' => 'first')),
1 => array('Item' => array('id' => 2, 'title' => 'second', 'test' => 2)),
2 => array('Item' => array('id' => 3, 'title' => 'third')),
3 => array('Item' => array('id' => 4, 'title' => 'fourth', 'test' => 2)),
4 => array('Item' => array('id' => 5, 'title' => 'fifth')),
);
$this->assertEquals($expected, $result);
}
/**
@ -1282,6 +1641,35 @@ class HashTest extends CakeTestCase {
$result = Hash::remove($a, 'pages.2.vars');
$expected = $a;
$this->assertEquals($expected, $result);
$a = array(
0 => array(
'name' => 'pages'
),
1 => array(
'name' => 'files'
)
);
$result = Hash::remove($a, '{n}[name=files]');
$expected = array(
0 => array(
'name' => 'pages'
)
);
$this->assertEquals($expected, $result);
$array = array(
0 => 'foo',
1 => array(
0 => 'baz'
)
);
$expected = $array;
$result = Hash::remove($array, '{n}.part');
$this->assertEquals($expected, $result);
$result = Hash::remove($array, '{n}.{n}.part');
$this->assertEquals($expected, $result);
}
/**
@ -1290,7 +1678,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testRemoveMulti() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::remove($data, '{n}.Article.title');
$this->assertFalse(isset($result[0]['Article']['title']));
@ -1301,6 +1689,22 @@ class HashTest extends CakeTestCase {
$this->assertFalse(isset($result[0]['Article']['user_id']));
$this->assertFalse(isset($result[0]['Article']['title']));
$this->assertFalse(isset($result[0]['Article']['body']));
$data = array(
0 => array('Item' => array('id' => 1, 'title' => 'first')),
1 => array('Item' => array('id' => 2, 'title' => 'second')),
2 => array('Item' => array('id' => 3, 'title' => 'third')),
3 => array('Item' => array('id' => 4, 'title' => 'fourth')),
4 => array('Item' => array('id' => 5, 'title' => 'fifth')),
);
$result = Hash::remove($data, '{n}.Item[id=/\b2|\b4/]');
$expected = array(
0 => array('Item' => array('id' => 1, 'title' => 'first')),
2 => array('Item' => array('id' => 3, 'title' => 'third')),
4 => array('Item' => array('id' => 5, 'title' => 'fifth')),
);
$this->assertEquals($expected, $result);
}
/**
@ -1341,7 +1745,7 @@ class HashTest extends CakeTestCase {
$result = Hash::combine(array(), '{n}.User.id', '{n}.User.Data');
$this->assertTrue(empty($result));
$a = self::userData();
$a = static::userData();
$result = Hash::combine($a, '{n}.User.id');
$expected = array(2 => null, 14 => null, 25 => null);
@ -1366,13 +1770,41 @@ class HashTest extends CakeTestCase {
$this->assertEquals($expected, $result);
}
/**
* test combine() giving errors on key/value length mismatches.
*
* @expectedException CakeException
* @return void
*/
public function testCombineErrorMissingValue() {
$data = array(
array('User' => array('id' => 1, 'name' => 'mark')),
array('User' => array('name' => 'jose')),
);
Hash::combine($data, '{n}.User.id', '{n}.User.name');
}
/**
* test combine() giving errors on key/value length mismatches.
*
* @expectedException CakeException
* @return void
*/
public function testCombineErrorMissingKey() {
$data = array(
array('User' => array('id' => 1, 'name' => 'mark')),
array('User' => array('id' => 2)),
);
Hash::combine($data, '{n}.User.id', '{n}.User.name');
}
/**
* test combine() with a group path.
*
* @return void
*/
public function testCombineWithGroupPath() {
$a = self::userData();
$a = static::userData();
$result = Hash::combine($a, '{n}.User.id', '{n}.User.Data', '{n}.User.group_id');
$expected = array(
@ -1429,7 +1861,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testCombineWithFormatting() {
$a = self::userData();
$a = static::userData();
$result = Hash::combine(
$a,
@ -1495,7 +1927,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testFormat() {
$data = self::userData();
$data = static::userData();
$result = Hash::format(
$data,
@ -1555,15 +1987,20 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testMap() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::map($data, '{n}.Article.id', array($this, 'mapCallback'));
$expected = array(2, 4, 6, 8, 10);
$this->assertEquals($expected, $result);
}
/**
* testApply
*
* @return void
*/
public function testApply() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::apply($data, '{n}.Article.id', 'array_sum');
$this->assertEquals(15, $result);
@ -1575,7 +2012,7 @@ class HashTest extends CakeTestCase {
* @return void
*/
public function testReduce() {
$data = self::articleData();
$data = static::articleData();
$result = Hash::reduce($data, '{n}.Article.id', array($this, 'reduceCallback'));
$this->assertEquals(15, $result);
@ -1584,8 +2021,8 @@ class HashTest extends CakeTestCase {
/**
* testing method for map callbacks.
*
* @param mixed $value
* @return mixed.
* @param mixed $value Value
* @return mixed
*/
public function mapCallback($value) {
return $value * 2;
@ -1594,9 +2031,9 @@ class HashTest extends CakeTestCase {
/**
* testing method for reduce callbacks.
*
* @param mixed $one
* @param mixed $two
* @return mixed.
* @param mixed $one First param
* @param mixed $two Second param
* @return mixed
*/
public function reduceCallback($one, $two) {
return $one + $two;
@ -2018,6 +2455,25 @@ class HashTest extends CakeTestCase {
$this->assertEquals($input, $result);
}
/**
* Tests that nest() throws an InvalidArgumentException when providing an invalid input.
*
* @expectedException InvalidArgumentException
* @return void
*/
public function testNestInvalid() {
$input = array(
array(
'ParentCategory' => array(
'id' => '1',
'name' => 'Lorem ipsum dolor sit amet',
'parent_id' => '1'
)
)
);
Hash::nest($input);
}
/**
* testMergeDiff method
*
@ -2162,7 +2618,19 @@ class HashTest extends CakeTestCase {
)
)
);
$this->assertEquals($result, $expected);
$this->assertEquals($expected, $result);
$data = array('a.b.100.a' => null, 'a.b.200.a' => null);
$expected = array(
'a' => array(
'b' => array(
100 => array('a' => null),
200 => array('a' => null)
)
)
);
$result = Hash::expand($data);
$this->assertEquals($expected, $result);
}
/**
@ -2210,52 +2678,52 @@ class HashTest extends CakeTestCase {
'Order.Item.0.Product.sizes.4.Size.qty' => '',
'Order.Item.0.Product.sizes.4.Size.size' => '12-18mo',
'Order.Item.0.Product.sizes.4.Size.id' => '42',
'Order.Item.0.Art.imprint_locations.0.id' => (int) 2,
'Order.Item.0.Art.imprint_locations.0.id' => 2,
'Order.Item.0.Art.imprint_locations.0.name' => 'Left Chest',
'Order.Item.0.Art.imprint_locations.0.imprint_type.id' => (int) 7,
'Order.Item.0.Art.imprint_locations.0.imprint_type.id' => 7,
'Order.Item.0.Art.imprint_locations.0.imprint_type.type' => 'Embroidery',
'Order.Item.0.Art.imprint_locations.0.art' => '',
'Order.Item.0.Art.imprint_locations.0.num_colors' => (int) 3,
'Order.Item.0.Art.imprint_locations.0.num_colors' => 3,
'Order.Item.0.Art.imprint_locations.0.description' => 'Wooo! This is Embroidery!!',
'Order.Item.0.Art.imprint_locations.0.lines.0' => 'Platen',
'Order.Item.0.Art.imprint_locations.0.lines.1' => 'Logo',
'Order.Item.0.Art.imprint_locations.0.height' => (int) 4,
'Order.Item.0.Art.imprint_locations.0.width' => (int) 5,
'Order.Item.0.Art.imprint_locations.0.height' => 4,
'Order.Item.0.Art.imprint_locations.0.width' => 5,
'Order.Item.0.Art.imprint_locations.0.stitch_density' => 'Light',
'Order.Item.0.Art.imprint_locations.0.metallic_thread' => true,
'Order.Item.0.Art.imprint_locations.1.id' => (int) 4,
'Order.Item.0.Art.imprint_locations.1.id' => 4,
'Order.Item.0.Art.imprint_locations.1.name' => 'Full Back',
'Order.Item.0.Art.imprint_locations.1.imprint_type.id' => (int) 6,
'Order.Item.0.Art.imprint_locations.1.imprint_type.id' => 6,
'Order.Item.0.Art.imprint_locations.1.imprint_type.type' => 'Screenprinting',
'Order.Item.0.Art.imprint_locations.1.art' => '',
'Order.Item.0.Art.imprint_locations.1.num_colors' => (int) 3,
'Order.Item.0.Art.imprint_locations.1.num_colors' => 3,
'Order.Item.0.Art.imprint_locations.1.description' => 'Wooo! This is Screenprinting!!',
'Order.Item.0.Art.imprint_locations.1.lines.0' => 'Platen',
'Order.Item.0.Art.imprint_locations.1.lines.1' => 'Logo',
'Order.Item.0.Art.imprint_locations.2.id' => (int) 26,
'Order.Item.0.Art.imprint_locations.2.id' => 26,
'Order.Item.0.Art.imprint_locations.2.name' => 'HS - JSY Name Below',
'Order.Item.0.Art.imprint_locations.2.imprint_type.id' => (int) 9,
'Order.Item.0.Art.imprint_locations.2.imprint_type.id' => 9,
'Order.Item.0.Art.imprint_locations.2.imprint_type.type' => 'Names',
'Order.Item.0.Art.imprint_locations.2.description' => 'Wooo! This is Names!!',
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.active' => (int) 1,
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.active' => 1,
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.name' => 'Benjamin Talavera',
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.color' => 'Red',
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.height' => '3',
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.layout' => 'Arched',
'Order.Item.0.Art.imprint_locations.2.sizes.S.0.style' => 'Classic',
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.active' => (int) 0,
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.active' => 0,
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.name' => 'Rishi Narayan',
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.color' => 'Cardinal',
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.height' => '4',
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.layout' => 'Straight',
'Order.Item.0.Art.imprint_locations.2.sizes.S.1.style' => 'Team US',
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.active' => (int) 1,
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.active' => 1,
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.name' => 'Brandon Plasters',
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.color' => 'Red',
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.height' => '3',
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.layout' => 'Arched',
'Order.Item.0.Art.imprint_locations.2.sizes.M.0.style' => 'Classic',
'Order.Item.0.Art.imprint_locations.2.sizes.M.1.active' => (int) 0,
'Order.Item.0.Art.imprint_locations.2.sizes.M.1.active' => 0,
'Order.Item.0.Art.imprint_locations.2.sizes.M.1.name' => 'Andrew Reed',
'Order.Item.0.Art.imprint_locations.2.sizes.M.1.color' => 'Cardinal',
'Order.Item.0.Art.imprint_locations.2.sizes.M.1.height' => '4',
@ -2280,10 +2748,10 @@ class HashTest extends CakeTestCase {
'Order.QualityControl' => '0',
'Order.Receiving' => '0',
'Order.ScreenPrinting' => '0',
'Order.Stage.art_approval' => (int) 0,
'Order.Stage.draft' => (int) 1,
'Order.Stage.quote' => (int) 1,
'Order.Stage.order' => (int) 1,
'Order.Stage.art_approval' => 0,
'Order.Stage.draft' => 1,
'Order.Stage.quote' => 1,
'Order.Stage.order' => 1,
'Order.StoreLiason' => '0',
'Order.Tag_UI_Email' => '',
'Order.Tags' => '',

View file

@ -4,24 +4,22 @@
*
* InflectorTest is used to test cases on the Inflector class
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license Open Group Test Suite License (http://www.opensource.org/licenses/opengroup.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
/**
* Included libraries.
*
*/
App::uses('Inflector', 'Utility');
@ -32,6 +30,57 @@ App::uses('Inflector', '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
*
@ -74,11 +123,12 @@ class InflectorTest extends CakeTestCase {
$this->assertEquals(Inflector::singularize('fungi'), 'fungus');
$this->assertEquals(Inflector::singularize('nuclei'), 'nucleus');
$this->assertEquals(Inflector::singularize('octopuses'), 'octopus');
$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('viruses'), 'virus');
$this->assertEquals(Inflector::singularize('people'), 'person');
$this->assertEquals(Inflector::singularize('gloves'), 'glove');
$this->assertEquals(Inflector::singularize('doves'), 'dove');
@ -94,6 +144,8 @@ class InflectorTest extends CakeTestCase {
$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');
@ -110,16 +162,60 @@ class InflectorTest extends CakeTestCase {
$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('files_metadata'), 'files_metadata');
$this->assertEquals(Inflector::singularize('sieves'), 'sieve');
$this->assertEquals(Inflector::singularize('blue_octopuses'), 'blue_octopus');
$this->assertEquals(Inflector::singularize(''), '');
}
/**
* Test that overlapping irregulars don't collide.
*
* @return void
*/
public function testSingularizeMultiWordIrregular() {
Inflector::rules('singular', array(
'irregular' => array(
'preguntas_frecuentes' => 'pregunta_frecuente',
'categorias_preguntas_frecuentes' => 'categoria_pregunta_frecuente',
)
));
$this->assertEquals('pregunta_frecuente', Inflector::singularize('preguntas_frecuentes'));
$this->assertEquals(
'categoria_pregunta_frecuente',
Inflector::singularize('categorias_preguntas_frecuentes')
);
$this->assertEquals(
'faq_categoria_pregunta_frecuente',
Inflector::singularize('faq_categorias_preguntas_frecuentes')
);
}
/**
* testInflectingPlurals method
*
* @return void
*/
public function testInflectingPlurals() {
$this->assertEquals(Inflector::pluralize('axman'), 'axmen');
$this->assertEquals(Inflector::pluralize('man'), 'men');
$this->assertEquals(Inflector::pluralize('woman'), 'women');
$this->assertEquals(Inflector::pluralize('human'), 'humans');
$this->assertEquals(Inflector::pluralize('categoria'), 'categorias');
$this->assertEquals(Inflector::pluralize('house'), 'houses');
$this->assertEquals(Inflector::pluralize('powerhouse'), 'powerhouses');
@ -150,7 +246,7 @@ class InflectorTest extends CakeTestCase {
$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('virus'), 'viruses');
$this->assertEquals(Inflector::pluralize('person'), 'people');
$this->assertEquals(Inflector::pluralize('people'), 'people');
$this->assertEquals(Inflector::pluralize('glove'), 'gloves');
@ -162,9 +258,82 @@ class InflectorTest extends CakeTestCase {
$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('files_metadata'), 'files_metadata');
$this->assertEquals(Inflector::pluralize('stadia'), 'stadia');
$this->assertEquals(Inflector::pluralize('sieve'), 'sieves');
$this->assertEquals(Inflector::pluralize('blue_octopus'), 'blue_octopuses');
$this->assertEquals(Inflector::pluralize(''), '');
}
/**
* Test that overlapping irregulars don't collide.
*
* @return void
*/
public function testPluralizeMultiWordIrregular() {
Inflector::rules('plural', array(
'irregular' => array(
'mytable1' => 'mytables1',
'mytable2' => 'mytables2',
'mytable1_mytable2' => 'mytables1_mytables2',
'pregunta_frecuente' => 'preguntas_frecuentes',
'categoria_pregunta_frecuente' => 'categorias_preguntas_frecuentes',
)
));
$this->assertEquals('preguntas_frecuentes', Inflector::pluralize('pregunta_frecuente'));
$this->assertEquals(
'categorias_preguntas_frecuentes',
Inflector::pluralize('categoria_pregunta_frecuente')
);
$this->assertEquals(
'faq_categorias_preguntas_frecuentes',
Inflector::pluralize('faq_categoria_pregunta_frecuente')
);
$this->assertEquals('mytables1', Inflector::pluralize('mytable1'));
$this->assertEquals('mytables2', Inflector::pluralize('mytable2'));
$this->assertEquals('mytables1_mytables2', Inflector::pluralize('mytable1_mytable2'));
$this->assertEquals('mytables1_mytables2', Inflector::tableize('Mytable1Mytable2'));
}
/**
* testInflectingMultiWordIrregulars
*
* @return void
*/
public function testInflectingMultiWordIrregulars() {
// unset the default rules in order to avoid them possibly matching
// the words in case the irregular regex won't match, the tests
// should fail in that case
Inflector::rules('plural', array(
'rules' => array(),
));
Inflector::rules('singular', array(
'rules' => array(),
));
$this->assertEquals(Inflector::singularize('wisdom teeth'), 'wisdom tooth');
$this->assertEquals(Inflector::singularize('wisdom-teeth'), 'wisdom-tooth');
$this->assertEquals(Inflector::singularize('wisdom_teeth'), 'wisdom_tooth');
$this->assertEquals(Inflector::pluralize('sweet potato'), 'sweet potatoes');
$this->assertEquals(Inflector::pluralize('sweet-potato'), 'sweet-potatoes');
$this->assertEquals(Inflector::pluralize('sweet_potato'), 'sweet_potatoes');
}
/**
* testInflectorSlug method
*
@ -226,6 +395,23 @@ class InflectorTest extends CakeTestCase {
$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 (static::$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);
}
}
}
/**
@ -266,12 +452,14 @@ class InflectorTest extends CakeTestCase {
$this->assertSame(Inflector::underscore('testThing'), 'test_thing');
$this->assertSame(Inflector::underscore('TestThingExtra'), 'test_thing_extra');
$this->assertSame(Inflector::underscore('testThingExtra'), 'test_thing_extra');
$this->assertSame(Inflector::underscore('testThingExtrå'), 'test_thing_extrå');
// 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');
$this->assertSame(Inflector::underscore('testThingExtrå'), 'test_thing_extrå');
// Test stupid values
$this->assertSame(Inflector::underscore(''), '');
@ -279,6 +467,19 @@ class InflectorTest extends CakeTestCase {
$this->assertSame(Inflector::underscore(false), '');
}
/**
* Test camelize()
*
* @return void
*/
public function testCamelize() {
$this->assertSame('BlogArticles', Inflector::camelize('blog_articles'));
$this->assertSame('BlogArticles', Inflector::camelize('blog articles'));
$this->assertSame('MyPlugin.MyClass', Inflector::camelize('MyPlugin.MyClass'));
$this->assertSame('MyPlugin.MyClass', Inflector::camelize('my_plugin.MyClass'));
$this->assertSame('MyPlugin.myClass', Inflector::camelize('MyPlugin.my_class'));
}
/**
* testVariableNaming method
*
@ -309,10 +510,10 @@ class InflectorTest extends CakeTestCase {
* @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');
$this->assertEquals('artists_genres', Inflector::tableize('ArtistsGenre'));
$this->assertEquals('file_systems', Inflector::tableize('FileSystem'));
$this->assertEquals('news', Inflector::tableize('News'));
$this->assertEquals('bureaus', Inflector::tableize('Bureau'));
}
/**
@ -321,9 +522,12 @@ class InflectorTest extends CakeTestCase {
* @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');
$this->assertEquals('Posts', Inflector::humanize('posts'));
$this->assertEquals('Posts Tags', Inflector::humanize('posts_tags'));
$this->assertEquals('File Systems', Inflector::humanize('file_systems'));
$this->assertEquals('FiLe SysTems', Inflector::humanize('FiLe_SysTems'));
$this->assertEquals('Hello Wörld', Inflector::humanize('hello_wörld'));
$this->assertEquals('福岡 City', Inflector::humanize('福岡_city'));
}
/**

View file

@ -2,19 +2,18 @@
/**
* ObjectCollectionTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('ObjectCollection', 'Utility');
@ -28,8 +27,8 @@ class GenericObject {
/**
* Constructor
*
* @param GenericObjectCollection $collection
* @param array $settings
* @param GenericObjectCollection $collection A collection.
* @param array $settings Settings.
*/
public function __construct(GenericObjectCollection $collection, $settings = array()) {
$this->_Collection = $collection;
@ -39,12 +38,14 @@ class GenericObject {
}
/**
* First Extension of Generic Object
* First Extension of Generic CakeObject
*/
class FirstGenericObject extends GenericObject {
/**
* A generic callback
*
* @return void
*/
public function callback() {
}
@ -52,20 +53,26 @@ class FirstGenericObject extends GenericObject {
}
/**
* Second Extension of Generic Object
* Second Extension of Generic CakeObject
*/
class SecondGenericObject extends GenericObject {
/**
* @return void
*/
public function callback() {
}
}
/**
* Third Extension of Generic Object
* Third Extension of Generic CakeObject
*/
class ThirdGenericObject extends GenericObject {
/**
* @return void
*/
public function callback() {
}
@ -79,12 +86,12 @@ class GenericObjectCollection extends ObjectCollection {
/**
* Loads a generic object
*
* @param string $object Object name
* @param string $object CakeObject name
* @param array $settings Settings array
* @return array List of loaded objects
*/
public function load($object, $settings = array()) {
list($plugin, $name) = pluginSplit($object);
list(, $name) = pluginSplit($object);
if (isset($this->_loaded[$name])) {
return $this->_loaded[$name];
}
@ -97,6 +104,27 @@ class GenericObjectCollection extends ObjectCollection {
return $this->_loaded[$name];
}
/**
* Helper method for adding/overwriting enabled objects including
* settings
*
* @param string $name Name of the object
* @param CakeObject $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 {
@ -131,8 +159,8 @@ class ObjectCollectionTest extends CakeTestCase {
$this->assertInstanceOf('FirstGenericObject', $result);
$this->assertInstanceOf('FirstGenericObject', $this->Objects->First);
$result = $this->Objects->attached();
$this->assertEquals(array('First'), $result, 'attached() results are wrong.');
$result = $this->Objects->loaded();
$this->assertEquals(array('First'), $result, 'loaded() results are wrong.');
$this->assertTrue($this->Objects->enabled('First'));
@ -149,17 +177,17 @@ class ObjectCollectionTest extends CakeTestCase {
$this->Objects->load('First');
$this->Objects->load('Second');
$result = $this->Objects->attached();
$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->attached();
$result = $this->Objects->loaded();
$this->assertEquals(array('Second'), $result, 'loaded objects are wrong');
$result = $this->Objects->enabled();
$result = $this->Objects->loaded();
$this->assertEquals(array('Second'), $result, 'enabled objects are wrong');
}
@ -171,7 +199,7 @@ class ObjectCollectionTest extends CakeTestCase {
public function testSet() {
$this->Objects->load('First');
$result = $this->Objects->attached();
$result = $this->Objects->loaded();
$this->assertEquals(array('First'), $result, 'loaded objects are wrong');
$result = $this->Objects->set('First', new SecondGenericObject($this->Objects));
@ -189,15 +217,9 @@ class ObjectCollectionTest extends CakeTestCase {
* @return void
*/
protected function _makeMockClasses() {
if (!class_exists('TriggerMockFirstGenericObject')) {
$this->getMock('FirstGenericObject', array(), array(), 'TriggerMockFirstGenericObject', false);
}
if (!class_exists('TriggerMockSecondGenericObject')) {
$this->getMock('SecondGenericObject', array(), array(), 'TriggerMockSecondGenericObject', false);
}
if (!class_exists('TriggerMockThirdGenericObject')) {
$this->getMock('ThirdGenericObject', array(), array(), 'TriggerMockThirdGenericObject', false);
}
$this->FirstGenericObject = $this->getMock('FirstGenericObject', array(), array(), '', false);
$this->SecondGenericObject = $this->getMock('SecondGenericObject', array(), array(), '', false);
$this->ThirdGenericObject = $this->getMock('ThirdGenericObject', array(), array(), '', false);
}
/**
@ -207,11 +229,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTrigger() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -230,11 +249,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerWithDisabledObjects() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject, array('enabled' => false));
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -243,8 +259,6 @@ class ObjectCollectionTest extends CakeTestCase {
->method('callback')
->will($this->returnValue(true));
$this->Objects->disable('TriggerMockSecond');
$this->assertTrue($this->Objects->trigger('callback', array()));
}
@ -255,11 +269,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerWithCollectReturn() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -283,11 +294,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerWithBreak() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -310,11 +318,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerWithModParams() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -342,11 +347,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerModParamsInvalidIndex() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->never())
->method('callback');
@ -354,7 +356,7 @@ class ObjectCollectionTest extends CakeTestCase {
$this->Objects->TriggerMockSecond->expects($this->never())
->method('callback');
$result = $this->Objects->trigger(
$this->Objects->trigger(
'callback',
array(array('value')),
array('modParams' => 2)
@ -368,11 +370,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerModParamsNullIgnored() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
@ -399,11 +398,8 @@ class ObjectCollectionTest extends CakeTestCase {
*/
public function testTriggerPriority() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond', array('priority' => 5));
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject, array('priority' => 5));
$this->Objects->TriggerMockFirst->expects($this->any())
->method('callback')
@ -419,8 +415,7 @@ class ObjectCollectionTest extends CakeTestCase {
);
$this->assertEquals($expected, $result);
$this->Objects->load('TriggerMockThird', array('priority' => 7));
$this->mockObjects[] = $this->Objects->TriggerMockThird;
$this->Objects->setObject('TriggerMockThird', $this->ThirdGenericObject, array('priority' => 7));
$this->Objects->TriggerMockThird->expects($this->any())
->method('callback')
->will($this->returnValue('3rd'));
@ -540,16 +535,14 @@ class ObjectCollectionTest extends CakeTestCase {
* tests that passing an instance of CakeEvent to trigger will prepend the subject to the list of arguments
*
* @return void
* @triggers callback $subjectClass, array('first argument')
*/
public function testDispatchEventWithSubject() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$subjectClass = new Object();
$subjectClass = new CakeObject();
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with($subjectClass, 'first argument')
@ -568,16 +561,14 @@ class ObjectCollectionTest extends CakeTestCase {
* will NOT prepend the subject to the list of arguments
*
* @return void
* @triggers callback $subjectClass, array('first argument')
*/
public function testDispatchEventNoSubject() {
$this->_makeMockClasses();
$this->Objects->load('TriggerMockFirst');
$this->Objects->load('TriggerMockSecond');
$this->Objects->setObject('TriggerMockFirst', $this->FirstGenericObject);
$this->Objects->setObject('TriggerMockSecond', $this->SecondGenericObject);
$this->mockObjects[] = $this->Objects->TriggerMockFirst;
$this->mockObjects[] = $this->Objects->TriggerMockSecond;
$subjectClass = new Object();
$subjectClass = new CakeObject();
$this->Objects->TriggerMockFirst->expects($this->once())
->method('callback')
->with('first argument')
@ -592,4 +583,33 @@ class ObjectCollectionTest extends CakeTestCase {
$this->assertTrue($this->Objects->trigger($event));
}
/**
* test that the various methods ignore plugin prefixes
*
* plugin prefixes should be removed consistently as load() will
* remove them. Furthermore the __get() method does not support
* names with '.' in them.
*
* @return void
*/
public function testPluginPrefixes() {
$this->Objects->load('TestPlugin.First');
$this->assertTrue($this->Objects->loaded('First'));
$this->assertTrue($this->Objects->loaded('TestPlugin.First'));
$this->assertTrue($this->Objects->enabled('First'));
$this->assertTrue($this->Objects->enabled('TestPlugin.First'));
$this->assertNull($this->Objects->disable('TestPlugin.First'));
$this->assertFalse($this->Objects->enabled('First'));
$this->assertFalse($this->Objects->enabled('TestPlugin.First'));
$this->assertNull($this->Objects->enable('TestPlugin.First'));
$this->assertTrue($this->Objects->enabled('First'));
$this->assertTrue($this->Objects->enabled('TestPlugin.First'));
$this->Objects->setPriority('TestPlugin.First', 1000);
$result = $this->Objects->prioritize();
$this->assertEquals(1000, $result['First'][0]);
}
}

View file

@ -2,20 +2,20 @@
/**
* SanitizeTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5428
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Sanitize', 'Utility');
/**
@ -25,17 +25,10 @@ App::uses('Sanitize', 'Utility');
*/
class SanitizeDataTest extends CakeTestModel {
/**
* name property
*
* @var string 'SanitizeDataTest'
*/
public $name = 'SanitizeDataTest';
/**
* useTable property
*
* @var string 'data_tests'
* @var string
*/
public $useTable = 'data_tests';
}
@ -47,17 +40,10 @@ class SanitizeDataTest extends CakeTestModel {
*/
class SanitizeArticle extends CakeTestModel {
/**
* name property
*
* @var string 'Article'
*/
public $name = 'SanitizeArticle';
/**
* useTable property
*
* @var string 'articles'
* @var string
*/
public $useTable = 'articles';
}
@ -72,7 +58,7 @@ class SanitizeTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
* @var bool
*/
public $autoFixtures = false;
@ -168,7 +154,7 @@ class SanitizeTest extends CakeTestCase {
$string = '';
$expected = '';
$result = Sanitize::clean($string, array('connection' => 'test'));
$this->assertEquals($expected, $string);
$this->assertEquals($expected, $result);
$data = array(
'Grant' => array(
@ -283,12 +269,12 @@ class SanitizeTest extends CakeTestCase {
$this->assertEquals($expected, $result);
$string = "x' AND 1=(SELECT COUNT(*) FROM users); --";
$expected = "xAND1SELECTCOUNTFROMusers";
$expected = 'xAND1SELECTCOUNTFROMusers';
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
$string = "x'; DROP TABLE members; --";
$expected = "xDROPTABLEmembers";
$expected = 'xDROPTABLEmembers';
$result = Sanitize::paranoid($string);
$this->assertEquals($expected, $result);
}

View file

@ -1,21 +1,18 @@
<?php
/**
* SecurityTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Security', 'Utility');
/**
@ -28,7 +25,7 @@ class SecurityTest extends CakeTestCase {
/**
* sut property
*
* @var mixed null
* @var mixed
*/
public $sut = null;
@ -67,6 +64,45 @@ class SecurityTest extends CakeTestCase {
$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
*
@ -78,10 +114,10 @@ class SecurityTest extends CakeTestCase {
$key = 'someKey';
$hash = 'someHash';
$this->assertSame(strlen(Security::hash($key, null, false)), 40);
$this->assertSame(strlen(Security::hash($key, 'sha1', false)), 40);
$this->assertSame(strlen(Security::hash($key, null, true)), 40);
$this->assertSame(strlen(Security::hash($key, 'sha1', true)), 40);
$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');
@ -91,30 +127,94 @@ class SecurityTest extends CakeTestCase {
$hashType = 'sha1';
Security::setHash($hashType);
$this->assertSame(Security::$hashType, $hashType);
$this->assertSame(strlen(Security::hash($key, null, true)), 40);
$this->assertSame(strlen(Security::hash($key, null, false)), 40);
$this->assertSame($hashType, Security::$hashType);
$this->assertSame(40, strlen(Security::hash($key, null, true)));
$this->assertSame(40, strlen(Security::hash($key, null, false)));
$this->assertSame(strlen(Security::hash($key, 'md5', false)), 32);
$this->assertSame(strlen(Security::hash($key, 'md5', true)), 32);
$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(Security::$hashType, $hashType);
$this->assertSame(strlen(Security::hash($key, null, false)), 32);
$this->assertSame(strlen(Security::hash($key, null, true)), 32);
$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(strlen(Security::hash($key, 'sha256', false)), 32);
$this->assertSame(strlen(Security::hash($key, 'sha256', true)), 32);
$this->assertSame(32, strlen(Security::hash($key, 'sha256', false)));
$this->assertSame(32, strlen(Security::hash($key, 'sha256', true)));
} else {
$this->assertSame(strlen(Security::hash($key, 'sha256', false)), 64);
$this->assertSame(strlen(Security::hash($key, 'sha256', true)), 64);
$this->assertSame(64, strlen(Security::hash($key, 'sha256', false)));
$this->assertSame(64, strlen(Security::hash($key, 'sha256', true)));
}
Security::setHash($_hashType);
}
/**
* Test that blowfish doesn't return '' when the salt is ''
*
* @return void
*/
public function testHashBlowfishEmptySalt() {
$test = Security::hash('password', 'blowfish');
$this->skipIf(strpos($test, '$2a$') === false, 'Blowfish hashes are incorrect.');
$stored = '';
$hash = Security::hash('anything', 'blowfish', $stored);
$this->assertNotEquals($stored, $hash);
$hash = Security::hash('anything', 'blowfish', false);
$this->assertNotEquals($stored, $hash);
$hash = Security::hash('anything', 'blowfish', null);
$this->assertNotEquals($stored, $hash);
}
/**
* Test that hash() works with blowfish.
*
* @return void
*/
public function testHashBlowfish() {
$test = Security::hash('password', 'blowfish');
$this->skipIf(strpos($test, '$2a$') === false, 'Blowfish hashes are incorrect.');
Security::setCost(10);
$_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
*
@ -155,7 +255,7 @@ class SecurityTest extends CakeTestCase {
public function testCipherEmptyKey() {
$txt = 'some_text';
$key = '';
$result = Security::cipher($txt, $key);
Security::cipher($txt, $key);
}
/**
@ -164,6 +264,7 @@ class SecurityTest extends CakeTestCase {
* @return void
*/
public function testRijndael() {
$this->skipIf(!function_exists('mcrypt_encrypt'));
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
@ -176,10 +277,27 @@ class SecurityTest extends CakeTestCase {
$result = Security::rijndael('', $key, 'encrypt');
$this->assertEquals('', Security::rijndael($result, $key, 'decrypt'));
$result = Security::rijndael($txt, $key = 'this is my key of over 32 chars, yes it is', 'encrypt');
$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
*
@ -189,7 +307,7 @@ class SecurityTest extends CakeTestCase {
public function testRijndaelInvalidOperation() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi';
$result = Security::rijndael($txt, $key, 'foo');
Security::rijndael($txt, $key, 'foo');
}
/**
@ -201,7 +319,146 @@ class SecurityTest extends CakeTestCase {
public function testRijndaelInvalidKey() {
$txt = 'The quick brown fox jumped over the lazy dog.';
$key = 'too small';
$result = Security::rijndael($txt, $key, 'encrypt');
Security::rijndael($txt, $key, 'encrypt');
}
/**
* Test encrypt/decrypt.
*
* @return void
*/
public function testEncryptDecrypt() {
$this->skipIf(!extension_loaded('mcrypt'), 'This test requires mcrypt to be installed');
$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() {
$this->skipIf(!extension_loaded('mcrypt'), 'This test requires mcrypt to be installed');
$txt = 'The quick brown fox';
$key = 'This key is longer than 32 bytes long.';
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() {
$this->skipIf(!extension_loaded('mcrypt'), 'This test requires mcrypt to be installed');
$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() {
$this->skipIf(!extension_loaded('mcrypt'), 'This test requires mcrypt to be installed');
$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() {
$this->skipIf(!extension_loaded('mcrypt'), 'This test requires mcrypt to be installed');
$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);
}
/**
* Test the random method.
*
* @return void
*/
public function testRandomBytes() {
$value = Security::randomBytes(16);
$this->assertSame(16, strlen($value));
$value = Security::randomBytes(64);
$this->assertSame(64, strlen($value));
}
}

View file

@ -2,20 +2,20 @@
/**
* SetTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Set', 'Utility');
App::uses('Model', 'Model');
@ -182,7 +182,7 @@ class SetTest extends CakeTestCase {
$expected = array('users' => array('lisa' => array('id' => 5, 'pw' => 'you-will-never-guess', 'age' => 25, 'pet' => 'dog')), 'cakephp', 'ice-cream', 'chocolate');
$this->assertEquals($expected, Set::merge($a, $b, $c));
$this->assertEquals(Set::merge($a, $b, array(), $c), $expected);
$this->assertEquals($expected, Set::merge($a, $b, array(), $c));
$r = Set::merge($a, $b, $c);
$this->assertEquals($expected, $r);
@ -230,10 +230,10 @@ class SetTest extends CakeTestCase {
$a = array(
0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))),
1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay')))
1 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay')))
);
$b = array(
0 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))),
0 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay'))),
1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate')))
);
@ -242,10 +242,10 @@ class SetTest extends CakeTestCase {
$b = array(
0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))),
1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay')))
1 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay')))
);
$a = array(
0 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))),
0 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay'))),
1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate')))
);
@ -254,42 +254,42 @@ class SetTest extends CakeTestCase {
$a = array(
0 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))),
1 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay'))),
2 => array('Person' => array('name' => 'Adam'),'Friend' => array(array('name' => 'Bob')))
1 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay'))),
2 => array('Person' => array('name' => 'Adam'), 'Friend' => array(array('name' => 'Bob')))
);
$b = array(
0 => array('Person' => array('name' => 'Adam'),'Friend' => array(array('name' => 'Bob'))),
0 => array('Person' => array('name' => 'Adam'), 'Friend' => array(array('name' => 'Bob'))),
1 => array('Person' => array('name' => 'Jeff'), 'Friend' => array(array('name' => 'Nate'))),
2 => array('Person' => array('name' => 'Tracy'),'Friend' => array(array('name' => 'Lindsay')))
2 => array('Person' => array('name' => 'Tracy'), 'Friend' => array(array('name' => 'Lindsay')))
);
$a = Set::sort($a, '{n}.Person.name', 'asc');
$this->assertEquals($a, $b);
$a = array(
array(7,6,4),
array(3,4,5),
array(3,2,1),
array(7, 6, 4),
array(3, 4, 5),
array(3, 2, 1),
);
$b = array(
array(3,2,1),
array(3,4,5),
array(7,6,4),
array(3, 2, 1),
array(3, 4, 5),
array(7, 6, 4),
);
$a = Set::sort($a, '{n}.{n}', 'asc');
$this->assertEquals($a, $b);
$a = array(
array(7,6,4),
array(3,4,5),
array(3,2,array(1,1,1)),
array(7, 6, 4),
array(3, 4, 5),
array(3, 2, array(1, 1, 1)),
);
$b = array(
array(3,2,array(1,1,1)),
array(3,4,5),
array(7,6,4),
array(3, 2, array(1, 1, 1)),
array(3, 4, 5),
array(7, 6, 4),
);
$a = Set::sort($a, '{n}', 'asc');
@ -878,11 +878,11 @@ class SetTest extends CakeTestCase {
)
)
);
$expected = array(array('name' => 'zipfile2.zip','type' => 'application/x-zip-compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784'));
$expected = array(array('name' => 'zipfile2.zip', 'type' => 'application/x-zip-compressed', 'tmp_name' => '/tmp/php179.tmp', 'error' => 0, 'size' => '354784'));
$r = Set::extract('/file/.[type=application/x-zip-compressed]', $f);
$this->assertEquals($expected, $r);
$expected = array(array('name' => 'zipfile.zip','type' => 'application/zip','tmp_name' => '/tmp/php178.tmp','error' => 0,'size' => '564647'));
$expected = array(array('name' => 'zipfile.zip', 'type' => 'application/zip', 'tmp_name' => '/tmp/php178.tmp', 'error' => 0, 'size' => '564647'));
$r = Set::extract('/file/.[type=application/zip]', $f);
$this->assertEquals($expected, $r);
@ -915,13 +915,13 @@ class SetTest extends CakeTestCase {
)
)
);
$expected = array(array('name' => 'zipfile2.zip','type' => 'application/x zip compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784'));
$expected = array(array('name' => 'zipfile2.zip', 'type' => 'application/x zip compressed', 'tmp_name' => '/tmp/php179.tmp', 'error' => 0, 'size' => '354784'));
$r = Set::extract('/file/.[type=application/x zip compressed]', $f);
$this->assertEquals($expected, $r);
$expected = array(
array('name' => 'zipfile.zip','type' => 'application/zip','tmp_name' => '/tmp/php178.tmp','error' => 0,'size' => '564647'),
array('name' => 'zipfile2.zip','type' => 'application/x zip compressed','tmp_name' => '/tmp/php179.tmp','error' => 0,'size' => '354784')
array('name' => 'zipfile.zip', 'type' => 'application/zip', 'tmp_name' => '/tmp/php178.tmp', 'error' => 0, 'size' => '564647'),
array('name' => 'zipfile2.zip', 'type' => 'application/x zip compressed', 'tmp_name' => '/tmp/php179.tmp', 'error' => 0, 'size' => '354784')
);
$r = Set::extract('/file/.[tmp_name=/tmp\/php17/]', $f);
$this->assertEquals($expected, $r);
@ -1108,7 +1108,7 @@ class SetTest extends CakeTestCase {
)
);
$expected = array(7,2,1);
$expected = array(7, 2, 1);
$r = Set::extract('/CallType[name=Internal Voice]/../x/hour', $multiple);
$this->assertEquals($expected, $r);
@ -1221,21 +1221,21 @@ class SetTest extends CakeTestCase {
$nonSequential = array(
'User' => array(
0 => array('id' => 1),
2 => array('id' => 2),
6 => array('id' => 3),
9 => array('id' => 4),
3 => array('id' => 5),
0 => array('id' => 1),
2 => array('id' => 2),
6 => array('id' => 3),
9 => array('id' => 4),
3 => array('id' => 5),
),
);
$nonZero = array(
'User' => array(
2 => array('id' => 1),
4 => array('id' => 2),
6 => array('id' => 3),
9 => array('id' => 4),
3 => array('id' => 5),
2 => array('id' => 1),
4 => array('id' => 2),
6 => array('id' => 3),
9 => array('id' => 4),
3 => array('id' => 5),
),
);
@ -1352,6 +1352,8 @@ class SetTest extends CakeTestCase {
/**
* Test that extract() + matching can hit null things.
*
* @return void
*/
public function testExtractMatchesNull() {
$data = array(
@ -1558,7 +1560,7 @@ class SetTest extends CakeTestCase {
0 => array('name' => 'zero')
);
$result = Set::extract($a, '{s}.name');
$expected = array('page','fruit');
$expected = array('page', 'fruit');
$this->assertEquals($expected, $result);
$a = array(
@ -1693,7 +1695,7 @@ class SetTest extends CakeTestCase {
$result = Set::remove($a, 'files');
$expected = array(
'pages' => array('name' => 'page')
'pages' => array('name' => 'page')
);
$this->assertEquals($expected, $result);
}
@ -1733,7 +1735,7 @@ class SetTest extends CakeTestCase {
$this->assertFalse(Set::check($set, 'Session Test'));
$expected = array('Session Test' => array('Test Case' => 'test'));
$this->assertEquals(Set::insert(array(), 'Session Test.Test Case', "test"), $expected);
$this->assertEquals($expected, Set::insert(array(), 'Session Test.Test Case', "test"));
$this->assertTrue(Set::check($expected, 'Session Test.Test Case'));
}
@ -1854,11 +1856,11 @@ class SetTest extends CakeTestCase {
$a = array(
array('User' => array('id' => 2, 'group_id' => 1,
'Data' => array('user' => 'mariano.iglesias','name' => 'Mariano Iglesias'))),
'Data' => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'))),
array('User' => array('id' => 14, 'group_id' => 2,
'Data' => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))),
array('User' => array('id' => 25, 'group_id' => 1,
'Data' => array('user' => 'gwoo','name' => 'The Gwoo'))));
'Data' => array('user' => 'gwoo', 'name' => 'The Gwoo'))));
$result = Set::combine($a, '{n}.User.id');
$expected = array(2 => null, 14 => null, 25 => null);
$this->assertEquals($expected, $result);
@ -1869,9 +1871,9 @@ class SetTest extends CakeTestCase {
$result = Set::combine($a, '{n}.User.id', '{n}.User.Data');
$expected = array(
2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'),
14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'),
25 => array('user' => 'gwoo', 'name' => 'The Gwoo'));
2 => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'),
14 => array('user' => 'phpnut', 'name' => 'Larry E. Masters'),
25 => array('user' => 'gwoo', 'name' => 'The Gwoo'));
$this->assertEquals($expected, $result);
$result = Set::combine($a, '{n}.User.id', '{n}.User.Data.name');
@ -1959,11 +1961,11 @@ class SetTest extends CakeTestCase {
$b = new stdClass();
$b->users = array(
array('User' => array('id' => 2, 'group_id' => 1,
'Data' => array('user' => 'mariano.iglesias','name' => 'Mariano Iglesias'))),
'Data' => array('user' => 'mariano.iglesias', 'name' => 'Mariano Iglesias'))),
array('User' => array('id' => 14, 'group_id' => 2,
'Data' => array('user' => 'phpnut', 'name' => 'Larry E. Masters'))),
array('User' => array('id' => 25, 'group_id' => 1,
'Data' => array('user' => 'gwoo','name' => 'The Gwoo'))));
'Data' => array('user' => 'gwoo', 'name' => 'The Gwoo'))));
$result = Set::combine($b, 'users.{n}.User.id');
$expected = array(2 => null, 14 => null, 25 => null);
$this->assertEquals($expected, $result);
@ -2030,7 +2032,7 @@ class SetTest extends CakeTestCase {
$expected = array(
'Array1' => array(
'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3','Array1Data4' => 'Array1Data4 value 4',
'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3', 'Array1Data4' => 'Array1Data4 value 4',
'Array1Data5' => 'Array1Data5 value 5', 'Array1Data6' => 'Array1Data6 value 6', 'Array1Data7' => 'Array1Data7 value 7', 'Array1Data8' => 'Array1Data8 value 8'),
'string' => 1,
'another' => 'string',
@ -2053,7 +2055,7 @@ class SetTest extends CakeTestCase {
$expected = array(
'Array1' => array(
'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3','Array1Data4' => 'Array1Data4 value 4',
'Array1Data1' => 'Array1Data1 value 1', 'Array1Data2' => 'Array1Data2 value 2', 'Array1Data3' => 'Array1Data3 value 3', 'Array1Data4' => 'Array1Data4 value 4',
'Array1Data5' => 'Array1Data5 value 5', 'Array1Data6' => 'Array1Data6 value 6', 'Array1Data7' => 'Array1Data7 value 7', 'Array1Data8' => 'Array1Data8 value 8'),
'string' => 1,
'another' => 'string',
@ -2355,7 +2357,7 @@ class SetTest extends CakeTestCase {
'Content-Length' => "50210",
),
'meta' => array(
'keywords' => array('testing','tests'),
'keywords' => array('testing', 'tests'),
'description' => 'describe me',
),
'get_vars' => '',
@ -2382,7 +2384,7 @@ class SetTest extends CakeTestCase {
'Content-Length' => "50210",
),
'meta' => array(
'keywords' => array('testing','tests'),
'keywords' => array('testing', 'tests'),
'description' => 'describe me',
),
'get_vars' => '',
@ -2441,8 +2443,8 @@ class SetTest extends CakeTestCase {
$expected->hash = '68a9f053b19526d08e36c6a9ad150737933816a5';
$expected->get_vars = '';
$expected->redirect = '';
$expected->created = "1195055503";
$expected->updated = "1195055503";
$expected->created = '1195055503';
$expected->updated = '1195055503';
// @codingStandardsIgnoreEnd
$this->assertEquals($expected, $mapped[1]);
@ -2468,8 +2470,8 @@ class SetTest extends CakeTestCase {
array(
'Post' => array('id' => '1', 'author_id' => '1', 'title' => 'First Post', 'body' => 'First Post Body', 'published' => 'Y', 'created' => '2007-03-18 10:39:23', 'updated' => '2007-03-18 10:41:31'),
'Author' => array('id' => '1', 'user' => 'mariano', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:16:23', 'updated' => '2007-03-17 01:18:31', 'test' => 'working'),
)
, array(
),
array(
'Post' => array('id' => '2', 'author_id' => '3', 'title' => 'Second Post', 'body' => 'Second Post Body', 'published' => 'Y', 'created' => '2007-03-18 10:41:23', 'updated' => '2007-03-18 10:43:31'),
'Author' => array('id' => '3', 'user' => 'larry', 'password' => '5f4dcc3b5aa765d61d8327deb882cf99', 'created' => '2007-03-17 01:20:23', 'updated' => '2007-03-17 01:22:31', 'test' => 'working'),
)
@ -2490,9 +2492,9 @@ class SetTest extends CakeTestCase {
$expected->Author->id = '1';
$expected->Author->user = 'mariano';
$expected->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99';
$expected->Author->created = "2007-03-17 01:16:23";
$expected->Author->updated = "2007-03-17 01:18:31";
$expected->Author->test = "working";
$expected->Author->created = '2007-03-17 01:16:23';
$expected->Author->updated = '2007-03-17 01:18:31';
$expected->Author->test = 'working';
$expected->Author->_name_ = 'Author';
$expected2 = new stdClass;
@ -2509,9 +2511,9 @@ class SetTest extends CakeTestCase {
$expected2->Author->id = '3';
$expected2->Author->user = 'larry';
$expected2->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99';
$expected2->Author->created = "2007-03-17 01:20:23";
$expected2->Author->updated = "2007-03-17 01:22:31";
$expected2->Author->test = "working";
$expected2->Author->created = '2007-03-17 01:20:23';
$expected2->Author->updated = '2007-03-17 01:22:31';
$expected2->Author->test = 'working';
$expected2->Author->_name_ = 'Author';
// @codingStandardsIgnoreEnd
@ -2544,7 +2546,7 @@ class SetTest extends CakeTestCase {
$expected->Author->password = '5f4dcc3b5aa765d61d8327deb882cf99';
$expected->Author->created = "2007-03-17 01:16:23";
$expected->Author->updated = "2007-03-17 01:18:31";
$expected->Author->test = "working";
$expected->Author->test = 'working';
$expected->Author->_name_ = 'Author';
// @codingStandardsIgnoreEnd
$this->assertEquals($expected, $result);
@ -2761,7 +2763,6 @@ class SetTest extends CakeTestCase {
/**
* testSetApply method
* @return void
*
*/
public function testApply() {
$data = array(

View file

@ -2,20 +2,20 @@
/**
* ValidationTest file
*
* PHP Version 5.x
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The Open Group Test Suite License
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Validation', 'Utility');
/**
@ -28,8 +28,8 @@ class CustomValidator {
/**
* Makes sure that a given $email address is valid and unique
*
* @param string $email
* @return boolean
* @param string $check Email to check.
* @return bool
*/
public static function customValidate($check) {
return (bool)preg_match('/^[0-9]{3}$/', $check);
@ -88,6 +88,25 @@ class TestDeValidation {
}
/**
* ValidationStub
*
* @package Cake.Test.Case.Utility
*/
class ValidationStub extends Validation {
/**
* Stub out is_uploaded_file check
*
* @param string $path
* @return void
*/
protected static function _isUploadedFile($path) {
return file_exists($path);
}
}
/**
* Test Case for Validation Class
*
@ -124,37 +143,37 @@ class ValidationTest extends CakeTestCase {
}
/**
* testNotEmpty method
* Test notBlank method
*
* @return void
*/
public function testNotEmpty() {
$this->assertTrue(Validation::notEmpty('abcdefg'));
$this->assertTrue(Validation::notEmpty('fasdf '));
$this->assertTrue(Validation::notEmpty('fooo' . chr(243) . 'blabla'));
$this->assertTrue(Validation::notEmpty('abçďĕʑʘπй'));
$this->assertTrue(Validation::notEmpty('José'));
$this->assertTrue(Validation::notEmpty('é'));
$this->assertTrue(Validation::notEmpty('π'));
$this->assertFalse(Validation::notEmpty("\t "));
$this->assertFalse(Validation::notEmpty(""));
public function testNotBlank() {
$this->assertTrue(Validation::notBlank('abcdefg'));
$this->assertTrue(Validation::notBlank('fasdf '));
$this->assertTrue(Validation::notBlank('fooo' . chr(243) . 'blabla'));
$this->assertTrue(Validation::notBlank('abçďĕʑʘπй'));
$this->assertTrue(Validation::notBlank('José'));
$this->assertTrue(Validation::notBlank('é'));
$this->assertTrue(Validation::notBlank('π'));
$this->assertFalse(Validation::notBlank("\t "));
$this->assertFalse(Validation::notBlank(""));
}
/**
* testNotEmptyISO88591Encoding method
* Test notBlank method with ISO88591 encoding
*
* @return void
*/
public function testNotEmptyISO88591AppEncoding() {
public function testNotBlankISO88591AppEncoding() {
Configure::write('App.encoding', 'ISO-8859-1');
$this->assertTrue(Validation::notEmpty('abcdefg'));
$this->assertTrue(Validation::notEmpty('fasdf '));
$this->assertTrue(Validation::notEmpty('fooo' . chr(243) . 'blabla'));
$this->assertTrue(Validation::notEmpty('abçďĕʑʘπй'));
$this->assertTrue(Validation::notEmpty('José'));
$this->assertTrue(Validation::notEmpty(utf8_decode('José')));
$this->assertFalse(Validation::notEmpty("\t "));
$this->assertFalse(Validation::notEmpty(""));
$this->assertTrue(Validation::notBlank('abcdefg'));
$this->assertTrue(Validation::notBlank('fasdf '));
$this->assertTrue(Validation::notBlank('fooo' . chr(243) . 'blabla'));
$this->assertTrue(Validation::notBlank('abçďĕʑʘπй'));
$this->assertTrue(Validation::notBlank('José'));
$this->assertTrue(Validation::notBlank(utf8_decode('José')));
$this->assertFalse(Validation::notBlank("\t "));
$this->assertFalse(Validation::notBlank(""));
}
/**
@ -175,6 +194,7 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::alphaNumeric('12 234'));
$this->assertFalse(Validation::alphaNumeric('dfd 234'));
$this->assertFalse(Validation::alphaNumeric("0\n"));
$this->assertFalse(Validation::alphaNumeric("\n"));
$this->assertFalse(Validation::alphaNumeric("\t"));
$this->assertFalse(Validation::alphaNumeric("\r"));
@ -183,36 +203,17 @@ class ValidationTest extends CakeTestCase {
}
/**
* testAlphaNumericPassedAsArray method
* testLengthBetween method
*
* @return void
*/
public function testAlphaNumericPassedAsArray() {
$this->assertTrue(Validation::alphaNumeric(array('check' => 'frferrf')));
$this->assertTrue(Validation::alphaNumeric(array('check' => '12234')));
$this->assertTrue(Validation::alphaNumeric(array('check' => '1w2e2r3t4y')));
$this->assertTrue(Validation::alphaNumeric(array('check' => '0')));
$this->assertFalse(Validation::alphaNumeric(array('check' => '12 234')));
$this->assertFalse(Validation::alphaNumeric(array('check' => 'dfd 234')));
$this->assertFalse(Validation::alphaNumeric(array('check' => "\n")));
$this->assertFalse(Validation::alphaNumeric(array('check' => "\t")));
$this->assertFalse(Validation::alphaNumeric(array('check' => "\r")));
$this->assertFalse(Validation::alphaNumeric(array('check' => ' ')));
$this->assertFalse(Validation::alphaNumeric(array('check' => '')));
}
public function testLengthBetween() {
$this->assertTrue(Validation::lengthBetween('abcdefg', 1, 7));
$this->assertTrue(Validation::lengthBetween('', 0, 7));
$this->assertTrue(Validation::lengthBetween('אกあアꀀ豈', 1, 7));
/**
* testBetween method
*
* @return void
*/
public function testBetween() {
$this->assertTrue(Validation::between('abcdefg', 1, 7));
$this->assertTrue(Validation::between('', 0, 7));
$this->assertTrue(Validation::between('אกあアꀀ豈', 1, 7));
$this->assertFalse(Validation::between('abcdefg', 1, 6));
$this->assertFalse(Validation::between('ÆΔΩЖÇ', 1, 3));
$this->assertFalse(Validation::lengthBetween('abcdefg', 1, 6));
$this->assertFalse(Validation::lengthBetween('ÆΔΩЖÇ', 1, 3));
}
/**
@ -230,21 +231,6 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::blank('Blank'));
}
/**
* testBlankAsArray method
*
* @return void
*/
public function testBlankAsArray() {
$this->assertTrue(Validation::blank(array('check' => '')));
$this->assertTrue(Validation::blank(array('check' => ' ')));
$this->assertTrue(Validation::blank(array('check' => "\n")));
$this->assertTrue(Validation::blank(array('check' => "\t")));
$this->assertTrue(Validation::blank(array('check' => "\r")));
$this->assertFalse(Validation::blank(array('check' => ' Blank')));
$this->assertFalse(Validation::blank(array('check' => 'Blank')));
}
/**
* testcc method
*
@ -417,6 +403,12 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::cc('5467639122779531', array('mc')));
$this->assertTrue(Validation::cc('5297350261550024', array('mc')));
$this->assertTrue(Validation::cc('5162739131368058', array('mc')));
//Mastercard (additional 2016 BIN)
$this->assertTrue(Validation::cc('2221000000000009', array('mc')));
$this->assertTrue(Validation::cc('2720999999999996', array('mc')));
$this->assertTrue(Validation::cc('2223000010005798', array('mc')));
$this->assertTrue(Validation::cc('2623430710235708', array('mc')));
$this->assertTrue(Validation::cc('2420452519835723', array('mc')));
//Solo 16
$this->assertTrue(Validation::cc('6767432107064987', array('solo')));
$this->assertTrue(Validation::cc('6334667758225411', array('solo')));
@ -929,42 +921,25 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::comparison(7, '==', 6));
$this->assertFalse(Validation::comparison(7, 'not equal', 7));
$this->assertFalse(Validation::comparison(7, '!=', 7));
$this->assertTrue(Validation::comparison('6.5', '!=', 6));
$this->assertTrue(Validation::comparison('6.5', '<', 7));
}
/**
* testComparisonAsArray method
* Test comparison casting values before comparisons.
*
* @return void
*/
public function testComparisonAsArray() {
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'is greater', 'check2' => 6)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>', 'check2' => 6)));
$this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => 'is less', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => '<', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'greater or equal', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>=', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'greater or equal','check2' => 6)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '>=', 'check2' => 6)));
$this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => 'less or equal', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 6, 'operator' => '<=', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'equal to', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '==', 'check2' => 7)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => 'not equal', 'check2' => 6)));
$this->assertTrue(Validation::comparison(array('check1' => 7, 'operator' => '!=', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'is greater', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'is less', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '<', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'greater or equal', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>=', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => 'greater or equal', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 6, 'operator' => '>=', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'less or equal', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '<=', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'equal to', 'check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '==','check2' => 6)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => 'not equal', 'check2' => 7)));
$this->assertFalse(Validation::comparison(array('check1' => 7, 'operator' => '!=', 'check2' => 7)));
public function testComparisonTypeChecks() {
$this->assertFalse(Validation::comparison('\x028', '>=', 1), 'hexish encoding fails');
$this->assertFalse(Validation::comparison('0b010', '>=', 1), 'binary string data fails');
$this->assertFalse(Validation::comparison('0x01', '>=', 1), 'hex string data fails');
$this->assertFalse(Validation::comparison('0x1', '>=', 1), 'hex string data fails');
$this->assertFalse(Validation::comparison('\x028', '>=', 1.5), 'hexish encoding fails');
$this->assertFalse(Validation::comparison('0b010', '>=', 1.5), 'binary string data fails');
$this->assertFalse(Validation::comparison('0x02', '>=', 1.5), 'hex string data fails');
}
/**
@ -979,17 +954,6 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::custom('missing regex'));
}
/**
* testCustomAsArray method
*
* @return void
*/
public function testCustomAsArray() {
$this->assertTrue(Validation::custom(array('check' => '12345', 'regex' => '/(?<!\\S)\\d++(?!\\S)/')));
$this->assertFalse(Validation::custom(array('check' => 'Text', 'regex' => '/(?<!\\S)\\d++(?!\\S)/')));
$this->assertFalse(Validation::custom(array('check' => '123.45', 'regex' => '/(?<!\\S)\\d++(?!\\S)/')));
}
/**
* testDateDdmmyyyy method
*
@ -1414,14 +1378,58 @@ class ValidationTest extends CakeTestCase {
* @return void
*/
public function testDateMyNumeric() {
$this->assertTrue(Validation::date('12/2006', array('my')));
$this->assertTrue(Validation::date('01/2006', array('my')));
$this->assertTrue(Validation::date('12-2006', array('my')));
$this->assertTrue(Validation::date('12.2006', array('my')));
$this->assertTrue(Validation::date('12 2006', array('my')));
$this->assertFalse(Validation::date('12/06', array('my')));
$this->assertFalse(Validation::date('12-06', array('my')));
$this->assertFalse(Validation::date('12.06', array('my')));
$this->assertFalse(Validation::date('12 06', array('my')));
$this->assertTrue(Validation::date('01/06', array('my')));
$this->assertTrue(Validation::date('12-06', array('my')));
$this->assertTrue(Validation::date('12.06', array('my')));
$this->assertTrue(Validation::date('12 06', array('my')));
$this->assertFalse(Validation::date('13 06', array('my')));
$this->assertFalse(Validation::date('13 2006', array('my')));
}
/**
* testDateYmNumeric method
*
* @return void
*/
public function testDateYmNumeric() {
$this->assertTrue(Validation::date('2006/12', array('ym')));
$this->assertTrue(Validation::date('2006-12', array('ym')));
$this->assertTrue(Validation::date('2006-12', array('ym')));
$this->assertTrue(Validation::date('2006 12', array('ym')));
$this->assertTrue(Validation::date('2006 12', array('ym')));
$this->assertTrue(Validation::date('1900-01', array('ym')));
$this->assertTrue(Validation::date('2153-01', array('ym')));
$this->assertTrue(Validation::date('06/12', array('ym')));
$this->assertTrue(Validation::date('06-12', array('ym')));
$this->assertTrue(Validation::date('06-12', array('ym')));
$this->assertTrue(Validation::date('06 12', array('ym')));
$this->assertFalse(Validation::date('2006/12 ', array('ym')));
$this->assertFalse(Validation::date('2006/12/', array('ym')));
$this->assertFalse(Validation::date('06/12 ', array('ym')));
$this->assertFalse(Validation::date('06/13 ', array('ym')));
}
/**
* testDateY method
*
* @return void
*/
public function testDateY() {
$this->assertTrue(Validation::date('1900', array('y')));
$this->assertTrue(Validation::date('1984', array('y')));
$this->assertTrue(Validation::date('2006', array('y')));
$this->assertTrue(Validation::date('2008', array('y')));
$this->assertTrue(Validation::date('2013', array('y')));
$this->assertTrue(Validation::date('2104', array('y')));
$this->assertTrue(Validation::date('1899', array('y')));
$this->assertFalse(Validation::date('20009', array('y')));
$this->assertFalse(Validation::date(' 2012', array('y')));
$this->assertFalse(Validation::date('3000', array('y')));
$this->assertFalse(Validation::date('1799', array('y')));
}
/**
@ -1610,6 +1618,25 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::decimal('.54321', null, '/^[-+]?[0-9]+(\\.[0-9]+)?$/s'));
}
/**
* Test localized floats with decimal.
*
* @return void
*/
public function testDecimalLocaleSet() {
$this->skipIf(DS === '\\', 'The locale is not supported in Windows and affects other tests.');
$restore = setlocale(LC_NUMERIC, 0);
$this->skipIf(setlocale(LC_NUMERIC, 'da_DK') === false, "The Danish locale isn't available.");
$this->assertTrue(Validation::decimal(1.54), '1.54 should be considered a valid float');
$this->assertTrue(Validation::decimal('1.54'), '"1.54" should be considered a valid float');
$this->assertTrue(Validation::decimal(12345.67), '12345.67 should be considered a valid float');
$this->assertTrue(Validation::decimal('12,345.67'), '"12,345.67" should be considered a valid float');
setlocale(LC_NUMERIC, $restore);
}
/**
* testEmail method
*
@ -1667,6 +1694,11 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::email('!def!xyz%abc@example.com'));
$this->assertTrue(Validation::email('_somename@example.com'));
/// Unicode
$this->assertTrue(Validation::email('some@eräume.foo'));
$this->assertTrue(Validation::email('äu@öe.eräume.foo'));
$this->assertTrue(Validation::email('Nyrée.surname@example.com'));
// invalid addresses
$this->assertFalse(Validation::email('abc@example'));
$this->assertFalse(Validation::email('abc@example.c'));
@ -1684,7 +1716,6 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::email("abc@sub'example.com"));
$this->assertFalse(Validation::email('abc@sub/example.com'));
$this->assertFalse(Validation::email('abc@yahoo!.com'));
$this->assertFalse(Validation::email("Nyrée.surname@example.com"));
$this->assertFalse(Validation::email('abc@example_underscored.com'));
$this->assertFalse(Validation::email('raw@test.ra.ru....com'));
}
@ -1699,7 +1730,6 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::email('abc.efg@cakephp.org', true));
$this->assertFalse(Validation::email('abc.efg@caphpkeinvalid.com', true));
$this->assertFalse(Validation::email('abc@example.abcd', true));
}
/**
@ -1855,6 +1885,7 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::url('http://_jabber._tcp.g_mail.com'));
$this->assertFalse(Validation::url('http://en.(wikipedia).org/'));
$this->assertFalse(Validation::url('http://www.domain.com/fakeenco%ode'));
$this->assertFalse(Validation::url('--.example.com'));
$this->assertFalse(Validation::url('www.cakephp.org', true));
$this->assertTrue(Validation::url('http://example.com/~userdir/subdir/index.html'));
@ -1862,6 +1893,8 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::url('http://www.zwischenraume.cz'));
$this->assertTrue(Validation::url('http://www.last.fm/music/浜崎あゆみ'), 'utf8 path failed');
$this->assertTrue(Validation::url('http://www.electrohome.ro/images/239537750-284232-215_300[1].jpg'));
$this->assertTrue(Validation::url('http://www.eräume.foo'));
$this->assertTrue(Validation::url('http://äüö.eräume.foo'));
$this->assertTrue(Validation::url('http://cakephp.org:80'));
$this->assertTrue(Validation::url('http://cakephp.org:443'));
@ -1882,6 +1915,7 @@ class ValidationTest extends CakeTestCase {
}
public function testUuid() {
$this->assertTrue(Validation::uuid('00000000-0000-0000-0000-000000000000'));
$this->assertTrue(Validation::uuid('550e8400-e29b-11d4-a716-446655440000'));
$this->assertFalse(Validation::uuid('BRAP-e29b-11d4-a716-446655440000'));
$this->assertTrue(Validation::uuid('550E8400-e29b-11D4-A716-446655440000'));
@ -1903,8 +1937,19 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::inList('three', array('one', 'two')));
$this->assertFalse(Validation::inList('1one', array(0, 1, 2, 3)));
$this->assertFalse(Validation::inList('one', array(0, 1, 2, 3)));
$this->assertFalse(Validation::inList('2', array(1, 2, 3)));
$this->assertTrue(Validation::inList('2', array(1, 2, 3), false));
$this->assertTrue(Validation::inList('2', array(1, 2, 3)));
$this->assertFalse(Validation::inList('2x', array(1, 2, 3)));
$this->assertFalse(Validation::inList(2, array('1', '2x', '3')));
$this->assertFalse(Validation::inList('One', array('one', 'two')));
// No hexadecimal for numbers.
$this->assertFalse(Validation::inList('0x7B', array('ABC', '123')));
$this->assertFalse(Validation::inList('0x7B', array('ABC', 123)));
// case insensitive
$this->assertTrue(Validation::inList('one', array('One', 'Two'), true));
$this->assertTrue(Validation::inList('Two', array('one', 'two'), true));
$this->assertFalse(Validation::inList('three', array('one', 'two'), true));
}
/**
@ -1922,6 +1967,22 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::range('word'));
}
/**
* Test range type checks
*
* @return void
*/
public function testRangeTypeChecks() {
$this->assertFalse(Validation::range('\x028', 1, 5), 'hexish encoding fails');
$this->assertFalse(Validation::range('0b010', 1, 5), 'binary string data fails');
$this->assertFalse(Validation::range('0x01', 1, 5), 'hex string data fails');
$this->assertFalse(Validation::range('0x1', 1, 5), 'hex string data fails');
$this->assertFalse(Validation::range('\x028', 1, 5), 'hexish encoding fails');
$this->assertFalse(Validation::range('0b010', 1, 5), 'binary string data fails');
$this->assertFalse(Validation::range('0x02', 1, 5), 'hex string data fails');
}
/**
* testExtension method
*
@ -1957,29 +2018,37 @@ class ValidationTest extends CakeTestCase {
* @return void
*/
public function testMoney() {
$this->assertTrue(Validation::money('100'));
$this->assertTrue(Validation::money('100.11'));
$this->assertTrue(Validation::money('100.112'));
$this->assertTrue(Validation::money('100.1'));
$this->assertTrue(Validation::money('100.111,1'));
$this->assertTrue(Validation::money('100.111,11'));
$this->assertFalse(Validation::money('100.111,111'));
$this->assertTrue(Validation::money('$100'));
$this->assertTrue(Validation::money('$100.11'));
$this->assertTrue(Validation::money('$100.112'));
$this->assertFalse(Validation::money('$100.1'));
$this->assertTrue(Validation::money('$100.1'));
$this->assertFalse(Validation::money('$100.1111'));
$this->assertFalse(Validation::money('text'));
$this->assertTrue(Validation::money('100', 'right'));
$this->assertTrue(Validation::money('100.11$', 'right'));
$this->assertTrue(Validation::money('100.112$', 'right'));
$this->assertFalse(Validation::money('100.1$', 'right'));
$this->assertTrue(Validation::money('100.1$', 'right'));
$this->assertFalse(Validation::money('100.1111$', 'right'));
$this->assertTrue(Validation::money('€100'));
$this->assertTrue(Validation::money('€100.11'));
$this->assertTrue(Validation::money('€100.112'));
$this->assertFalse(Validation::money('€100.1'));
$this->assertTrue(Validation::money('€100.1'));
$this->assertFalse(Validation::money('€100.1111'));
$this->assertTrue(Validation::money('100', 'right'));
$this->assertTrue(Validation::money('100.11€', 'right'));
$this->assertTrue(Validation::money('100.112€', 'right'));
$this->assertFalse(Validation::money('100.1€', 'right'));
$this->assertTrue(Validation::money('100.1€', 'right'));
$this->assertFalse(Validation::money('100.1111€', 'right'));
}
@ -1995,8 +2064,9 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::multiple(''));
$this->assertFalse(Validation::multiple(null));
$this->assertFalse(Validation::multiple(array()));
$this->assertFalse(Validation::multiple(array(0)));
$this->assertFalse(Validation::multiple(array('0')));
$this->assertTrue(Validation::multiple(array(0)));
$this->assertTrue(Validation::multiple(array('0')));
$this->assertFalse(Validation::multiple(array('')));
$this->assertTrue(Validation::multiple(array(0, 3, 4, 5), array('in' => range(0, 10))));
$this->assertFalse(Validation::multiple(array(0, 15, 20, 5), array('in' => range(0, 10))));
@ -2004,8 +2074,9 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::multiple(array('boo', 'foo', 'bar'), array('in' => array('foo', 'bar', 'baz'))));
$this->assertFalse(Validation::multiple(array('foo', '1bar'), array('in' => range(0, 10))));
$this->assertTrue(Validation::multiple(array(0, 5, 10, 11), array('max' => 3)));
$this->assertFalse(Validation::multiple(array(0, 5, 10, 11, 55), array('max' => 3)));
$this->assertFalse(Validation::multiple(array(1, 5, 10, 11), array('max' => 3)));
$this->assertTrue(Validation::multiple(array(0, 5, 10, 11), array('max' => 4)));
$this->assertFalse(Validation::multiple(array(0, 5, 10, 11, 55), array('max' => 4)));
$this->assertTrue(Validation::multiple(array('foo', 'bar', 'baz'), array('max' => 3)));
$this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz', 'squirrel'), array('max' => 3)));
@ -2015,14 +2086,24 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::multiple(array('foo', 'bar', 'baz', 'squirrel'), array('min' => 10)));
$this->assertTrue(Validation::multiple(array(0, 5, 9), array('in' => range(0, 10), 'max' => 5)));
$this->assertFalse(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5)));
$this->assertTrue(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5), false));
$this->assertTrue(Validation::multiple(array('0', '5', '9'), array('in' => range(0, 10), 'max' => 5)));
$this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5)));
$this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 11), array('in' => range(0, 10), 'max' => 5)));
$this->assertFalse(Validation::multiple(array(0, 5, 9), array('in' => range(0, 10), 'max' => 5, 'min' => 3)));
$this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5, 'min' => 2)));
$this->assertFalse(Validation::multiple(array(-1, 5, 9), array('in' => range(0, 10), 'max' => 5, 'min' => 3)));
$this->assertFalse(Validation::multiple(array(-1, 5, 9, 8, 6, 2, 1), array('in' => range(0, 10), 'max' => 5, 'min' => 2)));
$this->assertFalse(Validation::multiple(array(0, 5, 9, 8, 11), array('in' => range(0, 10), 'max' => 5, 'min' => 2)));
$this->assertFalse(Validation::multiple(array('2x', '3x'), array('in' => array(1, 2, 3, 4, 5))));
$this->assertFalse(Validation::multiple(array(2, 3), array('in' => array('1x', '2x', '3x', '4x'))));
$this->assertFalse(Validation::multiple(array('one'), array('in' => array('One', 'Two'))));
$this->assertFalse(Validation::multiple(array('Two'), array('in' => array('one', 'two'))));
// case insensitive
$this->assertTrue(Validation::multiple(array('one'), array('in' => array('One', 'Two')), true));
$this->assertTrue(Validation::multiple(array('Two'), array('in' => array('one', 'two')), true));
$this->assertFalse(Validation::multiple(array('three'), array('in' => array('one', 'two')), true));
}
/**
@ -2079,8 +2160,25 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::phone('(055) 999-9999'));
$this->assertFalse(Validation::phone('(155) 999-9999'));
$this->assertFalse(Validation::phone('(595) 999-9999'));
$this->assertFalse(Validation::phone('(555) 099-9999'));
$this->assertFalse(Validation::phone('(555) 199-9999'));
$this->assertFalse(Validation::phone('(213) 099-9999'));
$this->assertFalse(Validation::phone('(213) 199-9999'));
// invalid area-codes
$this->assertFalse(Validation::phone('1-(511)-999-9999'));
$this->assertFalse(Validation::phone('1-(555)-999-9999'));
// invalid phone number
$this->assertFalse(Validation::phone('1-(222)-555-0199'));
$this->assertFalse(Validation::phone('1-(222)-555-0122'));
// valid phone numbers
$this->assertTrue(Validation::phone('416-428-1234'));
$this->assertTrue(Validation::phone('1-(369)-333-4444'));
$this->assertTrue(Validation::phone('1-(973)-333-4444'));
$this->assertTrue(Validation::phone('1-(313)-555-9999'));
$this->assertTrue(Validation::phone('1-(222)-555-0299'));
$this->assertTrue(Validation::phone('508-428-1234'));
$this->assertTrue(Validation::phone('1-(508)-232-9651'));
$this->assertTrue(Validation::phone('1 (222) 333 4444'));
$this->assertTrue(Validation::phone('+1 (222) 333 4444'));
@ -2091,6 +2189,7 @@ class ValidationTest extends CakeTestCase {
$this->assertTrue(Validation::phone('1.(333).333-4444'));
$this->assertTrue(Validation::phone('1.(333).333.4444'));
$this->assertTrue(Validation::phone('1-333-333-4444'));
$this->assertTrue(Validation::phone('1-800-211-4511'));
}
/**
@ -2125,6 +2224,10 @@ class ValidationTest extends CakeTestCase {
$this->assertFalse(Validation::postal('BAA 0ABC', null, 'ca'));
$this->assertFalse(Validation::postal('B2A AABC', null, 'ca'));
$this->assertFalse(Validation::postal('B2A 2AB', null, 'ca'));
$this->assertFalse(Validation::postal('K1A 1D1', null, 'ca'));
$this->assertFalse(Validation::postal('K1O 1Q1', null, 'ca'));
$this->assertFalse(Validation::postal('A1A 1U1', null, 'ca'));
$this->assertFalse(Validation::postal('A1F 1B1', null, 'ca'));
$this->assertTrue(Validation::postal('X0A 0A2', null, 'ca'));
$this->assertTrue(Validation::postal('G4V 4C3', null, 'ca'));
@ -2171,7 +2274,7 @@ class ValidationTest extends CakeTestCase {
*
* @expectedException PHPUnit_Framework_Error
* @return void
**/
*/
public function testPassThroughClassFailure() {
Validation::postal('text', null, 'AUTOFAIL');
}
@ -2255,9 +2358,13 @@ class ValidationTest extends CakeTestCase {
public function testMimeType() {
$image = CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
$File = new File($image, false);
$this->skipIf(!$File->mime(), 'Cannot determine mimeType');
$this->assertTrue(Validation::mimeType($image, array('image/gif')));
$this->assertTrue(Validation::mimeType(array('tmp_name' => $image), array('image/gif')));
$this->assertTrue(Validation::mimeType(array('tmp_name' => $image), '#image/.+#'));
$this->assertTrue(Validation::mimeType($image, array('image/GIF')));
$this->assertFalse(Validation::mimeType($image, array('image/png')));
$this->assertFalse(Validation::mimeType(array('tmp_name' => $image), array('image/png')));
@ -2277,15 +2384,164 @@ class ValidationTest extends CakeTestCase {
}
/**
* testMimeType method
* testUploadError method
*
* @return void
*/
public function testUploadError() {
$this->assertTrue(Validation::uploadError(0));
$this->assertTrue(Validation::uploadError(array('error' => 0)));
$this->assertTrue(Validation::uploadError(array('error' => '0')));
$this->assertFalse(Validation::uploadError(2));
$this->assertFalse(Validation::uploadError(array('error' => 2)));
$this->assertFalse(Validation::uploadError(array('error' => '2')));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_NO_FILE));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_FORM_SIZE, true));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_INI_SIZE, true));
$this->assertFalse(Validation::uploadError(UPLOAD_ERR_NO_TMP_DIR, true));
$this->assertTrue(Validation::uploadError(UPLOAD_ERR_NO_FILE, true));
}
/**
* testFileSize method
*
* @return void
*/
public function testFileSize() {
$image = CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot' . DS . 'img' . DS . 'cake.power.gif';
$this->assertTrue(Validation::fileSize($image, '<', 1024));
$this->assertTrue(Validation::fileSize(array('tmp_name' => $image), 'isless', 1024));
$this->assertTrue(Validation::fileSize($image, '<', '1KB'));
$this->assertTrue(Validation::fileSize($image, '>=', 200));
$this->assertTrue(Validation::fileSize($image, '==', 201));
$this->assertTrue(Validation::fileSize($image, '==', '201B'));
$this->assertFalse(Validation::fileSize($image, 'isgreater', 1024));
$this->assertFalse(Validation::fileSize(array('tmp_name' => $image), '>', '1KB'));
}
/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileErrorCode() {
$this->assertFalse(ValidationStub::uploadedFile('derp'));
$invalid = array(
'name' => 'testing'
);
$this->assertFalse(ValidationStub::uploadedFile($invalid));
$file = array(
'name' => 'cake.power.gif',
'tmp_name' => CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot/img/cake.power.gif',
'error' => UPLOAD_ERR_OK,
'type' => 'image/gif',
'size' => 201
);
$this->assertTrue(ValidationStub::uploadedFile($file));
$file['error'] = UPLOAD_ERR_NO_FILE;
$this->assertFalse(ValidationStub::uploadedFile($file), 'Error upload should fail.');
}
/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileMimeType() {
$file = array(
'name' => 'cake.power.gif',
'tmp_name' => CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot/img/cake.power.gif',
'error' => UPLOAD_ERR_OK,
'type' => 'text/plain',
'size' => 201
);
$options = array(
'types' => array('text/plain')
);
$this->assertFalse(ValidationStub::uploadedFile($file, $options), 'Incorrect mimetype.');
$options = array(
'types' => array('image/gif', 'image/png')
);
$this->assertTrue(ValidationStub::uploadedFile($file, $options));
}
/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileSize() {
$file = array(
'name' => 'cake.power.gif',
'tmp_name' => CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot/img/cake.power.gif',
'error' => UPLOAD_ERR_OK,
'type' => 'text/plain',
'size' => 201
);
$options = array(
'minSize' => 500
);
$this->assertFalse(ValidationStub::uploadedFile($file, $options), 'Too small');
$options = array(
'maxSize' => 100
);
$this->assertFalse(ValidationStub::uploadedFile($file, $options), 'Too big');
$options = array(
'minSize' => 100,
);
$this->assertTrue(ValidationStub::uploadedFile($file, $options));
$options = array(
'maxSize' => 500,
);
$this->assertTrue(ValidationStub::uploadedFile($file, $options));
$options = array(
'minSize' => 100,
'maxSize' => 500
);
$this->assertTrue(ValidationStub::uploadedFile($file, $options));
}
/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileNoFile() {
$file = array(
'name' => '',
'tmp_name' => CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot/img/cake.power.gif',
'error' => UPLOAD_ERR_NO_FILE,
'type' => '',
'size' => 0
);
$options = array(
'optional' => true,
'minSize' => 500,
'types' => array('image/gif', 'image/png')
);
$this->assertTrue(Validation::uploadedFile($file, $options), 'No file should be ok.');
$options = array(
'optional' => false
);
$this->assertFalse(Validation::uploadedFile($file, $options), 'File is required.');
}
/**
* Test uploaded file validation.
*
* @return void
*/
public function testUploadedFileWithDifferentFileParametersOrder() {
$file = array(
'name' => 'cake.power.gif',
'error' => UPLOAD_ERR_OK,
'tmp_name' => CORE_PATH . 'Cake' . DS . 'Test' . DS . 'test_app' . DS . 'webroot/img/cake.power.gif',
'type' => 'text/plain',
'size' => 201
);
$options = array();
$this->assertTrue(ValidationStub::uploadedFile($file, $options), 'Wrong order');
}
}

View file

@ -2,20 +2,20 @@
/**
* XmlTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Utility
* @since CakePHP(tm) v 1.2.0.5432
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
App::uses('Xml', 'Utility');
App::uses('CakeTestModel', 'TestSuite/Fixture');
@ -29,7 +29,7 @@ class XmlArticle extends CakeTestModel {
/**
* name property
*
* @var string 'Article'
* @var string
*/
public $name = 'Article';
@ -56,7 +56,7 @@ class XmlUser extends CakeTestModel {
/**
* name property
*
* @var string 'User'
* @var string
*/
public $name = 'User';
@ -82,7 +82,7 @@ class XmlTest extends CakeTestCase {
/**
* autoFixtures property
*
* @var bool false
* @var bool
*/
public $autoFixtures = false;
@ -167,6 +167,40 @@ class XmlTest extends CakeTestCase {
$this->assertNotRegExp('/encoding/', $obj->saveXML());
}
/**
* test build() method with huge option
*
* @return void
*/
public function testBuildHuge() {
$xml = '<tag>value</tag>';
$obj = Xml::build($xml, array('parseHuge' => true));
$this->assertEquals('tag', $obj->getName());
$this->assertEquals('value', (string)$obj);
}
/**
* Test that the readFile option disables local file parsing.
*
* @expectedException XmlException
* @return void
*/
public function testBuildFromFileWhenDisabled() {
$xml = CAKE . 'Test' . DS . 'Fixture' . DS . 'sample.xml';
Xml::build($xml, array('readFile' => false));
}
/**
* Test that the readFile option disables local file parsing.
*
* @expectedException XmlException
* @return void
*/
public function testBuildFromUrlWhenDisabled() {
$xml = 'http://www.google.com';
Xml::build($xml, array('readFile' => false));
}
/**
* data provider function for testBuildInvalidData
*
@ -186,16 +220,27 @@ class XmlTest extends CakeTestCase {
*
* @dataProvider invalidDataProvider
* @expectedException XmlException
* return void
* @return void
*/
public function testBuildInvalidData($value) {
Xml::build($value);
}
/**
* Test that building SimpleXmlElement with invalid XML causes the right exception.
*
* @expectedException XmlException
* @return void
*/
public function testBuildInvalidDataSimpleXml() {
$input = '<derp';
Xml::build($input, array('return' => 'simplexml'));
}
/**
* test build with a single empty tag
*
* return void
* @return void
*/
public function testBuildEmptyTag() {
try {
@ -364,6 +409,36 @@ XML;
$this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
}
/**
* Test fromArray() with zero values.
*
* @return void
*/
public function testFromArrayZeroValue() {
$xml = array(
'tag' => array(
'@' => 0,
'@test' => 'A test'
)
);
$obj = Xml::fromArray($xml);
$xmlText = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tag test="A test">0</tag>
XML;
$this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
$xml = array(
'tag' => array('0')
);
$obj = Xml::fromArray($xml);
$xmlText = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tag>0</tag>
XML;
$this->assertXmlStringEqualsXmlString($xmlText, $obj->asXML());
}
/**
* Test non-sequential keys in list types.
*
@ -401,6 +476,87 @@ XML;
$this->assertXmlStringEqualsXmlString($expected, $obj->asXML());
}
/**
* testFromArrayPretty method
*
* @return void
*/
public function testFromArrayPretty() {
$xml = array(
'tags' => array(
'tag' => array(
array(
'id' => '1',
'name' => 'defect'
),
array(
'id' => '2',
'name' => 'enhancement'
)
)
)
);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tags><tag><id>1</id><name>defect</name></tag><tag><id>2</id><name>enhancement</name></tag></tags>
XML;
$xmlResponse = Xml::fromArray($xml, array('pretty' => false));
$this->assertTextEquals($expected, $xmlResponse->asXML());
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tags>
<tag>
<id>1</id>
<name>defect</name>
</tag>
<tag>
<id>2</id>
<name>enhancement</name>
</tag>
</tags>
XML;
$xmlResponse = Xml::fromArray($xml, array('pretty' => true));
$this->assertTextEquals($expected, $xmlResponse->asXML());
$xml = array(
'tags' => array(
'tag' => array(
array(
'id' => '1',
'name' => 'defect'
),
array(
'id' => '2',
'name' => 'enhancement'
)
)
)
);
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tags><tag id="1" name="defect"/><tag id="2" name="enhancement"/></tags>
XML;
$xmlResponse = Xml::fromArray($xml, array('pretty' => false, 'format' => 'attributes'));
$this->assertTextEquals($expected, $xmlResponse->asXML());
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<tags>
<tag id="1" name="defect"/>
<tag id="2" name="enhancement"/>
</tags>
XML;
$xmlResponse = Xml::fromArray($xml, array('pretty' => true, 'format' => 'attributes'));
$this->assertTextEquals($expected, $xmlResponse->asXML());
}
/**
* data provider for fromArray() failures
*
@ -448,6 +604,7 @@ XML;
* testFromArrayFail method
*
* @dataProvider invalidArrayDataProvider
* @return void
*/
public function testFromArrayFail($value) {
try {
@ -458,6 +615,41 @@ XML;
}
}
/**
* Test that there are not unterminated errors when building xml
*
* @return void
*/
public function testFromArrayUnterminatedError() {
$data = array(
'product_ID' => 'GENERT-DL',
'deeplink' => 'http://example.com/deep',
'image_URL' => 'http://example.com/image',
'thumbnail_image_URL' => 'http://example.com/thumb',
'brand' => 'Malte Lange & Co',
'availability' => 'in stock',
'authors' => array(
'author' => array('Malte Lange & Co')
)
);
$xml = Xml::fromArray(array('products' => $data), 'tags');
$expected = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<products>
<product_ID>GENERT-DL</product_ID>
<deeplink>http://example.com/deep</deeplink>
<image_URL>http://example.com/image</image_URL>
<thumbnail_image_URL>http://example.com/thumb</thumbnail_image_URL>
<brand>Malte Lange &amp; Co</brand>
<availability>in stock</availability>
<authors>
<author>Malte Lange &amp; Co</author>
</authors>
</products>
XML;
$this->assertXmlStringEqualsXmlString($expected, $xml->asXML());
}
/**
* testToArray method
*
@ -608,6 +800,16 @@ XML;
)
);
$this->assertEquals($expected, Xml::toArray($obj));
$xml = '<tag type="myType">0</tag>';
$obj = Xml::build($xml);
$expected = array(
'tag' => array(
'@type' => 'myType',
'@' => 0
)
);
$this->assertEquals($expected, Xml::toArray($obj));
}
/**
@ -632,7 +834,7 @@ XML;
'pubDate' => 'Tue, 31 Aug 2010 01:42:00 -0500',
'guid' => 'http://bakery.cakephp.org/articles/view/alertpay-automated-sales-via-ipn'
);
$this->assertSame($rssAsArray['rss']['channel']['item'][1], $expected);
$this->assertSame($expected, $rssAsArray['rss']['channel']['item'][1]);
$rss = array(
'rss' => array(
@ -698,7 +900,7 @@ XML;
'params' => ''
)
);
$this->assertSame(Xml::toArray($xml), $expected);
$this->assertSame($expected, Xml::toArray($xml));
$xml = Xml::build('<methodCall><methodName>test</methodName><params><param><value><array><data><value><int>12</int></value><value><string>Egypt</string></value><value><boolean>0</boolean></value><value><int>-31</int></value></data></array></value></param></params></methodCall>');
$expected = array(
@ -722,7 +924,7 @@ XML;
)
)
);
$this->assertSame(Xml::toArray($xml), $expected);
$this->assertSame($expected, Xml::toArray($xml));
$xmlText = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
@ -764,7 +966,7 @@ XML;
)
)
);
$this->assertSame(Xml::toArray($xml), $expected);
$this->assertSame($expected, Xml::toArray($xml));
$xml = Xml::fromArray($expected, 'tags');
$this->assertXmlStringEqualsXmlString($xmlText, $xml->asXML());
@ -888,7 +1090,7 @@ XML;
);
$expected = '<' . '?xml version="1.0" encoding="UTF-8"?><root><ns:attr xmlns:ns="http://cakephp.org">1</ns:attr></root>';
$xmlResponse = Xml::fromArray($xml);
$this->assertEquals(str_replace(array("\r", "\n"), '', $xmlResponse->asXML()), $expected);
$this->assertEquals($expected, str_replace(array("\r", "\n"), '', $xmlResponse->asXML()));
$xml = array(
'root' => array(
@ -973,6 +1175,7 @@ XML;
*
* @dataProvider invalidToArrayDataProvider
* @expectedException XmlException
* @return void
*/
public function testToArrayFail($value) {
Xml::toArray($value);
@ -1020,7 +1223,7 @@ XML;
</records>
</data>
XML;
$result = $obj->asXML();
$obj->asXML();
$this->assertXmlStringEqualsXmlString($expected, $obj->asXML());
}