ExceptionRendererTest.php 28 KB

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