| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481 |
- <?php
- declare(strict_types=1);
- /**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice
- *
- * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @link https://cakephp.org CakePHP(tm) Project
- * @since 1.2.0
- * @license https://opensource.org/licenses/mit-license.php MIT License
- */
- namespace Cake\Test\TestCase\Error;
- use Cake\Core\Configure;
- use Cake\Datasource\Exception\RecordNotFoundException;
- use Cake\Error\ErrorHandler;
- use Cake\Http\Exception\ForbiddenException;
- use Cake\Http\Exception\MissingControllerException;
- use Cake\Http\Exception\NotFoundException;
- use Cake\Http\ServerRequest;
- use Cake\Log\Log;
- use Cake\Routing\Router;
- use Cake\TestSuite\TestCase;
- use Psr\Log\LoggerInterface;
- use RuntimeException;
- use TestApp\Error\TestErrorHandler;
- /**
- * ErrorHandlerTest class
- */
- class ErrorHandlerTest extends TestCase
- {
- protected $_restoreError = false;
- /**
- * @var \Cake\Log\Engine\ArrayLog
- */
- protected $logger;
- /**
- * error level property
- */
- private static $errorLevel;
- /**
- * setup create a request object to get out of router later.
- *
- * @return void
- */
- public function setUp(): void
- {
- parent::setUp();
- Router::reload();
- $request = new ServerRequest([
- 'base' => '',
- 'environment' => [
- 'HTTP_REFERER' => '/referer',
- ],
- ]);
- Router::setRequest($request);
- Configure::write('debug', true);
- Log::reset();
- Log::setConfig('error_test', ['className' => 'Array']);
- $this->logger = Log::engine('error_test');
- }
- /**
- * tearDown
- *
- * @return void
- */
- public function tearDown(): void
- {
- parent::tearDown();
- Log::reset();
- $this->clearPlugins();
- if ($this->_restoreError) {
- restore_error_handler();
- restore_exception_handler();
- }
- error_reporting(self::$errorLevel);
- }
- /**
- * setUpBeforeClass
- *
- * @return void
- */
- public static function setUpBeforeClass(): void
- {
- parent::setUpBeforeClass();
- self::$errorLevel = error_reporting();
- }
- /**
- * Test an invalid rendering class.
- *
- * @return void
- */
- public function testInvalidRenderer()
- {
- $this->expectException(RuntimeException::class);
- $this->expectExceptionMessage('The \'TotallyInvalid\' renderer class could not be found');
- $errorHandler = new ErrorHandler(['exceptionRenderer' => 'TotallyInvalid']);
- $errorHandler->getRenderer(new \Exception('Something bad'));
- }
- /**
- * test error handling when debug is on, an error should be printed from Debugger.
- *
- * @return void
- */
- public function testHandleErrorDebugOn()
- {
- $errorHandler = new ErrorHandler();
- $errorHandler->register();
- $this->_restoreError = true;
- ob_start();
- $wrong = $wrong + 1;
- $result = ob_get_clean();
- $this->assertRegExp('/<pre class="cake-error">/', $result);
- $this->assertRegExp('/<b>Notice<\/b>/', $result);
- $this->assertRegExp('/variable:\s+wrong/', $result);
- }
- /**
- * provides errors for mapping tests.
- *
- * @return array
- */
- public static function errorProvider()
- {
- return [
- [E_USER_NOTICE, 'Notice'],
- [E_USER_WARNING, 'Warning'],
- ];
- }
- /**
- * test error mappings
- *
- * @dataProvider errorProvider
- * @return void
- */
- public function testErrorMapping($error, $expected)
- {
- $errorHandler = new ErrorHandler();
- $errorHandler->register();
- $this->_restoreError = true;
- ob_start();
- trigger_error('Test error', $error);
- $result = ob_get_clean();
- $this->assertStringContainsString('<b>' . $expected . '</b>', $result);
- }
- /**
- * test error prepended by @
- *
- * @return void
- */
- public function testErrorSuppressed()
- {
- $errorHandler = new ErrorHandler();
- $errorHandler->register();
- $this->_restoreError = true;
- ob_start();
- // phpcs:disable
- @include 'invalid.file';
- // phpcs:enable
- $result = ob_get_clean();
- $this->assertEmpty($result);
- }
- /**
- * Test that errors go into Cake Log when debug = 0.
- *
- * @return void
- */
- public function testHandleErrorDebugOff()
- {
- Configure::write('debug', false);
- $errorHandler = new ErrorHandler();
- $errorHandler->register();
- $this->_restoreError = true;
- $out = $out + 1;
- $messages = $this->logger->read();
- $this->assertRegExp('/^(notice|debug)/', $messages[0]);
- $this->assertStringContainsString(
- 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 5) . ']' . "\n\n",
- $messages[0]
- );
- }
- /**
- * Test that errors going into Cake Log include traces.
- *
- * @return void
- */
- public function testHandleErrorLoggingTrace()
- {
- Configure::write('debug', false);
- $errorHandler = new ErrorHandler(['trace' => true]);
- $errorHandler->register();
- $this->_restoreError = true;
- $out = $out + 1;
- $messages = $this->logger->read();
- $this->assertRegExp('/^(notice|debug)/', $messages[0]);
- $this->assertStringContainsString(
- 'Notice (8): Undefined variable: out in [' . __FILE__ . ', line ' . (__LINE__ - 5) . ']',
- $messages[0]
- );
- $this->assertStringContainsString('Trace:', $messages[0]);
- $this->assertStringContainsString(__NAMESPACE__ . '\ErrorHandlerTest::testHandleErrorLoggingTrace()', $messages[0]);
- $this->assertStringContainsString('Request URL:', $messages[0]);
- $this->assertStringContainsString('Referer URL:', $messages[0]);
- }
- /**
- * test handleException generating a page.
- *
- * @return void
- */
- public function testHandleException()
- {
- $error = new NotFoundException('Kaboom!');
- $errorHandler = new TestErrorHandler();
- $errorHandler->handleException($error);
- $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
- }
- /**
- * test handleException generating log.
- *
- * @return void
- */
- public function testHandleExceptionLog()
- {
- $errorHandler = new TestErrorHandler([
- 'log' => true,
- 'trace' => true,
- ]);
- $error = new NotFoundException('Kaboom!');
- $errorHandler->handleException($error);
- $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
- $messages = $this->logger->read();
- $this->assertRegExp('/^error/', $messages[0]);
- $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[0]);
- $this->assertStringContainsString(
- str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'),
- $messages[0]
- );
- $errorHandler = new TestErrorHandler([
- 'log' => true,
- 'trace' => false,
- ]);
- $errorHandler->handleException($error);
- $messages = $this->logger->read();
- $this->assertRegExp('/^error/', $messages[1]);
- $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[1]);
- $this->assertStringNotContainsString(
- str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'),
- $messages[1]
- );
- }
- /**
- * test logging attributes with/without debug
- *
- * @return void
- */
- public function testHandleExceptionLogAttributes()
- {
- $errorHandler = new TestErrorHandler([
- 'log' => true,
- 'trace' => true,
- ]);
- $error = new MissingControllerException(['class' => 'Derp']);
- $errorHandler->handleException($error);
- Configure::write('debug', false);
- $errorHandler->handleException($error);
- $messages = $this->logger->read();
- $this->assertRegExp('/^error/', $messages[0]);
- $this->assertStringContainsString(
- '[Cake\Http\Exception\MissingControllerException] Controller class Derp could not be found.',
- $messages[0]
- );
- $this->assertStringContainsString('Exception Attributes:', $messages[0]);
- $this->assertStringContainsString('Request URL:', $messages[0]);
- $this->assertStringContainsString('Referer URL:', $messages[0]);
- $this->assertStringContainsString(
- '[Cake\Http\Exception\MissingControllerException] Controller class Derp could not be found.',
- $messages[1]
- );
- $this->assertStringNotContainsString('Exception Attributes:', $messages[1]);
- }
- /**
- * test logging attributes with previous exception
- *
- * @return void
- */
- public function testHandleExceptionLogPrevious()
- {
- $errorHandler = new TestErrorHandler([
- 'log' => true,
- 'trace' => true,
- ]);
- $previous = new RecordNotFoundException('Previous logged');
- $error = new NotFoundException('Kaboom!', null, $previous);
- $errorHandler->handleException($error);
- $messages = $this->logger->read();
- $this->assertStringContainsString('[Cake\Http\Exception\NotFoundException] Kaboom!', $messages[0]);
- $this->assertStringContainsString(
- 'Caused by: [Cake\Datasource\Exception\RecordNotFoundException] Previous logged',
- $messages[0]
- );
- $this->assertStringContainsString(
- str_replace('/', DS, 'vendor/phpunit/phpunit/src/Framework/TestCase.php'),
- $messages[0]
- );
- }
- /**
- * test handleException generating log.
- *
- * @return void
- */
- public function testHandleExceptionLogSkipping()
- {
- $notFound = new NotFoundException('Kaboom!');
- $forbidden = new ForbiddenException('Fooled you!');
- $errorHandler = new TestErrorHandler([
- 'log' => true,
- 'skipLog' => ['Cake\Http\Exception\NotFoundException'],
- ]);
- $errorHandler->handleException($notFound);
- $this->assertStringContainsString('Kaboom!', (string)$errorHandler->response->getBody(), 'message missing.');
- $errorHandler->handleException($forbidden);
- $this->assertStringContainsString('Fooled you!', (string)$errorHandler->response->getBody(), 'message missing.');
- $messages = $this->logger->read();
- $this->assertCount(1, $messages);
- $this->assertRegExp('/^error/', $messages[0]);
- $this->assertStringContainsString(
- '[Cake\Http\Exception\ForbiddenException] Fooled you!',
- $messages[0]
- );
- }
- /**
- * tests it is possible to load a plugin exception renderer
- *
- * @return void
- */
- public function testLoadPluginHandler()
- {
- $this->loadPlugins(['TestPlugin']);
- $errorHandler = new TestErrorHandler([
- 'exceptionRenderer' => 'TestPlugin.TestPluginExceptionRenderer',
- ]);
- $error = new NotFoundException('Kaboom!');
- $errorHandler->handleException($error);
- $result = $errorHandler->response;
- $this->assertSame('Rendered by test plugin', (string)$result);
- }
- /**
- * test handleFatalError generating a page.
- *
- * These tests start two buffers as handleFatalError blows the outer one up.
- *
- * @return void
- */
- public function testHandleFatalErrorPage()
- {
- $line = __LINE__;
- $errorHandler = new TestErrorHandler();
- Configure::write('debug', true);
- $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
- $result = (string)$errorHandler->response->getBody();
- $this->assertStringContainsString('Something wrong', $result, 'message missing.');
- $this->assertStringContainsString(__FILE__, $result, 'filename missing.');
- $this->assertStringContainsString((string)$line, $result, 'line missing.');
- Configure::write('debug', false);
- $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, $line);
- $result = (string)$errorHandler->response->getBody();
- $this->assertStringNotContainsString('Something wrong', $result, 'message must not appear.');
- $this->assertStringNotContainsString(__FILE__, $result, 'filename must not appear.');
- $this->assertStringContainsString('An Internal Error Has Occurred.', $result);
- }
- /**
- * test handleFatalError generating log.
- *
- * @return void
- */
- public function testHandleFatalErrorLog()
- {
- $errorHandler = new TestErrorHandler(['log' => true]);
- $errorHandler->handleFatalError(E_ERROR, 'Something wrong', __FILE__, __LINE__);
- $messages = $this->logger->read();
- $this->assertCount(2, $messages);
- $this->assertStringContainsString(__FILE__ . ', line ' . (__LINE__ - 4), $messages[0]);
- $this->assertStringContainsString('Fatal Error (1)', $messages[0]);
- $this->assertStringContainsString('Something wrong', $messages[0]);
- $this->assertStringContainsString('[Cake\Error\FatalErrorException] Something wrong', $messages[1]);
- }
- /**
- * Data provider for memory limit changing.
- *
- * @return array
- */
- public function memoryLimitProvider()
- {
- return [
- // start, adjust, expected
- ['256M', 4, '262148K'],
- ['262144K', 4, '262148K'],
- ['1G', 128, '1048704K'],
- ];
- }
- /**
- * Test increasing the memory limit.
- *
- * @dataProvider memoryLimitProvider
- * @return void
- */
- public function testIncreaseMemoryLimit($start, $adjust, $expected)
- {
- $initial = ini_get('memory_limit');
- $this->skipIf(strlen($initial) === 0, 'Cannot read memory limit, and cannot test increasing it.');
- // phpunit.xml often has -1 as memory limit
- ini_set('memory_limit', $start);
- $errorHandler = new TestErrorHandler();
- $this->assertNull($errorHandler->increaseMemoryLimit($adjust));
- $new = ini_get('memory_limit');
- $this->assertEquals($expected, $new, 'memory limit did not get increased.');
- ini_set('memory_limit', $initial);
- }
- }
|