ExceptionRendererTest.php 29 KB

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