ExceptionRendererTest.php 31 KB

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