diff options
author | Thomas Steur <thomas.steur@gmail.com> | 2015-08-19 11:12:43 +0300 |
---|---|---|
committer | Thomas Steur <thomas.steur@gmail.com> | 2015-08-19 13:56:26 +0300 |
commit | 763d19b594ff4e1aec4785e0816f7d57114c3a82 (patch) | |
tree | 9e2a4251c827fabd5b818a50d1eb6bbe07cf2516 /plugins/Monolog/tests | |
parent | de5f4f219a8eb2b6d23129bb2bf767581b5c3320 (diff) |
use monolog in tracker
Diffstat (limited to 'plugins/Monolog/tests')
9 files changed, 788 insertions, 0 deletions
diff --git a/plugins/Monolog/tests/Integration/Fixture/LoggerWrapper.php b/plugins/Monolog/tests/Integration/Fixture/LoggerWrapper.php new file mode 100644 index 0000000000..325fba6627 --- /dev/null +++ b/plugins/Monolog/tests/Integration/Fixture/LoggerWrapper.php @@ -0,0 +1,19 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Integration\Fixture; + +use Piwik\Log; + +class LoggerWrapper +{ + public static function doLog($message) + { + Log::warning($message); + } +} diff --git a/plugins/Monolog/tests/Integration/LogTest.php b/plugins/Monolog/tests/Integration/LogTest.php new file mode 100644 index 0000000000..97dc5e818f --- /dev/null +++ b/plugins/Monolog/tests/Integration/LogTest.php @@ -0,0 +1,267 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Integration; + +use Exception; +use Piwik\Application\Environment; +use Piwik\Common; +use Piwik\Config; +use Piwik\Container\StaticContainer; +use Piwik\Db; +use Piwik\Log; +use Piwik\Plugins\Monolog\tests\Integration\Fixture\LoggerWrapper; +use Piwik\Tests\Framework\TestCase\IntegrationTestCase; + +/** + * @group Core + * @group Log + */ +class LogTest extends IntegrationTestCase +{ + const TESTMESSAGE = 'test%smessage'; + const STRING_MESSAGE_FORMAT = '[%tag%] %message%'; + const STRING_MESSAGE_FORMAT_SPRINTF = "[%s] %s"; + + public static $expectedExceptionOutput = '[Monolog] LogTest.php(112): dummy error message + dummy backtrace'; + + public static $expectedErrorOutput = '[Monolog] dummyerrorfile.php(145): Unknown error (102) - dummy error string + dummy backtrace'; + + public function setUp() + { + parent::setUp(); + + Log::unsetInstance(); + + @unlink(self::getLogFileLocation()); + Log::$debugBacktraceForTests = "dummy backtrace"; + } + + public function tearDown() + { + Log::unsetInstance(); + + @unlink(self::getLogFileLocation()); + Log::$debugBacktraceForTests = null; + + parent::tearDown(); + } + + /** + * Data provider for every test. + */ + public function getBackendsToTest() + { + return array( + 'file' => array('file'), + 'database' => array('database'), + ); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsString($backend) + { + $this->recreateLogSingleton($backend); + + Log::warning(self::TESTMESSAGE); + + $this->checkBackend($backend, self::TESTMESSAGE, $formatMessage = true, $tag = 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsSprintfString($backend) + { + $this->recreateLogSingleton($backend); + + Log::warning(self::TESTMESSAGE, " subst "); + + $this->checkBackend($backend, sprintf(self::TESTMESSAGE, " subst "), $formatMessage = true, $tag = 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsError($backend) + { + $this->recreateLogSingleton($backend); + + $error = new \ErrorException("dummy error string", 0, 102, "dummyerrorfile.php", 145); + Log::error($error); + + $this->checkBackend($backend, self::$expectedErrorOutput, $formatMessage = false, $tag = 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingWorksWhenMessageIsException($backend) + { + $this->recreateLogSingleton($backend); + + $exception = new Exception("dummy error message"); + Log::error($exception); + + $this->checkBackend($backend, self::$expectedExceptionOutput, $formatMessage = false, $tag = 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingCorrectlyIdentifiesPlugin($backend) + { + $this->recreateLogSingleton($backend); + + LoggerWrapper::doLog(self::TESTMESSAGE); + + $this->checkBackend($backend, self::TESTMESSAGE, $formatMessage = true, 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLogMessagesIgnoredWhenNotWithinLevel($backend) + { + $this->recreateLogSingleton($backend, 'ERROR'); + + Log::info(self::TESTMESSAGE); + + $this->checkNoMessagesLogged($backend); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLogMessagesAreTrimmed($backend) + { + $this->recreateLogSingleton($backend); + + LoggerWrapper::doLog(" \n ".self::TESTMESSAGE."\n\n\n \n"); + + $this->checkBackend($backend, self::TESTMESSAGE, $formatMessage = true, 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testTokenAuthIsRemoved($backend) + { + $this->recreateLogSingleton($backend); + + Log::error('token_auth=9b1cefc915ff6180071fb7dcd13ec5a4'); + + $this->checkBackend($backend, 'token_auth=removed', $formatMessage = true, $tag = 'Monolog'); + } + + /** + * The database logs requests at DEBUG level, so we check that there is no recursive + * loop (logger insert in databases, which logs the query, ...) + * @link https://github.com/piwik/piwik/issues/7017 + */ + public function testNoInfiniteLoopWhenLoggingToDatabase() + { + $this->recreateLogSingleton('database'); + + Log::info(self::TESTMESSAGE); + + $this->checkBackend('database', self::TESTMESSAGE, $formatMessage = true, $tag = 'Monolog'); + } + + /** + * @dataProvider getBackendsToTest + */ + public function testLoggingNonString($backend) + { + $this->recreateLogSingleton($backend); + + Log::warning(123); + + $this->checkBackend($backend, '123', $formatMessage = true, $tag = 'Monolog'); + } + + private function checkBackend($backend, $expectedMessage, $formatMessage = false, $tag = false) + { + if ($formatMessage) { + $expectedMessage = sprintf(self::STRING_MESSAGE_FORMAT_SPRINTF, $tag, $expectedMessage); + } + + if ($backend == 'file') { + $this->assertTrue(file_exists(self::getLogFileLocation())); + + $fileContents = file_get_contents(self::getLogFileLocation()); + $fileContents = $this->removePathsFromBacktrace($fileContents); + + $this->assertEquals($expectedMessage . "\n", $fileContents); + } else if ($backend == 'database') { + $queryLog = Db::isQueryLogEnabled(); + Db::enableQueryLog(false); + + $count = Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('logger_message')); + $this->assertEquals(1, $count); + + $message = Db::fetchOne("SELECT message FROM " . Common::prefixTable('logger_message') . " LIMIT 1"); + $message = $this->removePathsFromBacktrace($message); + $this->assertEquals($expectedMessage, $message); + + $tagInDb = Db::fetchOne("SELECT tag FROM " . Common::prefixTable('logger_message') . " LIMIT 1"); + if ($tag === false) { + $this->assertEmpty($tagInDb); + } else { + $this->assertEquals($tag, $tagInDb); + } + + Db::enableQueryLog($queryLog); + } + } + + private function checkNoMessagesLogged($backend) + { + if ($backend == 'file') { + $this->assertFalse(file_exists(self::getLogFileLocation())); + } else if ($backend == 'database') { + $this->assertEquals(0, Db::fetchOne("SELECT COUNT(*) FROM " . Common::prefixTable('logger_message'))); + } + } + + private function removePathsFromBacktrace($content) + { + return preg_replace_callback("/(?:\/[^\s(<>]+)*\//", function ($matches) { + if ($matches[0] == '/') { + return '/'; + } else { + return ''; + } + }, $content); + } + + public static function getLogFileLocation() + { + return StaticContainer::get('path.tmp') . '/logs/piwik.test.log'; + } + + private function recreateLogSingleton($backend, $level = 'INFO') + { + $newEnv = new Environment('test', array( + 'ini.log.log_writers' => array($backend), + 'ini.log.log_level' => $level, + 'ini.log.string_message_format' => self::STRING_MESSAGE_FORMAT, + 'ini.log.logger_file_path' => self::getLogFileLocation(), + 'Psr\Log\LoggerInterface' => \DI\get('Monolog\Logger') + )); + $newEnv->init(); + + $newMonologLogger = $newEnv->getContainer()->make('Psr\Log\LoggerInterface'); + $oldLogger = new Log($newMonologLogger); + Log::setSingletonInstance($oldLogger); + } +} diff --git a/plugins/Monolog/tests/System/TrackerLoggingTest.php b/plugins/Monolog/tests/System/TrackerLoggingTest.php new file mode 100644 index 0000000000..efbd7b838f --- /dev/null +++ b/plugins/Monolog/tests/System/TrackerLoggingTest.php @@ -0,0 +1,107 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\System; + +use Piwik\Config; +use Piwik\Date; +use Piwik\Tests\Framework\Fixture; +use Piwik\Tests\Framework\TestCase\SystemTestCase; +use PiwikTracker; + +/** + * @group Monolog + * @group TrackerLoggingTest + * @group Plugins + */ +class TrackerLoggingTest extends SystemTestCase +{ + private $idSite = 1; + + public function setUp() + { + parent::setUp(); + + $testingEnvironment = self::$fixture->getTestEnvironment(); + $configOverride = $testingEnvironment->configOverride; + $configOverride['Tracker']['debug'] = 1; + $configOverride['log']['log_writers'] = array('screen'); + $testingEnvironment->configOverride = $configOverride; + $testingEnvironment->save(); + + if (!Fixture::siteCreated($this->idSite)) { + Fixture::createWebsite('2014-01-01 00:00:00'); + } + } + + public function test_shouldReturnDebugOutput_IfDebugIsEnabled() + { + $this->setTrackerConfig(array('debug' => '1')); + + $tracker = $this->buildTracker(); + $this->assertTrackerResponseContainsLogOutput($tracker); + } + + public function test_shouldReturnDebugOutput_IfDebugOnDemandIsEnabled() + { + $this->setTrackerConfig(array('debug_on_demand' => '1', 'debug' => 0)); + + $tracker = $this->buildTracker(); + $tracker->setDebugStringAppend('debug=1'); + $this->assertTrackerResponseContainsLogOutput($tracker); + } + + public function test_shouldNotReturnDebugOutput_IfDebugOnDemandIsDisabled() + { + $this->setTrackerConfig(array('debug_on_demand' => '0', 'debug' => 0)); + + $tracker = $this->buildTracker(); + $tracker->setDebugStringAppend('debug=1'); + + Fixture::checkResponse($tracker->doTrackPageView('incredible title!')); + } + + private function buildTracker() + { + $t = Fixture::getTracker($this->idSite, Date::factory('2014-01-05 00:01:01')->getDatetime()); + $t->setDebugStringAppend('debug=1'); + $t->setTokenAuth(Fixture::getTokenAuth()); + $t->setUrl('http://example.org/index1.htm'); + + return $t; + } + + private function assertTrackerResponseContainsLogOutput(PiwikTracker $t) + { + $response = $t->doTrackPageView('incredible title!'); + + $this->assertStringStartsWith("DEBUG: Debug enabled - Input parameters: +DEBUG: array ( +DEBUG: 'idsite' => '1', +DEBUG: 'rec' => '1', +DEBUG: 'apiv' => '1',", $response); + } + + private function setTrackerConfig($trackerConfig) + { + $testingEnvironment = self::$fixture->getTestEnvironment(); + $configOverride = $testingEnvironment->configOverride; + $configOverride['Tracker'] = $trackerConfig; + $configOverride['log']['log_writers'] = array('screen'); + $testingEnvironment->configOverride = $configOverride; + $testingEnvironment->save(); + } + + public static function provideContainerConfigBeforeClass() + { + return array( + 'Psr\Log\LoggerInterface' => \DI\get('Monolog\Logger') + ); + } + +}
\ No newline at end of file diff --git a/plugins/Monolog/tests/Unit/Formatter/LineMessageFormatterTest.php b/plugins/Monolog/tests/Unit/Formatter/LineMessageFormatterTest.php new file mode 100644 index 0000000000..eac798e9c7 --- /dev/null +++ b/plugins/Monolog/tests/Unit/Formatter/LineMessageFormatterTest.php @@ -0,0 +1,84 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Formatter; + +use DateTime; +use Piwik\Plugins\Monolog\Formatter\LineMessageFormatter; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Formatter\LineMessageFormatter + */ +class LineMessageFormatterTest extends \PHPUnit_Framework_TestCase +{ + /** + * @test + */ + public function it_should_format_with_placeholders() + { + $formatter = new LineMessageFormatter('%level% %tag% %datetime% %message%'); + + $record = array( + 'message' => 'Hello world', + 'datetime' => DateTime::createFromFormat('U', 0), + 'level_name' => 'ERROR', + 'extra' => array( + 'class' => 'Foo' + ), + ); + + $formatted = "ERROR Foo 1970-01-01 00:00:00 Hello world\n"; + + $this->assertEquals($formatted, $formatter->format($record)); + } + + /** + * @test + */ + public function it_should_insert_request_id_if_defined() + { + $formatter = new LineMessageFormatter('%message%'); + + $record = array( + 'message' => 'Hello world', + 'datetime' => DateTime::createFromFormat('U', 0), + 'level_name' => 'ERROR', + 'extra' => array( + 'request_id' => 'request id' + ), + ); + + $formatted = "[request id] Hello world\n"; + + $this->assertEquals($formatted, $formatter->format($record)); + } + + /** + * @test + */ + public function it_should_indent_multiline_message() + { + $formatter = new LineMessageFormatter('%message%'); + + $record = array( + 'message' => "Hello world\ntest\ntest", + 'datetime' => DateTime::createFromFormat('U', 0), + 'level_name' => 'ERROR', + ); + + $formatted = <<<LOG +Hello world + test + test + +LOG; + + $this->assertEquals($formatted, $formatter->format($record)); + } +} diff --git a/plugins/Monolog/tests/Unit/Processor/ClassNameProcessorTest.php b/plugins/Monolog/tests/Unit/Processor/ClassNameProcessorTest.php new file mode 100644 index 0000000000..158aba272f --- /dev/null +++ b/plugins/Monolog/tests/Unit/Processor/ClassNameProcessorTest.php @@ -0,0 +1,41 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Processor; + +use Piwik\Plugins\Monolog\Processor\ClassNameProcessor; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Processor\ClassNameProcessor + */ +class ClassNameProcessorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @test + */ + public function it_should_append_classname_to_extra() + { + $processor = new ClassNameProcessor(); + + $result = $processor(array( + 'extra' => array( + 'foo' => 'bar', + ), + )); + + $expected = array( + 'extra' => array( + 'foo' => 'bar', + 'class' => 'Monolog', + ), + ); + + $this->assertEquals($expected, $result); + } +} diff --git a/plugins/Monolog/tests/Unit/Processor/ExceptionToTextProcessorTest.php b/plugins/Monolog/tests/Unit/Processor/ExceptionToTextProcessorTest.php new file mode 100644 index 0000000000..35c85ee17f --- /dev/null +++ b/plugins/Monolog/tests/Unit/Processor/ExceptionToTextProcessorTest.php @@ -0,0 +1,85 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Processor; + +use Piwik\Log; +use Piwik\Plugins\Monolog\Processor\ExceptionToTextProcessor; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Processor\ExceptionToTextProcessor + */ +class ExceptionToTextProcessorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @test + */ + public function it_should_skip_if_no_exception() + { + $processor = new ExceptionToTextProcessor(); + + $record = array('message' => 'Hello world'); + + $this->assertEquals($record, $processor($record)); + } + + /** + * @test + */ + public function it_should_replace_message_with_formatted_exception() + { + $processor = new ExceptionToTextProcessor(); + Log::$debugBacktraceForTests = '[stack trace]'; + + $exception = new \Exception('Hello world'); + $record = array( + 'context' => array( + 'exception' => $exception, + ), + ); + + $result = $processor($record); + + $expected = array( + 'message' => __FILE__ . "(40): Hello world\n[stack trace]", + 'context' => array( + 'exception' => $exception, + ), + ); + + $this->assertEquals($expected, $result); + } + + /** + * @test + */ + public function it_should_add_severity_for_errors() + { + $processor = new ExceptionToTextProcessor(); + Log::$debugBacktraceForTests = '[stack trace]'; + + $exception = new \ErrorException('Hello world', 0, 1, 'file.php', 123); + $record = array( + 'context' => array( + 'exception' => $exception, + ), + ); + + $result = $processor($record); + + $expected = array( + 'message' => "file.php(123): Error - Hello world\n[stack trace]", + 'context' => array( + 'exception' => $exception, + ), + ); + + $this->assertEquals($expected, $result); + } +} diff --git a/plugins/Monolog/tests/Unit/Processor/RequestIdProcessorTest.php b/plugins/Monolog/tests/Unit/Processor/RequestIdProcessorTest.php new file mode 100644 index 0000000000..8902103ed8 --- /dev/null +++ b/plugins/Monolog/tests/Unit/Processor/RequestIdProcessorTest.php @@ -0,0 +1,62 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Processor; + +use PHPUnit_Framework_TestCase; +use Piwik\Common; +use Piwik\Plugins\Monolog\Processor\RequestIdProcessor; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Processor\RequestIdProcessor + */ +class RequestIdProcessorTest extends \PHPUnit_Framework_TestCase +{ + public function setUp() + { + parent::setUp(); + Common::$isCliMode = false; + } + + public function tearDown() + { + parent::tearDown(); + Common::$isCliMode = true; + } + + /** + * @test + */ + public function it_should_append_request_id_to_extra() + { + $processor = new RequestIdProcessor(); + + $result = $processor(array()); + + $this->assertArrayHasKey('request_id', $result['extra']); + $this->assertInternalType('string', $result['extra']['request_id']); + $this->assertNotEmpty($result['extra']['request_id']); + } + + /** + * @test + */ + public function request_id_should_stay_the_same() + { + $processor = new RequestIdProcessor(); + + $result = $processor(array()); + $id1 = $result['extra']['request_id']; + + $result = $processor(array()); + $id2 = $result['extra']['request_id']; + + $this->assertEquals($id1, $id2); + } +} diff --git a/plugins/Monolog/tests/Unit/Processor/SprintfProcessorTest.php b/plugins/Monolog/tests/Unit/Processor/SprintfProcessorTest.php new file mode 100644 index 0000000000..53b6cb3910 --- /dev/null +++ b/plugins/Monolog/tests/Unit/Processor/SprintfProcessorTest.php @@ -0,0 +1,63 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Processor; + +use Piwik\Plugins\Monolog\Processor\SprintfProcessor; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Processor\SprintfProcessor + */ +class SprintfProcessorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @test + */ + public function it_should_replace_placeholders() + { + $result = $this->process(array( + 'message' => 'Test %s and %s.', + 'context' => array('here', 'there'), + )); + + $this->assertEquals('Test here and there.', $result['message']); + } + + /** + * @test + */ + public function it_should_ignore_strings_without_placeholders() + { + $result = $this->process(array( + 'message' => 'Hello world!', + 'context' => array('foo', 'bar'), + )); + + $this->assertEquals('Hello world!', $result['message']); + } + + /** + * @test + */ + public function it_should_serialize_arrays() + { + $result = $this->process(array( + 'message' => 'Error in the following modules: %s', + 'context' => array(array('import', 'export')), + )); + + $this->assertEquals('Error in the following modules: ["import","export"]', $result['message']); + } + + private function process($record) + { + $processor = new SprintfProcessor(); + return $processor($record); + } +} diff --git a/plugins/Monolog/tests/Unit/Processor/TokenProcessorTest.php b/plugins/Monolog/tests/Unit/Processor/TokenProcessorTest.php new file mode 100644 index 0000000000..c3fc419854 --- /dev/null +++ b/plugins/Monolog/tests/Unit/Processor/TokenProcessorTest.php @@ -0,0 +1,60 @@ +<?php +/** + * Piwik - free/libre analytics platform + * + * @link http://piwik.org + * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later + */ + +namespace Piwik\Plugins\Monolog\tests\Unit\Processor; + +use Piwik\Plugins\Monolog\Processor\TokenProcessor; + +/** + * @group Log + * @covers \Piwik\Plugins\Monolog\Processor\TokenProcessor + */ +class TokenProcessorTest extends \PHPUnit_Framework_TestCase +{ + /** + * @test + */ + public function it_should_remove_token() + { + $result = $this->process(array( + 'message' => '&token_auth=9b1cefc915ff6180071fb7dcd13ec5a4&trigger=archivephp', + )); + + $this->assertEquals('&token_auth=removed&trigger=archivephp', $result['message']); + } + + /** + * @test + */ + public function it_should_remove_multiple_tokens() + { + $result = $this->process(array( + 'message' => 'First token_auth=9b1cefc915ff6180071fb7dcd13ec5a4 and second token_auth=abec834efc915ff61801fb7dcd13ec', + )); + + $this->assertEquals('First token_auth=removed and second token_auth=removed', $result['message']); + } + + /** + * @test + */ + public function it_should_not_affect_other_strings() + { + $result = $this->process(array( + 'message' => 'Please check your token_auth.', + )); + + $this->assertEquals('Please check your token_auth.', $result['message']); + } + + private function process($record) + { + $processor = new TokenProcessor(); + return $processor($record); + } +} |