Backup of current cakephp version

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

View file

@ -0,0 +1,650 @@
<?php
/**
* CacheHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('Model', 'Model');
App::uses('View', 'View');
App::uses('CacheHelper', 'View/Helper');
/**
* CacheTestController class
*
* @package Cake.Test.Case.View.Helper
*/
class CacheTestController extends Controller {
/**
* helpers property
*
* @var array
*/
public $helpers = array('Html', 'Cache');
/**
* cache_parsing method
*
* @return void
*/
public function cache_parsing() {
$this->viewPath = 'Posts';
$this->layout = 'cache_layout';
$this->set('variable', 'variableValue');
$this->set('superman', 'clark kent');
$this->set('batman', 'bruce wayne');
$this->set('spiderman', 'peter parker');
}
}
/**
* CacheHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class CacheHelperTest extends CakeTestCase {
/**
* Checks if TMP/views is writable, and skips the case if it is not.
*
* @return void
*/
public function skip() {
if (!is_writable(TMP . 'cache' . DS . 'views' . DS)) {
$this->markTestSkipped('TMP/views is not writable %s');
}
}
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$_GET = array();
$request = new CakeRequest();
$this->Controller = new CacheTestController($request);
$View = new View($this->Controller);
$this->Cache = new CacheHelper($View);
Configure::write('Cache.check', true);
Configure::write('Cache.disable', false);
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
), App::RESET);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
clearCache();
unset($this->Cache);
parent::tearDown();
}
/**
* test cache parsing with no cake:nocache tags in view file.
*
* @return void
*/
public function testLayoutCacheParsingNoTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = 21600;
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->request->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertRegExp('/php echo \$variable/', $contents);
$this->assertRegExp('/php echo microtime()/', $contents);
$this->assertRegExp('/clark kent/', $result);
unlink($filename);
}
/**
* test cache parsing with non-latin characters in current route
*
* @return void
*/
public function testCacheNonLatinCharactersInRoute() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array('風街ろまん'),
'named' => array()
));
$this->Controller->cacheAction = 21600;
$this->Controller->request->here = '/posts/view/風街ろまん';
$this->Controller->action = 'view';
$View = new View($this->Controller);
$result = $View->render('index');
$filename = CACHE . 'views' . DS . 'posts_view_風街ろまん.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* Test cache parsing with cake:nocache tags in view file.
*
* @return void
*/
public function testLayoutCacheParsingWithTagsInView() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = 21600;
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('test_nocache_tags');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertRegExp('/if \(is_writable\(TMP\)\)\:/', $contents);
$this->assertRegExp('/php echo \$variable/', $contents);
$this->assertRegExp('/php echo microtime()/', $contents);
$this->assertNotRegExp('/cake:nocache/', $contents);
unlink($filename);
}
/**
* test that multiple <!--nocache--> tags function with multiple nocache tags in the layout.
*
* @return void
*/
public function testMultipleNoCacheTagsInViewfile() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = 21600;
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('multiple_nocache');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertNotRegExp('/cake:nocache/', $contents);
unlink($filename);
}
/**
* testComplexNoCache method
*
* @return void
*/
public function testComplexNoCache() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_complex',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = array('cache_complex' => 21600);
$this->Controller->request->here = '/cacheTest/cache_complex';
$this->Controller->action = 'cache_complex';
$this->Controller->layout = 'multi_cache';
$this->Controller->viewPath = 'Posts';
$View = new View($this->Controller);
$result = $View->render('sequencial_nocache');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$this->assertRegExp('/A\. Layout Before Content/', $result);
$this->assertRegExp('/B\. In Plain Element/', $result);
$this->assertRegExp('/C\. Layout After Test Element/', $result);
$this->assertRegExp('/D\. In View File/', $result);
$this->assertRegExp('/E\. Layout After Content/', $result);
$this->assertRegExp('/F\. In Element With No Cache Tags/', $result);
$this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $result);
$this->assertNotRegExp('/1\. layout before content/', $result);
$this->assertNotRegExp('/2\. in plain element/', $result);
$this->assertNotRegExp('/3\. layout after test element/', $result);
$this->assertNotRegExp('/4\. in view file/', $result);
$this->assertNotRegExp('/5\. layout after content/', $result);
$this->assertNotRegExp('/6\. in element with no cache tags/', $result);
$this->assertNotRegExp('/7\. layout after content and after element with no cache tags/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_complex.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
unlink($filename);
$this->assertRegExp('/A\. Layout Before Content/', $contents);
$this->assertNotRegExp('/B\. In Plain Element/', $contents);
$this->assertRegExp('/C\. Layout After Test Element/', $contents);
$this->assertRegExp('/D\. In View File/', $contents);
$this->assertRegExp('/E\. Layout After Content/', $contents);
$this->assertRegExp('/F\. In Element With No Cache Tags/', $contents);
$this->assertRegExp('/G\. Layout After Content And After Element With No Cache Tags/', $contents);
$this->assertRegExp('/1\. layout before content/', $contents);
$this->assertNotRegExp('/2\. in plain element/', $contents);
$this->assertRegExp('/3\. layout after test element/', $contents);
$this->assertRegExp('/4\. in view file/', $contents);
$this->assertRegExp('/5\. layout after content/', $contents);
$this->assertRegExp('/6\. in element with no cache tags/', $contents);
$this->assertRegExp('/7\. layout after content and after element with no cache tags/', $contents);
}
/**
* test cache of view vars
*
* @return void
*/
public function testCacheViewVars() {
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->cacheAction = 21600;
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertRegExp('/\$this\-\>viewVars/', $contents);
$this->assertRegExp('/extract\(\$this\-\>viewVars, EXTR_SKIP\);/', $contents);
$this->assertRegExp('/php echo \$variable/', $contents);
unlink($filename);
}
/**
* Test that callback code is generated correctly.
*
* @return void
*/
public function testCacheCallbacks() {
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = array(
'cache_parsing' => array(
'duration' => 21600,
'callbacks' => true
)
);
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->cache_parsing();
$View = new View($this->Controller);
$result = $View->render('index');
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertRegExp('/\$controller->startupProcess\(\);/', $contents);
unlink($filename);
}
/**
* test cacheAction set to a boolean
*
* @return void
*/
public function testCacheActionArray() {
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->request->here = '/cache_test/cache_parsing';
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->cache_parsing();
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_test_cache_parsing.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* Test that cacheAction works with camelcased controller names.
*
* @return void
*/
public function testCacheActionArrayCamelCase() {
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->request->here = '/cacheTest/cache_parsing';
$this->Controller->cache_parsing();
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_parsing.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* test with named and pass args.
*
* @return void
*/
public function testCacheWithNamedAndPassedArgs() {
Router::reload();
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(1, 2),
'named' => array(
'name' => 'mark',
'ice' => 'cream'
)
));
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->request->here = '/cache_test/cache_parsing/1/2/name:mark/ice:cream';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_test_cache_parsing_1_2_name_mark_ice_cream.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* Test that query string parameters are included in the cache filename.
*
* @return void
*/
public function testCacheWithQueryStringParams() {
Router::reload();
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->request->query = array('q' => 'cakephp');
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->request->here = '/cache_test/cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_test_cache_parsing_q_cakephp.php';
$this->assertTrue(file_exists($filename), 'Missing cache file ' . $filename);
unlink($filename);
}
/**
* test that custom routes are respected when generating cache files.
*
* @return void
*/
public function testCacheWithCustomRoutes() {
Router::reload();
Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
$this->Controller->cache_parsing();
$this->Controller->request->addParams(array(
'lang' => 'en',
'controller' => 'cache_test',
'action' => 'cache_parsing',
'pass' => array(),
'named' => array()
));
$this->Controller->cacheAction = array(
'cache_parsing' => 21600
);
$this->Controller->request->here = '/en/cache_test/cache_parsing';
$this->Controller->action = 'cache_parsing';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'en_cache_test_cache_parsing.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* test ControllerName contains AppName
*
* This test verifies view cache is created correctly when the app name is contained in part of the controller name.
* (webapp Name) base name is 'cache' controller is 'cacheTest' action is 'cache_name'
* apps url would look something like http://localhost/cache/cacheTest/cache_name
*
* @return void
**/
public function testCacheBaseNameControllerName() {
$this->Controller->cache_parsing();
$this->Controller->cacheAction = array(
'cache_name' => 21600
);
$this->Controller->params = array(
'controller' => 'cacheTest',
'action' => 'cache_name',
'pass' => array(),
'named' => array()
);
$this->Controller->here = '/cache/cacheTest/cache_name';
$this->Controller->action = 'cache_name';
$this->Controller->base = '/cache';
$View = new View($this->Controller);
$result = $View->render('index');
$this->assertNotRegExp('/cake:nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$filename = CACHE . 'views' . DS . 'cache_cachetest_cache_name.php';
$this->assertTrue(file_exists($filename));
unlink($filename);
}
/**
* test that afterRender checks the conditions correctly.
*
* @return void
*/
public function testAfterRenderConditions() {
Configure::write('Cache.check', true);
$View = new View($this->Controller);
$View->cacheAction = '+1 day';
$View->output = 'test';
$Cache = $this->getMock('CacheHelper', array('_parseContent'), array($View));
$Cache->expects($this->once())
->method('_parseContent')
->with('posts/index', 'content')
->will($this->returnValue(''));
$Cache->afterRenderFile('posts/index', 'content');
Configure::write('Cache.check', false);
$Cache->afterRender('posts/index');
Configure::write('Cache.check', true);
$View->cacheAction = false;
$Cache->afterRender('posts/index');
}
/**
* test that afterRender checks the conditions correctly.
*
* @return void
*/
public function testAfterLayoutConditions() {
Configure::write('Cache.check', true);
$View = new View($this->Controller);
$View->cacheAction = '+1 day';
$View->output = 'test';
$Cache = $this->getMock('CacheHelper', array('cache'), array($View));
$Cache->expects($this->once())
->method('cache')
->with('posts/index', $View->output)
->will($this->returnValue(''));
$Cache->afterLayout('posts/index');
Configure::write('Cache.check', false);
$Cache->afterLayout('posts/index');
Configure::write('Cache.check', true);
$View->cacheAction = false;
$Cache->afterLayout('posts/index');
}
/**
* testCacheEmptySections method
*
* This test must be uncommented/fixed in next release (1.2+)
*
* @return void
*/
public function testCacheEmptySections() {
$this->Controller->cache_parsing();
$this->Controller->params = array(
'controller' => 'cacheTest',
'action' => 'cache_empty_sections',
'pass' => array(),
'named' => array()
);
$this->Controller->cacheAction = array('cache_empty_sections' => 21600);
$this->Controller->here = '/cacheTest/cache_empty_sections';
$this->Controller->action = 'cache_empty_sections';
$this->Controller->layout = 'cache_empty_sections';
$this->Controller->viewPath = 'Posts';
$View = new View($this->Controller);
$result = $View->render('cache_empty_sections');
$this->assertNotRegExp('/nocache/', $result);
$this->assertNotRegExp('/php echo/', $result);
$this->assertRegExp(
'@</title>\s*</head>\s*' .
'<body>\s*' .
'View Content\s*' .
'cached count is: 3\s*' .
'</body>@', $result);
$filename = CACHE . 'views' . DS . 'cachetest_cache_empty_sections.php';
$this->assertTrue(file_exists($filename));
$contents = file_get_contents($filename);
$this->assertNotRegExp('/nocache/', $contents);
$this->assertRegExp(
'@<head>\s*<title>Posts</title>\s*' .
'<\?php \$x \= 1; \?>\s*' .
'</head>\s*' .
'<body>\s*' .
'<\?php \$x\+\+; \?>\s*' .
'<\?php \$x\+\+; \?>\s*' .
'View Content\s*' .
'<\?php \$y = 1; \?>\s*' .
'<\?php echo \'cached count is: \' . \$x; \?>\s*' .
'@', $contents);
unlink($filename);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,385 @@
<?php
/**
* JqueryEngineTestCase
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.View.Helper
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('HtmlHelper', 'View/Helper');
App::uses('JsHelper', 'View/Helper');
App::uses('JqueryEngineHelper', 'View/Helper');
App::uses('View', 'View');
class JqueryEngineHelperTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = $this->getMock('View', array('addScript'), array(&$controller));
$this->Jquery = new JqueryEngineHelper($this->View);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Jquery);
}
/**
* test selector method
*
* @return void
*/
public function testSelector() {
$result = $this->Jquery->get('#content');
$this->assertEquals($this->Jquery, $result);
$this->assertEquals($this->Jquery->selection, '$("#content")');
$result = $this->Jquery->get('document');
$this->assertEquals($this->Jquery, $result);
$this->assertEquals($this->Jquery->selection, '$(document)');
$result = $this->Jquery->get('window');
$this->assertEquals($this->Jquery, $result);
$this->assertEquals($this->Jquery->selection, '$(window)');
$result = $this->Jquery->get('ul');
$this->assertEquals($this->Jquery, $result);
$this->assertEquals($this->Jquery->selection, '$("ul")');
}
/**
* test event binding
*
* @return void
*/
public function testEvent() {
$this->Jquery->get('#myLink');
$result = $this->Jquery->event('click', 'doClick', array('wrap' => false));
$expected = '$("#myLink").bind("click", doClick);';
$this->assertEquals($expected, $result);
$result = $this->Jquery->event('click', '$(this).show();', array('stop' => false));
$expected = '$("#myLink").bind("click", function (event) {$(this).show();});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->event('click', '$(this).hide();');
$expected = '$("#myLink").bind("click", function (event) {$(this).hide();' . "\n" . 'return false;});';
$this->assertEquals($expected, $result);
}
/**
* test dom ready event creation
*
* @return void
*/
public function testDomReady() {
$result = $this->Jquery->domReady('foo.name = "bar";');
$expected = '$(document).ready(function () {foo.name = "bar";});';
$this->assertEquals($expected, $result);
}
/**
* test Each method
*
* @return void
*/
public function testEach() {
$this->Jquery->get('#foo');
$result = $this->Jquery->each('$(this).hide();');
$expected = '$("#foo").each(function () {$(this).hide();});';
$this->assertEquals($expected, $result);
}
/**
* test Effect generation
*
* @return void
*/
public function testEffect() {
$this->Jquery->get('#foo');
$result = $this->Jquery->effect('show');
$expected = '$("#foo").show();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('hide');
$expected = '$("#foo").hide();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('hide', array('speed' => 'fast'));
$expected = '$("#foo").hide("fast");';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('fadeIn');
$expected = '$("#foo").fadeIn();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('fadeOut');
$expected = '$("#foo").fadeOut();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('slideIn');
$expected = '$("#foo").slideDown();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('slideOut');
$expected = '$("#foo").slideUp();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('slideDown');
$expected = '$("#foo").slideDown();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->effect('slideUp');
$expected = '$("#foo").slideUp();';
$this->assertEquals($expected, $result);
}
/**
* Test Request Generation
*
* @return void
*/
public function testRequest() {
$result = $this->Jquery->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = '$.ajax({url:"\\/posts\\/view\\/1"});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->request(array('controller' => 'posts', 'action' => 'view', 1), array(
'update' => '#content'
));
$expected = '$.ajax({dataType:"html", success:function (data, textStatus) {$("#content").html(data);}, url:"\/posts\/view\/1"});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = '$.ajax({beforeSend:doBefore, complete:doComplete, data:"name=jim&height=185cm", dataType:"json", error:handleError, success:doSuccess, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'wrapCallbacks' => false
));
$expected = '$.ajax({dataType:"html", success:function (data, textStatus) {doFoo$("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'dataExpression' => true,
'data' => '$("#someId").serialize()',
'wrapCallbacks' => false
));
$expected = '$.ajax({data:$("#someId").serialize(), dataType:"html", success:function (data, textStatus) {doFoo$("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->request('/people/edit/1', array(
'success' => 'doFoo',
'before' => 'doBefore',
'method' => 'post',
'dataExpression' => true,
'data' => '$("#someId").serialize()',
));
$expected = '$.ajax({beforeSend:function (XMLHttpRequest) {doBefore}, data:$("#someId").serialize(), success:function (data, textStatus) {doFoo}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEquals($expected, $result);
}
/**
* Test that querystring arguments are not double escaped.
*
* @return void
*/
public function testRequestWithQueryStringArguments() {
$url = '/users/search/sort:User.name/direction:desc?nome=&cpm=&audience=public';
$result = $this->Jquery->request($url);
$expected = '$.ajax({url:"\\/users\\/search\\/sort:User.name\\/direction:desc?nome=&cpm=&audience=public"});';
$this->assertEquals($expected, $result);
}
/**
* test that alternate jQuery object values work for request()
*
* @return void
*/
public function testRequestWithAlternateJqueryObject() {
$this->Jquery->jQueryObject = '$j';
$result = $this->Jquery->request('/people/edit/1', array(
'update' => '#updated',
'success' => 'doFoo',
'method' => 'post',
'dataExpression' => true,
'data' => '$j("#someId").serialize()',
'wrapCallbacks' => false
));
$expected = '$j.ajax({data:$j("#someId").serialize(), dataType:"html", success:function (data, textStatus) {doFoo$j("#updated").html(data);}, type:"post", url:"\\/people\\/edit\\/1"});';
$this->assertEquals($expected, $result);
}
/**
* test sortable list generation
*
* @return void
*/
public function testSortable() {
$this->Jquery->get('#myList');
$result = $this->Jquery->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = '$("#myList").sortable({containment:"parent", distance:5, sort:onSort, start:onStart, stop:onStop});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
));
$expected = '$("#myList").sortable({containment:"parent", distance:5, sort:function (event, ui) {onSort}, start:function (event, ui) {onStart}, stop:function (event, ui) {onStop}});';
$this->assertEquals($expected, $result);
}
/**
* test drag() method
*
* @return void
*/
public function testDrag() {
$this->Jquery->get('#element');
$result = $this->Jquery->drag(array(
'container' => '#content',
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = '$("#element").draggable({containment:"#content", drag:onDrag, grid:[10,10], start:onStart, stop:onStop});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->drag(array(
'container' => '#content',
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
));
$expected = '$("#element").draggable({containment:"#content", drag:function (event, ui) {onDrag}, grid:[10,10], start:function (event, ui) {onStart}, stop:function (event, ui) {onStop}});';
$this->assertEquals($expected, $result);
}
/**
* test drop() method
*
* @return void
*/
public function testDrop() {
$this->Jquery->get('#element');
$result = $this->Jquery->drop(array(
'accept' => '.items',
'hover' => 'onHover',
'leave' => 'onExit',
'drop' => 'onDrop',
'wrapCallbacks' => false
));
$expected = '$("#element").droppable({accept:".items", drop:onDrop, out:onExit, over:onHover});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->drop(array(
'accept' => '.items',
'hover' => 'onHover',
'leave' => 'onExit',
'drop' => 'onDrop',
));
$expected = '$("#element").droppable({accept:".items", drop:function (event, ui) {onDrop}, out:function (event, ui) {onExit}, over:function (event, ui) {onHover}});';
$this->assertEquals($expected, $result);
}
/**
* test slider generation
*
* @return void
*/
public function testSlider() {
$this->Jquery->get('#element');
$result = $this->Jquery->slider(array(
'complete' => 'onComplete',
'change' => 'onChange',
'min' => 0,
'max' => 10,
'value' => 2,
'direction' => 'vertical',
'wrapCallbacks' => false
));
$expected = '$("#element").slider({change:onChange, max:10, min:0, orientation:"vertical", stop:onComplete, value:2});';
$this->assertEquals($expected, $result);
$result = $this->Jquery->slider(array(
'complete' => 'onComplete',
'change' => 'onChange',
'min' => 0,
'max' => 10,
'value' => 2,
'direction' => 'vertical',
));
$expected = '$("#element").slider({change:function (event, ui) {onChange}, max:10, min:0, orientation:"vertical", stop:function (event, ui) {onComplete}, value:2});';
$this->assertEquals($expected, $result);
}
/**
* test the serializeForm method
*
* @return void
*/
public function testSerializeForm() {
$this->Jquery->get('#element');
$result = $this->Jquery->serializeForm(array('isForm' => false));
$expected = '$("#element").closest("form").serialize();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->serializeForm(array('isForm' => true));
$expected = '$("#element").serialize();';
$this->assertEquals($expected, $result);
$result = $this->Jquery->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$("#element").closest("form").serialize()';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,940 @@
<?php
/**
* JsHelper Test Case
*
* TestCase for the JsHelper
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.3
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('HtmlHelper', 'View/Helper');
App::uses('JsHelper', 'View/Helper');
App::uses('JsBaseEngineHelper', 'View/Helper');
App::uses('FormHelper', 'View/Helper');
App::uses('View', 'View');
App::uses('ClassRegistry', 'Utility');
class JsEncodingObject {
protected $_title = 'Old thing';
//@codingStandardsIgnoreStart
private $__noshow = 'Never ever';
//@codingStandardsIgnoreEnd
}
class OptionEngineHelper extends JsBaseEngineHelper {
protected $_optionMap = array(
'request' => array(
'complete' => 'success',
'request' => 'beforeSend',
'type' => 'dataType'
)
);
/**
* test method for testing option mapping
*
* @return array
*/
public function testMap($options = array()) {
return $this->_mapOptions('request', $options);
}
/**
* test method for option parsing
*
* @return void
*/
public function testParseOptions($options, $safe = array()) {
return $this->_parseOptions($options, $safe);
}
public function get($selector) {
}
public function event($type, $callback, $options = array()) {
}
public function domReady($functionBody) {
}
public function each($callback) {
}
public function effect($name, $options = array()) {
}
public function request($url, $options = array()) {
}
public function drag($options = array()) {
}
public function drop($options = array()) {
}
public function sortable($options = array()) {
}
public function slider($options = array()) {
}
public function serializeForm($options = array()) {
}
}
/**
* JsHelper TestCase.
*
* @package Cake.Test.Case.View.Helper
*/
class JsHelperTest extends CakeTestCase {
/**
* Regexp for CDATA start block
*
* @var string
*/
public $cDataStart = 'preg:/^\/\/<!\[CDATA\[[\n\r]*/';
/**
* Regexp for CDATA end block
*
* @var string
*/
public $cDataEnd = 'preg:/[^\]]*\]\]\>[\s\r\n]*/';
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
Configure::write('Asset.timestamp', false);
$controller = null;
$this->View = $this->getMock('View', array('append'), array(&$controller));
$this->Js = new JsHelper($this->View, 'Option');
$request = new CakeRequest(null, false);
$this->Js->request = $request;
$this->Js->Html = new HtmlHelper($this->View);
$this->Js->Html->request = $request;
$this->Js->Form = new FormHelper($this->View);
$this->Js->Form->request = $request;
$this->Js->Form->Html = $this->Js->Html;
$this->Js->OptionEngine = new OptionEngineHelper($this->View);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Js);
}
/**
* Switches $this->Js to a mocked engine.
*
* @return void
*/
protected function _useMock() {
$request = new CakeRequest(null, false);
if (!class_exists('TestJsEngineHelper', false)) {
$this->getMock('JsBaseEngineHelper', array(), array($this->View), 'TestJsEngineHelper');
}
$this->Js = new JsHelper($this->View, array('TestJs'));
$this->Js->TestJsEngine = new TestJsEngineHelper($this->View);
$this->mockObjects[] = $this->Js->TestJsEngine;
$this->Js->request = $request;
$this->Js->Html = new HtmlHelper($this->View);
$this->Js->Html->request = $request;
$this->Js->Form = new FormHelper($this->View);
$this->Js->Form->request = $request;
$this->Js->Form->Html = new HtmlHelper($this->View);
}
/**
* test object construction
*
* @return void
*/
public function testConstruction() {
$js = new JsHelper($this->View);
$this->assertEquals(array('Html', 'Form', 'JqueryEngine'), $js->helpers);
$js = new JsHelper($this->View, array('mootools'));
$this->assertEquals(array('Html', 'Form', 'mootoolsEngine'), $js->helpers);
$js = new JsHelper($this->View, 'prototype');
$this->assertEquals(array('Html', 'Form', 'prototypeEngine'), $js->helpers);
$js = new JsHelper($this->View, 'MyPlugin.Dojo');
$this->assertEquals(array('Html', 'Form', 'MyPlugin.DojoEngine'), $js->helpers);
}
/**
* test that methods dispatch internally and to the engine class
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testMethodDispatching() {
$this->_useMock();
$this->Js->TestJsEngine
->expects($this->once())
->method('event')
->with('click', 'callback');
$this->Js->event('click', 'callback');
$this->Js->TestJsEngine = new StdClass();
$this->Js->someMethodThatSurelyDoesntExist();
}
/**
* Test that method dispatching for events respects buffer parameters and bufferedMethods Lists.
*
* @return void
*/
public function testEventDispatchWithBuffering() {
$this->_useMock();
$this->Js->TestJsEngine->bufferedMethods = array('event', 'sortables');
$this->Js->TestJsEngine->expects($this->exactly(3))
->method('event')
->will($this->returnValue('This is an event call'));
$this->Js->event('click', 'foo');
$result = $this->Js->getBuffer();
$this->assertEquals(1, count($result));
$this->assertEquals('This is an event call', $result[0]);
$result = $this->Js->event('click', 'foo', array('buffer' => false));
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEquals('This is an event call', $result);
$result = $this->Js->event('click', 'foo', false);
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEquals('This is an event call', $result);
}
/**
* Test that method dispatching for effects respects buffer parameters and bufferedMethods Lists.
*
* @return void
*/
public function testEffectDispatchWithBuffering() {
$this->_useMock();
$this->Js->TestJsEngine->expects($this->exactly(4))
->method('effect')
->will($this->returnValue('I am not buffered.'));
$result = $this->Js->effect('slideIn');
$buffer = $this->Js->getBuffer();
$this->assertTrue(empty($buffer));
$this->assertEquals('I am not buffered.', $result);
$result = $this->Js->effect('slideIn', true);
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEquals(1, count($buffer));
$this->assertEquals('I am not buffered.', $buffer[0]);
$result = $this->Js->effect('slideIn', array('speed' => 'slow'), true);
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEquals(1, count($buffer));
$this->assertEquals('I am not buffered.', $buffer[0]);
$result = $this->Js->effect('slideIn', array('speed' => 'slow', 'buffer' => true));
$buffer = $this->Js->getBuffer();
$this->assertNull($result);
$this->assertEquals(1, count($buffer));
$this->assertEquals('I am not buffered.', $buffer[0]);
}
/**
* test that writeScripts generates scripts inline.
*
* @return void
*/
public function testWriteScriptsNoFile() {
$this->_useMock();
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'cache' => false, 'clear' => false));
$expected = array(
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
"one = 1;\ntwo = 2;",
$this->cDataEnd,
'/script',
);
$this->assertTags($result, $expected);
$this->Js->TestJsEngine->expects($this->atLeastOnce())->method('domReady');
$result = $this->Js->writeBuffer(array('onDomReady' => true, 'cache' => false, 'clear' => false));
$this->View->expects($this->once())
->method('append')
->with('script', $this->matchesRegularExpression('/one\s\=\s1;\ntwo\s\=\s2;/'));
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'cache' => false));
}
/**
* test that writing the buffer with inline = false includes a script tag.
*
* @return void
*/
public function testWriteBufferNotInline() {
$this->Js->set('foo', 1);
$this->View->expects($this->once())
->method('append')
->with('script', $this->matchesRegularExpression('#<script type="text\/javascript">window.app \= \{"foo"\:1\}\;<\/script>#'));
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'inline' => false, 'safe' => false));
}
/**
* test that writeBuffer() sets domReady = false when the request is done by XHR.
* Including a domReady() when in XHR can cause issues as events aren't triggered by some libraries
*
* @return void
*/
public function testWriteBufferAndXhr() {
$this->_useMock();
$requestWith = null;
if (isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
$requestWith = $_SERVER['HTTP_X_REQUESTED_WITH'];
}
$_SERVER['HTTP_X_REQUESTED_WITH'] = 'XMLHttpRequest';
$this->Js->buffer('alert("test");');
$this->Js->TestJsEngine->expects($this->never())->method('domReady');
$result = $this->Js->writeBuffer();
unset($_SERVER['HTTP_X_REQUESTED_WITH']);
if ($requestWith !== null) {
$_SERVER['HTTP_X_REQUESTED_WITH'] = $requestWith;
}
}
/**
* test that writeScripts makes files, and puts the events into them.
*
* @return void
*/
public function testWriteScriptsInFile() {
$this->skipIf(!is_writable(JS), 'webroot/js is not Writable, script caching test has been skipped.');
Configure::write('Cache.disable', false);
$this->Js->request->webroot = '/';
$this->Js->JsBaseEngine = new TestJsEngineHelper($this->View);
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'cache' => true));
$expected = array(
'script' => array('type' => 'text/javascript', 'src' => 'preg:/(.)*\.js/'),
);
$this->assertTags($result, $expected);
preg_match('/src="(.*\.js)"/', $result, $filename);
$this->assertTrue(file_exists(WWW_ROOT . $filename[1]));
$contents = file_get_contents(WWW_ROOT . $filename[1]);
$this->assertRegExp('/one\s=\s1;\ntwo\s=\s2;/', $contents);
if (file_exists(WWW_ROOT . $filename[1])) {
unlink(WWW_ROOT . $filename[1]);
}
Configure::write('Cache.disable', true);
$this->Js->buffer('one = 1;');
$this->Js->buffer('two = 2;');
$result = $this->Js->writeBuffer(array('onDomReady' => false, 'cache' => true));
$this->assertRegExp('/one\s=\s1;\ntwo\s=\s2;/', $result);
$this->assertFalse(file_exists(WWW_ROOT . $filename[1]));
}
/**
* test link()
*
* @return void
*/
public function testLinkWithMock() {
$this->_useMock();
$options = array('update' => '#content');
$this->Js->TestJsEngine->expects($this->at(0))
->method('get');
$this->Js->TestJsEngine->expects($this->at(1))
->method('request')
->with('/posts/view/1', $options)
->will($this->returnValue('--ajax code--'));
$this->Js->TestJsEngine->expects($this->at(2))
->method('event')
->with('click', '--ajax code--', $options + array('buffer' => null));
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* test link with a mock and confirmation
*
* @return void
*/
public function testLinkWithMockAndConfirm() {
$this->_useMock();
$options = array(
'confirm' => 'Are you sure?',
'update' => '#content',
'class' => 'my-class',
'id' => 'custom-id',
'escape' => false
);
$this->Js->TestJsEngine->expects($this->once())
->method('confirmReturn')
->with($options['confirm'])
->will($this->returnValue('--confirm script--'));
$this->Js->TestJsEngine->expects($this->once())
->method('request')
->with('/posts/view/1');
$this->Js->TestJsEngine->expects($this->once())
->method('event')
->with('click', '--confirm script--');
$result = $this->Js->link('test link »', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => $options['id'], 'class' => $options['class'], 'href' => '/posts/view/1'),
'test link »',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* test link passing on htmlAttributes
*
* @return void
*/
public function testLinkWithAribtraryAttributes() {
$this->_useMock();
$options = array('id' => 'something', 'htmlAttributes' => array('arbitrary' => 'value', 'batman' => 'robin'));
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => $options['id'], 'href' => '/posts/view/1', 'arbitrary' => 'value',
'batman' => 'robin'),
'test link',
'/a'
);
$this->assertTags($result, $expected);
}
/**
* test that link() and no buffering returns an <a> and <script> tags.
*
* @return void
*/
public function testLinkWithNoBuffering() {
$this->_useMock();
$this->Js->TestJsEngine->expects($this->at(1))
->method('request')
->with('/posts/view/1', array('update' => '#content'))
->will($this->returnValue('ajax code'));
$this->Js->TestJsEngine->expects($this->at(2))
->method('event')
->will($this->returnValue('-event handler-'));
$options = array('update' => '#content', 'buffer' => false);
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a',
'script' => array('type' => 'text/javascript'),
$this->cDataStart,
'-event handler-',
$this->cDataEnd,
'/script'
);
$this->assertTags($result, $expected);
}
/**
* test link with buffering off and safe on.
*
* @return void
*/
public function testLinkWithNoBufferingAndSafe() {
$this->_useMock();
$this->Js->TestJsEngine->expects($this->at(1))
->method('request')
->with('/posts/view/1', array('update' => '#content'))
->will($this->returnValue('ajax code'));
$this->Js->TestJsEngine->expects($this->at(2))
->method('event')
->will($this->returnValue('-event handler-'));
$options = array('update' => '#content', 'buffer' => false, 'safe' => false);
$result = $this->Js->link('test link', '/posts/view/1', $options);
$expected = array(
'a' => array('id' => 'preg:/link-\d+/', 'href' => '/posts/view/1'),
'test link',
'/a',
'script' => array('type' => 'text/javascript'),
'-event handler-',
'/script'
);
$this->assertTags($result, $expected);
}
/**
* test submit() with a Mock to check Engine method calls
*
* @return void
*/
public function testSubmitWithMock() {
$this->_useMock();
$options = array('update' => '#content', 'id' => 'test-submit', 'style' => 'margin: 0');
$this->Js->TestJsEngine->expects($this->at(0))
->method('get');
$this->Js->TestJsEngine->expects($this->at(1))
->method('serializeForm')
->will($this->returnValue('serialize-code'));
$this->Js->TestJsEngine->expects($this->at(2))
->method('request')
->will($this->returnValue('ajax-code'));
$params = array(
'update' => $options['update'], 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => null
);
$this->Js->TestJsEngine->expects($this->at(3))
->method('event')
->with('click', "ajax-code", $params);
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save', 'style' => 'margin: 0'),
'/div'
);
$this->assertTags($result, $expected);
}
/**
* test submit() with a mock
*
* @return void
*/
public function testSubmitWithMockRequestParams() {
$this->_useMock();
$this->Js->TestJsEngine->expects($this->at(0))
->method('get');
$this->Js->TestJsEngine->expects($this->at(1))
->method('serializeForm')
->will($this->returnValue('serialize-code'));
$requestParams = array(
'update' => '#content',
'data' => 'serialize-code',
'method' => 'post',
'dataExpression' => true
);
$this->Js->TestJsEngine->expects($this->at(2))
->method('request')
->with('/custom/url', $requestParams)
->will($this->returnValue('ajax-code'));
$params = array(
'update' => '#content', 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => null
);
$this->Js->TestJsEngine->expects($this->at(3))
->method('event')
->with('click', "ajax-code", $params);
$options = array('update' => '#content', 'id' => 'test-submit', 'url' => '/custom/url');
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save'),
'/div'
);
$this->assertTags($result, $expected);
}
/**
* test that no buffer works with submit() and that parameters are leaking into the script tag.
*
* @return void
*/
public function testSubmitWithNoBuffer() {
$this->_useMock();
$options = array('update' => '#content', 'id' => 'test-submit', 'buffer' => false, 'safe' => false);
$this->Js->TestJsEngine->expects($this->at(0))
->method('get');
$this->Js->TestJsEngine->expects($this->at(1))
->method('serializeForm')
->will($this->returnValue('serialize-code'));
$this->Js->TestJsEngine->expects($this->at(2))
->method('request')
->will($this->returnValue('ajax-code'));
$this->Js->TestJsEngine->expects($this->at(3))
->method('event')
->will($this->returnValue('event-handler'));
$params = array(
'update' => $options['update'], 'data' => 'serialize-code',
'method' => 'post', 'dataExpression' => true, 'buffer' => false
);
$this->Js->TestJsEngine->expects($this->at(3))
->method('event')
->with('click', "ajax-code", $params);
$result = $this->Js->submit('Save', $options);
$expected = array(
'div' => array('class' => 'submit'),
'input' => array('type' => 'submit', 'id' => $options['id'], 'value' => 'Save'),
'/div',
'script' => array('type' => 'text/javascript'),
'event-handler',
'/script'
);
$this->assertTags($result, $expected);
}
/**
* Test that Object::Object() is not breaking json output in JsHelper
*
* @return void
*/
public function testObjectPassThrough() {
$result = $this->Js->object(array('one' => 'first', 'two' => 'second'));
$expected = '{"one":"first","two":"second"}';
$this->assertEquals($expected, $result);
}
/**
* Test that inherited Helper::value() is overwritten in JsHelper::value()
* and calls JsBaseEngineHelper::value().
*
* @return void
*/
public function testValuePassThrough() {
$result = $this->Js->value('string "quote"', true);
$expected = '"string \"quote\""';
$this->assertEquals($expected, $result);
}
/**
* test set()'ing variables to the Javascript buffer and controlling the output var name.
*
* @return void
*/
public function testSet() {
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$result = $this->Js->getBuffer();
$expected = 'window.app = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEquals($expected, $result[0]);
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->setVariable = 'WICKED';
$result = $this->Js->getBuffer();
$expected = 'window.WICKED = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEquals($expected, $result[0]);
$this->Js->set('loggedIn', true);
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->setVariable = 'Application.variables';
$result = $this->Js->getBuffer();
$expected = 'Application.variables = {"loggedIn":true,"height":"tall","color":"purple"};';
$this->assertEquals($expected, $result[0]);
}
/**
* test that vars set with Js->set() go to the top of the buffered scripts list.
*
* @return void
*/
public function testSetVarsAtTopOfBufferedScripts() {
$this->Js->set(array('height' => 'tall', 'color' => 'purple'));
$this->Js->alert('hey you!', array('buffer' => true));
$this->Js->confirm('Are you sure?', array('buffer' => true));
$result = $this->Js->getBuffer(false);
$expected = 'window.app = {"height":"tall","color":"purple"};';
$this->assertEquals($expected, $result[0]);
$this->assertEquals('alert("hey you!");', $result[1]);
$this->assertEquals('confirm("Are you sure?");', $result[2]);
}
}
/**
* JsBaseEngine Class Test case
*
* @package Cake.Test.Case.View.Helper
*/
class JsBaseEngineTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = $this->getMock('View', array('append'), array(&$controller));
$this->JsEngine = new OptionEngineHelper($this->View);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->JsEngine);
}
/**
* test escape string skills
*
* @return void
*/
public function testEscaping() {
$result = $this->JsEngine->escape('');
$expected = '';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->escape('CakePHP' . "\n" . 'Rapid Development Framework');
$expected = 'CakePHP\\nRapid Development Framework';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->escape('CakePHP' . "\r\n" . 'Rapid Development Framework' . "\r" . 'For PHP');
$expected = 'CakePHP\\r\\nRapid Development Framework\\rFor PHP';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->escape('CakePHP: "Rapid Development Framework"');
$expected = 'CakePHP: \\"Rapid Development Framework\\"';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->escape("CakePHP: 'Rapid Development Framework'");
$expected = "CakePHP: 'Rapid Development Framework'";
$this->assertEquals($expected, $result);
$result = $this->JsEngine->escape('my \\"string\\"');
$expected = 'my \\\\\\"string\\\\\\"';
$this->assertEquals($expected, $result);
}
/**
* test prompt() creation
*
* @return void
*/
public function testPrompt() {
$result = $this->JsEngine->prompt('Hey, hey you', 'hi!');
$expected = 'prompt("Hey, hey you", "hi!");';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->prompt('"Hey"', '"hi"');
$expected = 'prompt("\"Hey\"", "\"hi\"");';
$this->assertEquals($expected, $result);
}
/**
* test alert generation
*
* @return void
*/
public function testAlert() {
$result = $this->JsEngine->alert('Hey there');
$expected = 'alert("Hey there");';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->alert('"Hey"');
$expected = 'alert("\"Hey\"");';
$this->assertEquals($expected, $result);
}
/**
* test confirm generation
*
* @return void
*/
public function testConfirm() {
$result = $this->JsEngine->confirm('Are you sure?');
$expected = 'confirm("Are you sure?");';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->confirm('"Are you sure?"');
$expected = 'confirm("\"Are you sure?\"");';
$this->assertEquals($expected, $result);
}
/**
* test Redirect
*
* @return void
*/
public function testRedirect() {
$result = $this->JsEngine->redirect(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'window.location = "/posts/view/1";';
$this->assertEquals($expected, $result);
}
/**
* testObject encoding with non-native methods.
*
* @return void
*/
public function testObject() {
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8));
$result = $this->JsEngine->object($object);
$expected = '{"title":"New thing","indexes":[5,6,7,8]}';
$this->assertEquals($expected, $result);
$object = new JsEncodingObject();
$object->title = 'New thing';
$object->indexes = array(5,6,7,8);
$result = $this->JsEngine->object($object);
$this->assertEquals($expected, $result);
$result = $this->JsEngine->object(array('default' => 0));
$expected = '{"default":0}';
$this->assertEquals($expected, $result);
$result = $this->JsEngine->object(array(
'2007' => array(
'Spring' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
),
'Fall' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
)
),
'2006' => array(
'Spring' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
),
'Fall' => array(
'1' => array('id' => 1, 'name' => 'Josh'), '2' => array('id' => 2, 'name' => 'Becky')
)
)
));
$expected = '{"2007":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}},"2006":{"Spring":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}},"Fall":{"1":{"id":1,"name":"Josh"},"2":{"id":2,"name":"Becky"}}}}';
$this->assertEquals($expected, $result);
foreach (array('true' => true, 'false' => false, 'null' => null) as $expected => $data) {
$result = $this->JsEngine->object($data);
$this->assertEquals($expected, $result);
}
$object = array('title' => 'New thing', 'indexes' => array(5, 6, 7, 8), 'object' => array('inner' => array('value' => 1)));
$result = $this->JsEngine->object($object, array('prefix' => 'PREFIX', 'postfix' => 'POSTFIX'));
$this->assertRegExp('/^PREFIX/', $result);
$this->assertRegExp('/POSTFIX$/', $result);
$this->assertNotRegExp('/.PREFIX./', $result);
$this->assertNotRegExp('/.POSTFIX./', $result);
}
/**
* test Mapping of options.
*
* @return void
*/
public function testOptionMapping() {
$JsEngine = new OptionEngineHelper($this->View);
$result = $JsEngine->testMap();
$this->assertSame(array(), $result);
$result = $JsEngine->testMap(array('foo' => 'bar', 'baz' => 'sho'));
$this->assertEquals(array('foo' => 'bar', 'baz' => 'sho'), $result);
$result = $JsEngine->testMap(array('complete' => 'myFunc', 'type' => 'json', 'update' => '#element'));
$this->assertEquals(array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'), $result);
$result = $JsEngine->testMap(array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'));
$this->assertEquals(array('success' => 'myFunc', 'dataType' => 'json', 'update' => '#element'), $result);
}
/**
* test that option parsing escapes strings and saves what is supposed to be saved.
*
* @return void
*/
public function testOptionParsing() {
$JsEngine = new OptionEngineHelper($this->View);
$result = $JsEngine->testParseOptions(array('url' => '/posts/view/1', 'key' => 1));
$expected = 'key:1, url:"\\/posts\\/view\\/1"';
$this->assertEquals($expected, $result);
$result = $JsEngine->testParseOptions(array('url' => '/posts/view/1', 'success' => 'doSuccess'), array('success'));
$expected = 'success:doSuccess, url:"\\/posts\\/view\\/1"';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,378 @@
<?php
/**
* MooEngineTestCase
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.View.Helper
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('HtmlHelper', 'View/Helper');
App::uses('JsHelper', 'View/Helper');
App::uses('MootoolsEngineHelper', 'View/Helper');
class MootoolsEngineHelperTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = $this->getMock('View', array('addScript'), array(&$controller));
$this->Moo = new MootoolsEngineHelper($this->View);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Moo);
}
/**
* test selector method
*
* @return void
*/
public function testSelector() {
$result = $this->Moo->get('#content');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, '$("content")');
$result = $this->Moo->get('a .remove');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, '$$("a .remove")');
$result = $this->Moo->get('document');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, "$(document)");
$result = $this->Moo->get('window');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, "$(window)");
$result = $this->Moo->get('ul');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, '$$("ul")');
$result = $this->Moo->get('#some_long-id.class');
$this->assertEquals($this->Moo, $result);
$this->assertEquals($this->Moo->selection, '$$("#some_long-id.class")');
}
/**
* test event binding
*
* @return void
*/
public function testEvent() {
$this->Moo->get('#myLink');
$result = $this->Moo->event('click', 'doClick', array('wrap' => false));
$expected = '$("myLink").addEvent("click", doClick);';
$this->assertEquals($expected, $result);
$result = $this->Moo->event('click', 'this.setStyle("display", "");', array('stop' => false));
$expected = '$("myLink").addEvent("click", function (event) {this.setStyle("display", "");});';
$this->assertEquals($expected, $result);
$result = $this->Moo->event('click', 'this.setStyle("display", "none");');
$expected = "\$(\"myLink\").addEvent(\"click\", function (event) {event.stop();\nthis.setStyle(\"display\", \"none\");});";
$this->assertEquals($expected, $result);
}
/**
* test dom ready event creation
*
* @return void
*/
public function testDomReady() {
$result = $this->Moo->domReady('foo.name = "bar";');
$expected = 'window.addEvent("domready", function (event) {foo.name = "bar";});';
$this->assertEquals($expected, $result);
}
/**
* test Each method
*
* @return void
*/
public function testEach() {
$this->Moo->get('#foo');
$result = $this->Moo->each('item.setStyle("display", "none");');
$expected = '$("foo").each(function (item, index) {item.setStyle("display", "none");});';
$this->assertEquals($expected, $result);
}
/**
* test Effect generation
*
* @return void
*/
public function testEffect() {
$this->Moo->get('#foo');
$result = $this->Moo->effect('show');
$expected = '$("foo").setStyle("display", "");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('hide');
$expected = '$("foo").setStyle("display", "none");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('fadeIn');
$expected = '$("foo").fade("in");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('fadeOut');
$expected = '$("foo").fade("out");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('slideIn');
$expected = '$("foo").slide("in");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('slideOut');
$expected = '$("foo").slide("out");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('slideOut', array('speed' => 'fast'));
$expected = '$("foo").set("slide", {duration:"short"}).slide("out");';
$this->assertEquals($expected, $result);
$result = $this->Moo->effect('slideOut', array('speed' => 'slow'));
$expected = '$("foo").set("slide", {duration:"long"}).slide("out");';
$this->assertEquals($expected, $result);
}
/**
* Test Request Generation
*
* @return void
*/
public function testRequest() {
$result = $this->Moo->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'var jsRequest = new Request({url:"\\/posts\\/view\\/1"}).send();';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/posts/view/1', array('update' => 'content'));
$expected = 'var jsRequest = new Request.HTML({update:"content", url:"\\/posts\\/view\\/1"}).send();';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.JSON({method:"post", onComplete:doSuccess, onFailure:handleError, url:"\\/people\\/edit\\/1"}).send({"name":"jim","height":"185cm"});';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'update' => '#update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'doFailure',
'before' => 'doBefore',
'update' => 'update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doComplete, onFailure:doFailure, onRequest:doBefore, onSuccess:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doComplete',
'success' => 'doSuccess',
'error' => 'doFailure',
'before' => 'doBefore',
'update' => 'update-zone',
'dataExpression' => true,
'data' => '$("foo").toQueryString()',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:doComplete, onFailure:doFailure, onRequest:doBefore, onSuccess:doSuccess, update:"update-zone", url:"\\/people\\/edit\\/1"}).send($("foo").toQueryString());';
$this->assertEquals($expected, $result);
$result = $this->Moo->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore',
'success' => 'doSuccess',
'complete' => 'doComplete',
'update' => '#update-zone',
));
$expected = 'var jsRequest = new Request.HTML({method:"post", onComplete:function () {doComplete}, onRequest:function () {doBefore}, onSuccess:function (responseText, responseXML) {doSuccess}, update:"update-zone", url:"\\/people\\/edit\\/1"}).send();';
$this->assertEquals($expected, $result);
}
/**
* test sortable list generation
*
* @return void
*/
public function testSortable() {
$this->Moo->get('#myList');
$result = $this->Moo->sortable(array(
'distance' => 5,
'containment' => 'parent',
'start' => 'onStart',
'complete' => 'onStop',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = 'var jsSortable = new Sortables($("myList"), {constrain:"parent", onComplete:onStop, onSort:onSort, onStart:onStart, snap:5});';
$this->assertEquals($expected, $result);
}
/**
* test drag() method
*
* @return void
*/
public function testDrag() {
$this->Moo->get('#drag-me');
$result = $this->Moo->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10,10),
'wrapCallbacks' => false
));
$expected = '$("drag-me").makeDraggable({onComplete:onStop, onDrag:onDrag, onStart:onStart, snap:[10,10]});';
$this->assertEquals($expected, $result);
}
/**
* test drop() method with the required drag option missing
*
* @expectedException PHPUnit_Framework_Error_Warning
* @return void
*/
public function testDropWithMissingOption() {
$this->Moo->get('#drop-me');
$this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
));
}
/**
* test drop() method
*
* @return void
*/
public function testDrop() {
$this->Moo->get('#drop-me');
$result = $this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
'drag' => '#my-drag',
'wrapCallbacks' => false
));
$expected = '$("my-drag").makeDraggable({droppables:$("drop-me"), onDrop:onDrop, onEnter:onHover, onLeave:onLeave});';
$this->assertEquals($expected, $result);
$this->assertEquals($this->Moo->selection, '$("drop-me")');
$result = $this->Moo->drop(array(
'drop' => 'onDrop',
'leave' => 'onLeave',
'hover' => 'onHover',
'drag' => '#my-drag',
));
$expected = '$("my-drag").makeDraggable({droppables:$("drop-me"), onDrop:function (element, droppable, event) {onDrop}, onEnter:function (element, droppable) {onHover}, onLeave:function (element, droppable) {onLeave}});';
$this->assertEquals($expected, $result);
}
/**
* test slider generation
*
* @return void
*/
public function testSlider() {
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'onComplete',
'change' => 'onChange',
'direction' => 'horizontal',
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:onChange, onComplete:onComplete});';
$this->assertEquals($expected, $result);
$this->assertEquals($this->Moo->selection, '$("slider")');
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'onComplete',
'change' => 'onChange',
'direction' => 'horizontal',
'min' => 10,
'max' => 40,
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:onChange, onComplete:onComplete, range:[10,40]});';
$this->assertEquals($expected, $result);
$this->Moo->get('#slider');
$result = $this->Moo->slider(array(
'handle' => '#my-handle',
'complete' => 'complete;',
'change' => 'change;',
'direction' => 'horizontal',
));
$expected = 'var jsSlider = new Slider($("slider"), $("my-handle"), {mode:"horizontal", onChange:function (step) {change;}, onComplete:function (event) {complete;}});';
$this->assertEquals($expected, $result);
}
/**
* test the serializeForm implementation.
*
* @return void
*/
public function testSerializeForm() {
$this->Moo->get('#element');
$result = $this->Moo->serializeForm(array('isForm' => true));
$expected = '$("element").toQueryString();';
$this->assertEquals($expected, $result);
$result = $this->Moo->serializeForm(array('isForm' => true, 'inline' => true));
$expected = '$("element").toQueryString()';
$this->assertEquals($expected, $result);
$result = $this->Moo->serializeForm(array('isForm' => false));
$expected = '$($("element").form).toQueryString();';
$this->assertEquals($expected, $result);
$result = $this->Moo->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$($("element").form).toQueryString()';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,107 @@
<?php
/**
* NumberHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('NumberHelper', 'View/Helper');
/**
* NumberHelperTestObject class
*/
class NumberHelperTestObject extends NumberHelper {
public function attach(CakeNumberMock $cakeNumber) {
$this->_engine = $cakeNumber;
}
public function engine() {
return $this->_engine;
}
}
/**
* CakeNumberMock class
*/
class CakeNumberMock {
}
/**
* NumberHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class NumberHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->View = new View(null);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->View);
}
/**
* test CakeNumber class methods are called correctly
*/
public function testNumberHelperProxyMethodCalls() {
$methods = array(
'precision', 'toReadableSize', 'toPercentage', 'format',
'currency', 'addFormat',
);
$CakeNumber = $this->getMock('CakeNumberMock', $methods);
$Number = new NumberHelperTestObject($this->View, array('engine' => 'CakeNumberMock'));
$Number->attach($CakeNumber);
foreach ($methods as $method) {
$CakeNumber->expects($this->at(0))->method($method);
$Number->{$method}('who', 'what', 'when', 'where', 'how');
}
}
/**
* test engine override
*/
public function testEngineOverride() {
App::build(array(
'Utility' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Utility' . DS)
), App::REGISTER);
$Number = new NumberHelperTestObject($this->View, array('engine' => 'TestAppEngine'));
$this->assertInstanceOf('TestAppEngine', $Number->engine());
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$Number = new NumberHelperTestObject($this->View, array('engine' => 'TestPlugin.TestPluginEngine'));
$this->assertInstanceOf('TestPluginEngine', $Number->engine());
CakePlugin::unload('TestPlugin');
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,386 @@
<?php
/**
* PrototypeEngine TestCase
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
* @link http://cakephp.org CakePHP Project
* @package Cake.Test.Case.View.Helper
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('HtmlHelper', 'View/Helper');
App::uses('JsHelper', 'View/Helper');
App::uses('PrototypeEngineHelper', 'View/Helper');
class PrototypeEngineHelperTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = $this->getMock('View', array('addScript'), array(&$controller));
$this->Proto = new PrototypeEngineHelper($this->View);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Proto);
}
/**
* test selector method
*
* @return void
*/
public function testSelector() {
$result = $this->Proto->get('#content');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$("content")');
$result = $this->Proto->get('a .remove');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("a .remove")');
$result = $this->Proto->get('document');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, "$(document)");
$result = $this->Proto->get('window');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, "$(window)");
$result = $this->Proto->get('ul');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("ul")');
$result = $this->Proto->get('#some_long-id.class');
$this->assertEquals($this->Proto, $result);
$this->assertEquals($this->Proto->selection, '$$("#some_long-id.class")');
}
/**
* test event binding
*
* @return void
*/
public function testEvent() {
$this->Proto->get('#myLink');
$result = $this->Proto->event('click', 'doClick', array('wrap' => false));
$expected = '$("myLink").observe("click", doClick);';
$this->assertEquals($expected, $result);
$result = $this->Proto->event('click', 'Element.hide(this);', array('stop' => false));
$expected = '$("myLink").observe("click", function (event) {Element.hide(this);});';
$this->assertEquals($expected, $result);
$result = $this->Proto->event('click', 'Element.hide(this);');
$expected = "\$(\"myLink\").observe(\"click\", function (event) {event.stop();\nElement.hide(this);});";
$this->assertEquals($expected, $result);
}
/**
* test dom ready event creation
*
* @return void
*/
public function testDomReady() {
$result = $this->Proto->domReady('foo.name = "bar";');
$expected = 'document.observe("dom:loaded", function (event) {foo.name = "bar";});';
$this->assertEquals($expected, $result);
}
/**
* test Each method
*
* @return void
*/
public function testEach() {
$this->Proto->get('#foo li');
$result = $this->Proto->each('item.hide();');
$expected = '$$("#foo li").each(function (item, index) {item.hide();});';
$this->assertEquals($expected, $result);
}
/**
* test Effect generation
*
* @return void
*/
public function testEffect() {
$this->Proto->get('#foo');
$result = $this->Proto->effect('show');
$expected = '$("foo").show();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('hide');
$expected = '$("foo").hide();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn');
$expected = '$("foo").appear();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn', array('speed' => 'fast'));
$expected = '$("foo").appear({duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeIn', array('speed' => 'slow'));
$expected = '$("foo").appear({duration:2});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut');
$expected = '$("foo").fade();';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut', array('speed' => 'fast'));
$expected = '$("foo").fade({duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('fadeOut', array('speed' => 'slow'));
$expected = '$("foo").fade({duration:2});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideIn');
$expected = 'Effect.slideDown($("foo"));';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut');
$expected = 'Effect.slideUp($("foo"));';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut', array('speed' => 'fast'));
$expected = 'Effect.slideUp($("foo"), {duration:0.50000000000});';
$this->assertEquals($expected, $result);
$result = $this->Proto->effect('slideOut', array('speed' => 'slow'));
$expected = 'Effect.slideUp($("foo"), {duration:2});';
$this->assertEquals($expected, $result);
}
/**
* Test Request Generation
*
* @return void
*/
public function testRequest() {
$result = $this->Proto->request(array('controller' => 'posts', 'action' => 'view', 1));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1");';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/posts/view/1', array(
'method' => 'post',
'complete' => 'doComplete',
'before' => 'doBefore',
'success' => 'doSuccess',
'error' => 'doError',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/posts/view/1", {method:"post", onComplete:doComplete, onCreate:doBefore, onFailure:doError, onSuccess:doSuccess, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/posts/view/1', array('update' => 'content'));
$expected = 'var jsRequest = new Ajax.Updater("content", "/posts/view/1");';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'update' => '#update-zone',
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Updater("update-zone", "/people/edit/1", {method:"post", onComplete:doSuccess});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => array('name' => 'jim', 'height' => '185cm'),
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:{"name":"jim","height":"185cm"}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'complete' => 'doSuccess',
'error' => 'handleError',
'type' => 'json',
'data' => '$("element").serialize()',
'dataExpression' => true,
'wrapCallbacks' => false
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:doSuccess, onFailure:handleError, parameters:$("element").serialize()});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEquals($expected, $result);
$result = $this->Proto->request('/people/edit/1', array(
'async' => false,
'method' => 'post',
'before' => 'doBefore();',
'success' => 'doSuccess();',
'complete' => 'doComplete();',
'error' => 'handleError();',
));
$expected = 'var jsRequest = new Ajax.Request("/people/edit/1", {asynchronous:false, method:"post", onComplete:function (transport) {doComplete();}, onCreate:function (transport) {doBefore();}, onFailure:function (response, jsonHeader) {handleError();}, onSuccess:function (response, jsonHeader) {doSuccess();}});';
$this->assertEquals($expected, $result);
$this->Proto->get('#submit');
$result = $this->Proto->request('/users/login', array(
'before' => 'login.create(event)',
'complete' => 'login.complete(event)',
'update' => 'auth',
'data' => $this->Proto->serializeForm(array('isForm' => false, 'inline' => true)),
'dataExpression' => true
));
$this->assertTrue(strpos($result, '$($("submit").form).serialize()') > 0);
$this->assertFalse(strpos($result, 'parameters:function () {$($("submit").form).serialize()}') > 0);
}
/**
* test sortable list generation
*
* @return void
*/
public function testSortable() {
$this->Proto->get('#myList');
$result = $this->Proto->sortable(array(
'complete' => 'onComplete',
'sort' => 'onSort',
'wrapCallbacks' => false
));
$expected = 'var jsSortable = Sortable.create($("myList"), {onChange:onSort, onUpdate:onComplete});';
$this->assertEquals($expected, $result);
}
/**
* test drag() method. Scriptaculous lacks the ability to take an Array of Elements
* in new Drag() when selection is a multiple type. Iterate over the array.
*
* @return void
*/
public function testDrag() {
$this->Proto->get('#element');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = 'var jsDrag = new Draggable($("element"), {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});';
$this->assertEquals($expected, $result);
$this->Proto->get('div.dragger');
$result = $this->Proto->drag(array(
'start' => 'onStart',
'drag' => 'onDrag',
'stop' => 'onStop',
'snapGrid' => array(10, 10),
'wrapCallbacks' => false
));
$expected = '$$("div.dragger").each(function (item, index) {new Draggable(item, {onDrag:onDrag, onEnd:onStop, onStart:onStart, snap:[10,10]});});';
$this->assertEquals($expected, $result);
}
/**
* test drop() method
*
* @return void
*/
public function testDrop() {
$this->Proto->get('#element');
$result = $this->Proto->drop(array(
'hover' => 'onHover',
'drop' => 'onDrop',
'accept' => '.drag-me',
'wrapCallbacks' => false
));
$expected = 'Droppables.add($("element"), {accept:".drag-me", onDrop:onDrop, onHover:onHover});';
$this->assertEquals($expected, $result);
}
/**
* ensure that slider() method behaves properly
*
* @return void
*/
public function testSlider() {
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'direction' => 'horizontal',
'change' => 'onChange',
'complete' => 'onComplete',
'value' => 4,
'wrapCallbacks' => false
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {axis:"horizontal", onChange:onComplete, onSlide:onChange, sliderValue:4});';
$this->assertEquals($expected, $result);
$this->Proto->get('#element');
$result = $this->Proto->slider(array(
'handle' => '#handle',
'change' => 'change();',
'complete' => 'complete();',
'value' => 4,
'min' => 10,
'max' => 100
));
$expected = 'var jsSlider = new Control.Slider($("handle"), $("element"), {onChange:function (value) {complete();}, onSlide:function (value) {change();}, range:$R(10,100), sliderValue:4});';
$this->assertEquals($expected, $result);
}
/**
* test the serializeForm implementation.
*
* @return void
*/
public function testSerializeForm() {
$this->Proto->get('#element');
$result = $this->Proto->serializeForm(array('isForm' => true));
$expected = '$("element").serialize();';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => true, 'inline' => true));
$expected = '$("element").serialize()';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => false));
$expected = '$($("element").form).serialize();';
$this->assertEquals($expected, $result);
$result = $this->Proto->serializeForm(array('isForm' => false, 'inline' => true));
$expected = '$($("element").form).serialize()';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,778 @@
<?php
/**
* RssHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('RssHelper', 'View/Helper');
App::uses('TimeHelper', 'View/Helper');
App::uses('File', 'Utility');
/**
* RssHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class RssHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = new View($controller);
$this->Rss = new RssHelper($this->View);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->Rss);
}
/**
* testDocument method
*
* @return void
*/
public function testDocument() {
$result = $this->Rss->document();
$expected = array(
'rss' => array(
'version' => '2.0'
)
);
$this->assertTags($result, $expected);
$result = $this->Rss->document(null, 'content');
$expected = array(
'rss' => array(
'version' => '2.0'
),
'content'
);
$this->assertTags($result, $expected);
$result = $this->Rss->document(array('contrived' => 'parameter'), 'content');
$expected = array(
'rss' => array(
'contrived' => 'parameter',
'version' => '2.0'
),
'content'
);
$this->assertTags($result, $expected);
}
/**
* testChannel method
*
* @return void
*/
public function testChannel() {
$attrib = array('a' => '1', 'b' => '2');
$elements = array('title' => 'title');
$content = 'content';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'channel' => array(
'a' => '1',
'b' => '2'
),
'<title',
'title',
'/title',
'<link',
$this->Rss->url('/', true),
'/link',
'<description',
'content',
'/channel'
);
$this->assertTags($result, $expected);
$this->View->pageTitle = 'title';
$attrib = array('a' => '1', 'b' => '2');
$elements = array();
$content = 'content';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'channel' => array(
'a' => '1',
'b' => '2'
),
'<title',
'title',
'/title',
'<link',
$this->Rss->url('/', true),
'/link',
'<description',
'content',
'/channel'
);
$this->assertTags($result, $expected);
}
/**
* test correct creation of channel sub elements.
*
* @return void
*/
public function testChannelElements() {
$attrib = array();
$elements = array(
'title' => 'Title of RSS Feed',
'link' => 'http://example.com',
'description' => 'Description of RSS Feed',
'image' => array(
'title' => 'Title of image',
'url' => 'http://example.com/example.png',
'link' => 'http://example.com'
),
'cloud' => array(
'domain' => "rpc.sys.com",
'port' => "80",
'path' => "/RPC2",
'registerProcedure' => "myCloud.rssPleaseNotify",
'protocol' => "xml-rpc"
)
);
$content = 'content-here';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'<channel',
'<title', 'Title of RSS Feed', '/title',
'<link', 'http://example.com', '/link',
'<description', 'Description of RSS Feed', '/description',
'<image',
'<title', 'Title of image', '/title',
'<url', 'http://example.com/example.png', '/url',
'<link', 'http://example.com', '/link',
'/image',
'cloud' => array(
'domain' => "rpc.sys.com",
'port' => "80",
'path' => "/RPC2",
'registerProcedure' => "myCloud.rssPleaseNotify",
'protocol' => "xml-rpc"
),
'content-here',
'/channel',
);
$this->assertTags($result, $expected);
}
public function testChannelElementAttributes() {
$attrib = array();
$elements = array(
'title' => 'Title of RSS Feed',
'link' => 'http://example.com',
'description' => 'Description of RSS Feed',
'image' => array(
'title' => 'Title of image',
'url' => 'http://example.com/example.png',
'link' => 'http://example.com'
),
'atom:link' => array(
'attrib' => array(
'href' => 'http://www.example.com/rss.xml',
'rel' => 'self',
'type' => 'application/rss+xml')
)
);
$content = 'content-here';
$result = $this->Rss->channel($attrib, $elements, $content);
$expected = array(
'<channel',
'<title', 'Title of RSS Feed', '/title',
'<link', 'http://example.com', '/link',
'<description', 'Description of RSS Feed', '/description',
'<image',
'<title', 'Title of image', '/title',
'<url', 'http://example.com/example.png', '/url',
'<link', 'http://example.com', '/link',
'/image',
'atom:link' => array(
'xmlns:atom' => 'http://www.w3.org/2005/Atom',
'href' => "http://www.example.com/rss.xml",
'rel' => "self",
'type' => "application/rss+xml"
),
'content-here',
'/channel',
);
$this->assertTags($result, $expected);
}
/**
* testItems method
*
* @return void
*/
public function testItems() {
$items = array(
array('title' => 'title1', 'guid' => 'http://www.example.com/guid1', 'link' => 'http://www.example.com/link1', 'description' => 'description1'),
array('title' => 'title2', 'guid' => 'http://www.example.com/guid2', 'link' => 'http://www.example.com/link2', 'description' => 'description2'),
array('title' => 'title3', 'guid' => 'http://www.example.com/guid3', 'link' => 'http://www.example.com/link3', 'description' => 'description3')
);
$result = $this->Rss->items($items);
$expected = array(
'<item',
'<title', 'title1', '/title',
'<guid', 'http://www.example.com/guid1', '/guid',
'<link', 'http://www.example.com/link1', '/link',
'<description', 'description1', '/description',
'/item',
'<item',
'<title', 'title2', '/title',
'<guid', 'http://www.example.com/guid2', '/guid',
'<link', 'http://www.example.com/link2', '/link',
'<description', 'description2', '/description',
'/item',
'<item',
'<title', 'title3', '/title',
'<guid', 'http://www.example.com/guid3', '/guid',
'<link', 'http://www.example.com/link3', '/link',
'<description', 'description3', '/description',
'/item'
);
$this->assertTags($result, $expected);
$items = array(
array('title' => 'title1', 'guid' => 'http://www.example.com/guid1', 'link' => 'http://www.example.com/link1', 'description' => 'description1'),
array('title' => 'title2', 'guid' => 'http://www.example.com/guid2', 'link' => 'http://www.example.com/link2', 'description' => 'description2'),
array('title' => 'title3', 'guid' => 'http://www.example.com/guid3', 'link' => 'http://www.example.com/link3', 'description' => 'description3')
);
$result = $this->Rss->items($items, create_function('$v', '$v[\'title\'] = $v[\'title\'] . \'-transformed\'; return $v;'));
$expected = array(
'<item',
'<title', 'title1-transformed', '/title',
'<guid', 'http://www.example.com/guid1', '/guid',
'<link', 'http://www.example.com/link1', '/link',
'<description', 'description1', '/description',
'/item',
'<item',
'<title', 'title2-transformed', '/title',
'<guid', 'http://www.example.com/guid2', '/guid',
'<link', 'http://www.example.com/link2', '/link',
'<description', 'description2', '/description',
'/item',
'<item',
'<title', 'title3-transformed', '/title',
'<guid', 'http://www.example.com/guid3', '/guid',
'<link', 'http://www.example.com/link3', '/link',
'<description', 'description3', '/description',
'/item'
);
$this->assertTags($result, $expected);
$result = $this->Rss->items(array());
$expected = '';
$this->assertEquals($expected, $result);
}
/**
* testItem method
*
* @return void
*/
public function testItem() {
$item = array(
'title' => 'My title',
'description' => 'My description',
'link' => 'http://www.google.com/'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My title',
'/title',
'<description',
'My description',
'/description',
'<link',
'http://www.google.com/',
'/link',
'<guid',
'http://www.google.com/',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'My Title',
'link' => 'http://www.example.com/1',
'description' => 'descriptive words',
'pubDate' => '2008-05-31 12:00:00',
'source' => array('http://www.google.com/', 'Google'),
'guid' => 'http://www.example.com/1'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My Title',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'descriptive words',
'/description',
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'source' => array('url' => 'http://www.google.com/'),
'Google',
'/source',
'<guid',
'http://www.example.com/1',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'My Title & more'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title', 'My Title &amp; more', '/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'Foo bar',
'link' => array(
'url' => 'http://example.com/foo?a=1&b=2',
'convertEntities' => false
),
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'pubDate' => '2008-05-31 12:00:00',
'source' => 'http://www.google.com/'
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'Foo bar',
'/title',
'<link',
'http://example.com/foo?a=1&amp;b=2',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<source',
'http://www.google.com/',
'/source',
'<guid',
'http://example.com/foo?a=1&amp;b=2',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'My title',
'description' => 'My description',
'link' => 'http://www.google.com/',
'source' => array('url' => 'http://www.example.com/', 'title' => 'Example website')
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My title',
'/title',
'<description',
'My description',
'/description',
'<link',
'http://www.google.com/',
'/link',
'source' => array('url' => 'http://www.example.com/'),
'Example website',
'/source',
'<guid',
'http://www.google.com/',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => 'My title',
'description' => 'My description',
'link' => 'http://www.google.com/',
'category' => array('Category One', 'Category Two')
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'My title',
'/title',
'<description',
'My description',
'/description',
'<link',
'http://www.google.com/',
'/link',
'<category',
'Category One',
'/category',
'<category',
'Category Two',
'/category',
'<guid',
'http://www.google.com/',
'/guid',
'/item'
);
$this->assertTags($result, $expected);
}
/**
* test item() with cdata blocks.
*
* @return void
*/
public function testItemCdata() {
$item = array(
'title' => array(
'value' => 'My Title & more',
'cdata' => true,
'convertEntities' => false,
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title & more]]',
'/title',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'category' => array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org',
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'category' => array(
array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
),
array(
'value' => 'Bakery',
'cdata' => true
)
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'<category',
'<![CDATA[Bakery]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$item = array(
'title' => array(
'value' => 'My Title',
'cdata' => true,
),
'link' => 'http://www.example.com/1',
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'enclosure' => array(
'url' => '/test.flv'
),
'pubDate' => '2008-05-31 12:00:00',
'guid' => 'http://www.example.com/1',
'category' => array(
array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
),
array(
'value' => 'Bakery',
'cdata' => true
)
)
);
$result = $this->Rss->item(null, $item);
$expected = array(
'<item',
'<title',
'<![CDATA[My Title]]',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'enclosure' => array('url' => $this->Rss->url('/test.flv', true)),
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<guid',
'http://www.example.com/1',
'/guid',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'<category',
'<![CDATA[Bakery]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
}
/**
* test item() with enclosure data.
*
* @return void
*/
public function testItemEnclosureLength() {
if (!is_writable(WWW_ROOT)) {
$this->markTestSkipped(__d('cake_dev', 'Webroot is not writable.'));
}
$testExists = is_dir(WWW_ROOT . 'tests');
$tmpFile = WWW_ROOT . 'tests' . DS . 'cakephp.file.test.tmp';
$File = new File($tmpFile, true);
$this->assertTrue($File->write('123'), 'Could not write to ' . $tmpFile);
if (50300 <= PHP_VERSION_ID) {
clearstatcache(true, $tmpFile);
} else {
clearstatcache();
}
$item = array(
'title' => array(
'value' => 'My Title',
'cdata' => true,
),
'link' => 'http://www.example.com/1',
'description' => array(
'value' => 'descriptive words',
'cdata' => true,
),
'enclosure' => array(
'url' => '/tests/cakephp.file.test.tmp'
),
'pubDate' => '2008-05-31 12:00:00',
'guid' => 'http://www.example.com/1',
'category' => array(
array(
'value' => 'CakePHP',
'cdata' => true,
'domain' => 'http://www.cakephp.org'
),
array(
'value' => 'Bakery',
'cdata' => true
)
)
);
$result = $this->Rss->item(null, $item);
if (!function_exists('finfo_open') &&
(function_exists('mime_content_type') && false === mime_content_type($tmpFile))
) {
$type = false;
} else {
$type = 'text/plain';
}
$expected = array(
'<item',
'<title',
'<![CDATA[My Title]]',
'/title',
'<link',
'http://www.example.com/1',
'/link',
'<description',
'<![CDATA[descriptive words]]',
'/description',
'enclosure' => array(
'url' => $this->Rss->url('/tests/cakephp.file.test.tmp', true),
'length' => filesize($tmpFile),
'type' => $type
),
'<pubDate',
date('r', strtotime('2008-05-31 12:00:00')),
'/pubDate',
'<guid',
'http://www.example.com/1',
'/guid',
'category' => array('domain' => 'http://www.cakephp.org'),
'<![CDATA[CakePHP]]',
'/category',
'<category',
'<![CDATA[Bakery]]',
'/category',
'/item'
);
$this->assertTags($result, $expected);
$File->delete();
if (!$testExists) {
$Folder = new Folder(WWW_ROOT . 'tests');
$Folder->delete();
}
}
/**
* testElementAttrNotInParent method
*
* @return void
*/
public function testElementAttrNotInParent() {
$attributes = array(
'title' => 'Some Title',
'link' => 'http://link.com',
'description' => 'description'
);
$elements = array('enclosure' => array('url' => 'http://test.com'));
$result = $this->Rss->item($attributes, $elements);
$expected = array(
'item' => array(
'title' => 'Some Title',
'link' => 'http://link.com',
'description' => 'description'
),
'enclosure' => array(
'url' => 'http://test.com'
),
'/item'
);
$this->assertTags($result, $expected);
}
public function testElementNamespaceWithoutPrefix() {
$item = array(
'creator' => 'Alex',
);
$attributes = array(
'namespace' => 'http://link.com'
);
$result = $this->Rss->item($attributes, $item);
$expected = array(
'item' => array(
'xmlns' => 'http://link.com'
),
'creator' => array(
'xmlns' => 'http://link.com'
),
'Alex',
'/creator',
'/item'
);
$this->assertTags($result, $expected, true);
}
public function testElementNamespaceWithPrefix() {
$item = array(
'title' => 'Title',
'dc:creator' => 'Alex',
'xy:description' => 'descriptive words'
);
$attributes = array(
'namespace' => array(
'prefix' => 'dc',
'url' => 'http://link.com'
)
);
$result = $this->Rss->item($attributes, $item);
$expected = array(
'item' => array(
'xmlns:dc' => 'http://link.com'
),
'title' => array(
'xmlns:dc' => 'http://link.com'
),
'Title',
'/title',
'dc:creator' => array(
'xmlns:dc' => 'http://link.com'
),
'Alex',
'/dc:creator',
'description' => array(
'xmlns:dc' => 'http://link.com'
),
'descriptive words',
'/description',
'/item'
);
$this->assertTags($result, $expected, true);
}
}

View file

@ -0,0 +1,192 @@
<?php
/**
* SessionHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('View', 'View');
App::uses('SessionHelper', 'View/Helper');
/**
* SessionHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class SessionHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$controller = null;
$this->View = new View($controller);
$this->Session = new SessionHelper($this->View);
CakeSession::start();
if (!CakeSession::started()) {
CakeSession::start();
}
$_SESSION = array(
'test' => 'info',
'Message' => array(
'flash' => array(
'element' => 'default',
'params' => array(),
'message' => 'This is a calling'
),
'notification' => array(
'element' => 'session_helper',
'params' => array('title' => 'Notice!', 'name' => 'Alert!'),
'message' => 'This is a test of the emergency broadcasting system',
),
'classy' => array(
'element' => 'default',
'params' => array('class' => 'positive'),
'message' => 'Recorded'
),
'bare' => array(
'element' => null,
'message' => 'Bare message',
'params' => array(),
),
),
'Deeply' => array('nested' => array('key' => 'value')),
);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
$_SESSION = array();
unset($this->View, $this->Session);
CakePlugin::unload();
parent::tearDown();
}
/**
* testRead method
*
* @return void
*/
public function testRead() {
$result = $this->Session->read('Deeply.nested.key');
$this->assertEquals('value', $result);
$result = $this->Session->read('test');
$this->assertEquals('info', $result);
}
/**
* testCheck method
*
* @return void
*/
public function testCheck() {
$this->assertTrue($this->Session->check('test'));
$this->assertTrue($this->Session->check('Message.flash.element'));
$this->assertFalse($this->Session->check('Does.not.exist'));
$this->assertFalse($this->Session->check('Nope'));
}
/**
* testFlash method
*
* @return void
*/
public function testFlash() {
$result = $this->Session->flash('flash');
$expected = '<div id="flashMessage" class="message">This is a calling</div>';
$this->assertEquals($expected, $result);
$this->assertFalse($this->Session->check('Message.flash'));
$expected = '<div id="classyMessage" class="positive">Recorded</div>';
$result = $this->Session->flash('classy');
$this->assertEquals($expected, $result);
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$result = $this->Session->flash('notification');
$result = str_replace("\r\n", "\n", $result);
$expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a test of the emergency broadcasting system</p>\n</div>";
$this->assertEquals($expected, $result);
$this->assertFalse($this->Session->check('Message.notification'));
$result = $this->Session->flash('bare');
$expected = 'Bare message';
$this->assertEquals($expected, $result);
$this->assertFalse($this->Session->check('Message.bare'));
}
/**
* test flash() with the attributes.
*
* @return void
*/
public function testFlashAttributes() {
$result = $this->Session->flash('flash', array('params' => array('class' => 'test-message')));
$expected = '<div id="flashMessage" class="test-message">This is a calling</div>';
$this->assertEquals($expected, $result);
$this->assertFalse($this->Session->check('Message.flash'));
}
/**
* test setting the element from the attrs.
*
* @return void
*/
public function testFlashElementInAttrs() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$result = $this->Session->flash('flash', array(
'element' => 'session_helper',
'params' => array('title' => 'Notice!', 'name' => 'Alert!')
));
$expected = "<div id=\"notificationLayout\">\n\t<h1>Alert!</h1>\n\t<h3>Notice!</h3>\n\t<p>This is a calling</p>\n</div>";
$this->assertTextEquals($expected, $result);
}
/**
* test using elements in plugins.
*
* @return void
*/
public function testFlashWithPluginElement() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$result = $this->Session->flash('flash', array(
'element' => 'plugin_element',
'params' => array('plugin' => 'TestPlugin')
));
$expected = 'this is the plugin element using params[plugin]';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,337 @@
<?php
/**
* TextHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('TextHelper', 'View/Helper');
class TextHelperTestObject extends TextHelper {
public function attach(StringMock $string) {
$this->_engine = $string;
}
public function engine() {
return $this->_engine;
}
}
/**
* StringMock class
*/
class StringMock {
}
/**
* TextHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class TextHelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->View = new View(null);
$this->Text = new TextHelper($this->View);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->View);
parent::tearDown();
}
/**
* test String class methods are called correctly
*/
public function testTextHelperProxyMethodCalls() {
$methods = array(
'highlight', 'stripLinks', 'truncate', 'excerpt', 'toList',
);
$String = $this->getMock('StringMock', $methods);
$Text = new TextHelperTestObject($this->View, array('engine' => 'StringMock'));
$Text->attach($String);
foreach ($methods as $method) {
$String->expects($this->at(0))->method($method);
$Text->{$method}('who', 'what', 'when', 'where', 'how');
}
}
/**
* test engine override
*/
public function testEngineOverride() {
App::build(array(
'Utility' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Utility' . DS)
), App::REGISTER);
$Text = new TextHelperTestObject($this->View, array('engine' => 'TestAppEngine'));
$this->assertInstanceOf('TestAppEngine', $Text->engine());
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$Text = new TextHelperTestObject($this->View, array('engine' => 'TestPlugin.TestPluginEngine'));
$this->assertInstanceOf('TestPluginEngine', $Text->engine());
CakePlugin::unload('TestPlugin');
}
/**
* testAutoLink method
*
* @return void
*/
public function testAutoLink() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = 'Text with a partial www.cakephp.org URL and test@cakephp.org email address';
$result = $this->Text->autoLink($text);
$expected = 'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL and <a href="mailto:test@cakephp\.org">test@cakephp\.org</a> email address';
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = 'This is a test text with URL http://www.cakephp.org and some more text';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a> and some more text';
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = "This is a test text with URL http://www.cakephp.org\tand some more text";
$expected = "This is a test text with URL <a href=\"http://www.cakephp.org\">http://www.cakephp.org</a>\tand some more text";
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = 'This is a test text with URL http://www.cakephp.org(and some more text)';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>(and some more text)';
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org" class="link">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text, array('class' => 'link'));
$this->assertEquals($expected, $result);
$text = 'This is a test text with URL http://www.cakephp.org';
$expected = 'This is a test text with URL <a href="http://www.cakephp.org" class="link" id="MyLink">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text, array('class' => 'link', 'id' => 'MyLink'));
$this->assertEquals($expected, $result);
}
/**
* Test escaping for autoLink
*
* @return void
*/
public function testAutoLinkEscape() {
$text = 'This is a <b>test</b> text with URL http://www.cakephp.org';
$expected = 'This is a &lt;b&gt;test&lt;/b&gt; text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text);
$this->assertEquals($expected, $result);
$text = 'This is a <b>test</b> text with URL http://www.cakephp.org';
$expected = 'This is a <b>test</b> text with URL <a href="http://www.cakephp.org">http://www.cakephp.org</a>';
$result = $this->Text->autoLink($text, array('escape' => false));
$this->assertEquals($expected, $result);
}
/**
* Data provider for autoLinking
*/
public static function autoLinkProvider() {
return array(
array(
'This is a test text',
'This is a test text',
),
array(
'This is a test that includes (www.cakephp.org)',
'This is a test that includes (<a href="http://www.cakephp.org">www.cakephp.org</a>)',
),
array(
'This is a test that includes www.cakephp.org:8080',
'This is a test that includes <a href="http://www.cakephp.org:8080">www.cakephp.org:8080</a>',
),
array(
'This is a test that includes http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
'This is a test that includes <a href="http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">http://de.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
),
array(
'This is a test that includes www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment',
'This is a test that includes <a href="http://www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment">www.wikipedia.org/wiki/Kanton_(Schweiz)#fragment</a>',
),
array(
'This is a test that includes http://example.com/test.php?foo=bar text',
'This is a test that includes <a href="http://example.com/test.php?foo=bar">http://example.com/test.php?foo=bar</a> text',
),
array(
'This is a test that includes www.example.com/test.php?foo=bar text',
'This is a test that includes <a href="http://www.example.com/test.php?foo=bar">www.example.com/test.php?foo=bar</a> text',
),
array(
'Text with a partial www.cakephp.org URL',
'Text with a partial <a href="http://www.cakephp.org">www.cakephp.org</a> URL',
),
array(
'Text with a partial WWW.cakephp.org URL',
'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> URL',
),
array(
'Text with a partial WWW.cakephp.org &copy, URL',
'Text with a partial <a href="http://WWW.cakephp.org">WWW.cakephp.org</a> &amp;copy, URL',
),
array(
'Text with a url www.cot.ag/cuIb2Q and more',
'Text with a url <a href="http://www.cot.ag/cuIb2Q">www.cot.ag/cuIb2Q</a> and more',
),
array(
'Text with a url http://www.does--not--work.com and more',
'Text with a url <a href="http://www.does--not--work.com">http://www.does--not--work.com</a> and more',
),
array(
'Text with a url http://www.not--work.com and more',
'Text with a url <a href="http://www.not--work.com">http://www.not--work.com</a> and more',
),
);
}
/**
* testAutoLinkUrls method
*
* @dataProvider autoLinkProvider
* @return void
*/
public function testAutoLinkUrls($text, $expected) {
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
}
/**
* Test the options for autoLinkUrls
*
* @return void
*/
public function testAutoLinkUrlsOptions() {
$text = 'Text with a partial www.cakephp.org URL';
$expected = 'Text with a partial <a href="http://www.cakephp.org" \s*class="link">www.cakephp.org</a> URL';
$result = $this->Text->autoLinkUrls($text, array('class' => 'link'));
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = 'Text with a partial WWW.cakephp.org &copy; URL';
$expected = 'Text with a partial <a href="http://WWW.cakephp.org"\s*>WWW.cakephp.org</a> &copy; URL';
$result = $this->Text->autoLinkUrls($text, array('escape' => false));
$this->assertRegExp('#^' . $expected . '$#', $result);
}
/**
* Test autoLinkUrls with the escape option.
*
* @return void
*/
public function testAutoLinkUrlsEscape() {
$text = 'Text with a partial <a href="http://www.cakephp.org">link</a> link';
$expected = 'Text with a partial <a href="http://www.cakephp.org">link</a> link';
$result = $this->Text->autoLinkUrls($text, array('escape' => false));
$this->assertEquals($expected, $result);
$text = 'Text with a partial <iframe src="http://www.cakephp.org" /> link';
$expected = 'Text with a partial <iframe src="http://www.cakephp.org" /> link';
$result = $this->Text->autoLinkUrls($text, array('escape' => false));
$this->assertEquals($expected, $result);
$text = 'Text with a partial <iframe src="http://www.cakephp.org" /> link';
$expected = 'Text with a partial &lt;iframe src=&quot;http://www.cakephp.org&quot; /&gt; link';
$result = $this->Text->autoLinkUrls($text, array('escape' => true));
$this->assertEquals($expected, $result);
$text = 'Text with a url <a href="http://www.not-working-www.com">www.not-working-www.com</a> and more';
$expected = 'Text with a url &lt;a href=&quot;http://www.not-working-www.com&quot;&gt;www.not-working-www.com&lt;/a&gt; and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'Text with a url www.not-working-www.com and more';
$expected = 'Text with a url <a href="http://www.not-working-www.com">www.not-working-www.com</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'Text with a url http://www.not-working-www.com and more';
$expected = 'Text with a url <a href="http://www.not-working-www.com">http://www.not-working-www.com</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'Text with a url http://www.www.not-working-www.com and more';
$expected = 'Text with a url <a href="http://www.www.not-working-www.com">http://www.www.not-working-www.com</a> and more';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
}
/**
* testAutoLinkEmails method
*
* @return void
*/
public function testAutoLinkEmails() {
$text = 'This is a test text';
$expected = 'This is a test text';
$result = $this->Text->autoLinkUrls($text);
$this->assertEquals($expected, $result);
$text = 'Text with email@example.com address';
$expected = 'Text with <a href="mailto:email@example.com"\s*>email@example.com</a> address';
$result = $this->Text->autoLinkEmails($text);
$this->assertRegExp('#^' . $expected . '$#', $result);
$text = "Text with o'hare._-bob@example.com address";
$expected = 'Text with <a href="mailto:o&#039;hare._-bob@example.com">o&#039;hare._-bob@example.com</a> address';
$result = $this->Text->autoLinkEmails($text);
$this->assertEquals($expected, $result);
$text = 'Text with email@example.com address';
$expected = 'Text with <a href="mailto:email@example.com" \s*class="link">email@example.com</a> address';
$result = $this->Text->autoLinkEmails($text, array('class' => 'link'));
$this->assertRegExp('#^' . $expected . '$#', $result);
}
/**
* test invalid email addresses.
*
* @return void
*/
public function testAutoLinkEmailInvalid() {
$result = $this->Text->autoLinkEmails('this is a myaddress@gmx-de test');
$expected = 'this is a myaddress@gmx-de test';
$this->assertEquals($expected, $result);
}
}

View file

@ -0,0 +1,170 @@
<?php
/**
* TimeHelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View.Helper
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('TimeHelper', 'View/Helper');
App::uses('View', 'View');
App::uses('CakeTime', 'Utility');
/**
* TimeHelperTestObject class
*/
class TimeHelperTestObject extends TimeHelper {
public function attach(CakeTimeMock $cakeTime) {
$this->_engine = $cakeTime;
}
public function engine() {
return $this->_engine;
}
}
/**
* CakeTimeMock class
*/
class CakeTimeMock {
}
/**
* TimeHelperTest class
*
* @package Cake.Test.Case.View.Helper
*/
class TimeHelperTest extends CakeTestCase {
public $Time = null;
public $CakeTime = null;
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->View = new View(null);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->View);
parent::tearDown();
}
/**
* test CakeTime class methods are called correctly
*/
public function testTimeHelperProxyMethodCalls() {
$methods = array(
'convertSpecifiers', 'convert', 'serverOffset', 'fromString',
'nice', 'niceShort', 'daysAsSql', 'dayAsSql',
'isToday', 'isThisMonth', 'isThisYear', 'wasYesterday',
'isTomorrow', 'toQuarter', 'toUnix', 'toAtom', 'toRSS',
'timeAgoInWords', 'wasWithinLast', 'gmt', 'format', 'i18nFormat',
);
$CakeTime = $this->getMock('CakeTimeMock', $methods);
$Time = new TimeHelperTestObject($this->View, array('engine' => 'CakeTimeMock'));
$Time->attach($CakeTime);
foreach ($methods as $method) {
$CakeTime->expects($this->at(0))->method($method);
$Time->{$method}('who', 'what', 'when', 'where', 'how');
}
}
/**
* test engine override
*/
public function testEngineOverride() {
App::build(array(
'Utility' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Utility' . DS)
), App::REGISTER);
$Time = new TimeHelperTestObject($this->View, array('engine' => 'TestAppEngine'));
$this->assertInstanceOf('TestAppEngine', $Time->engine());
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
$Time = new TimeHelperTestObject($this->View, array('engine' => 'TestPlugin.TestPluginEngine'));
$this->assertInstanceOf('TestPluginEngine', $Time->engine());
CakePlugin::unload('TestPlugin');
}
/**
* Test element wrapping in timeAgoInWords
*
* @return void
*/
public function testTimeAgoInWords() {
$Time = new TimeHelper($this->View);
$timestamp = strtotime('+8 years, +4 months +2 weeks +3 days');
$result = $Time->timeAgoInWords($timestamp, array(
'end' => '1 years',
'element' => 'span'
));
$expected = array(
'span' => array(
'title' => $timestamp,
'class' => 'time-ago-in-words'
),
'on ' . date('j/n/y', $timestamp),
'/span'
);
$this->assertTags($result, $expected);
$result = $Time->timeAgoInWords($timestamp, array(
'end' => '1 years',
'element' => array(
'title' => 'testing',
'rel' => 'test'
)
));
$expected = array(
'span' => array(
'title' => 'testing',
'class' => 'time-ago-in-words',
'rel' => 'test'
),
'on ' . date('j/n/y', $timestamp),
'/span'
);
$this->assertTags($result, $expected);
$timestamp = strtotime('+2 weeks');
$result = $Time->timeAgoInWords(
$timestamp,
array('end' => '1 years', 'element' => 'div')
);
$expected = array(
'div' => array(
'title' => $timestamp,
'class' => 'time-ago-in-words'
),
'2 weeks',
'/div'
);
$this->assertTags($result, $expected);
}
}

View file

@ -0,0 +1,188 @@
<?php
/**
* HelperCollectionTest file
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('HelperCollection', 'View');
App::uses('HtmlHelper', 'View/Helper');
App::uses('View', 'View');
/**
* Extended HtmlHelper
*/
class HtmlAliasHelper extends HtmlHelper {
}
class HelperCollectionTest extends CakeTestCase {
/**
* setUp
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->View = $this->getMock('View', array(), array(null));
$this->Helpers = new HelperCollection($this->View);
}
/**
* tearDown
*
* @return void
*/
public function tearDown() {
CakePlugin::unload();
unset($this->Helpers, $this->View);
parent::tearDown();
}
/**
* test triggering callbacks on loaded helpers
*
* @return void
*/
public function testLoad() {
$result = $this->Helpers->load('Html');
$this->assertInstanceOf('HtmlHelper', $result);
$this->assertInstanceOf('HtmlHelper', $this->Helpers->Html);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Helpers->enabled('Html'));
}
/**
* test lazy loading of helpers
*
* @return void
*/
public function testLazyLoad() {
$result = $this->Helpers->Html;
$this->assertInstanceOf('HtmlHelper', $result);
$result = $this->Helpers->Form;
$this->assertInstanceOf('FormHelper', $result);
App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)));
$this->View->plugin = 'TestPlugin';
CakePlugin::load(array('TestPlugin'));
$result = $this->Helpers->OtherHelper;
$this->assertInstanceOf('OtherHelperHelper', $result);
}
/**
* test lazy loading of helpers
*
* @expectedException MissingHelperException
* @return void
*/
public function testLazyLoadException() {
$result = $this->Helpers->NotAHelper;
}
/**
* Tests loading as an alias
*
* @return void
*/
public function testLoadWithAlias() {
$result = $this->Helpers->load('Html', array('className' => 'HtmlAlias'));
$this->assertInstanceOf('HtmlAliasHelper', $result);
$this->assertInstanceOf('HtmlAliasHelper', $this->Helpers->Html);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html'), $result, 'attached() results are wrong.');
$this->assertTrue($this->Helpers->enabled('Html'));
$result = $this->Helpers->load('Html');
$this->assertInstanceOf('HtmlAliasHelper', $result);
App::build(array('Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)));
CakePlugin::load(array('TestPlugin'));
$result = $this->Helpers->load('SomeOther', array('className' => 'TestPlugin.OtherHelper'));
$this->assertInstanceOf('OtherHelperHelper', $result);
$this->assertInstanceOf('OtherHelperHelper', $this->Helpers->SomeOther);
$result = $this->Helpers->attached();
$this->assertEquals(array('Html', 'SomeOther'), $result, 'attached() results are wrong.');
App::build();
}
/**
* test that the enabled setting disables the helper.
*
* @return void
*/
public function testLoadWithEnabledFalse() {
$result = $this->Helpers->load('Html', array('enabled' => false));
$this->assertInstanceOf('HtmlHelper', $result);
$this->assertInstanceOf('HtmlHelper', $this->Helpers->Html);
$this->assertFalse($this->Helpers->enabled('Html'), 'Html should be disabled');
}
/**
* test missinghelper exception
*
* @expectedException MissingHelperException
* @return void
*/
public function testLoadMissingHelper() {
$result = $this->Helpers->load('ThisHelperShouldAlwaysBeMissing');
}
/**
* test loading a plugin helper.
*
* @return void
*/
public function testLoadPluginHelper() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
));
CakePlugin::load(array('TestPlugin'));
$result = $this->Helpers->load('TestPlugin.OtherHelper');
$this->assertInstanceOf('OtherHelperHelper', $result, 'Helper class is wrong.');
$this->assertInstanceOf('OtherHelperHelper', $this->Helpers->OtherHelper, 'Class is wrong');
App::build();
}
/**
* test unload()
*
* @return void
*/
public function testUnload() {
$this->Helpers->load('Form');
$this->Helpers->load('Html');
$result = $this->Helpers->attached();
$this->assertEquals(array('Form', 'Html'), $result, 'loaded helpers is wrong');
$this->Helpers->unload('Html');
$this->assertNotContains('Html', $this->Helpers->attached());
$this->assertContains('Form', $this->Helpers->attached());
$result = $this->Helpers->attached();
$this->assertEquals(array('Form'), $result, 'loaded helpers is wrong');
}
}

View file

@ -0,0 +1,944 @@
<?php
/**
* HelperTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('Helper', 'View');
App::uses('Model', 'Model');
App::uses('Router', 'Routing');
/**
* HelperTestPost class
*
* @package Cake.Test.Case.View
*/
class HelperTestPost extends Model {
/**
* useTable property
*
* @var bool false
*/
public $useTable = false;
/**
* schema method
*
* @return void
*/
public function schema($field = false) {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'body' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => ''),
'number' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'date' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
/**
* hasAndBelongsToMany property
*
* @var array
*/
public $hasAndBelongsToMany = array('HelperTestTag' => array('with' => 'HelperTestPostsTag'));
}
/**
* HelperTestComment class
*
* @package Cake.Test.Case.View
*/
class HelperTestComment extends Model {
/**
* useTable property
*
* @var bool false
*/
public $useTable = false;
/**
* schema method
*
* @return void
*/
public function schema($field = false) {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'author_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'title' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'body' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => ''),
'BigField' => array('type' => 'string', 'null' => true, 'default' => '', 'length' => ''),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
}
/**
* HelperTestTag class
*
* @package Cake.Test.Case.View
*/
class HelperTestTag extends Model {
/**
* useTable property
*
* @var bool false
*/
public $useTable = false;
/**
* schema method
*
* @return void
*/
public function schema($field = false) {
$this->_schema = array(
'id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'name' => array('type' => 'string', 'null' => false, 'default' => '', 'length' => '255'),
'created' => array('type' => 'date', 'null' => true, 'default' => '', 'length' => ''),
'modified' => array('type' => 'datetime', 'null' => true, 'default' => '', 'length' => null)
);
return $this->_schema;
}
}
/**
* HelperTestPostsTag class
*
* @package Cake.Test.Case.View
*/
class HelperTestPostsTag extends Model {
/**
* useTable property
*
* @var bool false
*/
public $useTable = false;
/**
* schema method
*
* @return void
*/
public function schema($field = false) {
$this->_schema = array(
'helper_test_post_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
'helper_test_tag_id' => array('type' => 'integer', 'null' => false, 'default' => '', 'length' => '8'),
);
return $this->_schema;
}
}
class TestHelper extends Helper {
/**
* Helpers for this helper.
*
* @var string
*/
public $helpers = array('Html', 'TestPlugin.OtherHelper');
/**
* expose a method as public
*
* @param string $options
* @param string $exclude
* @param string $insertBefore
* @param string $insertAfter
* @return void
*/
public function parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
return $this->_parseAttributes($options, $exclude, $insertBefore, $insertAfter);
}
}
/**
* HelperTest class
*
* @package Cake.Test.Case.View
*/
class HelperTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
ClassRegistry::flush();
Router::reload();
$null = null;
$this->View = new View($null);
$this->Helper = new Helper($this->View);
$this->Helper->request = new CakeRequest(null, false);
ClassRegistry::addObject('HelperTestPost', new HelperTestPost());
ClassRegistry::addObject('HelperTestComment', new HelperTestComment());
ClassRegistry::addObject('HelperTestTag', new HelperTestTag());
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
Configure::delete('Asset');
CakePlugin::unload();
unset($this->Helper, $this->View);
}
/**
* Provider for setEntity test.
*
* @return array
*/
public static function entityProvider() {
return array(
array(
'HelperTestPost.id',
array('HelperTestPost', 'id'),
'HelperTestPost',
'id'
),
array(
'HelperTestComment.body',
array('HelperTestComment', 'body'),
'HelperTestComment',
'body'
),
array(
'HelperTest.1.Comment.body',
array('HelperTest', '1', 'Comment', 'body'),
'Comment',
'body'
),
array(
'HelperTestComment.BigField',
array('HelperTestComment', 'BigField'),
'HelperTestComment',
'BigField'
),
array(
'HelperTestComment.min',
array('HelperTestComment', 'min'),
'HelperTestComment',
'min'
)
);
}
/**
* Test setting an entity and retrieving the entity, model and field.
*
* @dataProvider entityProvider
* @return void
*/
public function testSetEntity($entity, $expected, $modelKey, $fieldKey) {
$this->Helper->setEntity($entity);
$this->assertEquals($expected, $this->Helper->entity());
$this->assertEquals($modelKey, $this->Helper->model());
$this->assertEquals($fieldKey, $this->Helper->field());
}
/**
* test setEntity with setting a scope.
*
* @return
*/
public function testSetEntityScoped() {
$this->Helper->setEntity('HelperTestPost', true);
$this->assertEquals(array('HelperTestPost'), $this->Helper->entity());
$this->Helper->setEntity('id');
$expected = array('HelperTestPost', 'id');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('HelperTestComment.body');
$expected = array('HelperTestComment', 'body');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('body');
$expected = array('HelperTestPost', 'body');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('2.body');
$expected = array('HelperTestPost', '2', 'body');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('Something.else');
$expected = array('Something', 'else');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('HelperTestComment.5.id');
$expected = array('HelperTestComment', 5, 'id');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('HelperTestComment.id.time');
$expected = array('HelperTestComment', 'id', 'time');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('HelperTestComment.created.year');
$expected = array('HelperTestComment', 'created', 'year');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity(null);
$this->Helper->setEntity('ModelThatDoesntExist.field_that_doesnt_exist');
$expected = array('ModelThatDoesntExist', 'field_that_doesnt_exist');
$this->assertEquals($expected, $this->Helper->entity());
}
/**
* Test that setEntity() and model()/field() work with associated models.
*
* @return void
*/
public function testSetEntityAssociated() {
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->setEntity('HelperTestPost.1.HelperTestComment.1.title');
$expected = array('HelperTestPost', '1', 'HelperTestComment', '1', 'title');
$this->assertEquals($expected, $this->Helper->entity());
$this->assertEquals('HelperTestComment', $this->Helper->model());
}
/**
* Test creating saveMany() compatible entities
*
* @return void
*/
public function testSetEntitySaveMany() {
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->setEntity('0.HelperTestPost.id');
$expected = array('0', 'HelperTestPost', 'id');
$this->assertEquals($expected, $this->Helper->entity());
}
/**
* Test that setEntity doesn't make CamelCase fields that are not associations an
* associated model.
*
* @return void
*/
public function testSetEntityAssociatedCamelCaseField() {
$this->Helper->fieldset = array(
'HelperTestComment' => array(
'fields' => array('BigField' => array('type' => 'integer'))
)
);
$this->Helper->setEntity('HelperTestComment', true);
$this->Helper->setEntity('HelperTestComment.BigField');
$this->assertEquals('HelperTestComment', $this->Helper->model());
$this->assertEquals('BigField', $this->Helper->field());
}
/**
* Test that multiple fields work when they are camelcase and in fieldset
*
* @return void
*/
public function testSetEntityAssociatedCamelCaseFieldHabtmMultiple() {
$this->Helper->fieldset = array(
'HelperTestComment' => array(
'fields' => array('Tag' => array('type' => 'multiple'))
)
);
$this->Helper->setEntity('HelperTestComment', true);
$this->Helper->setEntity('Tag');
$this->assertEquals('Tag', $this->Helper->model());
$this->assertEquals('Tag', $this->Helper->field());
$this->assertEquals(array('Tag', 'Tag'), $this->Helper->entity());
}
/**
* Test that habtm associations can have property fields created.
*
* @return void
*/
public function testSetEntityHabtmPropertyFieldNames() {
$this->Helper->fieldset = array(
'HelperTestComment' => array(
'fields' => array('Tag' => array('type' => 'multiple'))
)
);
$this->Helper->setEntity('HelperTestComment', true);
$this->Helper->setEntity('Tag.name');
$this->assertEquals('Tag', $this->Helper->model());
$this->assertEquals('name', $this->Helper->field());
$this->assertEquals(array('Tag', 'name'), $this->Helper->entity());
}
/**
* test that 'view' doesn't break things.
*
* @return void
*/
public function testSetEntityWithView() {
$this->assertNull($this->Helper->setEntity('Allow.view.group_id'));
$this->assertNull($this->Helper->setEntity('Allow.view'));
$this->assertNull($this->Helper->setEntity('View.view'));
}
/**
* test getting values from Helper
*
* @return void
*/
public function testValue() {
$this->Helper->request->data = array('fullname' => 'This is me');
$this->Helper->setEntity('fullname');
$result = $this->Helper->value('fullname');
$this->assertEquals('This is me', $result);
$this->Helper->request->data = array(
'Post' => array('name' => 'First Post')
);
$this->Helper->setEntity('Post.name');
$result = $this->Helper->value('Post.name');
$this->assertEquals('First Post', $result);
$this->Helper->request->data = array(
'Post' => array(2 => array('name' => 'First Post'))
);
$this->Helper->setEntity('Post.2.name');
$result = $this->Helper->value('Post.2.name');
$this->assertEquals('First Post', $result);
$this->Helper->request->data = array(
'Post' => array(
2 => array('created' => array('year' => '2008'))
)
);
$this->Helper->setEntity('Post.2.created');
$result = $this->Helper->value('Post.2.created');
$this->assertEquals(array('year' => '2008'), $result);
$this->Helper->request->data = array(
'Post' => array(
2 => array('created' => array('year' => '2008'))
)
);
$this->Helper->setEntity('Post.2.created.year');
$result = $this->Helper->value('Post.2.created.year');
$this->assertEquals('2008', $result);
}
/**
* Test default values with value()
*
* @return void
*/
public function testValueWithDefault() {
$this->Helper->request->data = array('zero' => 0);
$this->Helper->setEntity('zero');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEquals(array('value' => 0), $result);
$this->Helper->request->data = array('zero' => '0');
$result = $this->Helper->value(array('default' => 'something'), 'zero');
$this->assertEquals(array('value' => '0'), $result);
$this->Helper->setEntity('inexistent');
$result = $this->Helper->value(array('default' => 'something'), 'inexistent');
$this->assertEquals(array('value' => 'something'), $result);
}
/**
* Test habtm data fetching and ensure no pollution happens.
*
* @return void
*/
public function testValueHabtmKeys() {
$this->Helper->request->data = array(
'HelperTestTag' => array('HelperTestTag' => '')
);
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEquals('', $result);
$this->Helper->request->data = array(
'HelperTestTag' => array(
'HelperTestTag' => array(2, 3, 4)
)
);
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEquals(array(2, 3, 4), $result);
$this->Helper->request->data = array(
'HelperTestTag' => array(
array('id' => 3),
array('id' => 5)
)
);
$this->Helper->setEntity('HelperTestTag.HelperTestTag');
$result = $this->Helper->value('HelperTestTag.HelperTestTag');
$this->assertEquals(array(3 => 3, 5 => 5), $result);
$this->Helper->request->data = array(
'HelperTestTag' => array(
'body' => '',
'title' => 'winning'
),
);
$this->Helper->setEntity('HelperTestTag.body');
$result = $this->Helper->value('HelperTestTag.body');
$this->assertEquals('', $result);
}
/**
* Ensure HTML escaping of url params. So link addresses are valid and not exploited
*
* @return void
*/
public function testUrlConversion() {
$result = $this->Helper->url('/controller/action/1');
$this->assertEquals('/controller/action/1', $result);
$result = $this->Helper->url('/controller/action/1?one=1&two=2');
$this->assertEquals('/controller/action/1?one=1&amp;two=2', $result);
$result = $this->Helper->url(array('controller' => 'posts', 'action' => 'index', 'page' => '1" onclick="alert(\'XSS\');"'));
$this->assertEquals("/posts/index/page:1%22%20onclick%3D%22alert%28%27XSS%27%29%3B%22", $result);
$result = $this->Helper->url('/controller/action/1/param:this+one+more');
$this->assertEquals('/controller/action/1/param:this+one+more', $result);
$result = $this->Helper->url('/controller/action/1/param:this%20one%20more');
$this->assertEquals('/controller/action/1/param:this%20one%20more', $result);
$result = $this->Helper->url('/controller/action/1/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24');
$this->assertEquals('/controller/action/1/param:%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24', $result);
$result = $this->Helper->url(array(
'controller' => 'posts', 'action' => 'index', 'param' => '%7Baround%20here%7D%5Bthings%5D%5Bare%5D%24%24'
));
$this->assertEquals("/posts/index/param:%257Baround%2520here%257D%255Bthings%255D%255Bare%255D%2524%2524", $result);
$result = $this->Helper->url(array(
'controller' => 'posts', 'action' => 'index', 'page' => '1',
'?' => array('one' => 'value', 'two' => 'value', 'three' => 'purple')
));
$this->assertEquals("/posts/index/page:1?one=value&amp;two=value&amp;three=purple", $result);
}
/**
* test assetTimestamp application
*
* @return void
*/
public function testAssetTimestamp() {
Configure::write('Foo.bar', 'test');
Configure::write('Asset.timestamp', false);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertEquals(CSS_URL . 'cake.generic.css', $result);
Configure::write('Asset.timestamp', true);
Configure::write('debug', 0);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertEquals(CSS_URL . 'cake.generic.css', $result);
Configure::write('Asset.timestamp', true);
Configure::write('debug', 2);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertRegExp('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
Configure::write('Asset.timestamp', 'force');
Configure::write('debug', 0);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css');
$this->assertRegExp('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
$result = $this->Helper->assetTimestamp(CSS_URL . 'cake.generic.css?someparam');
$this->assertEquals(CSS_URL . 'cake.generic.css?someparam', $result);
$this->Helper->request->webroot = '/some/dir/';
$result = $this->Helper->assetTimestamp('/some/dir/' . CSS_URL . 'cake.generic.css');
$this->assertRegExp('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
}
/**
* test assetUrl application
*
* @return void
*/
public function testAssetUrl() {
$this->Helper->webroot = '';
$result = $this->Helper->assetUrl(array(
'controller' => 'js',
'action' => 'post',
'ext' => 'js'
),
array('fullBase' => true)
);
$this->assertEquals(FULL_BASE_URL . '/js/post.js', $result);
$result = $this->Helper->assetUrl('foo.jpg', array('pathPrefix' => 'img/'));
$this->assertEquals('img/foo.jpg', $result);
$result = $this->Helper->assetUrl('foo.jpg', array('fullBase' => true));
$this->assertEquals(FULL_BASE_URL . '/foo.jpg', $result);
$result = $this->Helper->assetUrl('style', array('ext' => '.css'));
$this->assertEquals('style.css', $result);
$result = $this->Helper->assetUrl('dir/sub dir/my image', array('ext' => '.jpg'));
$this->assertEquals('dir/sub%20dir/my%20image.jpg', $result);
$result = $this->Helper->assetUrl('foo.jpg?one=two&three=four');
$this->assertEquals('foo.jpg?one=two&amp;three=four', $result);
}
/**
* Test assetUrl with plugins.
*
* @return void
*/
public function testAssetUrlPlugin() {
$this->Helper->webroot = '';
CakePlugin::load('TestPlugin');
$result = $this->Helper->assetUrl('TestPlugin.style', array('ext' => '.css'));
$this->assertEquals('test_plugin/style.css', $result);
$result = $this->Helper->assetUrl('TestPlugin.style', array('ext' => '.css', 'plugin' => false));
$this->assertEquals('TestPlugin.style.css', $result);
CakePlugin::unload('TestPlugin');
}
/**
* test assetUrl and Asset.timestamp = force
*
* @return void
*/
public function testAssetUrlTimestampForce() {
$this->Helper->webroot = '';
Configure::write('Asset.timestamp', 'force');
$result = $this->Helper->assetUrl('cake.generic.css', array('pathPrefix' => CSS_URL));
$this->assertRegExp('/' . preg_quote(CSS_URL . 'cake.generic.css?', '/') . '[0-9]+/', $result);
}
/**
* test assetTimestamp with plugins and themes
*
* @return void
*/
public function testAssetTimestampPluginsAndThemes() {
Configure::write('Asset.timestamp', 'force');
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
));
CakePlugin::load(array('TestPlugin'));
$result = $this->Helper->assetTimestamp('/test_plugin/css/test_plugin_asset.css');
$this->assertRegExp('#/test_plugin/css/test_plugin_asset.css\?[0-9]+$#', $result, 'Missing timestamp plugin');
$result = $this->Helper->assetTimestamp('/test_plugin/css/i_dont_exist.css');
$this->assertRegExp('#/test_plugin/css/i_dont_exist.css\?$#', $result, 'No error on missing file');
$result = $this->Helper->assetTimestamp('/theme/test_theme/js/theme.js');
$this->assertRegExp('#/theme/test_theme/js/theme.js\?[0-9]+$#', $result, 'Missing timestamp theme');
$result = $this->Helper->assetTimestamp('/theme/test_theme/js/non_existant.js');
$this->assertRegExp('#/theme/test_theme/js/non_existant.js\?$#', $result, 'No error on missing file');
}
/**
* testFieldsWithSameName method
*
* @return void
*/
public function testFieldsWithSameName() {
$this->Helper->setEntity('HelperTestTag', true);
$this->Helper->setEntity('HelperTestTag.id');
$expected = array('HelperTestTag', 'id');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('My.id');
$expected = array('My', 'id');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('MyOther.id');
$expected = array('MyOther', 'id');
$this->assertEquals($expected, $this->Helper->entity());
}
/**
* testFieldSameAsModel method
*
* @return void
*/
public function testFieldSameAsModel() {
$this->Helper->setEntity('HelperTestTag', true);
$this->Helper->setEntity('helper_test_post');
$expected = array('HelperTestTag', 'helper_test_post');
$this->assertEquals($expected, $this->Helper->entity());
$this->Helper->setEntity('HelperTestTag');
$expected = array('HelperTestTag', 'HelperTestTag');
$this->assertEquals($expected, $this->Helper->entity());
}
/**
* testFieldSuffixForDate method
*
* @return void
*/
public function testFieldSuffixForDate() {
$this->Helper->setEntity('HelperTestPost', true);
$expected = array('HelperTestPost');
$this->assertEquals($expected, $this->Helper->entity());
foreach (array('year', 'month', 'day', 'hour', 'min', 'meridian') as $d) {
$this->Helper->setEntity('date.' . $d);
$expected = array('HelperTestPost', 'date', $d);
$this->assertEquals($expected, $this->Helper->entity());
}
}
/**
* testMulitDimensionValue method
*
* @return void
*/
public function testMultiDimensionValue() {
$this->Helper->data = array();
for ($i = 0; $i < 2; $i++) {
$this->Helper->request->data['Model'][$i] = 'what';
$result[] = $this->Helper->value("Model.{$i}");
$this->Helper->request->data['Model'][$i] = array();
for ($j = 0; $j < 2; $j++) {
$this->Helper->request->data['Model'][$i][$j] = 'how';
$result[] = $this->Helper->value("Model.{$i}.{$j}");
}
}
$expected = array('what', 'how', 'how', 'what', 'how', 'how');
$this->assertEquals($expected, $result);
$this->Helper->request->data['HelperTestComment']['5']['id'] = 'ok';
$result = $this->Helper->value('HelperTestComment.5.id');
$this->assertEquals('ok', $result);
$this->Helper->setEntity('HelperTestPost', true);
$this->Helper->request->data['HelperTestPost']['5']['created']['month'] = '10';
$result = $this->Helper->value('5.created.month');
$this->assertEquals(10, $result);
$this->Helper->request->data['HelperTestPost']['0']['id'] = 100;
$result = $this->Helper->value('HelperTestPost.0.id');
$this->assertEquals(100, $result);
}
/**
* testClean method
*
* @return void
*/
public function testClean() {
$result = $this->Helper->clean(array());
$this->assertEquals(null, $result);
$result = $this->Helper->clean(array('<script>with something</script>', '<applet>something else</applet>'));
$this->assertEquals(array('with something', 'something else'), $result);
$result = $this->Helper->clean('<script>with something</script>');
$this->assertEquals('with something', $result);
$result = $this->Helper->clean('<script type="text/javascript">alert("ruined");</script>');
$this->assertNotRegExp('#</*script#', $result);
$result = $this->Helper->clean("<script \ntype=\"text/javascript\">\n\talert('ruined');\n\n\t\t</script>");
$this->assertNotRegExp('#</*script#', $result);
$result = $this->Helper->clean('<body/onload=do(/something/)>');
$this->assertEquals('<body/>', $result);
$result = $this->Helper->clean('&lt;script&gt;alert(document.cookie)&lt;/script&gt;');
$this->assertEquals('&amp;lt;script&amp;gt;alert(document.cookie)&amp;lt;/script&amp;gt;', $result);
}
/**
* testMultiDimensionalField method
*
* @return void
*/
public function testMultiDimensionalField() {
$this->Helper->setEntity('HelperTestPost', true);
$entity = 'HelperTestPost.2.HelperTestComment.1.title';
$this->Helper->setEntity($entity);
$expected = array(
'HelperTestPost', '2', 'HelperTestComment', '1', 'title'
);
$this->assertEquals($expected, $this->Helper->entity());
$entity = 'HelperTestPost.1.HelperTestComment.1.HelperTestTag.1.created';
$this->Helper->setEntity($entity);
$expected = array(
'HelperTestPost', '1', 'HelperTestComment', '1',
'HelperTestTag', '1', 'created'
);
$this->assertEquals($expected, $this->Helper->entity());
$entity = 'HelperTestPost.0.HelperTestComment.1.HelperTestTag.1.fake';
$expected = array(
'HelperTestPost', '0', 'HelperTestComment', '1',
'HelperTestTag', '1', 'fake'
);
$this->Helper->setEntity($entity);
$entity = '1.HelperTestComment.1.HelperTestTag.created.year';
$this->Helper->setEntity($entity);
$this->Helper->request->data['HelperTestPost'][2]['HelperTestComment'][1]['title'] = 'My Title';
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.title');
$this->assertEquals('My Title', $result);
$this->Helper->request->data['HelperTestPost'][2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEquals(2008, $result);
$this->Helper->request->data[2]['HelperTestComment'][1]['created']['year'] = 2008;
$result = $this->Helper->value('HelperTestPost.2.HelperTestComment.1.created.year');
$this->assertEquals(2008, $result);
$this->Helper->request->data['HelperTestPost']['title'] = 'My Title';
$result = $this->Helper->value('title');
$this->assertEquals('My Title', $result);
$this->Helper->request->data['My']['title'] = 'My Title';
$result = $this->Helper->value('My.title');
$this->assertEquals('My Title', $result);
}
public function testWebrootPaths() {
$this->Helper->request->webroot = '/';
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/img/cake.power.gif';
$this->assertEquals($expected, $result);
$this->Helper->theme = 'test_theme';
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/theme/test_theme/img/cake.power.gif';
$this->assertEquals($expected, $result);
$result = $this->Helper->webroot('/img/test.jpg');
$expected = '/theme/test_theme/img/test.jpg';
$this->assertEquals($expected, $result);
$webRoot = Configure::read('App.www_root');
Configure::write('App.www_root', CAKE . 'Test' . DS . 'test_app' . DS . 'webroot' . DS);
$result = $this->Helper->webroot('/img/cake.power.gif');
$expected = '/theme/test_theme/img/cake.power.gif';
$this->assertEquals($expected, $result);
$result = $this->Helper->webroot('/img/test.jpg');
$expected = '/theme/test_theme/img/test.jpg';
$this->assertEquals($expected, $result);
$result = $this->Helper->webroot('/img/cake.icon.gif');
$expected = '/img/cake.icon.gif';
$this->assertEquals($expected, $result);
$result = $this->Helper->webroot('/img/cake.icon.gif?some=param');
$expected = '/img/cake.icon.gif?some=param';
$this->assertEquals($expected, $result);
Configure::write('App.www_root', $webRoot);
}
/**
* test lazy loading helpers is seamless
*
* @return void
*/
public function testLazyLoadingHelpers() {
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
));
CakePlugin::load(array('TestPlugin'));
$Helper = new TestHelper($this->View);
$this->assertInstanceOf('OtherHelperHelper', $Helper->OtherHelper);
$this->assertInstanceOf('HtmlHelper', $Helper->Html);
App::build();
}
/**
* test that a helpers Helper is not 'attached' to the collection
*
* @return void
*/
public function testThatHelperHelpersAreNotAttached() {
$Helper = new TestHelper($this->View);
$Helper->OtherHelper;
$result = $this->View->Helpers->enabled();
$expected = array();
$this->assertEquals($expected, $result, 'Helper helpers were attached to the collection.');
}
/**
* test that the lazy loader doesn't duplicate objects on each access.
*
* @return void
*/
public function testLazyLoadingUsesReferences() {
$Helper = new TestHelper($this->View);
$resultA = $Helper->Html;
$resultB = $Helper->Html;
$resultA->testprop = 1;
$this->assertEquals($resultA->testprop, $resultB->testprop);
}
}

View file

@ -0,0 +1,101 @@
<?php
/**
* JsonViewTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 2.1.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('JsonView', 'View');
/**
* JsonViewTest
*
* @package Cake.Test.Case.View
*/
class JsonViewTest extends CakeTestCase {
/**
* testRenderWithoutView method
*
* @return void
*/
public function testRenderWithoutView() {
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$data = array('user' => 'fake', 'list' => array('item1', 'item2'));
$Controller->set(array('data' => $data, '_serialize' => 'data'));
$View = new JsonView($Controller);
$output = $View->render(false);
$this->assertSame(json_encode($data), $output);
$this->assertSame('application/json', $Response->type());
}
/**
* Test render with an array in _serialize
*
* @return void
*/
public function testRenderWithoutViewMultiple() {
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$data = array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2'));
$Controller->set($data);
$Controller->set('_serialize', array('no', 'user'));
$View = new JsonView($Controller);
$output = $View->render(false);
$this->assertSame(json_encode(array('no' => $data['no'], 'user' => $data['user'])), $output);
$this->assertSame('application/json', $Response->type());
}
/**
* testRenderWithView method
*
* @return void
*/
public function testRenderWithView() {
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$Controller->name = $Controller->viewPath = 'Posts';
$data = array(
'User' => array(
'username' => 'fake'
),
'Item' => array(
array('name' => 'item1'),
array('name' => 'item2')
)
);
$Controller->set('user', $data);
$View = new JsonView($Controller);
$output = $View->render('index');
$expected = json_encode(array('user' => 'fake', 'list' => array('item1', 'item2')));
$this->assertSame($expected, $output);
$this->assertSame('application/json', $Response->type());
}
}

View file

@ -0,0 +1,377 @@
<?php
/**
* MediaViewTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('MediaView', 'View');
App::uses('CakeResponse', 'Network');
/**
* MediaViewTest class
*
* @package Cake.Test.Case.View
*/
class MediaViewTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->MediaView = $this->getMock('MediaView', array('_isActive', '_clearBuffer', '_flushBuffer'));
$this->MediaView->response = $this->getMock(
'CakeResponse',
array('send', 'cache', 'type', 'download', 'statusCode')
);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->MediaView);
}
/**
* tests that rendering a file that does not exists throws an exception
*
* @expectedException NotFoundException
* @return void
*/
public function testRenderNotFound() {
$this->MediaView->viewVars = array(
'path' => '/some/missing/folder',
'id' => 'file.jpg'
);
$this->MediaView->render();
}
/**
* testRender method
*
* @return void
*/
public function testRender() {
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
'id' => 'test_asset.css',
'extension' => 'css',
);
$this->MediaView->expects($this->exactly(2))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->response->expects($this->exactly(1))
->method('type')
->with('css')
->will($this->returnArgument(0));
$this->MediaView->response->expects($this->once())->method('send');
$this->MediaView->expects($this->once())->method('_clearBuffer');
$this->MediaView->expects($this->once())->method('_flushBuffer');
ob_start();
$result = $this->MediaView->render();
$output = ob_get_clean();
$this->assertEquals('this is the test asset css file', $output);
$this->assertTrue($result !== false);
$headers = $this->MediaView->response->header();
$this->assertEquals(31, $headers['Content-Length']);
$this->assertEquals(0, $headers['Expires']);
$this->assertEquals(
'private, must-revalidate, post-check=0, pre-check=0',
$headers['Cache-Control']
);
$this->assertEquals('no-cache', $headers['Pragma']);
$this->assertContains(gmdate('D, d M Y H:i', time()), $headers['Date']);
}
/**
* testRenderWithUnknownFileTypeGeneric method
*
* @return void
*/
public function testRenderWithUnknownFileTypeGeneric() {
$currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
$_SERVER['HTTP_USER_AGENT'] = 'Some generic browser';
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
'id' => 'no_section.ini',
'extension' => 'ini',
);
$this->MediaView->expects($this->exactly(2))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->response->expects($this->exactly(1))
->method('type')
->with('ini')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->once())
->method('download')
->with('no_section.ini');
$this->MediaView->response->expects($this->once())->method('send');
$this->MediaView->expects($this->once())->method('_clearBuffer');
$this->MediaView->expects($this->once())->method('_flushBuffer');
ob_start();
$result = $this->MediaView->render();
$output = ob_get_clean();
$this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
$this->assertTrue($result !== false);
if ($currentUserAgent !== null) {
$_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
}
$headers = $this->MediaView->response->header();
$this->assertEquals(35, $headers['Content-Length']);
$this->assertEquals(0, $headers['Expires']);
$this->assertEquals('bytes', $headers['Accept-Ranges']);
$this->assertEquals(
'private, must-revalidate, post-check=0, pre-check=0',
$headers['Cache-Control']
);
$this->assertEquals('no-cache', $headers['Pragma']);
$this->assertContains(gmdate('D, d M Y H:i', time()), $headers['Date']);
}
/**
* testRenderWithUnknownFileTypeOpera method
*
* @return void
*/
public function testRenderWithUnknownFileTypeOpera() {
$currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
$_SERVER['HTTP_USER_AGENT'] = 'Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10';
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
'id' => 'no_section.ini',
'extension' => 'ini',
);
$this->MediaView->expects($this->exactly(2))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->response->expects($this->at(0))
->method('type')
->with('ini')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->at(1))
->method('type')
->with('application/octetstream')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->once())
->method('download')
->with('no_section.ini');
$this->MediaView->response->expects($this->once())->method('send');
$this->MediaView->expects($this->once())->method('_clearBuffer');
$this->MediaView->expects($this->once())->method('_flushBuffer');
ob_start();
$result = $this->MediaView->render();
$output = ob_get_clean();
$this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
$this->assertTrue($result !== false);
if ($currentUserAgent !== null) {
$_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
}
$headers = $this->MediaView->response->header();
$this->assertEquals(35, $headers['Content-Length']);
$this->assertEquals(0, $headers['Expires']);
$this->assertEquals('bytes', $headers['Accept-Ranges']);
$this->assertEquals(
'private, must-revalidate, post-check=0, pre-check=0',
$headers['Cache-Control']
);
$this->assertEquals('no-cache', $headers['Pragma']);
$this->assertContains(gmdate('D, d M Y H:i', time()), $headers['Date']);
}
/**
* testRenderWithUnknownFileTypeIE method
*
* @return void
*/
public function testRenderWithUnknownFileTypeIE() {
$currentUserAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : null;
$_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; Media Center PC 4.0; SLCC1; .NET CLR 3.0.04320)';
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Config' . DS,
'id' => 'no_section.ini',
'extension' => 'ini',
'name' => 'config'
);
$this->MediaView->expects($this->exactly(2))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->response->expects($this->at(0))
->method('type')
->with('ini')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->at(1))
->method('type')
->with('application/force-download')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->once())
->method('download')
->with('config.ini');
$this->MediaView->response->expects($this->once())->method('send');
$this->MediaView->expects($this->once())->method('_clearBuffer');
$this->MediaView->expects($this->once())->method('_flushBuffer');
ob_start();
$result = $this->MediaView->render();
$output = ob_get_clean();
$this->assertEquals("some_key = some_value\nbool_key = 1\n", $output);
$this->assertTrue($result !== false);
if ($currentUserAgent !== null) {
$_SERVER['HTTP_USER_AGENT'] = $currentUserAgent;
}
$headers = $this->MediaView->response->header();
$this->assertEquals(35, $headers['Content-Length']);
$this->assertEquals(0, $headers['Expires']);
$this->assertEquals('bytes', $headers['Accept-Ranges']);
$this->assertEquals(
'private, must-revalidate, post-check=0, pre-check=0',
$headers['Cache-Control']
);
$this->assertEquals('no-cache', $headers['Pragma']);
$this->assertContains(gmdate('D, d M Y H:i', time()), $headers['Date']);
}
/**
* testConnectionAborted method
*
* @return void
*/
public function testConnectionAborted() {
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
'id' => 'test_asset.css',
'extension' => 'css',
);
$this->MediaView->expects($this->once())
->method('_isActive')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->never())
->method('type');
$result = $this->MediaView->render();
$this->assertFalse($result);
}
/**
* testConnectionAbortedOnBuffering method
*
* @return void
*/
public function testConnectionAbortedOnBuffering() {
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'css' . DS,
'id' => 'test_asset.css',
'extension' => 'css',
);
$this->MediaView->expects($this->at(0))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->response->expects($this->any())
->method('type')
->with('css')
->will($this->returnArgument(0));
$this->MediaView->expects($this->at(1))
->method('_isActive')
->will($this->returnValue(false));
$this->MediaView->response->expects($this->once())->method('send');
$this->MediaView->expects($this->once())->method('_clearBuffer');
$this->MediaView->expects($this->never())->method('_flushBuffer');
$result = $this->MediaView->render();
$this->assertFalse($result);
}
/**
* Test downloading files with UPPERCASE extensions.
*
* @return void
*/
public function testRenderUpperExtension() {
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'img' . DS,
'id' => 'test_2.JPG',
'extension' => 'JPG',
);
$this->MediaView->response->expects($this->any())
->method('type')
->with('jpg')
->will($this->returnArgument(0));
$this->MediaView->expects($this->at(0))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->render();
}
/**
* Test downloading files with extension not explicitly set.
*
* @return void
*/
public function testRenderExtensionNotSet() {
$this->MediaView->viewVars = array(
'path' => CAKE . 'Test' . DS . 'test_app' . DS . 'Vendor' . DS . 'img' . DS,
'id' => 'test_2.JPG',
);
$this->MediaView->response->expects($this->any())
->method('type')
->with('jpg')
->will($this->returnArgument(0));
$this->MediaView->expects($this->at(0))
->method('_isActive')
->will($this->returnValue(true));
$this->MediaView->render();
}
}

View file

@ -0,0 +1,463 @@
<?php
/**
* ScaffoldViewTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.Controller
* @since CakePHP(tm) v 2.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('Scaffold', 'Controller');
App::uses('ScaffoldView', 'View');
App::uses('AppModel', 'Model');
require_once dirname(dirname(__FILE__)) . DS . 'Model' . DS . 'models.php';
/**
* TestScaffoldView class
*
* @package Cake.Test.Case.Controller
*/
class TestScaffoldView extends ScaffoldView {
/**
* testGetFilename method
*
* @param string $action
* @return void
*/
public function testGetFilename($action) {
return $this->_getViewFileName($action);
}
}
/**
* ScaffoldViewMockController class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldViewMockController extends Controller {
/**
* name property
*
* @var string 'ScaffoldMock'
*/
public $name = 'ScaffoldMock';
/**
* scaffold property
*
* @var mixed
*/
public $scaffold;
}
/**
* ScaffoldViewTest class
*
* @package Cake.Test.Case.Controller
*/
class ScaffoldViewTest extends CakeTestCase {
/**
* fixtures property
*
* @var array
*/
public $fixtures = array('core.article', 'core.user', 'core.comment', 'core.join_thing', 'core.tag');
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$this->request = new CakeRequest(null, false);
$this->Controller = new ScaffoldViewMockController($this->request);
$this->Controller->response = $this->getMock('CakeResponse', array('_sendHeader'));
App::build(array(
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS),
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS)
));
CakePlugin::load('TestPlugin');
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
unset($this->Controller, $this->request);
parent::tearDown();
}
/**
* testGetViewFilename method
*
* @return void
*/
public function testGetViewFilename() {
$_admin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$this->Controller->request->params['action'] = 'index';
$ScaffoldView = new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'index.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('edit');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('add');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('view');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'view.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('admin_index');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'index.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('admin_view');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'view.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('admin_edit');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('admin_add');
$expected = CAKE . 'View' . DS . 'Scaffolds' . DS . 'form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('error');
$expected = CAKE . 'View' . DS . 'Errors' . DS . 'scaffold_error.ctp';
$this->assertEquals($expected, $result);
$Controller = new ScaffoldViewMockController($this->request);
$Controller->scaffold = 'admin';
$Controller->viewPath = 'Posts';
$Controller->request['action'] = 'admin_edit';
$ScaffoldView = new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_edit');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('edit');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Posts' . DS . 'scaffold.form.ctp';
$this->assertEquals($expected, $result);
$Controller = new ScaffoldViewMockController($this->request);
$Controller->scaffold = 'admin';
$Controller->viewPath = 'Tests';
$Controller->request->addParams(array(
'plugin' => 'test_plugin',
'action' => 'admin_add',
'admin' => true
));
$Controller->plugin = 'TestPlugin';
$ScaffoldView = new TestScaffoldView($Controller);
$result = $ScaffoldView->testGetFilename('admin_add');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
$this->assertEquals($expected, $result);
$result = $ScaffoldView->testGetFilename('add');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' .
DS . 'TestPlugin' . DS . 'View' . DS . 'Tests' . DS . 'scaffold.form.ctp';
$this->assertEquals($expected, $result);
Configure::write('Routing.prefixes', $_admin);
}
/**
* test getting the view file name for themed scaffolds.
*
* @return void
*/
public function testGetViewFileNameWithTheme() {
$this->Controller->request['action'] = 'index';
$this->Controller->viewPath = 'Posts';
$this->Controller->theme = 'TestTheme';
$ScaffoldView = new TestScaffoldView($this->Controller);
$result = $ScaffoldView->testGetFilename('index');
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS .
'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'scaffold.index.ctp';
$this->assertEquals($expected, $result);
}
/**
* test default index scaffold generation
*
* @return void
*/
public function testIndexScaffold() {
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'index',
);
$this->Controller->request->addParams($params);
$this->Controller->request->webroot = '/';
$this->Controller->request->base = '';
$this->Controller->request->here = '/scaffold_mock/index';
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('#<h2>Scaffold Mock</h2>#', $result);
$this->assertRegExp('#<table cellpadding="0" cellspacing="0">#', $result);
$this->assertRegExp('#<a href="/scaffold_users/view/1">1</a>#', $result); //belongsTo links
$this->assertRegExp('#<li><a href="/scaffold_mock/add">New Scaffold Mock</a></li>#', $result);
$this->assertRegExp('#<li><a href="/scaffold_users">List Scaffold Users</a></li>#', $result);
$this->assertRegExp('#<li><a href="/scaffold_comments/add">New Comment</a></li>#', $result);
}
/**
* test default view scaffold generation
*
* @return void
*/
public function testViewScaffold() {
$this->Controller->request->base = '';
$this->Controller->request->here = '/scaffold_mock';
$this->Controller->request->webroot = '/';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock/view/1'),
'controller' => 'scaffold_mock',
'action' => 'view',
);
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/<h2>View Scaffold Mock<\/h2>/', $result);
$this->assertRegExp('/<dl>/', $result);
$this->assertRegExp('/<a href="\/scaffold_users\/view\/1">1<\/a>/', $result); //belongsTo links
$this->assertRegExp('/<li><a href="\/scaffold_mock\/edit\/1">Edit Scaffold Mock<\/a>\s<\/li>/', $result);
$this->assertRegExp('/<a href="\#" onclick="if[^>]*>Delete Scaffold Mock<\/a>\s<\/li>/', $result);
//check related table
$this->assertRegExp('/<div class="related">\s*<h3>Related Scaffold Comments<\/h3>\s*<table cellpadding="0" cellspacing="0">/', $result);
$this->assertRegExp('/<li><a href="\/scaffold_comments\/add">New Comment<\/a><\/li>/', $result);
$this->assertNotRegExp('/<th>JoinThing<\/th>/', $result);
}
/**
* test default view scaffold generation
*
* @return void
*/
public function testEditScaffold() {
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/scaffold_mock/edit/1';
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'url' => array('url' => 'scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'edit',
);
$this->Controller->request->addParams($params);
//set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->constructClasses();
ob_start();
new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertContains('<form action="/scaffold_mock/edit/1" id="ScaffoldMockEditForm" method="post"', $result);
$this->assertContains('<legend>Edit Scaffold Mock</legend>', $result);
$this->assertContains('input type="hidden" name="data[ScaffoldMock][id]" value="1" id="ScaffoldMockId"', $result);
$this->assertContains('select name="data[ScaffoldMock][user_id]" id="ScaffoldMockUserId"', $result);
$this->assertContains('input name="data[ScaffoldMock][title]" maxlength="255" type="text" value="First Article" id="ScaffoldMockTitle"', $result);
$this->assertContains('input name="data[ScaffoldMock][published]" maxlength="1" type="text" value="Y" id="ScaffoldMockPublished"', $result);
$this->assertContains('textarea name="data[ScaffoldMock][body]" cols="30" rows="6" id="ScaffoldMockBody"', $result);
$this->assertRegExp('/<a href="\#" onclick="if[^>]*>Delete<\/a><\/li>/', $result);
}
/**
* Test Admin Index Scaffolding.
*
* @return void
*/
public function testAdminIndexScaffold() {
$_backAdmin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin'));
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'prefix' => 'admin',
'url' => array('url' => 'admin/scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'admin_index',
'admin' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/<h2>Scaffold Mock<\/h2>/', $result);
$this->assertRegExp('/<table cellpadding="0" cellspacing="0">/', $result);
$this->assertRegExp('/<li><a href="\/admin\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
Configure::write('Routing.prefixes', $_backAdmin);
}
/**
* Test Admin Index Scaffolding.
*
* @return void
*/
public function testAdminEditScaffold() {
Configure::write('Routing.prefixes', array('admin'));
$params = array(
'plugin' => null,
'pass' => array(1),
'form' => array(),
'named' => array(),
'prefix' => 'admin',
'url' => array('url' => 'admin/scaffold_mock/edit/1'),
'controller' => 'scaffold_mock',
'action' => 'admin_edit',
'admin' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/admin/scaffold_mock/edit/1';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'admin';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('#admin/scaffold_mock/edit/1#', $result);
$this->assertRegExp('#Scaffold Mock#', $result);
}
/**
* Test Admin Index Scaffolding.
*
* @return void
*/
public function testMultiplePrefixScaffold() {
$_backAdmin = Configure::read('Routing.prefixes');
Configure::write('Routing.prefixes', array('admin', 'member'));
$params = array(
'plugin' => null,
'pass' => array(),
'form' => array(),
'named' => array(),
'prefix' => 'member',
'url' => array('url' => 'member/scaffold_mock'),
'controller' => 'scaffold_mock',
'action' => 'member_index',
'member' => 1,
);
$this->Controller->request->base = '';
$this->Controller->request->webroot = '/';
$this->Controller->request->here = '/member/scaffold_mock';
$this->Controller->request->addParams($params);
//reset, and set router.
Router::reload();
Router::setRequestInfo($this->Controller->request);
$this->Controller->scaffold = 'member';
$this->Controller->constructClasses();
ob_start();
$Scaffold = new Scaffold($this->Controller, $this->Controller->request);
$this->Controller->response->send();
$result = ob_get_clean();
$this->assertRegExp('/<h2>Scaffold Mock<\/h2>/', $result);
$this->assertRegExp('/<table cellpadding="0" cellspacing="0">/', $result);
$this->assertRegExp('/<li><a href="\/member\/scaffold_mock\/add">New Scaffold Mock<\/a><\/li>/', $result);
Configure::write('Routing.prefixes', $_backAdmin);
}
}

View file

@ -0,0 +1,265 @@
<?php
/**
* ThemeViewTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 1.2.0.4206
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('View', 'View');
App::uses('ThemeView', 'View');
App::uses('Controller', 'Controller');
/**
* ThemePosts2Controller class
*
* @package Cake.Test.Case.View
*/
class ThemePosts2Controller extends Controller {
/**
* name property
*
* @var string 'ThemePosts'
*/
public $name = 'ThemePosts';
public $theme = null;
/**
* index method
*
* @return void
*/
public function index() {
$this->set(array(
'testData' => 'Some test data',
'test2' => 'more data',
'test3' => 'even more data',
));
}
}
/**
* TestTheme2View class
*
* @package Cake.Test.Case.View
*/
class TestTheme2View extends ThemeView {
/**
* renderElement method
*
* @param string $name
* @param array $params
* @return void
*/
public function renderElement($name, $params = array()) {
return $name;
}
/**
* getViewFileName method
*
* @param string $name
* @return void
*/
public function getViewFileName($name = null) {
return $this->_getViewFileName($name);
}
/**
* getLayoutFileName method
*
* @param string $name
* @return void
*/
public function getLayoutFileName($name = null) {
return $this->_getLayoutFileName($name);
}
}
/**
* ThemeViewTest class
*
* @package Cake.Test.Case.View
*/
class ThemeViewTest extends CakeTestCase {
/**
* setUp method
*
* @return void
*/
public function setUp() {
parent::setUp();
$request = new CakeRequest('posts/index');
$this->Controller = new Controller($request);
$this->PostsController = new ThemePosts2Controller($request);
$this->PostsController->viewPath = 'posts';
$this->PostsController->index();
$this->ThemeView = new ThemeView($this->PostsController);
App::build(array(
'Plugin' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'Plugin' . DS),
'View' => array(CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS)
));
App::objects('plugins', null, false);
CakePlugin::load(array('TestPlugin'));
}
/**
* tearDown method
*
* @return void
*/
public function tearDown() {
parent::tearDown();
unset($this->ThemeView);
unset($this->PostsController);
unset($this->Controller);
CakePlugin::unload();
}
/**
* testPluginGetTemplate method
*
* @return void
*/
public function testPluginThemedGetTemplate() {
$this->Controller->plugin = 'TestPlugin';
$this->Controller->name = 'TestPlugin';
$this->Controller->viewPath = 'Tests';
$this->Controller->action = 'index';
$this->Controller->theme = 'TestTheme';
$ThemeView = new TestTheme2View($this->Controller);
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Tests' . DS . 'index.ctp';
$result = $ThemeView->getViewFileName('index');
$this->assertEquals($expected, $result);
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Plugin' . DS . 'TestPlugin' . DS . 'Layouts' . DS . 'plugin_default.ctp';
$result = $ThemeView->getLayoutFileName('plugin_default');
$this->assertEquals($expected, $result);
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
$result = $ThemeView->getLayoutFileName('default');
$this->assertEquals($expected, $result);
}
/**
* testGetTemplate method
*
* @return void
*/
public function testGetTemplate() {
$this->Controller->plugin = null;
$this->Controller->name = 'Pages';
$this->Controller->viewPath = 'Pages';
$this->Controller->action = 'display';
$this->Controller->params['pass'] = array('home');
$ThemeView = new TestTheme2View($this->Controller);
$ThemeView->theme = 'TestTheme';
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Pages' . DS . 'home.ctp';
$result = $ThemeView->getViewFileName('home');
$this->assertEquals($expected, $result);
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Posts' . DS . 'index.ctp';
$result = $ThemeView->getViewFileName('/Posts/index');
$this->assertEquals($expected, $result);
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Themed' . DS . 'TestTheme' . DS . 'Layouts' . DS . 'default.ctp';
$result = $ThemeView->getLayoutFileName();
$this->assertEquals($expected, $result);
$ThemeView->layoutPath = 'rss';
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Layouts' . DS . 'rss' . DS . 'default.ctp';
$result = $ThemeView->getLayoutFileName();
$this->assertEquals($expected, $result);
$ThemeView->layoutPath = 'Emails' . DS . 'html';
$expected = CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS . 'Layouts' . DS . 'Emails' . DS . 'html' . DS . 'default.ctp';
$result = $ThemeView->getLayoutFileName();
$this->assertEquals($expected, $result);
}
/**
* testMissingView method
*
* @expectedException MissingViewException
* @return void
*/
public function testMissingView() {
$this->Controller->plugin = null;
$this->Controller->name = 'Pages';
$this->Controller->viewPath = 'Pages';
$this->Controller->action = 'display';
$this->Controller->theme = 'my_theme';
$this->Controller->params['pass'] = array('home');
$View = new TestTheme2View($this->Controller);
ob_start();
$result = $View->getViewFileName('does_not_exist');
$expected = ob_get_clean();
$this->assertRegExp("/PagesController::/", $expected);
$this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)pages(\/|\\\)does_not_exist.ctp/", $expected);
}
/**
* testMissingLayout method
*
* @expectedException MissingLayoutException
* @return void
*/
public function testMissingLayout() {
$this->Controller->plugin = null;
$this->Controller->name = 'Posts';
$this->Controller->viewPath = 'posts';
$this->Controller->layout = 'whatever';
$this->Controller->theme = 'my_theme';
$View = new TestTheme2View($this->Controller);
ob_start();
$result = $View->getLayoutFileName();
$expected = ob_get_clean();
$this->assertRegExp("/Missing Layout/", $expected);
$this->assertRegExp("/views(\/|\\\)themed(\/|\\\)my_theme(\/|\\\)layouts(\/|\\\)whatever.ctp/", $expected);
}
/**
* test memory leaks that existed in _paths at one point.
*
* @return void
*/
public function testMemoryLeakInPaths() {
$this->Controller->plugin = null;
$this->Controller->name = 'Posts';
$this->Controller->viewPath = 'posts';
$this->Controller->layout = 'whatever';
$this->Controller->theme = 'TestTheme';
$View = new ThemeView($this->Controller);
$View->element('test_element');
$start = memory_get_usage();
for ($i = 0; $i < 10; $i++) {
$View->element('test_element');
}
$end = memory_get_usage();
$this->assertLessThanOrEqual($start + 5000, $end);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,130 @@
<?php
/**
* XmlViewTest file
*
* PHP 5
*
* CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice
*
* @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
* @package Cake.Test.Case.View
* @since CakePHP(tm) v 2.1.0
* @license MIT License (http://www.opensource.org/licenses/mit-license.php)
*/
App::uses('Controller', 'Controller');
App::uses('CakeRequest', 'Network');
App::uses('CakeResponse', 'Network');
App::uses('XmlView', 'View');
/**
* XmlViewTest
*
* @package Cake.Test.Case.View
*/
class XmlViewTest extends CakeTestCase {
/**
* testRenderWithoutView method
*
* @return void
*/
public function testRenderWithoutView() {
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$data = array('users' => array('user' => array('user1', 'user2')));
$Controller->set(array('users' => $data, '_serialize' => 'users'));
$View = new XmlView($Controller);
$output = $View->render(false);
$this->assertSame(Xml::build($data)->asXML(), $output);
$this->assertSame('application/xml', $Response->type());
$data = array(
array(
'User' => array(
'username' => 'user1'
)
),
array(
'User' => array(
'username' => 'user2'
)
)
);
$Controller->set(array('users' => $data, '_serialize' => 'users'));
$View = new XmlView($Controller);
$output = $View->render(false);
$expected = Xml::build(array('response' => array('users' => $data)))->asXML();
$this->assertSame($expected, $output);
}
/**
* Test render with an array in _serialize
*
* @return void
*/
public function testRenderWithoutViewMultiple() {
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$data = array('no' => 'nope', 'user' => 'fake', 'list' => array('item1', 'item2'));
$Controller->set($data);
$Controller->set('_serialize', array('no', 'user'));
$View = new XmlView($Controller);
$output = $View->render(false);
$expected = array(
'response' => array('no' => $data['no'], 'user' => $data['user'])
);
$this->assertSame(Xml::build($expected)->asXML(), $output);
$this->assertSame('application/xml', $Response->type());
}
/**
* testRenderWithView method
*
* @return void
*/
public function testRenderWithView() {
App::build(array('View' => array(
CAKE . 'Test' . DS . 'test_app' . DS . 'View' . DS
)));
$Request = new CakeRequest();
$Response = new CakeResponse();
$Controller = new Controller($Request, $Response);
$Controller->name = $Controller->viewPath = 'Posts';
$data = array(
array(
'User' => array(
'username' => 'user1'
)
),
array(
'User' => array(
'username' => 'user2'
)
)
);
$Controller->set('users', $data);
$View = new XmlView($Controller);
$output = $View->render('index');
$expected = array(
'users' => array('user' => array('user1', 'user2'))
);
$expected = Xml::build($expected)->asXML();
$this->assertSame($expected, $output);
$this->assertSame('application/xml', $Response->type());
$this->assertInstanceOf('HelperCollection', $View->Helpers);
}
}