ExceptionRendererTest.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Error;
  16. use Cake\Controller\Component;
  17. use Cake\Controller\Controller;
  18. use Cake\Controller\Exception\MissingActionException;
  19. use Cake\Controller\Exception\MissingComponentException;
  20. use Cake\Core\Configure;
  21. use Cake\Core\Exception\Exception as CakeException;
  22. use Cake\Core\Exception\MissingPluginException;
  23. use Cake\Core\Plugin;
  24. use Cake\Datasource\Exception\MissingDatasourceConfigException;
  25. use Cake\Datasource\Exception\MissingDatasourceException;
  26. use Cake\Error\ExceptionRenderer;
  27. use Cake\Event\Event;
  28. use Cake\Event\EventManager;
  29. use Cake\Http\Exception\InternalErrorException;
  30. use Cake\Http\Exception\MethodNotAllowedException;
  31. use Cake\Http\Exception\NotFoundException;
  32. use Cake\Http\ServerRequest;
  33. use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException;
  34. use Cake\ORM\Exception\MissingBehaviorException;
  35. use Cake\Routing\DispatcherFactory;
  36. use Cake\Routing\Exception\MissingControllerException;
  37. use Cake\Routing\Router;
  38. use Cake\TestSuite\TestCase;
  39. use Cake\View\Exception\MissingHelperException;
  40. use Cake\View\Exception\MissingLayoutException;
  41. use Cake\View\Exception\MissingTemplateException;
  42. use Exception;
  43. use RuntimeException;
  44. /**
  45. * BlueberryComponent class
  46. */
  47. class BlueberryComponent extends Component
  48. {
  49. /**
  50. * testName property
  51. *
  52. * @return void
  53. */
  54. public $testName = null;
  55. /**
  56. * initialize method
  57. *
  58. * @param array $config
  59. * @return void
  60. */
  61. public function initialize(array $config)
  62. {
  63. $this->testName = 'BlueberryComponent';
  64. }
  65. }
  66. /**
  67. * TestErrorController class
  68. */
  69. class TestErrorController extends Controller
  70. {
  71. /**
  72. * uses property
  73. *
  74. * @var array
  75. */
  76. public $uses = [];
  77. /**
  78. * components property
  79. *
  80. * @return void
  81. */
  82. public $components = ['Blueberry'];
  83. /**
  84. * beforeRender method
  85. *
  86. * @return void
  87. */
  88. public function beforeRender(Event $event)
  89. {
  90. echo $this->Blueberry->testName;
  91. }
  92. /**
  93. * index method
  94. *
  95. * @return array
  96. */
  97. public function index()
  98. {
  99. $this->autoRender = false;
  100. return 'what up';
  101. }
  102. }
  103. /**
  104. * MyCustomExceptionRenderer class
  105. */
  106. class MyCustomExceptionRenderer extends ExceptionRenderer
  107. {
  108. /**
  109. * custom error message type.
  110. *
  111. * @return string
  112. */
  113. public function missingWidgetThing()
  114. {
  115. return 'widget thing is missing';
  116. }
  117. }
  118. /**
  119. * Exception class for testing app error handlers and custom errors.
  120. */
  121. class MissingWidgetThingException extends NotFoundException
  122. {
  123. }
  124. /**
  125. * Exception class for testing app error handlers and custom errors.
  126. */
  127. class MissingWidgetThing extends \Exception
  128. {
  129. }
  130. /**
  131. * ExceptionRendererTest class
  132. */
  133. class ExceptionRendererTest extends TestCase
  134. {
  135. /**
  136. * @var bool
  137. */
  138. protected $_restoreError = false;
  139. /**
  140. * setup create a request object to get out of router later.
  141. *
  142. * @return void
  143. */
  144. public function setUp()
  145. {
  146. parent::setUp();
  147. Configure::write('Config.language', 'eng');
  148. Router::reload();
  149. $request = new ServerRequest(['base' => '']);
  150. Router::setRequestInfo($request);
  151. Configure::write('debug', true);
  152. }
  153. /**
  154. * tearDown
  155. *
  156. * @return void
  157. */
  158. public function tearDown()
  159. {
  160. parent::tearDown();
  161. if ($this->_restoreError) {
  162. restore_error_handler();
  163. }
  164. }
  165. /**
  166. * test that methods declared in an ExceptionRenderer subclass are not converted
  167. * into error400 when debug > 0
  168. *
  169. * @return void
  170. */
  171. public function testSubclassMethodsNotBeingConvertedToError()
  172. {
  173. $exception = new MissingWidgetThingException('Widget not found');
  174. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  175. $result = $ExceptionRenderer->render();
  176. $this->assertEquals('widget thing is missing', (string)$result->getBody());
  177. }
  178. /**
  179. * test that subclass methods are not converted when debug = 0
  180. *
  181. * @return void
  182. */
  183. public function testSubclassMethodsNotBeingConvertedDebug0()
  184. {
  185. Configure::write('debug', false);
  186. $exception = new MissingWidgetThingException('Widget not found');
  187. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  188. $result = $ExceptionRenderer->render();
  189. $this->assertEquals('missingWidgetThing', $ExceptionRenderer->method);
  190. $this->assertEquals(
  191. 'widget thing is missing',
  192. (string)$result->getBody(),
  193. 'Method declared in subclass converted to error400'
  194. );
  195. }
  196. /**
  197. * test that ExceptionRenderer subclasses properly convert framework errors.
  198. *
  199. * @return void
  200. */
  201. public function testSubclassConvertingFrameworkErrors()
  202. {
  203. Configure::write('debug', false);
  204. $exception = new MissingControllerException('PostsController');
  205. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  206. $result = $ExceptionRenderer->render();
  207. $this->assertRegExp(
  208. '/Not Found/',
  209. (string)$result->getBody(),
  210. 'Method declared in error handler not converted to error400. %s'
  211. );
  212. }
  213. /**
  214. * test things in the constructor.
  215. *
  216. * @return void
  217. */
  218. public function testConstruction()
  219. {
  220. $exception = new NotFoundException('Page not found');
  221. $ExceptionRenderer = new ExceptionRenderer($exception);
  222. $this->assertInstanceOf('Cake\Controller\ErrorController', $ExceptionRenderer->controller);
  223. $this->assertEquals($exception, $ExceptionRenderer->error);
  224. }
  225. /**
  226. * test that exception message gets coerced when debug = 0
  227. *
  228. * @return void
  229. */
  230. public function testExceptionMessageCoercion()
  231. {
  232. Configure::write('debug', false);
  233. $exception = new MissingActionException('Secret info not to be leaked');
  234. $ExceptionRenderer = new ExceptionRenderer($exception);
  235. $this->assertInstanceOf('Cake\Controller\ErrorController', $ExceptionRenderer->controller);
  236. $this->assertEquals($exception, $ExceptionRenderer->error);
  237. $result = (string)$ExceptionRenderer->render()->getBody();
  238. $this->assertEquals('error400', $ExceptionRenderer->template);
  239. $this->assertContains('Not Found', $result);
  240. $this->assertNotContains('Secret info not to be leaked', $result);
  241. }
  242. /**
  243. * test that helpers in custom CakeErrorController are not lost
  244. *
  245. * @return void
  246. */
  247. public function testCakeErrorHelpersNotLost()
  248. {
  249. static::setAppNamespace();
  250. $exception = new NotFoundException();
  251. $renderer = new \TestApp\Error\TestAppsExceptionRenderer($exception);
  252. $result = $renderer->render();
  253. $this->assertContains('<b>peeled</b>', (string)$result->getBody());
  254. }
  255. /**
  256. * test that unknown exception types with valid status codes are treated correctly.
  257. *
  258. * @return void
  259. */
  260. public function testUnknownExceptionTypeWithExceptionThatHasA400Code()
  261. {
  262. $exception = new MissingWidgetThingException('coding fail.');
  263. $ExceptionRenderer = new ExceptionRenderer($exception);
  264. $response = $ExceptionRenderer->render();
  265. $this->assertEquals(404, $response->getStatusCode());
  266. $this->assertFalse(method_exists($ExceptionRenderer, 'missingWidgetThing'), 'no method should exist.');
  267. $this->assertContains('coding fail', (string)$response->getBody(), 'Text should show up.');
  268. }
  269. /**
  270. * test that unknown exception types with valid status codes are treated correctly.
  271. *
  272. * @return void
  273. */
  274. public function testUnknownExceptionTypeWithNoCodeIsA500()
  275. {
  276. $exception = new \OutOfBoundsException('foul ball.');
  277. $ExceptionRenderer = new ExceptionRenderer($exception);
  278. $result = $ExceptionRenderer->render();
  279. $this->assertEquals(500, $result->getStatusCode());
  280. $this->assertContains('foul ball.', (string)$result->getBody(), 'Text should show up as its debug mode.');
  281. }
  282. /**
  283. * test that unknown exceptions have messages ignored.
  284. *
  285. * @return void
  286. */
  287. public function testUnknownExceptionInProduction()
  288. {
  289. Configure::write('debug', false);
  290. $exception = new \OutOfBoundsException('foul ball.');
  291. $ExceptionRenderer = new ExceptionRenderer($exception);
  292. $response = $ExceptionRenderer->render();
  293. $result = (string)$response->getBody();
  294. $this->assertEquals(500, $response->getStatusCode());
  295. $this->assertNotContains('foul ball.', $result, 'Text should no show up.');
  296. $this->assertContains('Internal Error', $result, 'Generic message only.');
  297. }
  298. /**
  299. * test that unknown exception types with valid status codes are treated correctly.
  300. *
  301. * @return void
  302. */
  303. public function testUnknownExceptionTypeWithCodeHigherThan500()
  304. {
  305. $exception = new \OutOfBoundsException('foul ball.', 501);
  306. $ExceptionRenderer = new ExceptionRenderer($exception);
  307. $response = $ExceptionRenderer->render();
  308. $result = (string)$response->getBody();
  309. $this->assertEquals(501, $response->getStatusCode());
  310. $this->assertContains('foul ball.', $result, 'Text should show up as its debug mode.');
  311. }
  312. /**
  313. * testerror400 method
  314. *
  315. * @return void
  316. */
  317. public function testError400()
  318. {
  319. Router::reload();
  320. $request = new ServerRequest('posts/view/1000');
  321. Router::setRequestInfo($request);
  322. $exception = new NotFoundException('Custom message');
  323. $ExceptionRenderer = new ExceptionRenderer($exception);
  324. $response = $ExceptionRenderer->render();
  325. $result = (string)$response->getBody();
  326. $this->assertEquals(404, $response->getStatusCode());
  327. $this->assertContains('<h2>Custom message</h2>', $result);
  328. $this->assertRegExp("/<strong>'.*?\/posts\/view\/1000'<\/strong>/", $result);
  329. }
  330. /**
  331. * testerror400 method when returning as json
  332. *
  333. * @return void
  334. */
  335. public function testError400AsJson()
  336. {
  337. Router::reload();
  338. $request = new ServerRequest('posts/view/1000?sort=title&direction=desc');
  339. $request = $request->withHeader('Accept', 'application/json');
  340. $request = $request->withHeader('Content-Type', 'application/json');
  341. Router::setRequestInfo($request);
  342. $exception = new NotFoundException('Custom message');
  343. $exceptionLine = __LINE__ - 1;
  344. $ExceptionRenderer = new ExceptionRenderer($exception);
  345. $response = $ExceptionRenderer->render();
  346. $result = (string)$response->getBody();
  347. $expected = [
  348. 'message' => 'Custom message',
  349. 'url' => '/posts/view/1000?sort=title&amp;direction=desc',
  350. 'code' => 404,
  351. 'file' => __FILE__,
  352. 'line' => $exceptionLine
  353. ];
  354. $this->assertEquals($expected, json_decode($result, true));
  355. $this->assertEquals(404, $response->getStatusCode());
  356. }
  357. /**
  358. * test that error400 only modifies the messages on Cake Exceptions.
  359. *
  360. * @return void
  361. */
  362. public function testerror400OnlyChangingCakeException()
  363. {
  364. Configure::write('debug', false);
  365. $exception = new NotFoundException('Custom message');
  366. $ExceptionRenderer = new ExceptionRenderer($exception);
  367. $result = $ExceptionRenderer->render();
  368. $this->assertContains('Custom message', (string)$result->getBody());
  369. $exception = new MissingActionException(['controller' => 'PostsController', 'action' => 'index']);
  370. $ExceptionRenderer = new ExceptionRenderer($exception);
  371. $result = $ExceptionRenderer->render();
  372. $this->assertContains('Not Found', (string)$result->getBody());
  373. }
  374. /**
  375. * test that error400 doesn't expose XSS
  376. *
  377. * @return void
  378. */
  379. public function testError400NoInjection()
  380. {
  381. Router::reload();
  382. $request = new ServerRequest('pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>');
  383. Router::setRequestInfo($request);
  384. $exception = new NotFoundException('Custom message');
  385. $ExceptionRenderer = new ExceptionRenderer($exception);
  386. $result = (string)$ExceptionRenderer->render()->getBody();
  387. $this->assertNotContains('<script>document', $result);
  388. $this->assertNotContains('alert(t);</script>', $result);
  389. }
  390. /**
  391. * testError500 method
  392. *
  393. * @return void
  394. */
  395. public function testError500Message()
  396. {
  397. $exception = new InternalErrorException('An Internal Error Has Occurred.');
  398. $ExceptionRenderer = new ExceptionRenderer($exception);
  399. $response = $ExceptionRenderer->render();
  400. $result = (string)$response->getBody();
  401. $this->assertEquals(500, $response->getStatusCode());
  402. $this->assertContains('<h2>An Internal Error Has Occurred.</h2>', $result);
  403. $this->assertContains('An Internal Error Has Occurred.</p>', $result);
  404. }
  405. /**
  406. * testExceptionResponseHeader method
  407. *
  408. * @return void
  409. */
  410. public function testExceptionResponseHeader()
  411. {
  412. $exception = new MethodNotAllowedException('Only allowing POST and DELETE');
  413. $exception->responseHeader(['Allow' => 'POST, DELETE']);
  414. $ExceptionRenderer = new ExceptionRenderer($exception);
  415. $result = $ExceptionRenderer->render();
  416. $this->assertTrue($result->hasHeader('Allow'));
  417. $this->assertEquals('POST, DELETE', $result->getHeaderLine('Allow'));
  418. }
  419. /**
  420. * testMissingController method
  421. *
  422. * @return void
  423. */
  424. public function testMissingController()
  425. {
  426. $exception = new MissingControllerException([
  427. 'class' => 'Posts',
  428. 'prefix' => '',
  429. 'plugin' => '',
  430. ]);
  431. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  432. $result = (string)$ExceptionRenderer->render()->getBody();
  433. $this->assertEquals('missingController', $ExceptionRenderer->template);
  434. $this->assertContains('Missing Controller', $result);
  435. $this->assertContains('<em>PostsController</em>', $result);
  436. }
  437. /**
  438. * test missingController method
  439. *
  440. * @return void
  441. */
  442. public function testMissingControllerLowerCase()
  443. {
  444. $exception = new MissingControllerException([
  445. 'class' => 'posts',
  446. 'prefix' => '',
  447. 'plugin' => '',
  448. ]);
  449. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  450. $result = (string)$ExceptionRenderer->render()->getBody();
  451. $this->assertEquals('missingController', $ExceptionRenderer->template);
  452. $this->assertContains('Missing Controller', $result);
  453. $this->assertContains('<em>PostsController</em>', $result);
  454. }
  455. /**
  456. * Returns an array of tests to run for the various Cake Exception classes.
  457. *
  458. * @return array
  459. */
  460. public static function exceptionProvider()
  461. {
  462. return [
  463. [
  464. new MissingActionException([
  465. 'controller' => 'postsController',
  466. 'action' => 'index',
  467. 'prefix' => '',
  468. 'plugin' => '',
  469. ]),
  470. [
  471. '/Missing Method in PostsController/',
  472. '/<em>PostsController::index\(\)<\/em>/'
  473. ],
  474. 404
  475. ],
  476. [
  477. new MissingActionException([
  478. 'controller' => 'PostsController',
  479. 'action' => 'index',
  480. 'prefix' => '',
  481. 'plugin' => '',
  482. ]),
  483. [
  484. '/Missing Method in PostsController/',
  485. '/<em>PostsController::index\(\)<\/em>/'
  486. ],
  487. 404
  488. ],
  489. [
  490. new MissingTemplateException(['file' => '/posts/about.ctp']),
  491. [
  492. "/posts\/about.ctp/"
  493. ],
  494. 500
  495. ],
  496. [
  497. new MissingLayoutException(['file' => 'layouts/my_layout.ctp']),
  498. [
  499. '/Missing Layout/',
  500. "/layouts\/my_layout.ctp/"
  501. ],
  502. 500
  503. ],
  504. [
  505. new MissingHelperException(['class' => 'MyCustomHelper']),
  506. [
  507. '/Missing Helper/',
  508. '/<em>MyCustomHelper<\/em> could not be found./',
  509. '/Create the class <em>MyCustomHelper<\/em> below in file:/',
  510. '/(\/|\\\)MyCustomHelper.php/'
  511. ],
  512. 500
  513. ],
  514. [
  515. new MissingBehaviorException(['class' => 'MyCustomBehavior']),
  516. [
  517. '/Missing Behavior/',
  518. '/Create the class <em>MyCustomBehavior<\/em> below in file:/',
  519. '/(\/|\\\)MyCustomBehavior.php/'
  520. ],
  521. 500
  522. ],
  523. [
  524. new MissingComponentException(['class' => 'SideboxComponent']),
  525. [
  526. '/Missing Component/',
  527. '/Create the class <em>SideboxComponent<\/em> below in file:/',
  528. '/(\/|\\\)SideboxComponent.php/'
  529. ],
  530. 500
  531. ],
  532. [
  533. new MissingDatasourceConfigException(['name' => 'MyDatasourceConfig']),
  534. [
  535. '/Missing Datasource Configuration/',
  536. '/<em>MyDatasourceConfig<\/em> was not found/'
  537. ],
  538. 500
  539. ],
  540. [
  541. new MissingDatasourceException(['class' => 'MyDatasource', 'plugin' => 'MyPlugin']),
  542. [
  543. '/Missing Datasource/',
  544. '/<em>MyPlugin.MyDatasource<\/em> could not be found./'
  545. ],
  546. 500
  547. ],
  548. [
  549. new MissingMailerActionException([
  550. 'mailer' => 'UserMailer',
  551. 'action' => 'welcome',
  552. 'prefix' => '',
  553. 'plugin' => '',
  554. ]),
  555. [
  556. '/Missing Method in UserMailer/',
  557. '/<em>UserMailer::welcome\(\)<\/em>/'
  558. ],
  559. 404
  560. ],
  561. [
  562. new Exception('boom'),
  563. [
  564. '/Internal Error/'
  565. ],
  566. 500
  567. ],
  568. [
  569. new RuntimeException('another boom'),
  570. [
  571. '/Internal Error/'
  572. ],
  573. 500
  574. ],
  575. [
  576. new CakeException('base class'),
  577. ['/Internal Error/'],
  578. 500
  579. ]
  580. ];
  581. }
  582. /**
  583. * Test the various Cake Exception sub classes
  584. *
  585. * @dataProvider exceptionProvider
  586. * @return void
  587. */
  588. public function testCakeExceptionHandling($exception, $patterns, $code)
  589. {
  590. $exceptionRenderer = new ExceptionRenderer($exception);
  591. $response = $exceptionRenderer->render();
  592. $this->assertEquals($code, $response->getStatusCode());
  593. $body = (string)$response->getBody();
  594. foreach ($patterns as $pattern) {
  595. $this->assertRegExp($pattern, $body);
  596. }
  597. }
  598. /**
  599. * Test that class names not ending in Exception are not mangled.
  600. *
  601. * @return void
  602. */
  603. public function testExceptionNameMangling()
  604. {
  605. $exceptionRenderer = new MyCustomExceptionRenderer(new MissingWidgetThing());
  606. $result = (string)$exceptionRenderer->render()->getBody();
  607. $this->assertContains('widget thing is missing', $result);
  608. }
  609. /**
  610. * Test exceptions being raised when helpers are missing.
  611. *
  612. * @return void
  613. */
  614. public function testMissingRenderSafe()
  615. {
  616. $exception = new MissingHelperException(['class' => 'Fail']);
  617. $ExceptionRenderer = new ExceptionRenderer($exception);
  618. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  619. ->setMethods(['render'])
  620. ->getMock();
  621. $ExceptionRenderer->controller->helpers = ['Fail', 'Boom'];
  622. $ExceptionRenderer->controller->request = new ServerRequest;
  623. $ExceptionRenderer->controller->expects($this->at(0))
  624. ->method('render')
  625. ->with('missingHelper')
  626. ->will($this->throwException($exception));
  627. $response = $ExceptionRenderer->render();
  628. sort($ExceptionRenderer->controller->helpers);
  629. $this->assertEquals(['Form', 'Html'], $ExceptionRenderer->controller->helpers);
  630. $this->assertContains('Helper class Fail', (string)$response->getBody());
  631. }
  632. /**
  633. * Test that exceptions in beforeRender() are handled by outputMessageSafe
  634. *
  635. * @return void
  636. */
  637. public function testRenderExceptionInBeforeRender()
  638. {
  639. $exception = new NotFoundException('Not there, sorry');
  640. $ExceptionRenderer = new ExceptionRenderer($exception);
  641. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  642. ->setMethods(['beforeRender'])
  643. ->getMock();
  644. $ExceptionRenderer->controller->request = new ServerRequest;
  645. $ExceptionRenderer->controller->expects($this->any())
  646. ->method('beforeRender')
  647. ->will($this->throwException($exception));
  648. $response = $ExceptionRenderer->render();
  649. $this->assertContains('Not there, sorry', (string)$response->getBody());
  650. }
  651. /**
  652. * Test that missing layoutPath don't cause other fatal errors.
  653. *
  654. * @return void
  655. */
  656. public function testMissingLayoutPathRenderSafe()
  657. {
  658. $this->called = false;
  659. $exception = new NotFoundException();
  660. $ExceptionRenderer = new ExceptionRenderer($exception);
  661. $ExceptionRenderer->controller = new Controller();
  662. $ExceptionRenderer->controller->helpers = ['Fail', 'Boom'];
  663. $ExceptionRenderer->controller->getEventManager()->on(
  664. 'Controller.beforeRender',
  665. function (Event $event) {
  666. $this->called = true;
  667. $event->getSubject()->viewBuilder()->setLayoutPath('boom');
  668. }
  669. );
  670. $ExceptionRenderer->controller->request = new ServerRequest;
  671. $response = $ExceptionRenderer->render();
  672. $this->assertEquals('text/html', $response->getType());
  673. $this->assertContains('Not Found', (string)$response->getBody());
  674. $this->assertTrue($this->called, 'Listener added was not triggered.');
  675. $this->assertEquals('', $ExceptionRenderer->controller->viewBuilder()->getLayoutPath());
  676. $this->assertEquals('Error', $ExceptionRenderer->controller->viewBuilder()->getTemplatePath());
  677. }
  678. /**
  679. * Test that missing plugin disables Controller::$plugin if the two are the same plugin.
  680. *
  681. * @return void
  682. */
  683. public function testMissingPluginRenderSafe()
  684. {
  685. $exception = new NotFoundException();
  686. $ExceptionRenderer = new ExceptionRenderer($exception);
  687. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  688. ->setMethods(['render'])
  689. ->getMock();
  690. $ExceptionRenderer->controller->setPlugin('TestPlugin');
  691. $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  692. $exception = new MissingPluginException(['plugin' => 'TestPlugin']);
  693. $ExceptionRenderer->controller->expects($this->once())
  694. ->method('render')
  695. ->with('error400')
  696. ->will($this->throwException($exception));
  697. $response = $ExceptionRenderer->render();
  698. $body = (string)$response->getBody();
  699. $this->assertNotContains('test plugin error500', $body);
  700. $this->assertContains('Not Found', $body);
  701. }
  702. /**
  703. * Test that missing plugin doesn't disable Controller::$plugin if the two aren't the same plugin.
  704. *
  705. * @return void
  706. */
  707. public function testMissingPluginRenderSafeWithPlugin()
  708. {
  709. Plugin::load('TestPlugin');
  710. $exception = new NotFoundException();
  711. $ExceptionRenderer = new ExceptionRenderer($exception);
  712. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  713. ->setMethods(['render'])
  714. ->getMock();
  715. $ExceptionRenderer->controller->setPlugin('TestPlugin');
  716. $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  717. $exception = new MissingPluginException(['plugin' => 'TestPluginTwo']);
  718. $ExceptionRenderer->controller->expects($this->once())
  719. ->method('render')
  720. ->with('error400')
  721. ->will($this->throwException($exception));
  722. $response = $ExceptionRenderer->render();
  723. $body = (string)$response->getBody();
  724. $this->assertContains('test plugin error500', $body);
  725. $this->assertContains('Not Found', $body);
  726. Plugin::unload();
  727. }
  728. /**
  729. * Test that exceptions can be rendered when a request hasn't been registered
  730. * with Router
  731. *
  732. * @return void
  733. */
  734. public function testRenderWithNoRequest()
  735. {
  736. Router::reload();
  737. $this->assertNull(Router::getRequest(false));
  738. $exception = new Exception('Terrible');
  739. $ExceptionRenderer = new ExceptionRenderer($exception);
  740. $result = $ExceptionRenderer->render();
  741. $this->assertContains('Internal Error', (string)$result->getBody());
  742. $this->assertEquals(500, $result->getStatusCode());
  743. }
  744. /**
  745. * Test that rendering exceptions triggers shutdown events.
  746. *
  747. * @return void
  748. */
  749. public function testRenderShutdownEvents()
  750. {
  751. $fired = [];
  752. $listener = function (Event $event) use (&$fired) {
  753. $fired[] = $event->getName();
  754. };
  755. $events = EventManager::instance();
  756. $events->on('Controller.shutdown', $listener);
  757. $events->on('Dispatcher.afterDispatch', $listener);
  758. $exception = new Exception('Terrible');
  759. $renderer = new ExceptionRenderer($exception);
  760. $renderer->render();
  761. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  762. $this->assertEquals($expected, $fired);
  763. }
  764. /**
  765. * Test that rendering exceptions triggers events
  766. * on filters attached to dispatcherfactory
  767. *
  768. * @return void
  769. */
  770. public function testRenderShutdownEventsOnDispatcherFactory()
  771. {
  772. $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter')
  773. ->setMethods(['afterDispatch'])
  774. ->getMock();
  775. $filter->expects($this->at(0))
  776. ->method('afterDispatch');
  777. DispatcherFactory::add($filter);
  778. $exception = new Exception('Terrible');
  779. $renderer = new ExceptionRenderer($exception);
  780. $renderer->render();
  781. }
  782. /**
  783. * test that subclass methods fire shutdown events.
  784. *
  785. * @return void
  786. */
  787. public function testSubclassTriggerShutdownEvents()
  788. {
  789. $fired = [];
  790. $listener = function (Event $event) use (&$fired) {
  791. $fired[] = $event->getName();
  792. };
  793. $events = EventManager::instance();
  794. $events->on('Controller.shutdown', $listener);
  795. $events->on('Dispatcher.afterDispatch', $listener);
  796. $exception = new MissingWidgetThingException('Widget not found');
  797. $renderer = new MyCustomExceptionRenderer($exception);
  798. $renderer->render();
  799. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  800. $this->assertEquals($expected, $fired);
  801. }
  802. /**
  803. * Tests the output of rendering a PDOException
  804. *
  805. * @return void
  806. */
  807. public function testPDOException()
  808. {
  809. $exception = new \PDOException('There was an error in the SQL query');
  810. $exception->queryString = 'SELECT * from poo_query < 5 and :seven';
  811. $exception->params = ['seven' => 7];
  812. $ExceptionRenderer = new ExceptionRenderer($exception);
  813. $response = $ExceptionRenderer->render();
  814. $this->assertEquals(500, $response->getStatusCode());
  815. $result = (string)$response->getBody();
  816. $this->assertContains('Database Error', $result);
  817. $this->assertContains('There was an error in the SQL query', $result);
  818. $this->assertContains(h('SELECT * from poo_query < 5 and :seven'), $result);
  819. $this->assertContains("'seven' => (int) 7", $result);
  820. }
  821. }