ExceptionRendererTest.php 28 KB

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