ControllerTest.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP Project
  12. * @since 1.2.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Controller;
  16. use Cake\Controller\Component;
  17. use Cake\Controller\Controller;
  18. use Cake\Core\Configure;
  19. use Cake\Core\Plugin;
  20. use Cake\Event\Event;
  21. use Cake\Http\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\ORM\TableRegistry;
  24. use Cake\Routing\Router;
  25. use Cake\TestSuite\TestCase;
  26. use TestApp\Controller\Admin\PostsController;
  27. use TestPlugin\Controller\TestPluginController;
  28. /**
  29. * AppController class
  30. */
  31. class ControllerTestAppController extends Controller
  32. {
  33. /**
  34. * helpers property
  35. *
  36. * @var array
  37. */
  38. public $helpers = ['Html'];
  39. /**
  40. * modelClass property
  41. *
  42. * @var string
  43. */
  44. public $modelClass = 'Posts';
  45. /**
  46. * components property
  47. *
  48. * @var array
  49. */
  50. public $components = ['Cookie'];
  51. }
  52. /**
  53. * TestController class
  54. */
  55. class TestController extends ControllerTestAppController
  56. {
  57. /**
  58. * Theme property
  59. *
  60. * @var string
  61. */
  62. public $theme = 'Foo';
  63. /**
  64. * helpers property
  65. *
  66. * @var array
  67. */
  68. public $helpers = ['Html'];
  69. /**
  70. * components property
  71. *
  72. * @var array
  73. */
  74. public $components = ['Security'];
  75. /**
  76. * modelClass property
  77. *
  78. * @var string
  79. */
  80. public $modelClass = 'Comments';
  81. /**
  82. * beforeFilter handler
  83. *
  84. * @param \Cake\Event\Event $event
  85. * @return void
  86. */
  87. public function beforeFilter(Event $event)
  88. {
  89. }
  90. /**
  91. * index method
  92. *
  93. * @param mixed $testId
  94. * @param mixed $testTwoId
  95. * @return void
  96. */
  97. public function index($testId, $testTwoId)
  98. {
  99. $this->request->data = [
  100. 'testId' => $testId,
  101. 'test2Id' => $testTwoId
  102. ];
  103. }
  104. /**
  105. * view method
  106. *
  107. * @param mixed $testId
  108. * @param mixed $testTwoId
  109. * @return void
  110. */
  111. public function view($testId, $testTwoId)
  112. {
  113. $this->request->data = [
  114. 'testId' => $testId,
  115. 'test2Id' => $testTwoId
  116. ];
  117. }
  118. public function returner()
  119. {
  120. return 'I am from the controller.';
  121. }
  122. //@codingStandardsIgnoreStart
  123. protected function protected_m()
  124. {
  125. }
  126. private function private_m()
  127. {
  128. }
  129. public function _hidden()
  130. {
  131. }
  132. //@codingStandardsIgnoreEnd
  133. public function admin_add()
  134. {
  135. }
  136. }
  137. /**
  138. * TestComponent class
  139. */
  140. class TestComponent extends Component
  141. {
  142. /**
  143. * beforeRedirect method
  144. *
  145. * @return void
  146. */
  147. public function beforeRedirect()
  148. {
  149. }
  150. /**
  151. * initialize method
  152. *
  153. * @param array $config
  154. * @return void
  155. */
  156. public function initialize(array $config)
  157. {
  158. }
  159. /**
  160. * startup method
  161. *
  162. * @param Event $event
  163. * @return void
  164. */
  165. public function startup(Event $event)
  166. {
  167. }
  168. /**
  169. * shutdown method
  170. *
  171. * @param Event $event
  172. * @return void
  173. */
  174. public function shutdown(Event $event)
  175. {
  176. }
  177. /**
  178. * beforeRender callback
  179. *
  180. * @param Event $event
  181. * @return void
  182. */
  183. public function beforeRender(Event $event)
  184. {
  185. $controller = $event->subject();
  186. if ($this->viewclass) {
  187. $controller->viewClass = $this->viewclass;
  188. }
  189. }
  190. }
  191. /**
  192. * AnotherTestController class
  193. */
  194. class AnotherTestController extends ControllerTestAppController
  195. {
  196. }
  197. /**
  198. * ControllerTest class
  199. */
  200. class ControllerTest extends TestCase
  201. {
  202. /**
  203. * fixtures property
  204. *
  205. * @var array
  206. */
  207. public $fixtures = [
  208. 'core.comments',
  209. 'core.posts'
  210. ];
  211. /**
  212. * reset environment.
  213. *
  214. * @return void
  215. */
  216. public function setUp()
  217. {
  218. parent::setUp();
  219. static::setAppNamespace();
  220. Router::reload();
  221. }
  222. /**
  223. * tearDown
  224. *
  225. * @return void
  226. */
  227. public function tearDown()
  228. {
  229. parent::tearDown();
  230. Plugin::unload();
  231. }
  232. /**
  233. * test autoload modelClass
  234. *
  235. * @return void
  236. */
  237. public function testTableAutoload()
  238. {
  239. $request = new ServerRequest('controller_posts/index');
  240. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  241. $Controller = new Controller($request, $response);
  242. $Controller->modelClass = 'SiteArticles';
  243. $this->assertFalse($Controller->Articles);
  244. $this->assertInstanceOf(
  245. 'Cake\ORM\Table',
  246. $Controller->SiteArticles
  247. );
  248. unset($Controller->SiteArticles);
  249. $Controller->modelClass = 'Articles';
  250. $this->assertFalse($Controller->SiteArticles);
  251. $this->assertInstanceOf(
  252. 'TestApp\Model\Table\ArticlesTable',
  253. $Controller->Articles
  254. );
  255. }
  256. /**
  257. * testLoadModel method
  258. *
  259. * @return void
  260. */
  261. public function testLoadModel()
  262. {
  263. $request = new ServerRequest('controller_posts/index');
  264. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  265. $Controller = new Controller($request, $response);
  266. $this->assertFalse(isset($Controller->Articles));
  267. $result = $Controller->loadModel('Articles');
  268. $this->assertInstanceOf(
  269. 'TestApp\Model\Table\ArticlesTable',
  270. $result
  271. );
  272. $this->assertInstanceOf(
  273. 'TestApp\Model\Table\ArticlesTable',
  274. $Controller->Articles
  275. );
  276. }
  277. /**
  278. * testLoadModel method from a plugin controller
  279. *
  280. * @return void
  281. */
  282. public function testLoadModelInPlugins()
  283. {
  284. Plugin::load('TestPlugin');
  285. $Controller = new TestPluginController();
  286. $Controller->plugin = 'TestPlugin';
  287. $this->assertFalse(isset($Controller->TestPluginComments));
  288. $result = $Controller->loadModel('TestPlugin.TestPluginComments');
  289. $this->assertInstanceOf(
  290. 'TestPlugin\Model\Table\TestPluginCommentsTable',
  291. $result
  292. );
  293. $this->assertInstanceOf(
  294. 'TestPlugin\Model\Table\TestPluginCommentsTable',
  295. $Controller->TestPluginComments
  296. );
  297. }
  298. /**
  299. * Test that the constructor sets modelClass properly.
  300. *
  301. * @return void
  302. */
  303. public function testConstructSetModelClass()
  304. {
  305. Plugin::load('TestPlugin');
  306. $request = new ServerRequest();
  307. $response = new Response();
  308. $controller = new \TestApp\Controller\PostsController($request, $response);
  309. $this->assertEquals('Posts', $controller->modelClass);
  310. $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
  311. $controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  312. $this->assertEquals('Posts', $controller->modelClass);
  313. $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
  314. $request->params['plugin'] = 'TestPlugin';
  315. $controller = new \TestPlugin\Controller\Admin\CommentsController($request, $response);
  316. $this->assertEquals('TestPlugin.Comments', $controller->modelClass);
  317. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $controller->Comments);
  318. }
  319. /**
  320. * testConstructClassesWithComponents method
  321. *
  322. * @return void
  323. */
  324. public function testConstructClassesWithComponents()
  325. {
  326. Plugin::load('TestPlugin');
  327. $Controller = new TestPluginController(new ServerRequest(), new Response());
  328. $Controller->loadComponent('TestPlugin.Other');
  329. $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $Controller->Other);
  330. }
  331. /**
  332. * testRender method
  333. *
  334. * @return void
  335. */
  336. public function testRender()
  337. {
  338. Plugin::load('TestPlugin');
  339. $request = new ServerRequest('controller_posts/index');
  340. $request->params['action'] = 'index';
  341. $Controller = new Controller($request, new Response());
  342. $Controller->viewBuilder()->templatePath('Posts');
  343. $result = $Controller->render('index');
  344. $this->assertRegExp('/posts index/', (string)$result);
  345. $Controller->viewBuilder()->template('index');
  346. $result = $Controller->render();
  347. $this->assertRegExp('/posts index/', (string)$result);
  348. $result = $Controller->render('/Element/test_element');
  349. $this->assertRegExp('/this is the test element/', (string)$result);
  350. }
  351. /**
  352. * test view rendering changing response
  353. *
  354. * @return void
  355. */
  356. public function testRenderViewChangesResponse()
  357. {
  358. $request = new ServerRequest('controller_posts/index');
  359. $request->params['action'] = 'header';
  360. $controller = new Controller($request, new Response());
  361. $controller->viewBuilder()->templatePath('Posts');
  362. $result = $controller->render('header');
  363. $this->assertContains('header template', (string)$result);
  364. $this->assertTrue($controller->response->hasHeader('X-view-template'));
  365. $this->assertSame('yes', $controller->response->getHeaderLine('X-view-template'));
  366. }
  367. /**
  368. * test that a component beforeRender can change the controller view class.
  369. *
  370. * @return void
  371. */
  372. public function testBeforeRenderCallbackChangingViewClass()
  373. {
  374. $Controller = new Controller(new ServerRequest, new Response());
  375. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  376. $controller = $event->subject();
  377. $controller->viewClass = 'Json';
  378. });
  379. $Controller->set([
  380. 'test' => 'value',
  381. '_serialize' => ['test']
  382. ]);
  383. $debug = Configure::read('debug');
  384. Configure::write('debug', false);
  385. $result = $Controller->render('index');
  386. $this->assertEquals('{"test":"value"}', $result->body());
  387. Configure::write('debug', $debug);
  388. }
  389. /**
  390. * test that a component beforeRender can change the controller view class.
  391. *
  392. * @return void
  393. */
  394. public function testBeforeRenderEventCancelsRender()
  395. {
  396. $Controller = new Controller(new ServerRequest, new Response());
  397. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  398. return false;
  399. });
  400. $result = $Controller->render('index');
  401. $this->assertInstanceOf('Cake\Http\Response', $result);
  402. }
  403. /**
  404. * Generates status codes for redirect test.
  405. *
  406. * @return void
  407. */
  408. public static function statusCodeProvider()
  409. {
  410. return [
  411. [300, 'Multiple Choices'],
  412. [301, 'Moved Permanently'],
  413. [302, 'Found'],
  414. [303, 'See Other'],
  415. [304, 'Not Modified'],
  416. [305, 'Use Proxy'],
  417. [307, 'Temporary Redirect'],
  418. [403, 'Forbidden'],
  419. ];
  420. }
  421. /**
  422. * testRedirect method
  423. *
  424. * @dataProvider statusCodeProvider
  425. * @return void
  426. */
  427. public function testRedirectByCode($code, $msg)
  428. {
  429. $Controller = new Controller(null, new Response());
  430. $response = $Controller->redirect('http://cakephp.org', (int)$code);
  431. $this->assertSame($response, $Controller->response);
  432. $this->assertEquals($code, $response->statusCode());
  433. $this->assertEquals('http://cakephp.org', $response->header()['Location']);
  434. $this->assertFalse($Controller->autoRender);
  435. }
  436. /**
  437. * test that beforeRedirect callbacks can set the URL that is being redirected to.
  438. *
  439. * @return void
  440. */
  441. public function testRedirectBeforeRedirectModifyingUrl()
  442. {
  443. $Controller = new Controller(null, new Response());
  444. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) {
  445. $response->location('https://book.cakephp.org');
  446. });
  447. $response = $Controller->redirect('http://cakephp.org', 301);
  448. $this->assertEquals('https://book.cakephp.org', $response->header()['Location']);
  449. $this->assertEquals(301, $response->statusCode());
  450. }
  451. /**
  452. * test that beforeRedirect callback returning null doesn't affect things.
  453. *
  454. * @return void
  455. */
  456. public function testRedirectBeforeRedirectModifyingStatusCode()
  457. {
  458. $Response = $this->getMockBuilder('Cake\Http\Response')
  459. ->setMethods(['stop'])
  460. ->getMock();
  461. $Controller = new Controller(null, $Response);
  462. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) {
  463. $response->statusCode(302);
  464. });
  465. $response = $Controller->redirect('http://cakephp.org', 301);
  466. $this->assertEquals('http://cakephp.org', $response->header()['Location']);
  467. $this->assertEquals(302, $response->statusCode());
  468. }
  469. public function testRedirectBeforeRedirectListenerReturnResponse()
  470. {
  471. $Response = $this->getMockBuilder('Cake\Http\Response')
  472. ->setMethods(['stop', 'header', 'statusCode'])
  473. ->getMock();
  474. $Controller = new Controller(null, $Response);
  475. $newResponse = new Response;
  476. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) {
  477. return $newResponse;
  478. });
  479. $result = $Controller->redirect('http://cakephp.org');
  480. $this->assertSame($newResponse, $result);
  481. $this->assertSame($newResponse, $Controller->response);
  482. }
  483. /**
  484. * testMergeVars method
  485. *
  486. * @return void
  487. */
  488. public function testMergeVars()
  489. {
  490. $request = new ServerRequest();
  491. $TestController = new TestController($request);
  492. $expected = [
  493. 'Html' => null,
  494. ];
  495. $this->assertEquals($expected, $TestController->helpers);
  496. $expected = [
  497. 'Security' => null,
  498. 'Cookie' => null,
  499. ];
  500. $this->assertEquals($expected, $TestController->components);
  501. $TestController = new AnotherTestController($request);
  502. $this->assertEquals(
  503. 'Posts',
  504. $TestController->modelClass,
  505. 'modelClass should not be overwritten when defined.'
  506. );
  507. }
  508. /**
  509. * testReferer method
  510. *
  511. * @return void
  512. */
  513. public function testReferer()
  514. {
  515. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  516. ->setMethods(['referer'])
  517. ->getMock();
  518. $request->expects($this->any())->method('referer')
  519. ->with(true)
  520. ->will($this->returnValue('/posts/index'));
  521. $Controller = new Controller($request);
  522. $result = $Controller->referer(null, true);
  523. $this->assertEquals('/posts/index', $result);
  524. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  525. ->setMethods(['referer'])
  526. ->getMock();
  527. $request->expects($this->any())->method('referer')
  528. ->with(true)
  529. ->will($this->returnValue('/posts/index'));
  530. $Controller = new Controller($request);
  531. $result = $Controller->referer(['controller' => 'posts', 'action' => 'index'], true);
  532. $this->assertEquals('/posts/index', $result);
  533. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  534. ->setMethods(['referer'])
  535. ->getMock();
  536. $request->expects($this->any())->method('referer')
  537. ->with(false)
  538. ->will($this->returnValue('http://localhost/posts/index'));
  539. $Controller = new Controller($request);
  540. $result = $Controller->referer();
  541. $this->assertEquals('http://localhost/posts/index', $result);
  542. $Controller = new Controller(null);
  543. $result = $Controller->referer();
  544. $this->assertEquals('/', $result);
  545. }
  546. /**
  547. * Test that the referer is not absolute if it is '/'.
  548. *
  549. * This avoids the base path being applied twice on string urls.
  550. *
  551. * @return void
  552. */
  553. public function testRefererSlash()
  554. {
  555. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  556. ->setMethods(['referer'])
  557. ->getMock();
  558. $request->base = '/base';
  559. Router::pushRequest($request);
  560. $request->expects($this->any())->method('referer')
  561. ->will($this->returnValue('/'));
  562. $controller = new Controller($request);
  563. $result = $controller->referer('/', true);
  564. $this->assertEquals('/', $result);
  565. $controller = new Controller($request);
  566. $result = $controller->referer('/some/path', true);
  567. $this->assertEquals('/some/path', $result);
  568. }
  569. /**
  570. * testSetAction method
  571. *
  572. * @return void
  573. */
  574. public function testSetAction()
  575. {
  576. $request = new ServerRequest('controller_posts/index');
  577. $TestController = new TestController($request);
  578. $TestController->setAction('view', 1, 2);
  579. $expected = ['testId' => 1, 'test2Id' => 2];
  580. $this->assertSame($expected, $TestController->request->data);
  581. $this->assertSame('view', $TestController->request->params['action']);
  582. }
  583. /**
  584. * Tests that the startup process calls the correct functions
  585. *
  586. * @return void
  587. */
  588. public function testStartupProcess()
  589. {
  590. $eventManager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  591. $controller = new Controller(null, null, null, $eventManager);
  592. $eventManager->expects($this->at(0))->method('dispatch')
  593. ->with(
  594. $this->logicalAnd(
  595. $this->isInstanceOf('Cake\Event\Event'),
  596. $this->attributeEqualTo('_name', 'Controller.initialize'),
  597. $this->attributeEqualTo('_subject', $controller)
  598. )
  599. )
  600. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  601. $eventManager->expects($this->at(1))->method('dispatch')
  602. ->with(
  603. $this->logicalAnd(
  604. $this->isInstanceOf('Cake\Event\Event'),
  605. $this->attributeEqualTo('_name', 'Controller.startup'),
  606. $this->attributeEqualTo('_subject', $controller)
  607. )
  608. )
  609. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  610. $controller->startupProcess();
  611. }
  612. /**
  613. * Tests that the shutdown process calls the correct functions
  614. *
  615. * @return void
  616. */
  617. public function testShutdownProcess()
  618. {
  619. $eventManager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  620. $controller = new Controller(null, null, null, $eventManager);
  621. $eventManager->expects($this->once())->method('dispatch')
  622. ->with(
  623. $this->logicalAnd(
  624. $this->isInstanceOf('Cake\Event\Event'),
  625. $this->attributeEqualTo('_name', 'Controller.shutdown'),
  626. $this->attributeEqualTo('_subject', $controller)
  627. )
  628. )
  629. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  630. $controller->shutdownProcess();
  631. }
  632. /**
  633. * test using Controller::paginate()
  634. *
  635. * @return void
  636. */
  637. public function testPaginate()
  638. {
  639. $request = new ServerRequest('controller_posts/index');
  640. $request->params['pass'] = [];
  641. $response = $this->getMockBuilder('Cake\Http\Response')
  642. ->setMethods(['httpCodes'])
  643. ->getMock();
  644. $Controller = new Controller($request, $response);
  645. $Controller->request->query = [
  646. 'url' => [],
  647. 'posts' => [
  648. 'page' => 2,
  649. 'limit' => 2,
  650. ]
  651. ];
  652. $this->assertEquals([], $Controller->paginate);
  653. $this->assertNotContains('Paginator', $Controller->helpers);
  654. $this->assertArrayNotHasKey('Paginator', $Controller->helpers);
  655. $results = $Controller->paginate('Posts');
  656. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  657. $this->assertCount(3, $results);
  658. $results = $Controller->paginate(TableRegistry::get('Posts'));
  659. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  660. $this->assertCount(3, $results);
  661. $this->assertSame($Controller->request->params['paging']['Posts']['page'], 1);
  662. $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 1);
  663. $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], false);
  664. $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false);
  665. $this->assertNull($Controller->request->params['paging']['Posts']['scope']);
  666. $results = $Controller->paginate(TableRegistry::get('Posts'), ['scope' => 'posts']);
  667. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  668. $this->assertCount(1, $results);
  669. $this->assertSame($Controller->request->params['paging']['Posts']['page'], 2);
  670. $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 2);
  671. $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], true);
  672. $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false);
  673. $this->assertSame($Controller->request->params['paging']['Posts']['scope'], 'posts');
  674. }
  675. /**
  676. * test that paginate uses modelClass property.
  677. *
  678. * @return void
  679. */
  680. public function testPaginateUsesModelClass()
  681. {
  682. $request = new ServerRequest('controller_posts/index');
  683. $request->params['pass'] = [];
  684. $response = $this->getMockBuilder('Cake\Http\Response')
  685. ->setMethods(['httpCodes'])
  686. ->getMock();
  687. $Controller = new Controller($request, $response);
  688. $Controller->request->query['url'] = [];
  689. $Controller->modelClass = 'Posts';
  690. $results = $Controller->paginate();
  691. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  692. }
  693. /**
  694. * testMissingAction method
  695. *
  696. * @expectedException \Cake\Controller\Exception\MissingActionException
  697. * @expectedExceptionMessage Action TestController::missing() could not be found, or is not accessible.
  698. * @return void
  699. */
  700. public function testInvokeActionMissingAction()
  701. {
  702. $url = new ServerRequest('test/missing');
  703. $url->addParams(['controller' => 'Test', 'action' => 'missing']);
  704. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  705. $Controller = new TestController($url, $response);
  706. $Controller->invokeAction();
  707. }
  708. /**
  709. * test invoking private methods.
  710. *
  711. * @expectedException \Cake\Controller\Exception\MissingActionException
  712. * @expectedExceptionMessage Action TestController::private_m() could not be found, or is not accessible.
  713. * @return void
  714. */
  715. public function testInvokeActionPrivate()
  716. {
  717. $url = new ServerRequest('test/private_m/');
  718. $url->addParams(['controller' => 'Test', 'action' => 'private_m']);
  719. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  720. $Controller = new TestController($url, $response);
  721. $Controller->invokeAction();
  722. }
  723. /**
  724. * test invoking protected methods.
  725. *
  726. * @expectedException \Cake\Controller\Exception\MissingActionException
  727. * @expectedExceptionMessage Action TestController::protected_m() could not be found, or is not accessible.
  728. * @return void
  729. */
  730. public function testInvokeActionProtected()
  731. {
  732. $url = new ServerRequest('test/protected_m/');
  733. $url->addParams(['controller' => 'Test', 'action' => 'protected_m']);
  734. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  735. $Controller = new TestController($url, $response);
  736. $Controller->invokeAction();
  737. }
  738. /**
  739. * test invoking controller methods.
  740. *
  741. * @expectedException \Cake\Controller\Exception\MissingActionException
  742. * @expectedExceptionMessage Action TestController::redirect() could not be found, or is not accessible.
  743. * @return void
  744. */
  745. public function testInvokeActionBaseMethods()
  746. {
  747. $url = new ServerRequest('test/redirect/');
  748. $url->addParams(['controller' => 'Test', 'action' => 'redirect']);
  749. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  750. $Controller = new TestController($url, $response);
  751. $Controller->invokeAction();
  752. }
  753. /**
  754. * test invoking controller methods.
  755. *
  756. * @return void
  757. */
  758. public function testInvokeActionReturnValue()
  759. {
  760. $url = new ServerRequest('test/returner/');
  761. $url->addParams([
  762. 'controller' => 'Test',
  763. 'action' => 'returner',
  764. 'pass' => []
  765. ]);
  766. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  767. $Controller = new TestController($url, $response);
  768. $result = $Controller->invokeAction();
  769. $this->assertEquals('I am from the controller.', $result);
  770. }
  771. /**
  772. * test invoking controller methods with passed params
  773. *
  774. * @return void
  775. */
  776. public function testInvokeActionWithPassedParams()
  777. {
  778. $url = new ServerRequest('test/index/1/2');
  779. $url->addParams([
  780. 'controller' => 'Test',
  781. 'action' => 'index',
  782. 'pass' => ['param1' => '1', 'param2' => '2']
  783. ]);
  784. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  785. $Controller = new TestController($url, $response);
  786. $result = $Controller->invokeAction();
  787. $this->assertEquals(
  788. ['testId' => '1', 'test2Id' => '2'],
  789. $Controller->request->data
  790. );
  791. }
  792. /**
  793. * test that a classes namespace is used in the viewPath.
  794. *
  795. * @return void
  796. */
  797. public function testViewPathConventions()
  798. {
  799. $request = new ServerRequest('admin/posts');
  800. $request->addParams([
  801. 'prefix' => 'admin'
  802. ]);
  803. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  804. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  805. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  806. return $e->subject()->response;
  807. });
  808. $Controller->render();
  809. $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
  810. $request->addParams([
  811. 'prefix' => 'admin/super'
  812. ]);
  813. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  814. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  815. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  816. return $e->subject()->response;
  817. });
  818. $Controller->render();
  819. $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
  820. $request = new ServerRequest('pages/home');
  821. $request->addParams([
  822. 'prefix' => false
  823. ]);
  824. $Controller = new \TestApp\Controller\PagesController($request, $response);
  825. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  826. return $e->subject()->response;
  827. });
  828. $Controller->render();
  829. $this->assertEquals('Pages', $Controller->viewBuilder()->templatePath());
  830. }
  831. /**
  832. * Test the components() method.
  833. *
  834. * @return void
  835. */
  836. public function testComponents()
  837. {
  838. $request = new ServerRequest('/');
  839. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  840. $controller = new TestController($request, $response);
  841. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  842. $result = $controller->components();
  843. $this->assertSame($result, $controller->components());
  844. }
  845. /**
  846. * Test the components() method with the custom ObjectRegistry.
  847. *
  848. * @return void
  849. */
  850. public function testComponentsWithCustomRegistry()
  851. {
  852. $request = new ServerRequest('/');
  853. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  854. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  855. ->setMethods(['offsetGet'])
  856. ->getMock();
  857. $controller = new TestController($request, $response, null, null, $componentRegistry);
  858. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  859. $result = $controller->components();
  860. $this->assertSame($result, $controller->components());
  861. }
  862. /**
  863. * Test adding a component
  864. *
  865. * @return void
  866. */
  867. public function testLoadComponent()
  868. {
  869. $request = new ServerRequest('/');
  870. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  871. $controller = new TestController($request, $response);
  872. $result = $controller->loadComponent('Paginator');
  873. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  874. $this->assertSame($result, $controller->Paginator);
  875. $registry = $controller->components();
  876. $this->assertTrue(isset($registry->Paginator));
  877. }
  878. /**
  879. * Test adding a component that is a duplicate.
  880. *
  881. * @return void
  882. */
  883. public function testLoadComponentDuplicate()
  884. {
  885. $request = new ServerRequest('/');
  886. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  887. $controller = new TestController($request, $response);
  888. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  889. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  890. try {
  891. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  892. $this->fail('No exception');
  893. } catch (\RuntimeException $e) {
  894. $this->assertContains('The "Paginator" alias has already been loaded', $e->getMessage());
  895. }
  896. }
  897. /**
  898. * Test the isAction method.
  899. *
  900. * @return void
  901. */
  902. public function testIsAction()
  903. {
  904. $request = new ServerRequest('/');
  905. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  906. $controller = new TestController($request, $response);
  907. $this->assertFalse($controller->isAction('redirect'));
  908. $this->assertFalse($controller->isAction('beforeFilter'));
  909. $this->assertTrue($controller->isAction('index'));
  910. }
  911. /**
  912. * Test declared deprecated properties like $theme are properly passed to view.
  913. *
  914. * @return void
  915. */
  916. public function testDeclaredDeprecatedProperty()
  917. {
  918. $controller = new TestController(new ServerRequest(), new Response());
  919. $theme = $controller->theme;
  920. // @codingStandardsIgnoreStart
  921. $this->assertEquals($theme, @$controller->createView()->theme);
  922. // @codingStandardsIgnoreEnd
  923. }
  924. /**
  925. * Test that view variables are being set after the beforeRender event gets dispatched
  926. *
  927. * @return void
  928. */
  929. public function testBeforeRenderViewVariables()
  930. {
  931. $controller = new PostsController();
  932. $controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  933. /* @var Controller $controller */
  934. $controller = $event->subject();
  935. $controller->set('testVariable', 'test');
  936. });
  937. $controller->render('index');
  938. $this->assertArrayHasKey('testVariable', $controller->View->viewVars);
  939. }
  940. /**
  941. * Tests deprecated view propertiyes work
  942. *
  943. * @param $property Deprecated property name
  944. * @param $getter Getter name
  945. * @param $setter Setter name
  946. * @param mixed $value Value to be set
  947. * @return void
  948. * @dataProvider deprecatedViewPropertyProvider
  949. */
  950. public function testDeprecatedViewProperty($property, $getter, $setter, $value)
  951. {
  952. $controller = new AnotherTestController();
  953. $message = false;
  954. set_error_handler(function ($errno, $errstr) use (&$message) {
  955. $message = ($errno === E_USER_DEPRECATED ? $errstr : false);
  956. });
  957. try {
  958. $controller->$property = $value;
  959. $this->assertSame(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $property, $setter), $message);
  960. $this->assertSame($value, $controller->$property);
  961. $this->assertSame(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $property, $getter), $message);
  962. $this->assertSame($value, $controller->viewBuilder()->{$getter}());
  963. } finally {
  964. restore_error_handler();
  965. }
  966. }
  967. /**
  968. * Data provider for testing deprecated view properties
  969. *
  970. * @return array
  971. */
  972. public function deprecatedViewPropertyProvider()
  973. {
  974. return [
  975. ['layout', 'getLayout', 'setLayout', 'custom'],
  976. ['view', 'getTemplate', 'setTemplate', 'view'],
  977. ['theme', 'getTheme', 'setTheme', 'Modern'],
  978. ['autoLayout', 'isAutoLayoutEnabled', 'enableAutoLayout', false],
  979. ['viewPath', 'getTemplatePath', 'setTemplatePath', 'Templates'],
  980. ['layoutPath', 'getLayoutPath', 'setLayoutPath', 'Layouts'],
  981. ];
  982. }
  983. }