ExceptionRendererTest.php 31 KB

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