ControllerTest.php 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117
  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 that a component beforeRender can change the controller view class.
  353. *
  354. * @return void
  355. */
  356. public function testBeforeRenderCallbackChangingViewClass()
  357. {
  358. $Controller = new Controller(new ServerRequest, new Response());
  359. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  360. $controller = $event->subject();
  361. $controller->viewClass = 'Json';
  362. });
  363. $Controller->set([
  364. 'test' => 'value',
  365. '_serialize' => ['test']
  366. ]);
  367. $debug = Configure::read('debug');
  368. Configure::write('debug', false);
  369. $result = $Controller->render('index');
  370. $this->assertEquals('{"test":"value"}', $result->body());
  371. Configure::write('debug', $debug);
  372. }
  373. /**
  374. * test that a component beforeRender can change the controller view class.
  375. *
  376. * @return void
  377. */
  378. public function testBeforeRenderEventCancelsRender()
  379. {
  380. $Controller = new Controller(new ServerRequest, new Response());
  381. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  382. return false;
  383. });
  384. $result = $Controller->render('index');
  385. $this->assertInstanceOf('Cake\Http\Response', $result);
  386. }
  387. /**
  388. * Generates status codes for redirect test.
  389. *
  390. * @return void
  391. */
  392. public static function statusCodeProvider()
  393. {
  394. return [
  395. [300, 'Multiple Choices'],
  396. [301, 'Moved Permanently'],
  397. [302, 'Found'],
  398. [303, 'See Other'],
  399. [304, 'Not Modified'],
  400. [305, 'Use Proxy'],
  401. [307, 'Temporary Redirect'],
  402. [403, 'Forbidden'],
  403. ];
  404. }
  405. /**
  406. * testRedirect method
  407. *
  408. * @dataProvider statusCodeProvider
  409. * @return void
  410. */
  411. public function testRedirectByCode($code, $msg)
  412. {
  413. $Controller = new Controller(null, new Response());
  414. $response = $Controller->redirect('http://cakephp.org', (int)$code);
  415. $this->assertSame($response, $Controller->response);
  416. $this->assertEquals($code, $response->statusCode());
  417. $this->assertEquals('http://cakephp.org', $response->header()['Location']);
  418. $this->assertFalse($Controller->autoRender);
  419. }
  420. /**
  421. * test that beforeRedirect callbacks can set the URL that is being redirected to.
  422. *
  423. * @return void
  424. */
  425. public function testRedirectBeforeRedirectModifyingUrl()
  426. {
  427. $Controller = new Controller(null, new Response());
  428. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) {
  429. $response->location('https://book.cakephp.org');
  430. });
  431. $response = $Controller->redirect('http://cakephp.org', 301);
  432. $this->assertEquals('https://book.cakephp.org', $response->header()['Location']);
  433. $this->assertEquals(301, $response->statusCode());
  434. }
  435. /**
  436. * test that beforeRedirect callback returning null doesn't affect things.
  437. *
  438. * @return void
  439. */
  440. public function testRedirectBeforeRedirectModifyingStatusCode()
  441. {
  442. $Response = $this->getMockBuilder('Cake\Http\Response')
  443. ->setMethods(['stop'])
  444. ->getMock();
  445. $Controller = new Controller(null, $Response);
  446. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) {
  447. $response->statusCode(302);
  448. });
  449. $response = $Controller->redirect('http://cakephp.org', 301);
  450. $this->assertEquals('http://cakephp.org', $response->header()['Location']);
  451. $this->assertEquals(302, $response->statusCode());
  452. }
  453. public function testRedirectBeforeRedirectListenerReturnResponse()
  454. {
  455. $Response = $this->getMockBuilder('Cake\Http\Response')
  456. ->setMethods(['stop', 'header', 'statusCode'])
  457. ->getMock();
  458. $Controller = new Controller(null, $Response);
  459. $newResponse = new Response;
  460. $Controller->getEventManager()->on('Controller.beforeRedirect', function (Event $event, $url, Response $response) use ($newResponse) {
  461. return $newResponse;
  462. });
  463. $result = $Controller->redirect('http://cakephp.org');
  464. $this->assertSame($newResponse, $result);
  465. $this->assertSame($newResponse, $Controller->response);
  466. }
  467. /**
  468. * testMergeVars method
  469. *
  470. * @return void
  471. */
  472. public function testMergeVars()
  473. {
  474. $request = new ServerRequest();
  475. $TestController = new TestController($request);
  476. $expected = [
  477. 'Html' => null,
  478. ];
  479. $this->assertEquals($expected, $TestController->helpers);
  480. $expected = [
  481. 'Security' => null,
  482. 'Cookie' => null,
  483. ];
  484. $this->assertEquals($expected, $TestController->components);
  485. $TestController = new AnotherTestController($request);
  486. $this->assertEquals(
  487. 'Posts',
  488. $TestController->modelClass,
  489. 'modelClass should not be overwritten when defined.'
  490. );
  491. }
  492. /**
  493. * testReferer method
  494. *
  495. * @return void
  496. */
  497. public function testReferer()
  498. {
  499. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  500. ->setMethods(['referer'])
  501. ->getMock();
  502. $request->expects($this->any())->method('referer')
  503. ->with(true)
  504. ->will($this->returnValue('/posts/index'));
  505. $Controller = new Controller($request);
  506. $result = $Controller->referer(null, true);
  507. $this->assertEquals('/posts/index', $result);
  508. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  509. ->setMethods(['referer'])
  510. ->getMock();
  511. $request->expects($this->any())->method('referer')
  512. ->with(true)
  513. ->will($this->returnValue('/posts/index'));
  514. $Controller = new Controller($request);
  515. $result = $Controller->referer(['controller' => 'posts', 'action' => 'index'], true);
  516. $this->assertEquals('/posts/index', $result);
  517. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  518. ->setMethods(['referer'])
  519. ->getMock();
  520. $request->expects($this->any())->method('referer')
  521. ->with(false)
  522. ->will($this->returnValue('http://localhost/posts/index'));
  523. $Controller = new Controller($request);
  524. $result = $Controller->referer();
  525. $this->assertEquals('http://localhost/posts/index', $result);
  526. $Controller = new Controller(null);
  527. $result = $Controller->referer();
  528. $this->assertEquals('/', $result);
  529. }
  530. /**
  531. * Test that the referer is not absolute if it is '/'.
  532. *
  533. * This avoids the base path being applied twice on string urls.
  534. *
  535. * @return void
  536. */
  537. public function testRefererSlash()
  538. {
  539. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  540. ->setMethods(['referer'])
  541. ->getMock();
  542. $request->base = '/base';
  543. Router::pushRequest($request);
  544. $request->expects($this->any())->method('referer')
  545. ->will($this->returnValue('/'));
  546. $controller = new Controller($request);
  547. $result = $controller->referer('/', true);
  548. $this->assertEquals('/', $result);
  549. $controller = new Controller($request);
  550. $result = $controller->referer('/some/path', true);
  551. $this->assertEquals('/some/path', $result);
  552. }
  553. /**
  554. * testSetAction method
  555. *
  556. * @return void
  557. */
  558. public function testSetAction()
  559. {
  560. $request = new ServerRequest('controller_posts/index');
  561. $TestController = new TestController($request);
  562. $TestController->setAction('view', 1, 2);
  563. $expected = ['testId' => 1, 'test2Id' => 2];
  564. $this->assertSame($expected, $TestController->request->data);
  565. $this->assertSame('view', $TestController->request->params['action']);
  566. }
  567. /**
  568. * Tests that the startup process calls the correct functions
  569. *
  570. * @return void
  571. */
  572. public function testStartupProcess()
  573. {
  574. $eventManager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  575. $controller = new Controller(null, null, null, $eventManager);
  576. $eventManager->expects($this->at(0))->method('dispatch')
  577. ->with(
  578. $this->logicalAnd(
  579. $this->isInstanceOf('Cake\Event\Event'),
  580. $this->attributeEqualTo('_name', 'Controller.initialize'),
  581. $this->attributeEqualTo('_subject', $controller)
  582. )
  583. )
  584. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  585. $eventManager->expects($this->at(1))->method('dispatch')
  586. ->with(
  587. $this->logicalAnd(
  588. $this->isInstanceOf('Cake\Event\Event'),
  589. $this->attributeEqualTo('_name', 'Controller.startup'),
  590. $this->attributeEqualTo('_subject', $controller)
  591. )
  592. )
  593. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  594. $controller->startupProcess();
  595. }
  596. /**
  597. * Tests that the shutdown process calls the correct functions
  598. *
  599. * @return void
  600. */
  601. public function testShutdownProcess()
  602. {
  603. $eventManager = $this->getMockBuilder('Cake\Event\EventManager')->getMock();
  604. $controller = new Controller(null, null, null, $eventManager);
  605. $eventManager->expects($this->once())->method('dispatch')
  606. ->with(
  607. $this->logicalAnd(
  608. $this->isInstanceOf('Cake\Event\Event'),
  609. $this->attributeEqualTo('_name', 'Controller.shutdown'),
  610. $this->attributeEqualTo('_subject', $controller)
  611. )
  612. )
  613. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  614. $controller->shutdownProcess();
  615. }
  616. /**
  617. * test using Controller::paginate()
  618. *
  619. * @return void
  620. */
  621. public function testPaginate()
  622. {
  623. $request = new ServerRequest('controller_posts/index');
  624. $request->params['pass'] = [];
  625. $response = $this->getMockBuilder('Cake\Http\Response')
  626. ->setMethods(['httpCodes'])
  627. ->getMock();
  628. $Controller = new Controller($request, $response);
  629. $Controller->request->query = [
  630. 'url' => [],
  631. 'posts' => [
  632. 'page' => 2,
  633. 'limit' => 2,
  634. ]
  635. ];
  636. $this->assertEquals([], $Controller->paginate);
  637. $this->assertNotContains('Paginator', $Controller->helpers);
  638. $this->assertArrayNotHasKey('Paginator', $Controller->helpers);
  639. $results = $Controller->paginate('Posts');
  640. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  641. $this->assertCount(3, $results);
  642. $results = $Controller->paginate(TableRegistry::get('Posts'));
  643. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  644. $this->assertCount(3, $results);
  645. $this->assertSame($Controller->request->params['paging']['Posts']['page'], 1);
  646. $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 1);
  647. $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], false);
  648. $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false);
  649. $this->assertNull($Controller->request->params['paging']['Posts']['scope']);
  650. $results = $Controller->paginate(TableRegistry::get('Posts'), ['scope' => 'posts']);
  651. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  652. $this->assertCount(1, $results);
  653. $this->assertSame($Controller->request->params['paging']['Posts']['page'], 2);
  654. $this->assertSame($Controller->request->params['paging']['Posts']['pageCount'], 2);
  655. $this->assertSame($Controller->request->params['paging']['Posts']['prevPage'], true);
  656. $this->assertSame($Controller->request->params['paging']['Posts']['nextPage'], false);
  657. $this->assertSame($Controller->request->params['paging']['Posts']['scope'], 'posts');
  658. }
  659. /**
  660. * test that paginate uses modelClass property.
  661. *
  662. * @return void
  663. */
  664. public function testPaginateUsesModelClass()
  665. {
  666. $request = new ServerRequest('controller_posts/index');
  667. $request->params['pass'] = [];
  668. $response = $this->getMockBuilder('Cake\Http\Response')
  669. ->setMethods(['httpCodes'])
  670. ->getMock();
  671. $Controller = new Controller($request, $response);
  672. $Controller->request->query['url'] = [];
  673. $Controller->modelClass = 'Posts';
  674. $results = $Controller->paginate();
  675. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  676. }
  677. /**
  678. * testMissingAction method
  679. *
  680. * @expectedException \Cake\Controller\Exception\MissingActionException
  681. * @expectedExceptionMessage Action TestController::missing() could not be found, or is not accessible.
  682. * @return void
  683. */
  684. public function testInvokeActionMissingAction()
  685. {
  686. $url = new ServerRequest('test/missing');
  687. $url->addParams(['controller' => 'Test', 'action' => 'missing']);
  688. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  689. $Controller = new TestController($url, $response);
  690. $Controller->invokeAction();
  691. }
  692. /**
  693. * test invoking private methods.
  694. *
  695. * @expectedException \Cake\Controller\Exception\MissingActionException
  696. * @expectedExceptionMessage Action TestController::private_m() could not be found, or is not accessible.
  697. * @return void
  698. */
  699. public function testInvokeActionPrivate()
  700. {
  701. $url = new ServerRequest('test/private_m/');
  702. $url->addParams(['controller' => 'Test', 'action' => 'private_m']);
  703. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  704. $Controller = new TestController($url, $response);
  705. $Controller->invokeAction();
  706. }
  707. /**
  708. * test invoking protected methods.
  709. *
  710. * @expectedException \Cake\Controller\Exception\MissingActionException
  711. * @expectedExceptionMessage Action TestController::protected_m() could not be found, or is not accessible.
  712. * @return void
  713. */
  714. public function testInvokeActionProtected()
  715. {
  716. $url = new ServerRequest('test/protected_m/');
  717. $url->addParams(['controller' => 'Test', 'action' => 'protected_m']);
  718. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  719. $Controller = new TestController($url, $response);
  720. $Controller->invokeAction();
  721. }
  722. /**
  723. * test invoking controller methods.
  724. *
  725. * @expectedException \Cake\Controller\Exception\MissingActionException
  726. * @expectedExceptionMessage Action TestController::redirect() could not be found, or is not accessible.
  727. * @return void
  728. */
  729. public function testInvokeActionBaseMethods()
  730. {
  731. $url = new ServerRequest('test/redirect/');
  732. $url->addParams(['controller' => 'Test', 'action' => 'redirect']);
  733. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  734. $Controller = new TestController($url, $response);
  735. $Controller->invokeAction();
  736. }
  737. /**
  738. * test invoking controller methods.
  739. *
  740. * @return void
  741. */
  742. public function testInvokeActionReturnValue()
  743. {
  744. $url = new ServerRequest('test/returner/');
  745. $url->addParams([
  746. 'controller' => 'Test',
  747. 'action' => 'returner',
  748. 'pass' => []
  749. ]);
  750. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  751. $Controller = new TestController($url, $response);
  752. $result = $Controller->invokeAction();
  753. $this->assertEquals('I am from the controller.', $result);
  754. }
  755. /**
  756. * test invoking controller methods with passed params
  757. *
  758. * @return void
  759. */
  760. public function testInvokeActionWithPassedParams()
  761. {
  762. $url = new ServerRequest('test/index/1/2');
  763. $url->addParams([
  764. 'controller' => 'Test',
  765. 'action' => 'index',
  766. 'pass' => ['param1' => '1', 'param2' => '2']
  767. ]);
  768. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  769. $Controller = new TestController($url, $response);
  770. $result = $Controller->invokeAction();
  771. $this->assertEquals(
  772. ['testId' => '1', 'test2Id' => '2'],
  773. $Controller->request->data
  774. );
  775. }
  776. /**
  777. * test that a classes namespace is used in the viewPath.
  778. *
  779. * @return void
  780. */
  781. public function testViewPathConventions()
  782. {
  783. $request = new ServerRequest('admin/posts');
  784. $request->addParams([
  785. 'prefix' => 'admin'
  786. ]);
  787. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  788. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  789. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  790. return $e->subject()->response;
  791. });
  792. $Controller->render();
  793. $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
  794. $request->addParams([
  795. 'prefix' => 'admin/super'
  796. ]);
  797. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  798. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  799. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  800. return $e->subject()->response;
  801. });
  802. $Controller->render();
  803. $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->templatePath());
  804. $request = new ServerRequest('pages/home');
  805. $request->addParams([
  806. 'prefix' => false
  807. ]);
  808. $Controller = new \TestApp\Controller\PagesController($request, $response);
  809. $Controller->getEventManager()->on('Controller.beforeRender', function (Event $e) {
  810. return $e->subject()->response;
  811. });
  812. $Controller->render();
  813. $this->assertEquals('Pages', $Controller->viewBuilder()->templatePath());
  814. }
  815. /**
  816. * Test the components() method.
  817. *
  818. * @return void
  819. */
  820. public function testComponents()
  821. {
  822. $request = new ServerRequest('/');
  823. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  824. $controller = new TestController($request, $response);
  825. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  826. $result = $controller->components();
  827. $this->assertSame($result, $controller->components());
  828. }
  829. /**
  830. * Test the components() method with the custom ObjectRegistry.
  831. *
  832. * @return void
  833. */
  834. public function testComponentsWithCustomRegistry()
  835. {
  836. $request = new ServerRequest('/');
  837. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  838. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  839. ->setMethods(['offsetGet'])
  840. ->getMock();
  841. $controller = new TestController($request, $response, null, null, $componentRegistry);
  842. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  843. $result = $controller->components();
  844. $this->assertSame($result, $controller->components());
  845. }
  846. /**
  847. * Test adding a component
  848. *
  849. * @return void
  850. */
  851. public function testLoadComponent()
  852. {
  853. $request = new ServerRequest('/');
  854. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  855. $controller = new TestController($request, $response);
  856. $result = $controller->loadComponent('Paginator');
  857. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  858. $this->assertSame($result, $controller->Paginator);
  859. $registry = $controller->components();
  860. $this->assertTrue(isset($registry->Paginator));
  861. }
  862. /**
  863. * Test adding a component that is a duplicate.
  864. *
  865. * @return void
  866. */
  867. public function testLoadComponentDuplicate()
  868. {
  869. $request = new ServerRequest('/');
  870. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  871. $controller = new TestController($request, $response);
  872. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  873. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  874. try {
  875. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  876. $this->fail('No exception');
  877. } catch (\RuntimeException $e) {
  878. $this->assertContains('The "Paginator" alias has already been loaded', $e->getMessage());
  879. }
  880. }
  881. /**
  882. * Test the isAction method.
  883. *
  884. * @return void
  885. */
  886. public function testIsAction()
  887. {
  888. $request = new ServerRequest('/');
  889. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  890. $controller = new TestController($request, $response);
  891. $this->assertFalse($controller->isAction('redirect'));
  892. $this->assertFalse($controller->isAction('beforeFilter'));
  893. $this->assertTrue($controller->isAction('index'));
  894. }
  895. /**
  896. * Test declared deprecated properties like $theme are properly passed to view.
  897. *
  898. * @return void
  899. */
  900. public function testDeclaredDeprecatedProperty()
  901. {
  902. $controller = new TestController(new ServerRequest(), new Response());
  903. $theme = $controller->theme;
  904. // @codingStandardsIgnoreStart
  905. $this->assertEquals($theme, @$controller->createView()->theme);
  906. // @codingStandardsIgnoreEnd
  907. }
  908. /**
  909. * Test that view variables are being set after the beforeRender event gets dispatched
  910. *
  911. * @return void
  912. */
  913. public function testBeforeRenderViewVariables()
  914. {
  915. $controller = new PostsController();
  916. $controller->getEventManager()->on('Controller.beforeRender', function (Event $event) {
  917. /* @var Controller $controller */
  918. $controller = $event->subject();
  919. $controller->set('testVariable', 'test');
  920. });
  921. $controller->render('index');
  922. $this->assertArrayHasKey('testVariable', $controller->View->viewVars);
  923. }
  924. /**
  925. * Tests deprecated view propertiyes work
  926. *
  927. * @param $property Deprecated property name
  928. * @param $getter Getter name
  929. * @param $setter Setter name
  930. * @param mixed $value Value to be set
  931. * @return void
  932. * @dataProvider deprecatedViewPropertyProvider
  933. */
  934. public function testDeprecatedViewProperty($property, $getter, $setter, $value)
  935. {
  936. $controller = new AnotherTestController();
  937. $message = false;
  938. set_error_handler(function ($errno, $errstr) use (&$message) {
  939. $message = ($errno === E_USER_DEPRECATED ? $errstr : false);
  940. });
  941. try {
  942. $controller->$property = $value;
  943. $this->assertSame(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $property, $setter), $message);
  944. $this->assertSame($value, $controller->$property);
  945. $this->assertSame(sprintf('Controller::$%s is deprecated. Use $this->viewBuilder()->%s() instead.', $property, $getter), $message);
  946. $this->assertSame($value, $controller->viewBuilder()->{$getter}());
  947. } finally {
  948. restore_error_handler();
  949. }
  950. }
  951. /**
  952. * Data provider for testing deprecated view properties
  953. *
  954. * @return array
  955. */
  956. public function deprecatedViewPropertyProvider()
  957. {
  958. return [
  959. ['layout', 'getLayout', 'setLayout', 'custom'],
  960. ['view', 'getTemplate', 'setTemplate', 'view'],
  961. ['theme', 'getTheme', 'setTheme', 'Modern'],
  962. ['autoLayout', 'isAutoLayoutEnabled', 'enableAutoLayout', false],
  963. ['viewPath', 'getTemplatePath', 'setTemplatePath', 'Templates'],
  964. ['layoutPath', 'getLayoutPath', 'setLayoutPath', 'Layouts'],
  965. ];
  966. }
  967. }