ExceptionRendererTest.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  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\Http\ServerRequest;
  30. use Cake\Mailer\Exception\MissingActionException as MissingMailerActionException;
  31. use Cake\Network\Exception\InternalErrorException;
  32. use Cake\Network\Exception\MethodNotAllowedException;
  33. use Cake\Network\Exception\NotFoundException;
  34. use Cake\Network\Exception\SocketException;
  35. use Cake\ORM\Exception\MissingBehaviorException;
  36. use Cake\Routing\DispatcherFactory;
  37. use Cake\Routing\Exception\MissingControllerException;
  38. use Cake\Routing\Router;
  39. use Cake\TestSuite\TestCase;
  40. use Cake\View\Exception\MissingHelperException;
  41. use Cake\View\Exception\MissingLayoutException;
  42. use Cake\View\Exception\MissingTemplateException;
  43. use Exception;
  44. use RuntimeException;
  45. /**
  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 ServerRequest();
  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\Http\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\Http\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\Http\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\Http\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\Http\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 ServerRequest('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\Http\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. * testerror400 method when returning as json
  362. *
  363. * @return void
  364. */
  365. public function testError400AsJson()
  366. {
  367. Router::reload();
  368. $request = new ServerRequest('posts/view/1000?sort=title&direction=desc');
  369. $request = $request->withHeader('Accept', 'application/json');
  370. $request = $request->withHeader('Content-Type', 'application/json');
  371. Router::setRequestInfo($request);
  372. $exception = new NotFoundException('Custom message');
  373. $exceptionLine = __LINE__ - 1;
  374. $ExceptionRenderer = new ExceptionRenderer($exception);
  375. $ExceptionRenderer->controller->response = $this->getMockBuilder('Cake\Network\Response')
  376. ->setMethods(['statusCode', '_sendHeader'])
  377. ->getMock();
  378. $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(404);
  379. $result = $ExceptionRenderer->render()->body();
  380. $expected = [
  381. 'message' => 'Custom message',
  382. 'url' => '/posts/view/1000?sort=title&amp;direction=desc',
  383. 'code' => 404,
  384. 'file' => __FILE__,
  385. 'line' => $exceptionLine
  386. ];
  387. $this->assertEquals($expected, json_decode($result, true));
  388. }
  389. /**
  390. * test that error400 only modifies the messages on Cake Exceptions.
  391. *
  392. * @return void
  393. */
  394. public function testerror400OnlyChangingCakeException()
  395. {
  396. Configure::write('debug', false);
  397. $exception = new NotFoundException('Custom message');
  398. $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception));
  399. $result = $ExceptionRenderer->render();
  400. $this->assertContains('Custom message', $result->body());
  401. $exception = new MissingActionException(['controller' => 'PostsController', 'action' => 'index']);
  402. $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception));
  403. $result = $ExceptionRenderer->render();
  404. $this->assertContains('Not Found', $result->body());
  405. }
  406. /**
  407. * test that error400 doesn't expose XSS
  408. *
  409. * @return void
  410. */
  411. public function testError400NoInjection()
  412. {
  413. Router::reload();
  414. $request = new ServerRequest('pages/<span id=333>pink</span></id><script>document.body.style.background = t=document.getElementById(333).innerHTML;window.alert(t);</script>');
  415. Router::setRequestInfo($request);
  416. $exception = new NotFoundException('Custom message');
  417. $ExceptionRenderer = $this->_mockResponse(new ExceptionRenderer($exception));
  418. $result = $ExceptionRenderer->render()->body();
  419. $this->assertNotContains('<script>document', $result);
  420. $this->assertNotContains('alert(t);</script>', $result);
  421. }
  422. /**
  423. * testError500 method
  424. *
  425. * @return void
  426. */
  427. public function testError500Message()
  428. {
  429. $exception = new InternalErrorException('An Internal Error Has Occurred.');
  430. $ExceptionRenderer = new ExceptionRenderer($exception);
  431. $ExceptionRenderer->controller->response = $this->getMockBuilder('Cake\Http\Response')
  432. ->setMethods(['statusCode', '_sendHeader'])
  433. ->getMock();
  434. $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(500);
  435. $result = $ExceptionRenderer->render();
  436. $this->assertContains('<h2>An Internal Error Has Occurred.</h2>', $result->body());
  437. $this->assertContains('An Internal Error Has Occurred.</p>', $result->body());
  438. }
  439. /**
  440. * testExceptionResponseHeader method
  441. *
  442. * @return void
  443. */
  444. public function testExceptionResponseHeader()
  445. {
  446. $exception = new MethodNotAllowedException('Only allowing POST and DELETE');
  447. $exception->responseHeader(['Allow: POST, DELETE']);
  448. $ExceptionRenderer = new ExceptionRenderer($exception);
  449. $result = $ExceptionRenderer->render();
  450. $headers = $result->header();
  451. $this->assertArrayHasKey('Allow', $headers);
  452. $this->assertEquals('POST, DELETE', $headers['Allow']);
  453. }
  454. /**
  455. * testMissingController method
  456. *
  457. * @return void
  458. */
  459. public function testMissingController()
  460. {
  461. $exception = new MissingControllerException([
  462. 'class' => 'Posts',
  463. 'prefix' => '',
  464. 'plugin' => '',
  465. ]);
  466. $ExceptionRenderer = $this->_mockResponse(new MyCustomExceptionRenderer($exception));
  467. $result = $ExceptionRenderer->render()->body();
  468. $this->assertEquals('missingController', $ExceptionRenderer->template);
  469. $this->assertContains('Missing Controller', $result);
  470. $this->assertContains('<em>PostsController</em>', $result);
  471. }
  472. /**
  473. * Returns an array of tests to run for the various Cake Exception classes.
  474. *
  475. * @return array
  476. */
  477. public static function exceptionProvider()
  478. {
  479. return [
  480. [
  481. new MissingActionException([
  482. 'controller' => 'PostsController',
  483. 'action' => 'index',
  484. 'prefix' => '',
  485. 'plugin' => '',
  486. ]),
  487. [
  488. '/Missing Method in PostsController/',
  489. '/<em>PostsController::index\(\)<\/em>/'
  490. ],
  491. 404
  492. ],
  493. [
  494. new MissingTemplateException(['file' => '/posts/about.ctp']),
  495. [
  496. "/posts\/about.ctp/"
  497. ],
  498. 500
  499. ],
  500. [
  501. new MissingLayoutException(['file' => 'layouts/my_layout.ctp']),
  502. [
  503. "/Missing Layout/",
  504. "/layouts\/my_layout.ctp/"
  505. ],
  506. 500
  507. ],
  508. [
  509. new MissingHelperException(['class' => 'MyCustomHelper']),
  510. [
  511. '/Missing Helper/',
  512. '/<em>MyCustomHelper<\/em> could not be found./',
  513. '/Create the class <em>MyCustomHelper<\/em> below in file:/',
  514. '/(\/|\\\)MyCustomHelper.php/'
  515. ],
  516. 500
  517. ],
  518. [
  519. new MissingBehaviorException(['class' => 'MyCustomBehavior']),
  520. [
  521. '/Missing Behavior/',
  522. '/Create the class <em>MyCustomBehavior<\/em> below in file:/',
  523. '/(\/|\\\)MyCustomBehavior.php/'
  524. ],
  525. 500
  526. ],
  527. [
  528. new MissingComponentException(['class' => 'SideboxComponent']),
  529. [
  530. '/Missing Component/',
  531. '/Create the class <em>SideboxComponent<\/em> below in file:/',
  532. '/(\/|\\\)SideboxComponent.php/'
  533. ],
  534. 500
  535. ],
  536. [
  537. new MissingDatasourceConfigException(['name' => 'MyDatasourceConfig']),
  538. [
  539. '/Missing Datasource Configuration/',
  540. '/<em>MyDatasourceConfig<\/em> was not found/'
  541. ],
  542. 500
  543. ],
  544. [
  545. new MissingDatasourceException(['class' => 'MyDatasource', 'plugin' => 'MyPlugin']),
  546. [
  547. '/Missing Datasource/',
  548. '/<em>MyPlugin.MyDatasource<\/em> could not be found./'
  549. ],
  550. 500
  551. ],
  552. [
  553. new MissingMailerActionException([
  554. 'mailer' => 'UserMailer',
  555. 'action' => 'welcome',
  556. 'prefix' => '',
  557. 'plugin' => '',
  558. ]),
  559. [
  560. '/Missing Method in UserMailer/',
  561. '/<em>UserMailer::welcome\(\)<\/em>/'
  562. ],
  563. 404
  564. ],
  565. [
  566. new Exception('boom'),
  567. [
  568. '/Internal Error/'
  569. ],
  570. 500
  571. ],
  572. [
  573. new RuntimeException('another boom'),
  574. [
  575. '/Internal Error/'
  576. ],
  577. 500
  578. ],
  579. [
  580. new CakeException('base class'),
  581. ['/Internal Error/'],
  582. 500
  583. ]
  584. ];
  585. }
  586. /**
  587. * Test the various Cake Exception sub classes
  588. *
  589. * @dataProvider exceptionProvider
  590. * @return void
  591. */
  592. public function testCakeExceptionHandling($exception, $patterns, $code)
  593. {
  594. $ExceptionRenderer = new ExceptionRenderer($exception);
  595. $ExceptionRenderer->controller->response = $this->getMockBuilder('Cake\Http\Response')
  596. ->setMethods(['statusCode', '_sendHeader'])
  597. ->getMock();
  598. $ExceptionRenderer->controller->response->expects($this->once())
  599. ->method('statusCode')
  600. ->with($code);
  601. $result = $ExceptionRenderer->render()->body();
  602. foreach ($patterns as $pattern) {
  603. $this->assertRegExp($pattern, $result);
  604. }
  605. }
  606. /**
  607. * Test that class names not ending in Exception are not mangled.
  608. *
  609. * @return void
  610. */
  611. public function testExceptionNameMangling()
  612. {
  613. $exceptionRenderer = new MyCustomExceptionRenderer(new MissingWidgetThing());
  614. $result = $exceptionRenderer->render()->body();
  615. $this->assertContains('widget thing is missing', $result);
  616. }
  617. /**
  618. * Test exceptions being raised when helpers are missing.
  619. *
  620. * @return void
  621. */
  622. public function testMissingRenderSafe()
  623. {
  624. $exception = new MissingHelperException(['class' => 'Fail']);
  625. $ExceptionRenderer = new ExceptionRenderer($exception);
  626. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  627. ->setMethods(['render'])
  628. ->getMock();
  629. $ExceptionRenderer->controller->helpers = ['Fail', 'Boom'];
  630. $ExceptionRenderer->controller->request = new ServerRequest;
  631. $ExceptionRenderer->controller->expects($this->at(0))
  632. ->method('render')
  633. ->with('missingHelper')
  634. ->will($this->throwException($exception));
  635. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  636. $response->expects($this->once())
  637. ->method('body')
  638. ->with($this->stringContains('Helper class Fail'));
  639. $ExceptionRenderer->controller->response = $response;
  640. $ExceptionRenderer->render();
  641. sort($ExceptionRenderer->controller->helpers);
  642. $this->assertEquals(['Form', 'Html'], $ExceptionRenderer->controller->helpers);
  643. }
  644. /**
  645. * Test that exceptions in beforeRender() are handled by outputMessageSafe
  646. *
  647. * @return void
  648. */
  649. public function testRenderExceptionInBeforeRender()
  650. {
  651. $exception = new NotFoundException('Not there, sorry');
  652. $ExceptionRenderer = new ExceptionRenderer($exception);
  653. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  654. ->setMethods(['beforeRender'])
  655. ->getMock();
  656. $ExceptionRenderer->controller->request = new ServerRequest;
  657. $ExceptionRenderer->controller->expects($this->any())
  658. ->method('beforeRender')
  659. ->will($this->throwException($exception));
  660. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  661. $response->expects($this->once())
  662. ->method('body')
  663. ->with($this->stringContains('Not there, sorry'));
  664. $ExceptionRenderer->controller->response = $response;
  665. $ExceptionRenderer->render();
  666. }
  667. /**
  668. * Test that missing layoutPath don't cause other fatal errors.
  669. *
  670. * @return void
  671. */
  672. public function testMissingLayoutPathRenderSafe()
  673. {
  674. $this->called = false;
  675. $exception = new NotFoundException();
  676. $ExceptionRenderer = new ExceptionRenderer($exception);
  677. $ExceptionRenderer->controller = new Controller();
  678. $ExceptionRenderer->controller->helpers = ['Fail', 'Boom'];
  679. $ExceptionRenderer->controller->eventManager()->on(
  680. 'Controller.beforeRender',
  681. function (Event $event) {
  682. $this->called = true;
  683. $event->subject()->viewBuilder()->setLayoutPath('boom');
  684. }
  685. );
  686. $ExceptionRenderer->controller->request = new ServerRequest;
  687. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  688. $response->expects($this->once())
  689. ->method('body')
  690. ->with($this->stringContains('Not Found'));
  691. $response->expects($this->once())
  692. ->method('type')
  693. ->with('html');
  694. $ExceptionRenderer->controller->response = $response;
  695. $ExceptionRenderer->render();
  696. $this->assertTrue($this->called, 'Listener added was not triggered.');
  697. $this->assertEquals('', $ExceptionRenderer->controller->viewBuilder()->layoutPath());
  698. $this->assertEquals('Error', $ExceptionRenderer->controller->viewBuilder()->templatePath());
  699. }
  700. /**
  701. * Test that missing plugin disables Controller::$plugin if the two are the same plugin.
  702. *
  703. * @return void
  704. */
  705. public function testMissingPluginRenderSafe()
  706. {
  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\Http\ServerRequest')->getMock();
  714. $exception = new MissingPluginException(['plugin' => 'TestPlugin']);
  715. $ExceptionRenderer->controller->expects($this->once())
  716. ->method('render')
  717. ->with('error400')
  718. ->will($this->throwException($exception));
  719. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  720. $response->expects($this->once())
  721. ->method('body')
  722. ->with($this->logicalAnd(
  723. $this->logicalNot($this->stringContains('test plugin error500')),
  724. $this->stringContains('Not Found')
  725. ));
  726. $ExceptionRenderer->controller->response = $response;
  727. $ExceptionRenderer->render();
  728. }
  729. /**
  730. * Test that missing plugin doesn't disable Controller::$plugin if the two aren't the same plugin.
  731. *
  732. * @return void
  733. */
  734. public function testMissingPluginRenderSafeWithPlugin()
  735. {
  736. Plugin::load('TestPlugin');
  737. $exception = new NotFoundException();
  738. $ExceptionRenderer = new ExceptionRenderer($exception);
  739. $ExceptionRenderer->controller = $this->getMockBuilder('Cake\Controller\Controller')
  740. ->setMethods(['render'])
  741. ->getMock();
  742. $ExceptionRenderer->controller->plugin = 'TestPlugin';
  743. $ExceptionRenderer->controller->request = $this->getMockBuilder('Cake\Http\ServerRequest')->getMock();
  744. $exception = new MissingPluginException(['plugin' => 'TestPluginTwo']);
  745. $ExceptionRenderer->controller->expects($this->once())
  746. ->method('render')
  747. ->with('error400')
  748. ->will($this->throwException($exception));
  749. $response = $this->getMockBuilder('Cake\Http\Response')->getMock();
  750. $response->expects($this->once())
  751. ->method('body')
  752. ->with($this->logicalAnd(
  753. $this->stringContains('test plugin error500'),
  754. $this->stringContains('Not Found')
  755. ));
  756. $ExceptionRenderer->controller->response = $response;
  757. $ExceptionRenderer->render();
  758. Plugin::unload();
  759. }
  760. /**
  761. * Test that exceptions can be rendered when a request hasn't been registered
  762. * with Router
  763. *
  764. * @return void
  765. */
  766. public function testRenderWithNoRequest()
  767. {
  768. Router::reload();
  769. $this->assertNull(Router::getRequest(false));
  770. $exception = new Exception('Terrible');
  771. $ExceptionRenderer = new ExceptionRenderer($exception);
  772. $result = $ExceptionRenderer->render();
  773. $this->assertContains('Internal Error', $result->body());
  774. $this->assertEquals(500, $result->statusCode());
  775. }
  776. /**
  777. * Test that rendering exceptions triggers shutdown events.
  778. *
  779. * @return void
  780. */
  781. public function testRenderShutdownEvents()
  782. {
  783. $fired = [];
  784. $listener = function (Event $event) use (&$fired) {
  785. $fired[] = $event->name();
  786. };
  787. $events = EventManager::instance();
  788. $events->attach($listener, 'Controller.shutdown');
  789. $events->attach($listener, 'Dispatcher.afterDispatch');
  790. $exception = new Exception('Terrible');
  791. $renderer = new ExceptionRenderer($exception);
  792. $renderer->render();
  793. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  794. $this->assertEquals($expected, $fired);
  795. }
  796. /**
  797. * Test that rendering exceptions triggers events
  798. * on filters attached to dispatcherfactory
  799. *
  800. * @return void
  801. */
  802. public function testRenderShutdownEventsOnDispatcherFactory()
  803. {
  804. $filter = $this->getMockBuilder('Cake\Routing\DispatcherFilter')
  805. ->setMethods(['afterDispatch'])
  806. ->getMock();
  807. $filter->expects($this->at(0))
  808. ->method('afterDispatch');
  809. DispatcherFactory::add($filter);
  810. $exception = new Exception('Terrible');
  811. $renderer = new ExceptionRenderer($exception);
  812. $renderer->render();
  813. }
  814. /**
  815. * test that subclass methods fire shutdown events.
  816. *
  817. * @return void
  818. */
  819. public function testSubclassTriggerShutdownEvents()
  820. {
  821. $fired = [];
  822. $listener = function (Event $event) use (&$fired) {
  823. $fired[] = $event->name();
  824. };
  825. $events = EventManager::instance();
  826. $events->attach($listener, 'Controller.shutdown');
  827. $events->attach($listener, 'Dispatcher.afterDispatch');
  828. $exception = new MissingWidgetThingException('Widget not found');
  829. $renderer = $this->_mockResponse(new MyCustomExceptionRenderer($exception));
  830. $renderer->render();
  831. $expected = ['Controller.shutdown', 'Dispatcher.afterDispatch'];
  832. $this->assertEquals($expected, $fired);
  833. }
  834. /**
  835. * Tests the output of rendering a PDOException
  836. *
  837. * @return void
  838. */
  839. public function testPDOException()
  840. {
  841. $exception = new \PDOException('There was an error in the SQL query');
  842. $exception->queryString = 'SELECT * from poo_query < 5 and :seven';
  843. $exception->params = ['seven' => 7];
  844. $ExceptionRenderer = new ExceptionRenderer($exception);
  845. $ExceptionRenderer->controller->response = $this->getMockBuilder('Cake\Http\Response')
  846. ->setMethods(['statusCode', '_sendHeader'])
  847. ->getMock();
  848. $ExceptionRenderer->controller->response->expects($this->once())->method('statusCode')->with(500);
  849. $result = $ExceptionRenderer->render()->body();
  850. $this->assertContains('Database Error', $result);
  851. $this->assertContains('There was an error in the SQL query', $result);
  852. $this->assertContains(h('SELECT * from poo_query < 5 and :seven'), $result);
  853. $this->assertContains("'seven' => (int) 7", $result);
  854. }
  855. }