ExceptionRendererTest.php 30 KB

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