ControllerTest.php 35 KB

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