ExceptionRendererTest.php 30 KB

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