ControllerTest.php 34 KB

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