ExceptionRendererTest.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985
  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. 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 void
  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 void
  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 SocketException('socket exception');
  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. }
  618. /**
  619. * Test the various Cake Exception sub classes
  620. *
  621. * @dataProvider exceptionProvider
  622. * @return void
  623. */
  624. public function testCakeExceptionHandling($exception, $patterns, $code)
  625. {
  626. $exceptionRenderer = new ExceptionRenderer($exception);
  627. $response = $exceptionRenderer->render();
  628. $this->assertEquals($code, $response->getStatusCode());
  629. $body = (string)$response->getBody();
  630. foreach ($patterns as $pattern) {
  631. $this->assertRegExp($pattern, $body);
  632. }
  633. }
  634. /**
  635. * Test that class names not ending in Exception are not mangled.
  636. *
  637. * @return void
  638. */
  639. public function testExceptionNameMangling()
  640. {
  641. $exceptionRenderer = new MyCustomExceptionRenderer(new MissingWidgetThing());
  642. $result = (string)$exceptionRenderer->render()->getBody();
  643. $this->assertContains('widget thing is missing', $result);
  644. }
  645. /**
  646. * Test exceptions being raised when helpers are missing.
  647. *
  648. * @return void
  649. */
  650. public function testMissingRenderSafe()
  651. {
  652. $exception = new MissingHelperException(['class' => 'Fail']);
  653. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  654. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  655. ->setMethods(['render'])
  656. ->getMock();
  657. $controller->helpers = ['Fail', 'Boom'];
  658. $controller->request = new ServerRequest;
  659. $controller->expects($this->at(0))
  660. ->method('render')
  661. ->with('missingHelper')
  662. ->will($this->throwException($exception));
  663. $ExceptionRenderer->setController($controller);
  664. $response = $ExceptionRenderer->render();
  665. sort($controller->helpers);
  666. $this->assertEquals(['Form', 'Html'], $controller->helpers);
  667. $this->assertContains('Helper class Fail', (string)$response->getBody());
  668. }
  669. /**
  670. * Test that exceptions in beforeRender() are handled by outputMessageSafe
  671. *
  672. * @return void
  673. */
  674. public function testRenderExceptionInBeforeRender()
  675. {
  676. $exception = new NotFoundException('Not there, sorry');
  677. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  678. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  679. ->setMethods(['beforeRender'])
  680. ->getMock();
  681. $controller->request = new ServerRequest;
  682. $controller->expects($this->any())
  683. ->method('beforeRender')
  684. ->will($this->throwException($exception));
  685. $ExceptionRenderer->setController($controller);
  686. $response = $ExceptionRenderer->render();
  687. $this->assertContains('Not there, sorry', (string)$response->getBody());
  688. }
  689. /**
  690. * Test that missing layoutPath don't cause other fatal errors.
  691. *
  692. * @return void
  693. */
  694. public function testMissingLayoutPathRenderSafe()
  695. {
  696. $this->called = false;
  697. $exception = new NotFoundException();
  698. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  699. $controller = new Controller();
  700. $controller->helpers = ['Fail', 'Boom'];
  701. $controller->getEventManager()->on(
  702. 'Controller.beforeRender',
  703. function (Event $event) {
  704. $this->called = true;
  705. $event->getSubject()->viewBuilder()->setLayoutPath('boom');
  706. }
  707. );
  708. $controller->setRequest(new ServerRequest);
  709. $ExceptionRenderer->setController($controller);
  710. $response = $ExceptionRenderer->render();
  711. $this->assertEquals('text/html', $response->getType());
  712. $this->assertContains('Not Found', (string)$response->getBody());
  713. $this->assertTrue($this->called, 'Listener added was not triggered.');
  714. $this->assertEquals('', $controller->viewBuilder()->getLayoutPath());
  715. $this->assertEquals('Error', $controller->viewBuilder()->getTemplatePath());
  716. }
  717. /**
  718. * Test that missing plugin disables Controller::$plugin if the two are the same plugin.
  719. *
  720. * @return void
  721. */
  722. public function testMissingPluginRenderSafe()
  723. {
  724. $exception = new NotFoundException();
  725. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  726. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  727. ->setMethods(['render'])
  728. ->getMock();
  729. $controller->setPlugin('TestPlugin');
  730. $controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  731. $exception = new MissingPluginException(['plugin' => 'TestPlugin']);
  732. $controller->expects($this->once())
  733. ->method('render')
  734. ->with('error400')
  735. ->will($this->throwException($exception));
  736. $ExceptionRenderer->setController($controller);
  737. $response = $ExceptionRenderer->render();
  738. $body = (string)$response->getBody();
  739. $this->assertNotContains('test plugin error500', $body);
  740. $this->assertContains('Not Found', $body);
  741. }
  742. /**
  743. * Test that missing plugin doesn't disable Controller::$plugin if the two aren't the same plugin.
  744. *
  745. * @return void
  746. */
  747. public function testMissingPluginRenderSafeWithPlugin()
  748. {
  749. $this->loadPlugins(['TestPlugin']);
  750. $exception = new NotFoundException();
  751. $ExceptionRenderer = new MyCustomExceptionRenderer($exception);
  752. $controller = $this->getMockBuilder('Cake\Controller\Controller')
  753. ->setMethods(['render'])
  754. ->getMock();
  755. $controller->setPlugin('TestPlugin');
  756. $controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  757. $exception = new MissingPluginException(['plugin' => 'TestPluginTwo']);
  758. $controller->expects($this->once())
  759. ->method('render')
  760. ->with('error400')
  761. ->will($this->throwException($exception));
  762. $ExceptionRenderer->setController($controller);
  763. $response = $ExceptionRenderer->render();
  764. $body = (string)$response->getBody();
  765. $this->assertContains('test plugin error500', $body);
  766. $this->assertContains('Not Found', $body);
  767. Plugin::unload();
  768. }
  769. /**
  770. * Test that exceptions can be rendered when a request hasn't been registered
  771. * with Router
  772. *
  773. * @return void
  774. */
  775. public function testRenderWithNoRequest()
  776. {
  777. Router::reload();
  778. $this->assertNull(Router::getRequest(false));
  779. $exception = new Exception('Terrible');
  780. $ExceptionRenderer = new ExceptionRenderer($exception);
  781. $result = $ExceptionRenderer->render();
  782. $this->assertContains('Internal Error', (string)$result->getBody());
  783. $this->assertEquals(500, $result->getStatusCode());
  784. }
  785. /**
  786. * Test that rendering exceptions triggers shutdown events.
  787. *
  788. * @return void
  789. */
  790. public function testRenderShutdownEvents()
  791. {
  792. $fired = [];
  793. $listener = function (Event $event) use (&$fired) {
  794. $fired[] = $event->getName();
  795. };
  796. $events = EventManager::instance();
  797. $events->on('Controller.shutdown', $listener);
  798. $events->on('Dispatcher.afterDispatch', $listener);
  799. $exception = new Exception('Terrible');
  800. $renderer = new ExceptionRenderer($exception);
  801. $renderer->render();
  802. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  803. $this->assertEquals($expected, $fired);
  804. }
  805. /**
  806. * Test that rendering exceptions triggers events
  807. * on filters attached to dispatcherfactory
  808. *
  809. * @return void
  810. */
  811. public function testRenderShutdownEventsOnDispatcherFactory()
  812. {
  813. $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter')
  814. ->setMethods(['afterDispatch'])
  815. ->getMock();
  816. $filter->expects($this->at(0))
  817. ->method('afterDispatch');
  818. DispatcherFactory::add($filter);
  819. $exception = new Exception('Terrible');
  820. $renderer = new ExceptionRenderer($exception);
  821. $renderer->render();
  822. }
  823. /**
  824. * test that subclass methods fire shutdown events.
  825. *
  826. * @return void
  827. */
  828. public function testSubclassTriggerShutdownEvents()
  829. {
  830. $fired = [];
  831. $listener = function (Event $event) use (&$fired) {
  832. $fired[] = $event->getName();
  833. };
  834. $events = EventManager::instance();
  835. $events->on('Controller.shutdown', $listener);
  836. $events->on('Dispatcher.afterDispatch', $listener);
  837. $exception = new MissingWidgetThingException('Widget not found');
  838. $renderer = new MyCustomExceptionRenderer($exception);
  839. $renderer->render();
  840. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  841. $this->assertEquals($expected, $fired);
  842. }
  843. /**
  844. * Tests the output of rendering a PDOException
  845. *
  846. * @return void
  847. */
  848. public function testPDOException()
  849. {
  850. $exception = new \PDOException('There was an error in the SQL query');
  851. $exception->queryString = 'SELECT * from poo_query < 5 and :seven';
  852. $exception->params = ['seven' => 7];
  853. $ExceptionRenderer = new ExceptionRenderer($exception);
  854. $response = $ExceptionRenderer->render();
  855. $this->assertEquals(500, $response->getStatusCode());
  856. $result = (string)$response->getBody();
  857. $this->assertContains('Database Error', $result);
  858. $this->assertContains('There was an error in the SQL query', $result);
  859. $this->assertContains(h('SELECT * from poo_query < 5 and :seven'), $result);
  860. $this->assertContains("'seven' => (int) 7", $result);
  861. }
  862. }