ExceptionRendererTest.php 29 KB

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