ExceptionRendererTest.php 28 KB

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