ControllerTest.php 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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\Controller;
  18. use Cake\Core\Configure;
  19. use Cake\Event\EventInterface;
  20. use Cake\Http\Response;
  21. use Cake\Http\ServerRequest;
  22. use Cake\Routing\Router;
  23. use Cake\TestSuite\TestCase;
  24. use PHPUnit\Framework\Error\Notice;
  25. use PHPUnit\Framework\Error\Warning;
  26. use TestApp\Controller\Admin\PostsController;
  27. use TestApp\Controller\TestController;
  28. use TestPlugin\Controller\TestPluginController;
  29. /**
  30. * ControllerTest class
  31. */
  32. class ControllerTest extends TestCase
  33. {
  34. /**
  35. * fixtures property
  36. *
  37. * @var array
  38. */
  39. public $fixtures = [
  40. 'core.Comments',
  41. 'core.Posts',
  42. ];
  43. /**
  44. * reset environment.
  45. *
  46. * @return void
  47. */
  48. public function setUp(): void
  49. {
  50. parent::setUp();
  51. static::setAppNamespace();
  52. Router::reload();
  53. }
  54. /**
  55. * tearDown
  56. *
  57. * @return void
  58. */
  59. public function tearDown(): void
  60. {
  61. parent::tearDown();
  62. $this->clearPlugins();
  63. }
  64. /**
  65. * test autoload modelClass
  66. *
  67. * @return void
  68. */
  69. public function testTableAutoload(): void
  70. {
  71. $request = new ServerRequest(['url' => 'controller/posts/index']);
  72. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  73. $Controller = new Controller($request, $response);
  74. $Controller->modelClass = 'SiteArticles';
  75. $this->assertFalse(isset($Controller->Articles));
  76. $this->assertInstanceOf(
  77. 'Cake\ORM\Table',
  78. $Controller->SiteArticles
  79. );
  80. unset($Controller->SiteArticles);
  81. $Controller->modelClass = 'Articles';
  82. $this->assertFalse(isset($Controller->SiteArticles));
  83. $this->assertInstanceOf(
  84. 'TestApp\Model\Table\ArticlesTable',
  85. $Controller->Articles
  86. );
  87. }
  88. /**
  89. * testUndefinedPropertyError
  90. *
  91. * @return void
  92. */
  93. public function testUndefinedPropertyError()
  94. {
  95. $controller = new Controller();
  96. $controller->Bar = true;
  97. $this->assertTrue($controller->Bar);
  98. $this->expectException(Notice::class);
  99. $this->expectExceptionMessage(sprintf(
  100. 'Undefined property: Controller::$Foo in %s on line %s',
  101. __FILE__,
  102. __LINE__ + 2
  103. ));
  104. $controller->Foo->baz();
  105. }
  106. /**
  107. * testLoadModel method
  108. *
  109. * @return void
  110. */
  111. public function testLoadModel(): void
  112. {
  113. $request = new ServerRequest(['url' => 'controller/posts/index']);
  114. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  115. $Controller = new Controller($request, $response);
  116. $this->assertFalse(isset($Controller->Articles));
  117. $result = $Controller->loadModel('Articles');
  118. $this->assertInstanceOf(
  119. 'TestApp\Model\Table\ArticlesTable',
  120. $result
  121. );
  122. $this->assertInstanceOf(
  123. 'TestApp\Model\Table\ArticlesTable',
  124. $Controller->Articles
  125. );
  126. }
  127. /**
  128. * testLoadModel method from a plugin controller
  129. *
  130. * @return void
  131. */
  132. public function testLoadModelInPlugins(): void
  133. {
  134. $this->loadPlugins(['TestPlugin']);
  135. $Controller = new TestPluginController();
  136. $Controller->setPlugin('TestPlugin');
  137. $this->assertFalse(isset($Controller->TestPluginComments));
  138. $result = $Controller->loadModel('TestPlugin.TestPluginComments');
  139. $this->assertInstanceOf(
  140. 'TestPlugin\Model\Table\TestPluginCommentsTable',
  141. $result
  142. );
  143. $this->assertInstanceOf(
  144. 'TestPlugin\Model\Table\TestPluginCommentsTable',
  145. $Controller->TestPluginComments
  146. );
  147. }
  148. /**
  149. * Test that the constructor sets modelClass properly.
  150. *
  151. * @return void
  152. */
  153. public function testConstructSetModelClass(): void
  154. {
  155. $this->loadPlugins(['TestPlugin']);
  156. $request = new ServerRequest();
  157. $response = new Response();
  158. $controller = new \TestApp\Controller\PostsController($request, $response);
  159. $this->assertInstanceOf('Cake\ORM\Table', $controller->loadModel());
  160. $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
  161. $controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  162. $this->assertInstanceOf('Cake\ORM\Table', $controller->loadModel());
  163. $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
  164. $request = $request->withParam('plugin', 'TestPlugin');
  165. $controller = new \TestPlugin\Controller\Admin\CommentsController($request, $response);
  166. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $controller->loadModel());
  167. $this->assertInstanceOf('TestPlugin\Model\Table\CommentsTable', $controller->Comments);
  168. }
  169. /**
  170. * testConstructClassesWithComponents method
  171. *
  172. * @return void
  173. */
  174. public function testConstructClassesWithComponents(): void
  175. {
  176. $this->loadPlugins(['TestPlugin']);
  177. $Controller = new TestPluginController(new ServerRequest(), new Response());
  178. $Controller->loadComponent('TestPlugin.Other');
  179. $this->assertInstanceOf('TestPlugin\Controller\Component\OtherComponent', $Controller->Other);
  180. }
  181. /**
  182. * testRender method
  183. *
  184. * @return void
  185. */
  186. public function testRender(): void
  187. {
  188. $this->loadPlugins(['TestPlugin']);
  189. $request = new ServerRequest([
  190. 'url' => 'controller_posts/index',
  191. 'params' => [
  192. 'action' => 'header',
  193. ],
  194. ]);
  195. $Controller = new Controller($request, new Response());
  196. $Controller->viewBuilder()->setTemplatePath('Posts');
  197. $result = $Controller->render('index');
  198. $this->assertRegExp('/posts index/', (string)$result);
  199. $Controller->viewBuilder()->setTemplate('index');
  200. $result = $Controller->render();
  201. $this->assertRegExp('/posts index/', (string)$result);
  202. $result = $Controller->render('/element/test_element');
  203. $this->assertRegExp('/this is the test element/', (string)$result);
  204. }
  205. /**
  206. * test view rendering changing response
  207. *
  208. * @return void
  209. */
  210. public function testRenderViewChangesResponse(): void
  211. {
  212. $request = new ServerRequest([
  213. 'url' => 'controller_posts/index',
  214. 'params' => [
  215. 'action' => 'header',
  216. ],
  217. ]);
  218. $controller = new Controller($request, new Response());
  219. $controller->viewBuilder()->setTemplatePath('Posts');
  220. $result = $controller->render('header');
  221. $this->assertStringContainsString('header template', (string)$result);
  222. $this->assertTrue($controller->getResponse()->hasHeader('X-view-template'));
  223. $this->assertSame('yes', $controller->getResponse()->getHeaderLine('X-view-template'));
  224. }
  225. /**
  226. * test that a component beforeRender can change the controller view class.
  227. *
  228. * @return void
  229. */
  230. public function testBeforeRenderCallbackChangingViewClass(): void
  231. {
  232. $Controller = new Controller(new ServerRequest(), new Response());
  233. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  234. $controller = $event->getSubject();
  235. $controller->viewBuilder()->setClassName('Json');
  236. });
  237. $Controller->set([
  238. 'test' => 'value',
  239. ]);
  240. $Controller->viewBuilder()->setOption('serialize', ['test']);
  241. $debug = Configure::read('debug');
  242. Configure::write('debug', false);
  243. $result = $Controller->render('index');
  244. $this->assertEquals('{"test":"value"}', (string)$result->getBody());
  245. Configure::write('debug', $debug);
  246. }
  247. /**
  248. * test that a component beforeRender can change the controller view class.
  249. *
  250. * @return void
  251. */
  252. public function testBeforeRenderEventCancelsRender(): void
  253. {
  254. $Controller = new Controller(new ServerRequest(), new Response());
  255. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event) {
  256. return false;
  257. });
  258. $result = $Controller->render('index');
  259. $this->assertInstanceOf('Cake\Http\Response', $result);
  260. }
  261. /**
  262. * Generates status codes for redirect test.
  263. *
  264. * @return array
  265. */
  266. public static function statusCodeProvider(): array
  267. {
  268. return [
  269. [300, 'Multiple Choices'],
  270. [301, 'Moved Permanently'],
  271. [302, 'Found'],
  272. [303, 'See Other'],
  273. [304, 'Not Modified'],
  274. [305, 'Use Proxy'],
  275. [307, 'Temporary Redirect'],
  276. [403, 'Forbidden'],
  277. ];
  278. }
  279. /**
  280. * testRedirect method
  281. *
  282. * @dataProvider statusCodeProvider
  283. * @return void
  284. */
  285. public function testRedirectByCode($code, $msg): void
  286. {
  287. $Controller = new Controller(null, new Response());
  288. $response = $Controller->redirect('http://cakephp.org', (int)$code);
  289. $this->assertSame($response, $Controller->getResponse());
  290. $this->assertEquals($code, $response->getStatusCode());
  291. $this->assertEquals('http://cakephp.org', $response->getHeaderLine('Location'));
  292. $this->assertFalse($Controller->isAutoRenderEnabled());
  293. }
  294. /**
  295. * test that beforeRedirect callbacks can set the URL that is being redirected to.
  296. *
  297. * @return void
  298. */
  299. public function testRedirectBeforeRedirectModifyingUrl(): void
  300. {
  301. $Controller = new Controller(null, new Response());
  302. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  303. $controller = $event->getSubject();
  304. $controller->setResponse($response->withLocation('https://book.cakephp.org'));
  305. });
  306. $response = $Controller->redirect('http://cakephp.org', 301);
  307. $this->assertEquals('https://book.cakephp.org', $response->getHeaderLine('Location'));
  308. $this->assertEquals(301, $response->getStatusCode());
  309. }
  310. /**
  311. * test that beforeRedirect callback returning null doesn't affect things.
  312. *
  313. * @return void
  314. */
  315. public function testRedirectBeforeRedirectModifyingStatusCode(): void
  316. {
  317. $response = new Response();
  318. $Controller = new Controller(null, $response);
  319. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response): void {
  320. $controller = $event->getSubject();
  321. $controller->setResponse($response->withStatus(302));
  322. });
  323. $response = $Controller->redirect('http://cakephp.org', 301);
  324. $this->assertEquals('http://cakephp.org', $response->getHeaderLine('Location'));
  325. $this->assertEquals(302, $response->getStatusCode());
  326. }
  327. public function testRedirectBeforeRedirectListenerReturnResponse(): void
  328. {
  329. $Response = $this->getMockBuilder('Cake\Http\Response')
  330. ->setMethods(['stop', 'header', 'statusCode'])
  331. ->getMock();
  332. $Controller = new Controller(null, $Response);
  333. $newResponse = new Response();
  334. $Controller->getEventManager()->on('Controller.beforeRedirect', function (EventInterface $event, $url, Response $response) use ($newResponse) {
  335. return $newResponse;
  336. });
  337. $result = $Controller->redirect('http://cakephp.org');
  338. $this->assertSame($newResponse, $result);
  339. $this->assertSame($newResponse, $Controller->getResponse());
  340. }
  341. /**
  342. * testReferer method
  343. *
  344. * @return void
  345. */
  346. public function testReferer(): void
  347. {
  348. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  349. ->setMethods(['referer'])
  350. ->getMock();
  351. $request->expects($this->any())->method('referer')
  352. ->with(true)
  353. ->will($this->returnValue('/posts/index'));
  354. $Controller = new Controller($request);
  355. $result = $Controller->referer();
  356. $this->assertEquals('/posts/index', $result);
  357. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  358. ->setMethods(['referer'])
  359. ->getMock();
  360. $request->expects($this->any())->method('referer')
  361. ->with(true)
  362. ->will($this->returnValue('/posts/index'));
  363. $Controller = new Controller($request);
  364. $result = $Controller->referer(['controller' => 'posts', 'action' => 'index'], true);
  365. $this->assertEquals('/posts/index', $result);
  366. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  367. ->setMethods(['referer'])
  368. ->getMock();
  369. $request->expects($this->any())->method('referer')
  370. ->with(false)
  371. ->will($this->returnValue('http://localhost/posts/index'));
  372. $Controller = new Controller($request);
  373. $result = $Controller->referer(null, false);
  374. $this->assertEquals('http://localhost/posts/index', $result);
  375. $Controller = new Controller(null);
  376. $result = $Controller->referer('/', false);
  377. $this->assertEquals('http://localhost/', $result);
  378. }
  379. /**
  380. * Test that the referer is not absolute if it is '/'.
  381. *
  382. * This avoids the base path being applied twice on string urls.
  383. *
  384. * @return void
  385. */
  386. public function testRefererSlash(): void
  387. {
  388. /** @var \Cake\Http\ServerRequest|\PHPUnit\Framework\MockObject\MockObject $request */
  389. $request = $this->getMockBuilder(ServerRequest::class)
  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 = new Response();
  628. $Controller = new TestController($url, $response);
  629. $result = $Controller->invokeAction();
  630. $this->assertEquals('I am from the controller.', (string)$result);
  631. $this->assertEquals('I am from the controller.', (string)$Controller->getResponse());
  632. }
  633. /**
  634. * test invoking controller methods with passed params
  635. *
  636. * @return void
  637. */
  638. public function testInvokeActionWithPassedParams(): void
  639. {
  640. $url = new ServerRequest([
  641. 'url' => 'test/index/1/2',
  642. 'params' => [
  643. 'controller' => 'Test',
  644. 'action' => 'index',
  645. 'pass' => ['param1' => '1', 'param2' => '2'],
  646. ],
  647. ]);
  648. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  649. $Controller = new TestController($url, $response);
  650. $result = $Controller->invokeAction();
  651. $this->assertEquals(
  652. ['testId' => '1', 'test2Id' => '2'],
  653. $Controller->getRequest()->getData()
  654. );
  655. }
  656. /**
  657. * test invalid return value from action method.
  658. *
  659. * @return void
  660. */
  661. public function testInvokeActionException()
  662. {
  663. $this->expectException(\UnexpectedValueException::class);
  664. $this->expectExceptionMessage(
  665. 'Controller actions can only return ResponseInterface instance or null. '
  666. . 'Got string instead.'
  667. );
  668. $url = new ServerRequest([
  669. 'url' => 'test/willCauseException',
  670. 'params' => [
  671. 'controller' => 'Test',
  672. 'action' => 'willCauseException',
  673. 'pass' => [],
  674. ],
  675. ]);
  676. $response = $this->getMockBuilder(Response::class)->getMock();
  677. $Controller = new TestController($url, $response);
  678. $Controller->invokeAction();
  679. }
  680. /**
  681. * test that a classes namespace is used in the viewPath.
  682. *
  683. * @return void
  684. */
  685. public function testViewPathConventions(): void
  686. {
  687. $request = new ServerRequest([
  688. 'url' => 'admin/posts',
  689. 'params' => ['prefix' => 'admin'],
  690. ]);
  691. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  692. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  693. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  694. return $e->getSubject()->getResponse();
  695. });
  696. $Controller->render();
  697. $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  698. $request = $request->withParam('prefix', 'admin/super');
  699. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  700. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  701. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  702. return $e->getSubject()->getResponse();
  703. });
  704. $Controller->render();
  705. $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  706. $request = new ServerRequest([
  707. 'url' => 'pages/home',
  708. 'params' => [
  709. 'prefix' => false,
  710. ],
  711. ]);
  712. $Controller = new \TestApp\Controller\PagesController($request, $response);
  713. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  714. return $e->getSubject()->getResponse();
  715. });
  716. $Controller->render();
  717. $this->assertEquals('Pages', $Controller->viewBuilder()->getTemplatePath());
  718. }
  719. /**
  720. * Test the components() method.
  721. *
  722. * @return void
  723. */
  724. public function testComponents(): void
  725. {
  726. $request = new ServerRequest(['url' => '/']);
  727. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  728. $controller = new TestController($request, $response);
  729. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  730. $result = $controller->components();
  731. $this->assertSame($result, $controller->components());
  732. }
  733. /**
  734. * Test the components property errors
  735. *
  736. * @return void
  737. */
  738. public function testComponentsPropertyError(): void
  739. {
  740. $this->expectException(Warning::class);
  741. $request = new ServerRequest(['url' => '/']);
  742. $response = new Response();
  743. $controller = new TestController($request, $response);
  744. $controller->components = ['Flash'];
  745. }
  746. /**
  747. * Test the helpers property errors
  748. *
  749. * @return void
  750. */
  751. public function testHelpersPropertyError(): void
  752. {
  753. $this->expectException(Warning::class);
  754. $request = new ServerRequest(['url' => '/']);
  755. $response = new Response();
  756. $controller = new TestController($request, $response);
  757. $controller->helpers = ['Flash'];
  758. }
  759. /**
  760. * Test the components() method with the custom ObjectRegistry.
  761. *
  762. * @return void
  763. */
  764. public function testComponentsWithCustomRegistry(): void
  765. {
  766. $request = new ServerRequest(['url' => '/']);
  767. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  768. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  769. ->setMethods(['offsetGet'])
  770. ->getMock();
  771. $controller = new TestController($request, $response, null, null, $componentRegistry);
  772. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  773. $result = $controller->components();
  774. $this->assertSame($result, $controller->components());
  775. }
  776. /**
  777. * Test adding a component
  778. *
  779. * @return void
  780. */
  781. public function testLoadComponent(): void
  782. {
  783. $request = new ServerRequest(['url' => '/']);
  784. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  785. $controller = new TestController($request, $response);
  786. $result = $controller->loadComponent('Paginator');
  787. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  788. $this->assertSame($result, $controller->Paginator);
  789. $registry = $controller->components();
  790. $this->assertTrue(isset($registry->Paginator));
  791. }
  792. /**
  793. * Test adding a component that is a duplicate.
  794. *
  795. * @return void
  796. */
  797. public function testLoadComponentDuplicate(): void
  798. {
  799. $request = new ServerRequest(['url' => '/']);
  800. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  801. $controller = new TestController($request, $response);
  802. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  803. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  804. try {
  805. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  806. $this->fail('No exception');
  807. } catch (\RuntimeException $e) {
  808. $this->assertStringContainsString('The "Paginator" alias has already been loaded', $e->getMessage());
  809. }
  810. }
  811. /**
  812. * Test the isAction method.
  813. *
  814. * @return void
  815. */
  816. public function testIsAction(): void
  817. {
  818. $request = new ServerRequest(['url' => '/']);
  819. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  820. $controller = new TestController($request, $response);
  821. $this->assertFalse($controller->isAction('redirect'));
  822. $this->assertFalse($controller->isAction('beforeFilter'));
  823. $this->assertTrue($controller->isAction('index'));
  824. }
  825. /**
  826. * Test that view variables are being set after the beforeRender event gets dispatched
  827. *
  828. * @return void
  829. */
  830. public function testBeforeRenderViewVariables(): void
  831. {
  832. $controller = new PostsController();
  833. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  834. /** @var Controller $controller */
  835. $controller = $event->getSubject();
  836. $controller->set('testVariable', 'test');
  837. });
  838. $controller->dispatchEvent('Controller.beforeRender');
  839. $view = $controller->createView();
  840. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  841. }
  842. /**
  843. * Test that render()'s arguments are available in beforeRender() through view builder.
  844. *
  845. * @return void
  846. */
  847. public function testBeforeRenderTemplateAndLayout()
  848. {
  849. $Controller = new Controller(new ServerRequest(), new Response());
  850. $Controller->getEventManager()->on('Controller.beforeRender', function ($event) {
  851. $this->assertEquals(
  852. '/Element/test_element',
  853. $event->getSubject()->viewBuilder()->getTemplate()
  854. );
  855. $this->assertEquals(
  856. 'default',
  857. $event->getSubject()->viewBuilder()->getLayout()
  858. );
  859. $event->getSubject()->viewBuilder()
  860. ->setTemplatePath('Posts')
  861. ->setTemplate('index');
  862. });
  863. $result = $Controller->render('/Element/test_element', 'default');
  864. $this->assertRegExp('/posts index/', (string)$result);
  865. }
  866. /**
  867. * Test name getter and setter.
  868. *
  869. * @return void
  870. */
  871. public function testName(): void
  872. {
  873. $controller = new PostsController();
  874. $this->assertEquals('Posts', $controller->getName());
  875. $this->assertSame($controller, $controller->setName('Articles'));
  876. $this->assertEquals('Articles', $controller->getName());
  877. }
  878. /**
  879. * Test plugin getter and setter.
  880. *
  881. * @return void
  882. */
  883. public function testPlugin(): void
  884. {
  885. $controller = new PostsController();
  886. $this->assertEquals('', $controller->getPlugin());
  887. $this->assertSame($controller, $controller->setPlugin('Articles'));
  888. $this->assertEquals('Articles', $controller->getPlugin());
  889. }
  890. /**
  891. * Test request getter and setter.
  892. *
  893. * @return void
  894. */
  895. public function testRequest(): void
  896. {
  897. $controller = new PostsController();
  898. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  899. $request = new ServerRequest([
  900. 'params' => [
  901. 'plugin' => 'Posts',
  902. 'pass' => [
  903. 'foo',
  904. 'bar',
  905. ],
  906. ],
  907. ]);
  908. $this->assertSame($controller, $controller->setRequest($request));
  909. $this->assertSame($request, $controller->getRequest());
  910. $this->assertEquals('Posts', $controller->getRequest()->getParam('plugin'));
  911. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  912. }
  913. /**
  914. * Test response getter and setter.
  915. *
  916. * @return void
  917. */
  918. public function testResponse(): void
  919. {
  920. $controller = new PostsController();
  921. $this->assertInstanceOf(Response::class, $controller->getResponse());
  922. $response = new Response();
  923. $this->assertSame($controller, $controller->setResponse($response));
  924. $this->assertSame($response, $controller->getResponse());
  925. }
  926. /**
  927. * Test autoRender getter and setter.
  928. *
  929. * @return void
  930. */
  931. public function testAutoRender(): void
  932. {
  933. $controller = new PostsController();
  934. $this->assertTrue($controller->isAutoRenderEnabled());
  935. $this->assertSame($controller, $controller->disableAutoRender());
  936. $this->assertFalse($controller->isAutoRenderEnabled());
  937. $this->assertSame($controller, $controller->enableAutoRender());
  938. $this->assertTrue($controller->isAutoRenderEnabled());
  939. }
  940. }