ControllerTest.php 32 KB

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