ExceptionRendererTest.php 29 KB

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