ControllerTest.php 34 KB

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