ExceptionRendererTest.php 30 KB

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