ControllerTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  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. '_serialize' => ['test'],
  240. ]);
  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 = $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->assertStringContainsString('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. }