ControllerTest.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  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->assertContains('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. $request = $this->getMockBuilder('Cake\Http\ServerRequest')
  389. ->setMethods(['referer'])
  390. ->getMock();
  391. $request = $request->withAttribute('base', '/base');
  392. Router::pushRequest($request);
  393. $request->expects($this->any())->method('referer')
  394. ->will($this->returnValue(null));
  395. $controller = new Controller($request);
  396. $result = $controller->referer('/', true);
  397. $this->assertEquals('/', $result);
  398. $controller = new Controller($request);
  399. $result = $controller->referer('/some/path', true);
  400. $this->assertEquals('/some/path', $result);
  401. }
  402. /**
  403. * testSetAction method
  404. *
  405. * @return void
  406. */
  407. public function testSetAction(): void
  408. {
  409. $request = new ServerRequest(['url' => 'controller/posts/index']);
  410. $TestController = new TestController($request);
  411. $TestController->setAction('view', 1, 2);
  412. $expected = ['testId' => 1, 'test2Id' => 2];
  413. $this->assertSame($expected, $TestController->getRequest()->getData());
  414. $this->assertSame('view', $TestController->getRequest()->getParam('action'));
  415. }
  416. /**
  417. * Tests that the startup process calls the correct functions
  418. *
  419. * @return void
  420. */
  421. public function testStartupProcess(): void
  422. {
  423. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  424. $controller = new Controller(null, null, null, $eventManager);
  425. $eventManager->expects($this->at(0))->method('dispatch')
  426. ->with(
  427. $this->logicalAnd(
  428. $this->isInstanceOf('Cake\Event\Event'),
  429. $this->attributeEqualTo('_name', 'Controller.initialize'),
  430. $this->attributeEqualTo('_subject', $controller)
  431. )
  432. )
  433. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  434. $eventManager->expects($this->at(1))->method('dispatch')
  435. ->with(
  436. $this->logicalAnd(
  437. $this->isInstanceOf('Cake\Event\Event'),
  438. $this->attributeEqualTo('_name', 'Controller.startup'),
  439. $this->attributeEqualTo('_subject', $controller)
  440. )
  441. )
  442. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  443. $controller->startupProcess();
  444. }
  445. /**
  446. * Tests that the shutdown process calls the correct functions
  447. *
  448. * @return void
  449. */
  450. public function testShutdownProcess(): void
  451. {
  452. $eventManager = $this->getMockBuilder('Cake\Event\EventManagerInterface')->getMock();
  453. $controller = new Controller(null, null, null, $eventManager);
  454. $eventManager->expects($this->once())->method('dispatch')
  455. ->with(
  456. $this->logicalAnd(
  457. $this->isInstanceOf('Cake\Event\Event'),
  458. $this->attributeEqualTo('_name', 'Controller.shutdown'),
  459. $this->attributeEqualTo('_subject', $controller)
  460. )
  461. )
  462. ->will($this->returnValue($this->getMockBuilder('Cake\Event\Event')->disableOriginalConstructor()->getMock()));
  463. $controller->shutdownProcess();
  464. }
  465. /**
  466. * test using Controller::paginate()
  467. *
  468. * @return void
  469. */
  470. public function testPaginate(): void
  471. {
  472. $request = new ServerRequest(['url' => 'controller_posts/index']);
  473. $response = $this->getMockBuilder('Cake\Http\Response')
  474. ->setMethods(['httpCodes'])
  475. ->getMock();
  476. $Controller = new Controller($request, $response);
  477. $Controller->setRequest($Controller->getRequest()->withQueryParams([
  478. 'posts' => [
  479. 'page' => 2,
  480. 'limit' => 2,
  481. ],
  482. ]));
  483. $this->assertEquals([], $Controller->paginate);
  484. $this->assertNotContains('Paginator', $Controller->viewBuilder()->getHelpers());
  485. $this->assertArrayNotHasKey('Paginator', $Controller->viewBuilder()->getHelpers());
  486. $results = $Controller->paginate('Posts');
  487. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  488. $this->assertCount(3, $results);
  489. $results = $Controller->paginate($this->getTableLocator()->get('Posts'));
  490. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  491. $this->assertCount(3, $results);
  492. $paging = $Controller->getRequest()->getParam('paging');
  493. $this->assertSame($paging['Posts']['page'], 1);
  494. $this->assertSame($paging['Posts']['pageCount'], 1);
  495. $this->assertFalse($paging['Posts']['prevPage']);
  496. $this->assertFalse($paging['Posts']['nextPage']);
  497. $this->assertNull($paging['Posts']['scope']);
  498. $results = $Controller->paginate($this->getTableLocator()->get('Posts'), ['scope' => 'posts']);
  499. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  500. $this->assertCount(1, $results);
  501. $paging = $Controller->getRequest()->getParam('paging');
  502. $this->assertSame($paging['Posts']['page'], 2);
  503. $this->assertSame($paging['Posts']['pageCount'], 2);
  504. $this->assertTrue($paging['Posts']['prevPage']);
  505. $this->assertFalse($paging['Posts']['nextPage']);
  506. $this->assertSame($paging['Posts']['scope'], 'posts');
  507. }
  508. /**
  509. * test that paginate uses modelClass property.
  510. *
  511. * @return void
  512. */
  513. public function testPaginateUsesModelClass(): void
  514. {
  515. $request = new ServerRequest([
  516. 'url' => 'controller_posts/index',
  517. ]);
  518. $response = $this->getMockBuilder('Cake\Http\Response')
  519. ->setMethods(['httpCodes'])
  520. ->getMock();
  521. $Controller = new Controller($request, $response);
  522. $Controller->modelClass = 'Posts';
  523. $results = $Controller->paginate();
  524. $this->assertInstanceOf('Cake\Datasource\ResultSetInterface', $results);
  525. }
  526. /**
  527. * testMissingAction method
  528. *
  529. * @return void
  530. */
  531. public function testInvokeActionMissingAction(): void
  532. {
  533. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  534. $this->expectExceptionMessage('Action TestController::missing() could not be found, or is not accessible.');
  535. $url = new ServerRequest([
  536. 'url' => 'test/missing',
  537. 'params' => ['controller' => 'Test', 'action' => 'missing'],
  538. ]);
  539. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  540. $Controller = new TestController($url, $response);
  541. $Controller->invokeAction();
  542. }
  543. /**
  544. * test invoking private methods.
  545. *
  546. * @return void
  547. */
  548. public function testInvokeActionPrivate(): void
  549. {
  550. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  551. $this->expectExceptionMessage('Action TestController::private_m() could not be found, or is not accessible.');
  552. $url = new ServerRequest([
  553. 'url' => 'test/private_m/',
  554. 'params' => ['controller' => 'Test', 'action' => 'private_m'],
  555. ]);
  556. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  557. $Controller = new TestController($url, $response);
  558. $Controller->invokeAction();
  559. }
  560. /**
  561. * test invoking protected methods.
  562. *
  563. * @return void
  564. */
  565. public function testInvokeActionProtected(): void
  566. {
  567. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  568. $this->expectExceptionMessage('Action TestController::protected_m() could not be found, or is not accessible.');
  569. $url = new ServerRequest([
  570. 'url' => 'test/protected_m/',
  571. 'params' => ['controller' => 'Test', 'action' => 'protected_m'],
  572. ]);
  573. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  574. $Controller = new TestController($url, $response);
  575. $Controller->invokeAction();
  576. }
  577. /**
  578. * test invoking controller methods.
  579. *
  580. * @return void
  581. */
  582. public function testInvokeActionBaseMethods(): void
  583. {
  584. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  585. $this->expectExceptionMessage('Action TestController::redirect() could not be found, or is not accessible.');
  586. $url = new ServerRequest([
  587. 'url' => 'test/redirect/',
  588. 'params' => ['controller' => 'Test', 'action' => 'redirect'],
  589. ]);
  590. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  591. $Controller = new TestController($url, $response);
  592. $Controller->invokeAction();
  593. }
  594. /**
  595. * test invoking action method with mismatched casing.
  596. *
  597. * @return void
  598. */
  599. public function testInvokeActionMethodCasing(): void
  600. {
  601. $this->expectException(\Cake\Controller\Exception\MissingActionException::class);
  602. $this->expectExceptionMessage('Action TestController::RETURNER() could not be found, or is not accessible.');
  603. $url = new ServerRequest([
  604. 'url' => 'test/RETURNER/',
  605. 'params' => ['controller' => 'Test', 'action' => 'RETURNER'],
  606. ]);
  607. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  608. $Controller = new TestController($url, $response);
  609. $Controller->invokeAction();
  610. }
  611. /**
  612. * test invoking controller methods.
  613. *
  614. * @return void
  615. */
  616. public function testInvokeActionReturnValue(): void
  617. {
  618. $url = new ServerRequest([
  619. 'url' => 'test/returner/',
  620. 'params' => [
  621. 'controller' => 'Test',
  622. 'action' => 'returner',
  623. 'pass' => [],
  624. ],
  625. ]);
  626. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  627. $Controller = new TestController($url, $response);
  628. $result = $Controller->invokeAction();
  629. $this->assertEquals('I am from the controller.', $result);
  630. }
  631. /**
  632. * test invoking controller methods with passed params
  633. *
  634. * @return void
  635. */
  636. public function testInvokeActionWithPassedParams(): void
  637. {
  638. $url = new ServerRequest([
  639. 'url' => 'test/index/1/2',
  640. 'params' => [
  641. 'controller' => 'Test',
  642. 'action' => 'index',
  643. 'pass' => ['param1' => '1', 'param2' => '2'],
  644. ],
  645. ]);
  646. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  647. $Controller = new TestController($url, $response);
  648. $result = $Controller->invokeAction();
  649. $this->assertEquals(
  650. ['testId' => '1', 'test2Id' => '2'],
  651. $Controller->getRequest()->getData()
  652. );
  653. }
  654. /**
  655. * test that a classes namespace is used in the viewPath.
  656. *
  657. * @return void
  658. */
  659. public function testViewPathConventions(): void
  660. {
  661. $request = new ServerRequest([
  662. 'url' => 'admin/posts',
  663. 'params' => ['prefix' => 'admin'],
  664. ]);
  665. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  666. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  667. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  668. return $e->getSubject()->getResponse();
  669. });
  670. $Controller->render();
  671. $this->assertEquals('Admin' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  672. $request = $request->withParam('prefix', 'admin/super');
  673. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  674. $Controller = new \TestApp\Controller\Admin\PostsController($request, $response);
  675. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  676. return $e->getSubject()->getResponse();
  677. });
  678. $Controller->render();
  679. $this->assertEquals('Admin' . DS . 'Super' . DS . 'Posts', $Controller->viewBuilder()->getTemplatePath());
  680. $request = new ServerRequest([
  681. 'url' => 'pages/home',
  682. 'params' => [
  683. 'prefix' => false,
  684. ],
  685. ]);
  686. $Controller = new \TestApp\Controller\PagesController($request, $response);
  687. $Controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $e) {
  688. return $e->getSubject()->getResponse();
  689. });
  690. $Controller->render();
  691. $this->assertEquals('Pages', $Controller->viewBuilder()->getTemplatePath());
  692. }
  693. /**
  694. * Test the components() method.
  695. *
  696. * @return void
  697. */
  698. public function testComponents(): void
  699. {
  700. $request = new ServerRequest(['url' => '/']);
  701. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  702. $controller = new TestController($request, $response);
  703. $this->assertInstanceOf('Cake\Controller\ComponentRegistry', $controller->components());
  704. $result = $controller->components();
  705. $this->assertSame($result, $controller->components());
  706. }
  707. /**
  708. * Test the components property errors
  709. *
  710. * @return void
  711. */
  712. public function testComponentsPropertyError(): void
  713. {
  714. $this->expectException(Warning::class);
  715. $request = new ServerRequest(['url' => '/']);
  716. $response = new Response();
  717. $controller = new TestController($request, $response);
  718. $controller->components = ['Flash'];
  719. }
  720. /**
  721. * Test the helpers property errors
  722. *
  723. * @return void
  724. */
  725. public function testHelpersPropertyError(): void
  726. {
  727. $this->expectException(Warning::class);
  728. $request = new ServerRequest(['url' => '/']);
  729. $response = new Response();
  730. $controller = new TestController($request, $response);
  731. $controller->helpers = ['Flash'];
  732. }
  733. /**
  734. * Test the components() method with the custom ObjectRegistry.
  735. *
  736. * @return void
  737. */
  738. public function testComponentsWithCustomRegistry(): void
  739. {
  740. $request = new ServerRequest(['url' => '/']);
  741. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  742. $componentRegistry = $this->getMockBuilder('Cake\Controller\ComponentRegistry')
  743. ->setMethods(['offsetGet'])
  744. ->getMock();
  745. $controller = new TestController($request, $response, null, null, $componentRegistry);
  746. $this->assertInstanceOf(get_class($componentRegistry), $controller->components());
  747. $result = $controller->components();
  748. $this->assertSame($result, $controller->components());
  749. }
  750. /**
  751. * Test adding a component
  752. *
  753. * @return void
  754. */
  755. public function testLoadComponent(): void
  756. {
  757. $request = new ServerRequest(['url' => '/']);
  758. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  759. $controller = new TestController($request, $response);
  760. $result = $controller->loadComponent('Paginator');
  761. $this->assertInstanceOf('Cake\Controller\Component\PaginatorComponent', $result);
  762. $this->assertSame($result, $controller->Paginator);
  763. $registry = $controller->components();
  764. $this->assertTrue(isset($registry->Paginator));
  765. }
  766. /**
  767. * Test adding a component that is a duplicate.
  768. *
  769. * @return void
  770. */
  771. public function testLoadComponentDuplicate(): void
  772. {
  773. $request = new ServerRequest(['url' => '/']);
  774. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  775. $controller = new TestController($request, $response);
  776. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  777. $this->assertNotEmpty($controller->loadComponent('Paginator'));
  778. try {
  779. $controller->loadComponent('Paginator', ['bad' => 'settings']);
  780. $this->fail('No exception');
  781. } catch (\RuntimeException $e) {
  782. $this->assertContains('The "Paginator" alias has already been loaded', $e->getMessage());
  783. }
  784. }
  785. /**
  786. * Test the isAction method.
  787. *
  788. * @return void
  789. */
  790. public function testIsAction(): void
  791. {
  792. $request = new ServerRequest(['url' => '/']);
  793. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  794. $controller = new TestController($request, $response);
  795. $this->assertFalse($controller->isAction('redirect'));
  796. $this->assertFalse($controller->isAction('beforeFilter'));
  797. $this->assertTrue($controller->isAction('index'));
  798. }
  799. /**
  800. * Test that view variables are being set after the beforeRender event gets dispatched
  801. *
  802. * @return void
  803. */
  804. public function testBeforeRenderViewVariables(): void
  805. {
  806. $controller = new PostsController();
  807. $controller->getEventManager()->on('Controller.beforeRender', function (EventInterface $event): void {
  808. /** @var Controller $controller */
  809. $controller = $event->getSubject();
  810. $controller->set('testVariable', 'test');
  811. });
  812. $controller->dispatchEvent('Controller.beforeRender');
  813. $view = $controller->createView();
  814. $this->assertNotEmpty('testVariable', $view->get('testVariable'));
  815. }
  816. /**
  817. * Test that render()'s arguments are available in beforeRender() through view builder.
  818. *
  819. * @return void
  820. */
  821. public function testBeforeRenderTemplateAndLayout()
  822. {
  823. $Controller = new Controller(new ServerRequest(), new Response());
  824. $Controller->getEventManager()->on('Controller.beforeRender', function ($event) {
  825. $this->assertEquals(
  826. '/Element/test_element',
  827. $event->getSubject()->viewBuilder()->getTemplate()
  828. );
  829. $this->assertEquals(
  830. 'default',
  831. $event->getSubject()->viewBuilder()->getLayout()
  832. );
  833. $event->getSubject()->viewBuilder()
  834. ->setTemplatePath('Posts')
  835. ->setTemplate('index');
  836. });
  837. $result = $Controller->render('/Element/test_element', 'default');
  838. $this->assertRegExp('/posts index/', (string)$result);
  839. }
  840. /**
  841. * Test name getter and setter.
  842. *
  843. * @return void
  844. */
  845. public function testName(): void
  846. {
  847. $controller = new PostsController();
  848. $this->assertEquals('Posts', $controller->getName());
  849. $this->assertSame($controller, $controller->setName('Articles'));
  850. $this->assertEquals('Articles', $controller->getName());
  851. }
  852. /**
  853. * Test plugin getter and setter.
  854. *
  855. * @return void
  856. */
  857. public function testPlugin(): void
  858. {
  859. $controller = new PostsController();
  860. $this->assertEquals('', $controller->getPlugin());
  861. $this->assertSame($controller, $controller->setPlugin('Articles'));
  862. $this->assertEquals('Articles', $controller->getPlugin());
  863. }
  864. /**
  865. * Test request getter and setter.
  866. *
  867. * @return void
  868. */
  869. public function testRequest(): void
  870. {
  871. $controller = new PostsController();
  872. $this->assertInstanceOf(ServerRequest::class, $controller->getRequest());
  873. $request = new ServerRequest([
  874. 'params' => [
  875. 'plugin' => 'Posts',
  876. 'pass' => [
  877. 'foo',
  878. 'bar',
  879. ],
  880. ],
  881. ]);
  882. $this->assertSame($controller, $controller->setRequest($request));
  883. $this->assertSame($request, $controller->getRequest());
  884. $this->assertEquals('Posts', $controller->getRequest()->getParam('plugin'));
  885. $this->assertEquals(['foo', 'bar'], $controller->getRequest()->getParam('pass'));
  886. }
  887. /**
  888. * Test response getter and setter.
  889. *
  890. * @return void
  891. */
  892. public function testResponse(): void
  893. {
  894. $controller = new PostsController();
  895. $this->assertInstanceOf(Response::class, $controller->getResponse());
  896. $response = new Response();
  897. $this->assertSame($controller, $controller->setResponse($response));
  898. $this->assertSame($response, $controller->getResponse());
  899. }
  900. /**
  901. * Test autoRender getter and setter.
  902. *
  903. * @return void
  904. */
  905. public function testAutoRender(): void
  906. {
  907. $controller = new PostsController();
  908. $this->assertTrue($controller->isAutoRenderEnabled());
  909. $this->assertSame($controller, $controller->disableAutoRender());
  910. $this->assertFalse($controller->isAutoRenderEnabled());
  911. $this->assertSame($controller, $controller->enableAutoRender());
  912. $this->assertTrue($controller->isAutoRenderEnabled());
  913. }
  914. }