diff options
Diffstat (limited to 'tests/Monolog/Handler')
55 files changed, 1106 insertions, 868 deletions
diff --git a/tests/Monolog/Handler/AbstractHandlerTest.php b/tests/Monolog/Handler/AbstractHandlerTest.php index 568eb9d..b7451a7 100644 --- a/tests/Monolog/Handler/AbstractHandlerTest.php +++ b/tests/Monolog/Handler/AbstractHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,10 +11,8 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; -use Monolog\Formatter\LineFormatter; -use Monolog\Processor\WebProcessor; class AbstractHandlerTest extends TestCase { @@ -24,21 +22,17 @@ class AbstractHandlerTest extends TestCase * @covers Monolog\Handler\AbstractHandler::setLevel * @covers Monolog\Handler\AbstractHandler::getBubble * @covers Monolog\Handler\AbstractHandler::setBubble - * @covers Monolog\Handler\AbstractHandler::getFormatter - * @covers Monolog\Handler\AbstractHandler::setFormatter */ public function testConstructAndGetSet() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]); $this->assertEquals(Logger::WARNING, $handler->getLevel()); $this->assertEquals(false, $handler->getBubble()); $handler->setLevel(Logger::ERROR); $handler->setBubble(true); - $handler->setFormatter($formatter = new LineFormatter); $this->assertEquals(Logger::ERROR, $handler->getLevel()); $this->assertEquals(true, $handler->getBubble()); - $this->assertSame($formatter, $handler->getFormatter()); } /** @@ -49,7 +43,7 @@ class AbstractHandlerTest extends TestCase $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); $handler->expects($this->exactly(2)) ->method('handle'); - $handler->handleBatch(array($this->getRecord(), $this->getRecord())); + $handler->handleBatch([$this->getRecord(), $this->getRecord()]); } /** @@ -57,7 +51,7 @@ class AbstractHandlerTest extends TestCase */ public function testIsHandling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array(Logger::WARNING, false)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', [Logger::WARNING, false]); $this->assertTrue($handler->isHandling($this->getRecord())); $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); } @@ -67,49 +61,9 @@ class AbstractHandlerTest extends TestCase */ public function testHandlesPsrStyleLevels() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', array('warning', false)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler', ['warning', false]); $this->assertFalse($handler->isHandling($this->getRecord(Logger::DEBUG))); $handler->setLevel('debug'); $this->assertTrue($handler->isHandling($this->getRecord(Logger::DEBUG))); } - - /** - * @covers Monolog\Handler\AbstractHandler::getFormatter - * @covers Monolog\Handler\AbstractHandler::getDefaultFormatter - */ - public function testGetFormatterInitializesDefault() - { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); - $this->assertInstanceOf('Monolog\Formatter\LineFormatter', $handler->getFormatter()); - } - - /** - * @covers Monolog\Handler\AbstractHandler::pushProcessor - * @covers Monolog\Handler\AbstractHandler::popProcessor - * @expectedException LogicException - */ - public function testPushPopProcessor() - { - $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); - $processor1 = new WebProcessor; - $processor2 = new WebProcessor; - - $logger->pushProcessor($processor1); - $logger->pushProcessor($processor2); - - $this->assertEquals($processor2, $logger->popProcessor()); - $this->assertEquals($processor1, $logger->popProcessor()); - $logger->popProcessor(); - } - - /** - * @covers Monolog\Handler\AbstractHandler::pushProcessor - * @expectedException InvalidArgumentException - */ - public function testPushProcessorWithNonCallable() - { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractHandler'); - - $handler->pushProcessor(new \stdClass()); - } } diff --git a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php index 24d4f63..58d0920 100644 --- a/tests/Monolog/Handler/AbstractProcessingHandlerTest.php +++ b/tests/Monolog/Handler/AbstractProcessingHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,18 +11,30 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Processor\WebProcessor; +use Monolog\Formatter\LineFormatter; class AbstractProcessingHandlerTest extends TestCase { /** + * @covers Monolog\Handler\FormattableHandlerTrait::getFormatter + * @covers Monolog\Handler\FormattableHandlerTrait::setFormatter + */ + public function testConstructAndGetSet() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]); + $handler->setFormatter($formatter = new LineFormatter); + $this->assertSame($formatter, $handler->getFormatter()); + } + + /** * @covers Monolog\Handler\AbstractProcessingHandler::handle */ public function testHandleLowerLevelMessage() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, true)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, true]); $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); } @@ -31,7 +43,7 @@ class AbstractProcessingHandlerTest extends TestCase */ public function testHandleBubbling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, true)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, true]); $this->assertFalse($handler->handle($this->getRecord())); } @@ -40,7 +52,7 @@ class AbstractProcessingHandlerTest extends TestCase */ public function testHandleNotBubbling() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::DEBUG, false)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::DEBUG, false]); $this->assertTrue($handler->handle($this->getRecord())); } @@ -49,7 +61,7 @@ class AbstractProcessingHandlerTest extends TestCase */ public function testHandleIsFalseWhenNotHandled() { - $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', array(Logger::WARNING, false)); + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler', [Logger::WARNING, false]); $this->assertTrue($handler->handle($this->getRecord())); $this->assertFalse($handler->handle($this->getRecord(Logger::DEBUG))); } @@ -60,13 +72,13 @@ class AbstractProcessingHandlerTest extends TestCase public function testProcessRecord() { $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); - $handler->pushProcessor(new WebProcessor(array( + $handler->pushProcessor(new WebProcessor([ 'REQUEST_URI' => '', 'REQUEST_METHOD' => '', 'REMOTE_ADDR' => '', 'SERVER_NAME' => '', 'UNIQUE_ID' => '', - ))); + ])); $handledRecord = null; $handler->expects($this->once()) ->method('write') @@ -77,4 +89,44 @@ class AbstractProcessingHandlerTest extends TestCase $handler->handle($this->getRecord()); $this->assertEquals(6, count($handledRecord['extra'])); } + + /** + * @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor + * @covers Monolog\Handler\ProcessableHandlerTrait::popProcessor + * @expectedException LogicException + */ + public function testPushPopProcessor() + { + $logger = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); + $processor1 = new WebProcessor; + $processor2 = new WebProcessor; + + $logger->pushProcessor($processor1); + $logger->pushProcessor($processor2); + + $this->assertEquals($processor2, $logger->popProcessor()); + $this->assertEquals($processor1, $logger->popProcessor()); + $logger->popProcessor(); + } + + /** + * @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor + * @expectedException TypeError + */ + public function testPushProcessorWithNonCallable() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); + + $handler->pushProcessor(new \stdClass()); + } + + /** + * @covers Monolog\Handler\FormattableHandlerTrait::getFormatter + * @covers Monolog\Handler\FormattableHandlerTrait::getDefaultFormatter + */ + public function testGetFormatterInitializesDefault() + { + $handler = $this->getMockForAbstractClass('Monolog\Handler\AbstractProcessingHandler'); + $this->assertInstanceOf(LineFormatter::class, $handler->getFormatter()); + } } diff --git a/tests/Monolog/Handler/AmqpHandlerTest.php b/tests/Monolog/Handler/AmqpHandlerTest.php index 8e0e723..680de29 100644 --- a/tests/Monolog/Handler/AmqpHandlerTest.php +++ b/tests/Monolog/Handler/AmqpHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use PhpAmqpLib\Message\AMQPMessage; use PhpAmqpLib\Connection\AMQPConnection; @@ -31,43 +31,43 @@ class AmqpHandlerTest extends TestCase $this->markTestSkipped("Please update AMQP to version >= 1.0"); } - $messages = array(); + $messages = []; + + $exchange = $this->getMockBuilder('AMQPExchange') + ->setMethods(['publish', 'setName']) + ->disableOriginalConstructor() + ->getMock(); - $exchange = $this->getMock('AMQPExchange', array('publish', 'setName'), array(), '', false); - $exchange->expects($this->once()) - ->method('setName') - ->with('log') - ; $exchange->expects($this->any()) ->method('publish') - ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = array()) use (&$messages) { - $messages[] = array($message, $routing_key, $flags, $attributes); + ->will($this->returnCallback(function ($message, $routing_key, $flags = 0, $attributes = []) use (&$messages) { + $messages[] = [$message, $routing_key, $flags, $attributes]; })) ; - $handler = new AmqpHandler($exchange, 'log'); + $handler = new AmqpHandler($exchange); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); - $expected = array( - array( + $expected = [ + [ 'message' => 'test', - 'context' => array( - 'data' => array(), + 'context' => [ + 'data' => [], 'foo' => 34, - ), + ], 'level' => 300, 'level_name' => 'WARNING', 'channel' => 'test', - 'extra' => array(), - ), - 'warn.test', + 'extra' => [], + ], + 'warning.test', 0, - array( + [ 'delivery_mode' => 2, 'content_type' => 'application/json', - ), - ); + ], + ]; $handler->handle($record); @@ -83,43 +83,46 @@ class AmqpHandlerTest extends TestCase $this->markTestSkipped("php-amqplib not installed"); } - $messages = array(); + $messages = []; - $exchange = $this->getMock('PhpAmqpLib\Channel\AMQPChannel', array('basic_publish', '__destruct'), array(), '', false); + $exchange = $this->getMockBuilder('PhpAmqpLib\Channel\AMQPChannel') + ->setMethods(['basic_publish', '__destruct']) + ->disableOriginalConstructor() + ->getMock(); $exchange->expects($this->any()) ->method('basic_publish') ->will($this->returnCallback(function (AMQPMessage $msg, $exchange = "", $routing_key = "", $mandatory = false, $immediate = false, $ticket = null) use (&$messages) { - $messages[] = array($msg, $exchange, $routing_key, $mandatory, $immediate, $ticket); + $messages[] = [$msg, $exchange, $routing_key, $mandatory, $immediate, $ticket]; })) ; $handler = new AmqpHandler($exchange, 'log'); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); - $expected = array( - array( + $expected = [ + [ 'message' => 'test', - 'context' => array( - 'data' => array(), + 'context' => [ + 'data' => [], 'foo' => 34, - ), + ], 'level' => 300, 'level_name' => 'WARNING', 'channel' => 'test', - 'extra' => array(), - ), + 'extra' => [], + ], 'log', - 'warn.test', + 'warning.test', false, false, null, - array( + [ 'delivery_mode' => 2, 'content_type' => 'application/json', - ), - ); + ], + ]; $handler->handle($record); diff --git a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php index ffb1d74..048ee1c 100644 --- a/tests/Monolog/Handler/BrowserConsoleHandlerTest.php +++ b/tests/Monolog/Handler/BrowserConsoleHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -89,7 +89,7 @@ EOF; $handler = new BrowserConsoleHandler(); $handler->setFormatter($this->getIdentityFormatter()); - $handler->handle($this->getRecord(Logger::DEBUG, 'test', array('foo' => 'bar'))); + $handler->handle($this->getRecord(Logger::DEBUG, 'test', ['foo' => 'bar'])); $expected = <<<EOF (function (c) {if (c && c.groupCollapsed) { diff --git a/tests/Monolog/Handler/BufferHandlerTest.php b/tests/Monolog/Handler/BufferHandlerTest.php index da8b3c3..f1338b4 100644 --- a/tests/Monolog/Handler/BufferHandlerTest.php +++ b/tests/Monolog/Handler/BufferHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class BufferHandlerTest extends TestCase @@ -47,7 +47,7 @@ class BufferHandlerTest extends TestCase $handler->handle($this->getRecord(Logger::WARNING)); $handler->handle($this->getRecord(Logger::DEBUG)); $this->shutdownCheckHandler = $test; - register_shutdown_function(array($this, 'checkPropagation')); + register_shutdown_function([$this, 'checkPropagation']); } public function checkPropagation() diff --git a/tests/Monolog/Handler/ChromePHPHandlerTest.php b/tests/Monolog/Handler/ChromePHPHandlerTest.php index 0449f8b..e9a1f98 100644 --- a/tests/Monolog/Handler/ChromePHPHandlerTest.php +++ b/tests/Monolog/Handler/ChromePHPHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -37,17 +37,17 @@ class ChromePHPHandlerTest extends TestCase $handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::WARNING)); - $expected = array( - 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + $expected = [ + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'version' => ChromePHPHandler::VERSION, - 'columns' => array('label', 'log', 'backtrace', 'type'), - 'rows' => array( + 'columns' => ['label', 'log', 'backtrace', 'type'], + 'rows' => [ 'test', 'test', - ), + ], 'request_uri' => '', - )))), - ); + ]))), + ]; $this->assertEquals($expected, $handler->getHeaders()); } @@ -71,33 +71,33 @@ class ChromePHPHandlerTest extends TestCase // overflow chrome headers limit $handler->handle($this->getRecord(Logger::WARNING, str_repeat('a', 100 * 1024))); - $expected = array( - 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + $expected = [ + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'version' => ChromePHPHandler::VERSION, - 'columns' => array('label', 'log', 'backtrace', 'type'), - 'rows' => array( - array( + 'columns' => ['label', 'log', 'backtrace', 'type'], + 'rows' => [ + [ 'test', 'test', 'unknown', 'log', - ), - array( + ], + [ 'test', str_repeat('a', 150 * 1024), 'unknown', 'warn', - ), - array( + ], + [ 'monolog', 'Incomplete logs, chrome header size limit reached', 'unknown', 'warn', - ), - ), + ], + ], 'request_uri' => '', - )))), - ); + ]))), + ]; $this->assertEquals($expected, $handler->getHeaders()); } @@ -114,19 +114,19 @@ class ChromePHPHandlerTest extends TestCase $handler2->handle($this->getRecord(Logger::DEBUG)); $handler2->handle($this->getRecord(Logger::WARNING)); - $expected = array( - 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode(array( + $expected = [ + 'X-ChromeLogger-Data' => base64_encode(utf8_encode(json_encode([ 'version' => ChromePHPHandler::VERSION, - 'columns' => array('label', 'log', 'backtrace', 'type'), - 'rows' => array( + 'columns' => ['label', 'log', 'backtrace', 'type'], + 'rows' => [ 'test', 'test', 'test', 'test', - ), + ], 'request_uri' => '', - )))), - ); + ]))), + ]; $this->assertEquals($expected, $handler2->getHeaders()); } @@ -134,14 +134,14 @@ class ChromePHPHandlerTest extends TestCase class TestChromePHPHandler extends ChromePHPHandler { - protected $headers = array(); + protected $headers = []; public static function reset() { self::$initialized = false; self::$overflowed = false; self::$sendHeaders = true; - self::$json['rows'] = array(); + self::$json['rows'] = []; } protected function sendHeader($header, $content) diff --git a/tests/Monolog/Handler/CouchDBHandlerTest.php b/tests/Monolog/Handler/CouchDBHandlerTest.php index 9fc4b38..f89a130 100644 --- a/tests/Monolog/Handler/CouchDBHandlerTest.php +++ b/tests/Monolog/Handler/CouchDBHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,14 +11,14 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class CouchDBHandlerTest extends TestCase { public function testHandle() { - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new CouchDBHandler(); diff --git a/tests/Monolog/Handler/DeduplicationHandlerTest.php b/tests/Monolog/Handler/DeduplicationHandlerTest.php index e2aff86..491fd85 100644 --- a/tests/Monolog/Handler/DeduplicationHandlerTest.php +++ b/tests/Monolog/Handler/DeduplicationHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class DeduplicationHandlerTest extends TestCase @@ -88,10 +88,10 @@ class DeduplicationHandlerTest extends TestCase $handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', 0); $record = $this->getRecord(Logger::ERROR); - $record['datetime']->modify('+62seconds'); + $record['datetime'] = $record['datetime']->modify('+62seconds'); $handler->handle($record); $record = $this->getRecord(Logger::CRITICAL); - $record['datetime']->modify('+62seconds'); + $record['datetime'] = $record['datetime']->modify('+62seconds'); $handler->handle($record); $handler->flush(); @@ -115,13 +115,13 @@ class DeduplicationHandlerTest extends TestCase // handle two records from yesterday, and one recent $record = $this->getRecord(Logger::ERROR); - $record['datetime']->modify('-1day -10seconds'); + $record['datetime'] = $record['datetime']->modify('-1day -10seconds'); $handler->handle($record); $record2 = $this->getRecord(Logger::CRITICAL); - $record2['datetime']->modify('-1day -10seconds'); + $record2['datetime'] = $record2['datetime']->modify('-1day -10seconds'); $handler->handle($record2); $record3 = $this->getRecord(Logger::CRITICAL); - $record3['datetime']->modify('-30seconds'); + $record3['datetime'] = $record3['datetime']->modify('-30seconds'); $handler->handle($record3); // log is written as none of them are duplicate diff --git a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php index d67da90..f72f323 100644 --- a/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php +++ b/tests/Monolog/Handler/DoctrineCouchDBHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class DoctrineCouchDBHandlerTest extends TestCase @@ -26,21 +26,21 @@ class DoctrineCouchDBHandlerTest extends TestCase public function testHandle() { $client = $this->getMockBuilder('Doctrine\\CouchDB\\CouchDBClient') - ->setMethods(array('postDocument')) + ->setMethods(['postDocument']) ->disableOriginalConstructor() ->getMock(); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); - $expected = array( + $expected = [ 'message' => 'test', - 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34), + 'context' => ['data' => ['stdClass' => []], 'foo' => 34], 'level' => Logger::WARNING, 'level_name' => 'WARNING', 'channel' => 'test', - 'datetime' => $record['datetime']->format('Y-m-d H:i:s'), - 'extra' => array(), - ); + 'datetime' => (string) $record['datetime'], + 'extra' => [], + ]; $client->expects($this->once()) ->method('postDocument') diff --git a/tests/Monolog/Handler/DynamoDbHandlerTest.php b/tests/Monolog/Handler/DynamoDbHandlerTest.php index 2e6c348..9d61356 100644 --- a/tests/Monolog/Handler/DynamoDbHandlerTest.php +++ b/tests/Monolog/Handler/DynamoDbHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; class DynamoDbHandlerTest extends TestCase { @@ -24,8 +24,9 @@ class DynamoDbHandlerTest extends TestCase } $this->client = $this->getMockBuilder('Aws\DynamoDb\DynamoDbClient') - ->setMethods(array('formatAttributes', '__call')) - ->disableOriginalConstructor()->getMock(); + ->setMethods(['formatAttributes', '__call']) + ->disableOriginalConstructor() + ->getMock(); } public function testConstruct() @@ -47,8 +48,8 @@ class DynamoDbHandlerTest extends TestCase public function testHandle() { $record = $this->getRecord(); - $formatter = $this->getMock('Monolog\Formatter\FormatterInterface'); - $formatted = array('foo' => 1, 'bar' => 2); + $formatter = $this->createMock('Monolog\Formatter\FormatterInterface'); + $formatted = ['foo' => 1, 'bar' => 2]; $handler = new DynamoDbHandler($this->client, 'foo'); $handler->setFormatter($formatter); @@ -72,10 +73,10 @@ class DynamoDbHandlerTest extends TestCase $this->client ->expects($this->once()) ->method('__call') - ->with('putItem', array(array( + ->with('putItem', [[ 'TableName' => 'foo', 'Item' => $expFormatted, - ))); + ]]); $handler->handle($record); } diff --git a/tests/Monolog/Handler/ElasticSearchHandlerTest.php b/tests/Monolog/Handler/ElasticSearchHandlerTest.php index 1687074..e0e207d 100644 --- a/tests/Monolog/Handler/ElasticSearchHandlerTest.php +++ b/tests/Monolog/Handler/ElasticSearchHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -13,7 +13,7 @@ namespace Monolog\Handler; use Monolog\Formatter\ElasticaFormatter; use Monolog\Formatter\NormalizerFormatter; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Elastica\Client; use Elastica\Request; @@ -29,10 +29,10 @@ class ElasticSearchHandlerTest extends TestCase /** * @var array Default handler options */ - protected $options = array( + protected $options = [ 'index' => 'my_index', 'type' => 'doc_type', - ); + ]; public function setUp() { @@ -43,7 +43,7 @@ class ElasticSearchHandlerTest extends TestCase // base mock Elastica Client object $this->client = $this->getMockBuilder('Elastica\Client') - ->setMethods(array('addDocuments')) + ->setMethods(['addDocuments']) ->disableOriginalConstructor() ->getMock(); } @@ -57,19 +57,19 @@ class ElasticSearchHandlerTest extends TestCase public function testHandle() { // log message - $msg = array( + $msg = [ 'level' => Logger::ERROR, 'level_name' => 'ERROR', 'channel' => 'meh', - 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), - 'datetime' => new \DateTime("@0"), - 'extra' => array(), + 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass], + 'datetime' => new \DateTimeImmutable("@0"), + 'extra' => [], 'message' => 'log', - ); + ]; // format expected result $formatter = new ElasticaFormatter($this->options['index'], $this->options['type']); - $expected = array($formatter->format($msg)); + $expected = [$formatter->format($msg)]; // setup ES client mock $this->client->expects($this->any()) @@ -79,7 +79,7 @@ class ElasticSearchHandlerTest extends TestCase // perform tests $handler = new ElasticSearchHandler($this->client, $this->options); $handler->handle($msg); - $handler->handleBatch(array($msg)); + $handler->handleBatch([$msg]); } /** @@ -113,11 +113,11 @@ class ElasticSearchHandlerTest extends TestCase */ public function testOptions() { - $expected = array( + $expected = [ 'index' => $this->options['index'], 'type' => $this->options['type'], 'ignore_error' => false, - ); + ]; $handler = new ElasticSearchHandler($this->client, $this->options); $this->assertEquals($expected, $handler->getOptions()); } @@ -128,13 +128,14 @@ class ElasticSearchHandlerTest extends TestCase */ public function testConnectionErrors($ignore, $expectedError) { - $clientOpts = array('host' => '127.0.0.1', 'port' => 1); + $clientOpts = ['host' => '127.0.0.1', 'port' => 1]; $client = new Client($clientOpts); - $handlerOpts = array('ignore_error' => $ignore); + $handlerOpts = ['ignore_error' => $ignore]; $handler = new ElasticSearchHandler($client, $handlerOpts); if ($expectedError) { - $this->setExpectedException($expectedError[0], $expectedError[1]); + $this->expectException($expectedError[0]); + $this->expectExceptionMessage($expectedError[1]); $handler->handle($this->getRecord()); } else { $this->assertFalse($handler->handle($this->getRecord())); @@ -146,10 +147,10 @@ class ElasticSearchHandlerTest extends TestCase */ public function providerTestConnectionErrors() { - return array( - array(false, array('RuntimeException', 'Error sending messages to Elasticsearch')), - array(true, false), - ); + return [ + [false, ['RuntimeException', 'Error sending messages to Elasticsearch']], + [true, false], + ]; } /** @@ -162,28 +163,28 @@ class ElasticSearchHandlerTest extends TestCase */ public function testHandleIntegration() { - $msg = array( + $msg = [ 'level' => Logger::ERROR, 'level_name' => 'ERROR', 'channel' => 'meh', - 'context' => array('foo' => 7, 'bar', 'class' => new \stdClass), - 'datetime' => new \DateTime("@0"), - 'extra' => array(), + 'context' => ['foo' => 7, 'bar', 'class' => new \stdClass], + 'datetime' => new \DateTimeImmutable("@0"), + 'extra' => [], 'message' => 'log', - ); + ]; $expected = $msg; $expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601); - $expected['context'] = array( + $expected['context'] = [ 'class' => '[object] (stdClass: {})', 'foo' => 7, 0 => 'bar', - ); + ]; $client = new Client(); $handler = new ElasticSearchHandler($client, $this->options); try { - $handler->handleBatch(array($msg)); + $handler->handleBatch([$msg]); } catch (\RuntimeException $e) { $this->markTestSkipped("Cannot connect to Elastic Search server on localhost"); } @@ -234,6 +235,6 @@ class ElasticSearchHandlerTest extends TestCase return $data['_source']; } - return array(); + return []; } } diff --git a/tests/Monolog/Handler/ErrorLogHandlerTest.php b/tests/Monolog/Handler/ErrorLogHandlerTest.php index 99785cb..d230fb1 100644 --- a/tests/Monolog/Handler/ErrorLogHandlerTest.php +++ b/tests/Monolog/Handler/ErrorLogHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\LineFormatter; @@ -24,7 +24,7 @@ class ErrorLogHandlerTest extends TestCase { protected function setUp() { - $GLOBALS['error_log'] = array(); + $GLOBALS['error_log'] = []; } /** diff --git a/tests/Monolog/Handler/FilterHandlerTest.php b/tests/Monolog/Handler/FilterHandlerTest.php index 31b7686..0e64e76 100644 --- a/tests/Monolog/Handler/FilterHandlerTest.php +++ b/tests/Monolog/Handler/FilterHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; class FilterHandlerTest extends TestCase { @@ -63,7 +63,7 @@ class FilterHandlerTest extends TestCase $this->assertFalse($test->hasEmergencyRecords()); $test = new TestHandler(); - $handler = new FilterHandler($test, array(Logger::INFO, Logger::ERROR)); + $handler = new FilterHandler($test, [Logger::INFO, Logger::ERROR]); $handler->handle($this->getRecord(Logger::DEBUG)); $this->assertFalse($test->hasDebugRecords()); @@ -86,14 +86,14 @@ class FilterHandlerTest extends TestCase $test = new TestHandler(); $handler = new FilterHandler($test); - $levels = array(Logger::INFO, Logger::ERROR); + $levels = [Logger::INFO, Logger::ERROR]; $handler->setAcceptedLevels($levels); $this->assertSame($levels, $handler->getAcceptedLevels()); - $handler->setAcceptedLevels(array('info', 'error')); + $handler->setAcceptedLevels(['info', 'error']); $this->assertSame($levels, $handler->getAcceptedLevels()); - $levels = array(Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY); + $levels = [Logger::CRITICAL, Logger::ALERT, Logger::EMERGENCY]; $handler->setAcceptedLevels(Logger::CRITICAL, Logger::EMERGENCY); $this->assertSame($levels, $handler->getAcceptedLevels()); diff --git a/tests/Monolog/Handler/FingersCrossedHandlerTest.php b/tests/Monolog/Handler/FingersCrossedHandlerTest.php index b92bf43..5b25a36 100644 --- a/tests/Monolog/Handler/FingersCrossedHandlerTest.php +++ b/tests/Monolog/Handler/FingersCrossedHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy; use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy; @@ -114,8 +114,8 @@ class FingersCrossedHandlerTest extends TestCase { $test = new TestHandler(); $handler = new FingersCrossedHandler(function ($record, $handler) use ($test) { - return $test; - }); + return $test; + }); $handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::INFO)); $this->assertFalse($test->hasDebugRecords()); @@ -133,8 +133,8 @@ class FingersCrossedHandlerTest extends TestCase public function testHandleWithBadCallbackThrowsException() { $handler = new FingersCrossedHandler(function ($record, $handler) { - return 'foo'; - }); + return 'foo'; + }); $handler->handle($this->getRecord(Logger::WARNING)); } @@ -203,7 +203,7 @@ class FingersCrossedHandlerTest extends TestCase public function testChannelLevelActivationStrategy() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, array('othertest' => Logger::DEBUG))); + $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Logger::ERROR, ['othertest' => Logger::DEBUG])); $handler->handle($this->getRecord(Logger::WARNING)); $this->assertFalse($test->hasWarningRecords()); $record = $this->getRecord(Logger::DEBUG); @@ -220,7 +220,7 @@ class FingersCrossedHandlerTest extends TestCase public function testChannelLevelActivationStrategyWithPsrLevels() { $test = new TestHandler(); - $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', array('othertest' => 'debug'))); + $handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug'])); $handler->handle($this->getRecord(Logger::WARNING)); $this->assertFalse($test->hasWarningRecords()); $record = $this->getRecord(Logger::DEBUG); diff --git a/tests/Monolog/Handler/FirePHPHandlerTest.php b/tests/Monolog/Handler/FirePHPHandlerTest.php index 0eb10a6..b62e7fd 100644 --- a/tests/Monolog/Handler/FirePHPHandlerTest.php +++ b/tests/Monolog/Handler/FirePHPHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -32,13 +32,13 @@ class FirePHPHandlerTest extends TestCase $handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::WARNING)); - $expected = array( + $expected = [ 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', 'X-Wf-1-1-1-1' => 'test', 'X-Wf-1-1-1-2' => 'test', - ); + ]; $this->assertEquals($expected, $handler->getHeaders()); } @@ -55,18 +55,18 @@ class FirePHPHandlerTest extends TestCase $handler2->handle($this->getRecord(Logger::DEBUG)); $handler2->handle($this->getRecord(Logger::WARNING)); - $expected = array( + $expected = [ 'X-Wf-Protocol-1' => 'http://meta.wildfirehq.org/Protocol/JsonStream/0.2', 'X-Wf-1-Structure-1' => 'http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1', 'X-Wf-1-Plugin-1' => 'http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3', 'X-Wf-1-1-1-1' => 'test', 'X-Wf-1-1-1-2' => 'test', - ); + ]; - $expected2 = array( + $expected2 = [ 'X-Wf-1-1-1-3' => 'test', 'X-Wf-1-1-1-4' => 'test', - ); + ]; $this->assertEquals($expected, $handler->getHeaders()); $this->assertEquals($expected2, $handler2->getHeaders()); @@ -75,7 +75,7 @@ class FirePHPHandlerTest extends TestCase class TestFirePHPHandler extends FirePHPHandler { - protected $headers = array(); + protected $headers = []; public static function reset() { diff --git a/tests/Monolog/Handler/FleepHookHandlerTest.php b/tests/Monolog/Handler/FleepHookHandlerTest.php index 91cdd31..11b5a65 100644 --- a/tests/Monolog/Handler/FleepHookHandlerTest.php +++ b/tests/Monolog/Handler/FleepHookHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -13,7 +13,7 @@ namespace Monolog\Handler; use Monolog\Formatter\LineFormatter; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; /** * @coversDefaultClass \Monolog\Handler\FleepHookHandler @@ -56,15 +56,15 @@ class FleepHookHandlerTest extends TestCase */ public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays() { - $record = array( + $record = [ 'message' => 'msg', - 'context' => array(), + 'context' => [], 'level' => Logger::DEBUG, 'level_name' => Logger::getLevelName(Logger::DEBUG), 'channel' => 'channel', - 'datetime' => new \DateTime(), - 'extra' => array(), - ); + 'datetime' => new \DateTimeImmutable(), + 'extra' => [], + ]; $expectedFormatter = new LineFormatter(null, null, true, true); $expected = $expectedFormatter->format($record); diff --git a/tests/Monolog/Handler/FlowdockHandlerTest.php b/tests/Monolog/Handler/FlowdockHandlerTest.php index 4b120d5..23f8b06 100644 --- a/tests/Monolog/Handler/FlowdockHandlerTest.php +++ b/tests/Monolog/Handler/FlowdockHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Formatter\FlowdockFormatter; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -61,15 +61,14 @@ class FlowdockHandlerTest extends TestCase private function createHandler($token = 'myToken') { - $constructorArgs = array($token, Logger::DEBUG); + $constructorArgs = [$token, Logger::DEBUG]; $this->res = fopen('php://memory', 'a'); - $this->handler = $this->getMock( - '\Monolog\Handler\FlowdockHandler', - array('fsockopen', 'streamSetTimeout', 'closeSocket'), - $constructorArgs - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\FlowdockHandler') + ->setConstructorArgs($constructorArgs) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); - $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); diff --git a/tests/Monolog/Handler/GelfHandlerLegacyTest.php b/tests/Monolog/Handler/GelfHandlerLegacyTest.php deleted file mode 100644 index 9d007b1..0000000 --- a/tests/Monolog/Handler/GelfHandlerLegacyTest.php +++ /dev/null @@ -1,95 +0,0 @@ -<?php - -/* - * This file is part of the Monolog package. - * - * (c) Jordi Boggiano <j.boggiano@seld.be> - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Monolog\Handler; - -use Gelf\Message; -use Monolog\TestCase; -use Monolog\Logger; -use Monolog\Formatter\GelfMessageFormatter; - -class GelfHandlerLegacyTest extends TestCase -{ - public function setUp() - { - if (!class_exists('Gelf\MessagePublisher') || !class_exists('Gelf\Message')) { - $this->markTestSkipped("mlehner/gelf-php not installed"); - } - - require_once __DIR__ . '/GelfMockMessagePublisher.php'; - } - - /** - * @covers Monolog\Handler\GelfHandler::__construct - */ - public function testConstruct() - { - $handler = new GelfHandler($this->getMessagePublisher()); - $this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler); - } - - protected function getHandler($messagePublisher) - { - $handler = new GelfHandler($messagePublisher); - - return $handler; - } - - protected function getMessagePublisher() - { - return new GelfMockMessagePublisher('localhost'); - } - - public function testDebug() - { - $messagePublisher = $this->getMessagePublisher(); - $handler = $this->getHandler($messagePublisher); - - $record = $this->getRecord(Logger::DEBUG, "A test debug message"); - $handler->handle($record); - - $this->assertEquals(7, $messagePublisher->lastMessage->getLevel()); - $this->assertEquals('test', $messagePublisher->lastMessage->getFacility()); - $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage()); - $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage()); - } - - public function testWarning() - { - $messagePublisher = $this->getMessagePublisher(); - $handler = $this->getHandler($messagePublisher); - - $record = $this->getRecord(Logger::WARNING, "A test warning message"); - $handler->handle($record); - - $this->assertEquals(4, $messagePublisher->lastMessage->getLevel()); - $this->assertEquals('test', $messagePublisher->lastMessage->getFacility()); - $this->assertEquals($record['message'], $messagePublisher->lastMessage->getShortMessage()); - $this->assertEquals(null, $messagePublisher->lastMessage->getFullMessage()); - } - - public function testInjectedGelfMessageFormatter() - { - $messagePublisher = $this->getMessagePublisher(); - $handler = $this->getHandler($messagePublisher); - - $handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX')); - - $record = $this->getRecord(Logger::WARNING, "A test warning message"); - $record['extra']['blarg'] = 'yep'; - $record['context']['from'] = 'logger'; - $handler->handle($record); - - $this->assertEquals('mysystem', $messagePublisher->lastMessage->getHost()); - $this->assertArrayHasKey('_EXTblarg', $messagePublisher->lastMessage->toArray()); - $this->assertArrayHasKey('_CTXfrom', $messagePublisher->lastMessage->toArray()); - } -} diff --git a/tests/Monolog/Handler/GelfHandlerTest.php b/tests/Monolog/Handler/GelfHandlerTest.php index 8cdd64f..12e5f8b 100644 --- a/tests/Monolog/Handler/GelfHandlerTest.php +++ b/tests/Monolog/Handler/GelfHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Gelf\Message; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\GelfMessageFormatter; @@ -43,7 +43,10 @@ class GelfHandlerTest extends TestCase protected function getMessagePublisher() { - return $this->getMock('Gelf\Publisher', array('publish'), array(), '', false); + return $this->getMockBuilder('Gelf\Publisher') + ->setMethods(['publish']) + ->disableOriginalConstructor() + ->getMock(); } public function testDebug() diff --git a/tests/Monolog/Handler/GelfMockMessagePublisher.php b/tests/Monolog/Handler/GelfMockMessagePublisher.php deleted file mode 100644 index 873d92f..0000000 --- a/tests/Monolog/Handler/GelfMockMessagePublisher.php +++ /dev/null @@ -1,25 +0,0 @@ -<?php - -/* - * This file is part of the Monolog package. - * - * (c) Jordi Boggiano <j.boggiano@seld.be> - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Monolog\Handler; - -use Gelf\MessagePublisher; -use Gelf\Message; - -class GelfMockMessagePublisher extends MessagePublisher -{ - public function publish(Message $message) - { - $this->lastMessage = $message; - } - - public $lastMessage = null; -} diff --git a/tests/Monolog/Handler/GroupHandlerTest.php b/tests/Monolog/Handler/GroupHandlerTest.php index a1b8617..d0ffdf0 100644 --- a/tests/Monolog/Handler/GroupHandlerTest.php +++ b/tests/Monolog/Handler/GroupHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class GroupHandlerTest extends TestCase @@ -22,7 +22,7 @@ class GroupHandlerTest extends TestCase */ public function testConstructorOnlyTakesHandler() { - new GroupHandler(array(new TestHandler(), "foo")); + new GroupHandler([new TestHandler(), "foo"]); } /** @@ -31,7 +31,7 @@ class GroupHandlerTest extends TestCase */ public function testHandle() { - $testHandlers = array(new TestHandler(), new TestHandler()); + $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new GroupHandler($testHandlers); $handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::INFO)); @@ -47,9 +47,9 @@ class GroupHandlerTest extends TestCase */ public function testHandleBatch() { - $testHandlers = array(new TestHandler(), new TestHandler()); + $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new GroupHandler($testHandlers); - $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -62,7 +62,7 @@ class GroupHandlerTest extends TestCase */ public function testIsHandling() { - $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)); + $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)]; $handler = new GroupHandler($testHandlers); $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); @@ -75,7 +75,7 @@ class GroupHandlerTest extends TestCase public function testHandleUsesProcessors() { $test = new TestHandler(); - $handler = new GroupHandler(array($test)); + $handler = new GroupHandler([$test]); $handler->pushProcessor(function ($record) { $record['extra']['foo'] = true; @@ -92,14 +92,14 @@ class GroupHandlerTest extends TestCase */ public function testHandleBatchUsesProcessors() { - $testHandlers = array(new TestHandler(), new TestHandler()); + $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new GroupHandler($testHandlers); $handler->pushProcessor(function ($record) { $record['extra']['foo'] = true; return $record; }); - $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); diff --git a/tests/Monolog/Handler/HandlerWrapperTest.php b/tests/Monolog/Handler/HandlerWrapperTest.php index d8d0452..bedc175 100644 --- a/tests/Monolog/Handler/HandlerWrapperTest.php +++ b/tests/Monolog/Handler/HandlerWrapperTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; /** * @author Alexey Karapetov <alexey@karapetov.com> @@ -28,7 +28,7 @@ class HandlerWrapperTest extends TestCase public function setUp() { parent::setUp(); - $this->handler = $this->getMock('Monolog\\Handler\\HandlerInterface'); + $this->handler = $this->createMock('Monolog\\Handler\\HandlerInterface'); $this->wrapper = new HandlerWrapper($this->handler); } @@ -37,10 +37,10 @@ class HandlerWrapperTest extends TestCase */ public function trueFalseDataProvider() { - return array( - array(true), - array(false), - ); + return [ + [true], + [false], + ]; } /** @@ -87,44 +87,4 @@ class HandlerWrapperTest extends TestCase $this->assertEquals($result, $this->wrapper->handleBatch($records)); } - - public function testPushProcessor() - { - $processor = function () {}; - $this->handler->expects($this->once()) - ->method('pushProcessor') - ->with($processor); - - $this->assertEquals($this->wrapper, $this->wrapper->pushProcessor($processor)); - } - - public function testPopProcessor() - { - $processor = function () {}; - $this->handler->expects($this->once()) - ->method('popProcessor') - ->willReturn($processor); - - $this->assertEquals($processor, $this->wrapper->popProcessor()); - } - - public function testSetFormatter() - { - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); - $this->handler->expects($this->once()) - ->method('setFormatter') - ->with($formatter); - - $this->assertEquals($this->wrapper, $this->wrapper->setFormatter($formatter)); - } - - public function testGetFormatter() - { - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); - $this->handler->expects($this->once()) - ->method('getFormatter') - ->willReturn($formatter); - - $this->assertEquals($formatter, $this->wrapper->getFormatter()); - } } diff --git a/tests/Monolog/Handler/HipChatHandlerTest.php b/tests/Monolog/Handler/HipChatHandlerTest.php index 52dc9da..4df4de4 100644 --- a/tests/Monolog/Handler/HipChatHandlerTest.php +++ b/tests/Monolog/Handler/HipChatHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -24,30 +24,6 @@ class HipChatHandlerTest extends TestCase /** @var HipChatHandler */ private $handler; - public function testWriteHeader() - { - $this->createHandler(); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); - fseek($this->res, 0); - $content = fread($this->res, 1024); - - $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: api.hipchat.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); - - return $content; - } - - public function testWriteCustomHostHeader() - { - $this->createHandler('myToken', 'room1', 'Monolog', true, 'hipchat.foo.bar'); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); - fseek($this->res, 0); - $content = fread($this->res, 1024); - - $this->assertRegexp('/POST \/v1\/rooms\/message\?format=json&auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); - - return $content; - } - public function testWriteV2() { $this->createHandler('myToken', 'room1', 'Monolog', false, 'hipchat.foo.bar', 'v2'); @@ -55,7 +31,7 @@ class HipChatHandlerTest extends TestCase fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + $this->assertRegexp('{POST /v2/room/room1/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content); return $content; } @@ -67,7 +43,7 @@ class HipChatHandlerTest extends TestCase fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/POST \/v2\/room\/room1\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + $this->assertRegexp('{POST /v2/room/room1/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content); return $content; } @@ -79,7 +55,7 @@ class HipChatHandlerTest extends TestCase fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/POST \/v2\/room\/room%20name\/notification\?auth_token=.* HTTP\/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + $this->assertRegexp('{POST /v2/room/room%20name/notification\?auth_token=.* HTTP/1.1\\r\\nHost: hipchat.foo.bar\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content); return $content; } @@ -92,18 +68,6 @@ class HipChatHandlerTest extends TestCase $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=Monolog$/', $content); } - public function testWriteContentV1WithoutName() - { - $this->createHandler('myToken', 'room1', null, false, 'hipchat.foo.bar', 'v1'); - $this->handler->handle($this->getRecord(Logger::CRITICAL, 'test1')); - fseek($this->res, 0); - $content = fread($this->res, 1024); - - $this->assertRegexp('/notify=0&message=test1&message_format=text&color=red&room_id=room1&from=$/', $content); - - return $content; - } - /** * @depends testWriteCustomHostHeader */ @@ -175,16 +139,16 @@ class HipChatHandlerTest extends TestCase public function provideLevelColors() { - return array( - array(Logger::DEBUG, 'gray'), - array(Logger::INFO, 'green'), - array(Logger::WARNING, 'yellow'), - array(Logger::ERROR, 'red'), - array(Logger::CRITICAL, 'red'), - array(Logger::ALERT, 'red'), - array(Logger::EMERGENCY,'red'), - array(Logger::NOTICE, 'green'), - ); + return [ + [Logger::DEBUG, 'gray'], + [Logger::INFO, 'green'], + [Logger::WARNING, 'yellow'], + [Logger::ERROR, 'red'], + [Logger::CRITICAL, 'red'], + [Logger::ALERT, 'red'], + [Logger::EMERGENCY,'red'], + [Logger::NOTICE, 'green'], + ]; } /** @@ -204,49 +168,48 @@ class HipChatHandlerTest extends TestCase public function provideBatchRecords() { - return array( - array( - array( - array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()), - array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), - array('level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTime()), - ), + return [ + [ + [ + ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()], + ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()], + ['level' => Logger::CRITICAL, 'message' => 'Everything is broken!', 'level_name' => 'critical', 'datetime' => new \DateTimeImmutable()], + ], 'red', - ), - array( - array( - array('level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTime()), - array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), - ), + ], + [ + [ + ['level' => Logger::WARNING, 'message' => 'Oh bugger!', 'level_name' => 'warning', 'datetime' => new \DateTimeImmutable()], + ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()], + ], 'yellow', - ), - array( - array( - array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()), - array('level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTime()), - ), + ], + [ + [ + ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()], + ['level' => Logger::NOTICE, 'message' => 'Something noticeable happened.', 'level_name' => 'notice', 'datetime' => new \DateTimeImmutable()], + ], 'green', - ), - array( - array( - array('level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTime()), - ), + ], + [ + [ + ['level' => Logger::DEBUG, 'message' => 'Just debugging.', 'level_name' => 'debug', 'datetime' => new \DateTimeImmutable()], + ], 'gray', - ), - ); + ], + ]; } private function createHandler($token = 'myToken', $room = 'room1', $name = 'Monolog', $notify = false, $host = 'api.hipchat.com', $version = 'v1') { - $constructorArgs = array($token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version); + $constructorArgs = [$token, $room, $name, $notify, Logger::DEBUG, true, true, 'text', $host, $version]; $this->res = fopen('php://memory', 'a'); - $this->handler = $this->getMock( - '\Monolog\Handler\HipChatHandler', - array('fsockopen', 'streamSetTimeout', 'closeSocket'), - $constructorArgs - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\HipChatHandler') + ->setConstructorArgs($constructorArgs) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); - $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); @@ -263,14 +226,6 @@ class HipChatHandlerTest extends TestCase $this->handler->setFormatter($this->getIdentityFormatter()); } - /** - * @expectedException InvalidArgumentException - */ - public function testCreateWithTooLongName() - { - $hipChatHandler = new HipChatHandler('token', 'room', 'SixteenCharsHere'); - } - public function testCreateWithTooLongNameV2() { // creating a handler with too long of a name but using the v2 api doesn't matter. diff --git a/tests/Monolog/Handler/LogEntriesHandlerTest.php b/tests/Monolog/Handler/LogEntriesHandlerTest.php index b2deb40..92a206d 100644 --- a/tests/Monolog/Handler/LogEntriesHandlerTest.php +++ b/tests/Monolog/Handler/LogEntriesHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -37,37 +37,36 @@ class LogEntriesHandlerTest extends TestCase fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] test.CRITICAL: Critical write test/', $content); + $this->assertRegexp('/testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] test.CRITICAL: Critical write test/', $content); } public function testWriteBatchContent() { - $records = array( + $records = [ $this->getRecord(), $this->getRecord(), $this->getRecord(), - ); + ]; $this->createHandler(); $this->handler->handleBatch($records); fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] .* \[\] \[\]\n){3}/', $content); + $this->assertRegexp('/(testToken \[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{6}\+00:00\] .* \[\] \[\]\n){3}/', $content); } private function createHandler() { $useSSL = extension_loaded('openssl'); - $args = array('testToken', $useSSL, Logger::DEBUG, true); + $args = ['testToken', $useSSL, Logger::DEBUG, true]; $this->res = fopen('php://memory', 'a'); - $this->handler = $this->getMock( - '\Monolog\Handler\LogEntriesHandler', - array('fsockopen', 'streamSetTimeout', 'closeSocket'), - $args - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\LogEntriesHandler') + ->setConstructorArgs($args) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); - $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); diff --git a/tests/Monolog/Handler/LogmaticHandlerTest.php b/tests/Monolog/Handler/LogmaticHandlerTest.php new file mode 100644 index 0000000..bab74ac --- /dev/null +++ b/tests/Monolog/Handler/LogmaticHandlerTest.php @@ -0,0 +1,83 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Test\TestCase; +use Monolog\Logger; + +/** + * @author Julien Breux <julien.breux@gmail.com> + */ +class LogmaticHandlerTest extends TestCase +{ + /** + * @var resource + */ + private $res; + + /** + * @var LogmaticHandler + */ + private $handler; + + public function testWriteContent() + { + $this->createHandler(); + $this->handler->handle($this->getRecord(Logger::CRITICAL, 'Critical write test')); + + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/testToken {"message":"Critical write test","context":\[\],"level":500,"level_name":"CRITICAL","channel":"test","datetime":"(.*)","extra":\[\],"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content); + } + + public function testWriteBatchContent() + { + $records = [ + $this->getRecord(), + $this->getRecord(), + $this->getRecord(), + ]; + $this->createHandler(); + $this->handler->handleBatch($records); + + fseek($this->res, 0); + $content = fread($this->res, 1024); + + $this->assertRegexp('/testToken {"message":"test","context":\[\],"level":300,"level_name":"WARNING","channel":"test","datetime":"(.*)","extra":\[\],"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content); + } + + private function createHandler() + { + $useSSL = extension_loaded('openssl'); + $args = ['testToken', 'testHostname', 'testAppname', $useSSL, Logger::DEBUG, true]; + $this->res = fopen('php://memory', 'a'); + $this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler') + ->setConstructorArgs($args) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); + + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty->setAccessible(true); + $reflectionProperty->setValue($this->handler, 'localhost:1234'); + + $this->handler->expects($this->any()) + ->method('fsockopen') + ->will($this->returnValue($this->res)); + $this->handler->expects($this->any()) + ->method('streamSetTimeout') + ->will($this->returnValue(true)); + $this->handler->expects($this->any()) + ->method('closeSocket') + ->will($this->returnValue(true)); + } +} diff --git a/tests/Monolog/Handler/MailHandlerTest.php b/tests/Monolog/Handler/MailHandlerTest.php index 6754f3d..5a52819 100644 --- a/tests/Monolog/Handler/MailHandlerTest.php +++ b/tests/Monolog/Handler/MailHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; class MailHandlerTest extends TestCase { @@ -21,11 +21,11 @@ class MailHandlerTest extends TestCase */ public function testHandleBatch() { - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $formatter->expects($this->once()) ->method('formatBatch'); // Each record is formatted - $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); + $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler', [], '', true, true, true, ['send', 'write']); $handler->expects($this->once()) ->method('send'); $handler->expects($this->never()) @@ -41,11 +41,11 @@ class MailHandlerTest extends TestCase */ public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel() { - $records = array( + $records = [ $this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Logger::INFO, 'information'), - ); + ]; $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); $handler->expects($this->never()) @@ -61,10 +61,11 @@ class MailHandlerTest extends TestCase public function testHandle() { $handler = $this->getMockForAbstractClass('Monolog\\Handler\\MailHandler'); + $handler->setFormatter(new \Monolog\Formatter\LineFormatter); $record = $this->getRecord(); - $records = array($record); - $records[0]['formatted'] = '['.$record['datetime']->format('Y-m-d H:i:s').'] test.WARNING: test [] []'."\n"; + $records = [$record]; + $records[0]['formatted'] = '['.$record['datetime'].'] test.WARNING: test [] []'."\n"; $handler->expects($this->once()) ->method('send') diff --git a/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php b/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php new file mode 100644 index 0000000..07434e4 --- /dev/null +++ b/tests/Monolog/Handler/MockRavenClient-gte-0-16-0.php @@ -0,0 +1,27 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Raven_Client; + +class MockRavenClient extends Raven_Client +{ + public function capture($data, $stack = null, $vars = null) + { + $data = array_merge($this->get_user_data(), $data); + $this->lastData = $data; + $this->lastStack = $stack; + } + + public $lastData; + public $lastStack; +} diff --git a/tests/Monolog/Handler/MockRavenClient.php b/tests/Monolog/Handler/MockRavenClient.php index a083322..d344d34 100644 --- a/tests/Monolog/Handler/MockRavenClient.php +++ b/tests/Monolog/Handler/MockRavenClient.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. diff --git a/tests/Monolog/Handler/MongoDBHandlerTest.php b/tests/Monolog/Handler/MongoDBHandlerTest.php index 0fdef63..7333ef6 100644 --- a/tests/Monolog/Handler/MongoDBHandlerTest.php +++ b/tests/Monolog/Handler/MongoDBHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,8 +11,9 @@ namespace Monolog\Handler; -use Monolog\TestCase; -use Monolog\Logger; +use MongoDB\Driver\Manager; +use Monolog\Test\TestCase; +use Monolog\Formatter\NormalizerFormatter; class MongoDBHandlerTest extends TestCase { @@ -21,45 +22,57 @@ class MongoDBHandlerTest extends TestCase */ public function testConstructorShouldThrowExceptionForInvalidMongo() { - new MongoDBHandler(new \stdClass(), 'DB', 'Collection'); + new MongoDBHandler(new \stdClass, 'db', 'collection'); } - public function testHandle() + public function testHandleWithLibraryClient() { - $mongo = $this->getMock('Mongo', array('selectCollection'), array(), '', false); - $collection = $this->getMock('stdClass', array('save')); + if (!(class_exists('MongoDB\Client'))) { + $this->markTestSkipped('mongodb/mongodb not installed'); + } + + $mongodb = $this->getMockBuilder('MongoDB\Client') + ->disableOriginalConstructor() + ->getMock(); - $mongo->expects($this->once()) + $collection = $this->getMockBuilder('MongoDB\Collection') + ->disableOriginalConstructor() + ->getMock(); + + $mongodb->expects($this->once()) ->method('selectCollection') - ->with('DB', 'Collection') + ->with('db', 'collection') ->will($this->returnValue($collection)); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); - - $expected = array( - 'message' => 'test', - 'context' => array('data' => '[object] (stdClass: {})', 'foo' => 34), - 'level' => Logger::WARNING, - 'level_name' => 'WARNING', - 'channel' => 'test', - 'datetime' => $record['datetime']->format('Y-m-d H:i:s'), - 'extra' => array(), - ); + $record = $this->getRecord(); + $expected = $record; + $expected['datetime'] = $record['datetime']->format(NormalizerFormatter::SIMPLE_DATE); $collection->expects($this->once()) - ->method('save') + ->method('insertOne') ->with($expected); - $handler = new MongoDBHandler($mongo, 'DB', 'Collection'); + $handler = new MongoDBHandler($mongodb, 'db', 'collection'); $handler->handle($record); } -} -if (!class_exists('Mongo')) { - class Mongo + public function testHandleWithDriverManager() { - public function selectCollection() - { + if (!(class_exists('MongoDB\Driver\Manager'))) { + $this->markTestSkipped('ext-mongodb not installed'); + } + + /* This can become a unit test once ManagerInterface can be mocked. + * See: https://jira.mongodb.org/browse/PHPC-378 + */ + $mongodb = new Manager('mongodb://localhost:27017'); + $handler = new MongoDBHandler($mongodb, 'test', 'monolog'); + $record = $this->getRecord(); + + try { + $handler->handle($record); + } catch (\RuntimeException $e) { + $this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017'); } } } diff --git a/tests/Monolog/Handler/NativeMailerHandlerTest.php b/tests/Monolog/Handler/NativeMailerHandlerTest.php index ddf545d..d4aef95 100644 --- a/tests/Monolog/Handler/NativeMailerHandlerTest.php +++ b/tests/Monolog/Handler/NativeMailerHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use InvalidArgumentException; @@ -24,7 +24,7 @@ class NativeMailerHandlerTest extends TestCase { protected function setUp() { - $GLOBALS['mail'] = array(); + $GLOBALS['mail'] = []; } /** @@ -50,7 +50,7 @@ class NativeMailerHandlerTest extends TestCase public function testSetterArrayHeaderInjection() { $mailer = new NativeMailerHandler('spammer@example.org', 'dear victim', 'receiver@example.org'); - $mailer->addHeader(array("Content-Type: text/html\r\nFrom: faked@attacker.org")); + $mailer->addHeader(["Content-Type: text/html\r\nFrom: faked@attacker.org"]); } /** @@ -78,7 +78,8 @@ class NativeMailerHandlerTest extends TestCase $from = 'receiver@example.org'; $mailer = new NativeMailerHandler($to, $subject, $from); - $mailer->handleBatch(array()); + $mailer->setFormatter(new \Monolog\Formatter\LineFormatter); + $mailer->handleBatch([]); // batch is empty, nothing sent $this->assertEmpty($GLOBALS['mail']); diff --git a/tests/Monolog/Handler/NewRelicHandlerTest.php b/tests/Monolog/Handler/NewRelicHandlerTest.php index 4d3a615..a71bbf8 100644 --- a/tests/Monolog/Handler/NewRelicHandlerTest.php +++ b/tests/Monolog/Handler/NewRelicHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Formatter\LineFormatter; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class NewRelicHandlerTest extends TestCase @@ -24,7 +24,7 @@ class NewRelicHandlerTest extends TestCase public function setUp() { self::$appname = null; - self::$customParameters = array(); + self::$customParameters = []; self::$transactionName = null; } @@ -46,8 +46,8 @@ class NewRelicHandlerTest extends TestCase public function testThehandlerCanAddContextParamsToTheNewRelicTrace() { $handler = new StubNewRelicHandler(); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('a' => 'b'))); - $this->assertEquals(array('context_a' => 'b'), self::$customParameters); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['a' => 'b'])); + $this->assertEquals(['context_a' => 'b'], self::$customParameters); } public function testThehandlerCanAddExplodedContextParamsToTheNewRelicTrace() @@ -56,10 +56,10 @@ class NewRelicHandlerTest extends TestCase $handler->handle($this->getRecord( Logger::ERROR, 'log message', - array('a' => array('key1' => 'value1', 'key2' => 'value2')) + ['a' => ['key1' => 'value1', 'key2' => 'value2']] )); $this->assertEquals( - array('context_a_key1' => 'value1', 'context_a_key2' => 'value2'), + ['context_a_key1' => 'value1', 'context_a_key2' => 'value2'], self::$customParameters ); } @@ -67,40 +67,40 @@ class NewRelicHandlerTest extends TestCase public function testThehandlerCanAddExtraParamsToTheNewRelicTrace() { $record = $this->getRecord(Logger::ERROR, 'log message'); - $record['extra'] = array('c' => 'd'); + $record['extra'] = ['c' => 'd']; $handler = new StubNewRelicHandler(); $handler->handle($record); - $this->assertEquals(array('extra_c' => 'd'), self::$customParameters); + $this->assertEquals(['extra_c' => 'd'], self::$customParameters); } public function testThehandlerCanAddExplodedExtraParamsToTheNewRelicTrace() { $record = $this->getRecord(Logger::ERROR, 'log message'); - $record['extra'] = array('c' => array('key1' => 'value1', 'key2' => 'value2')); + $record['extra'] = ['c' => ['key1' => 'value1', 'key2' => 'value2']]; $handler = new StubNewRelicHandler(Logger::ERROR, true, self::$appname, true); $handler->handle($record); $this->assertEquals( - array('extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'), + ['extra_c_key1' => 'value1', 'extra_c_key2' => 'value2'], self::$customParameters ); } public function testThehandlerCanAddExtraContextAndParamsToTheNewRelicTrace() { - $record = $this->getRecord(Logger::ERROR, 'log message', array('a' => 'b')); - $record['extra'] = array('c' => 'd'); + $record = $this->getRecord(Logger::ERROR, 'log message', ['a' => 'b']); + $record['extra'] = ['c' => 'd']; $handler = new StubNewRelicHandler(); $handler->handle($record); - $expected = array( + $expected = [ 'context_a' => 'b', 'extra_c' => 'd', - ); + ]; $this->assertEquals($expected, self::$customParameters); } @@ -131,7 +131,7 @@ class NewRelicHandlerTest extends TestCase public function testTheAppNameCanBeOverriddenFromEachLog() { $handler = new StubNewRelicHandler(Logger::DEBUG, false, 'myAppName'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('appname' => 'logAppName'))); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['appname' => 'logAppName'])); $this->assertEquals('logAppName', self::$appname); } @@ -155,7 +155,7 @@ class NewRelicHandlerTest extends TestCase public function testTheTransactionNameCanBeOverriddenFromEachLog() { $handler = new StubNewRelicHandler(Logger::DEBUG, false, null, false, 'myTransaction'); - $handler->handle($this->getRecord(Logger::ERROR, 'log message', array('transaction_name' => 'logTransactName'))); + $handler->handle($this->getRecord(Logger::ERROR, 'log message', ['transaction_name' => 'logTransactName'])); $this->assertEquals('logTransactName', self::$transactionName); } diff --git a/tests/Monolog/Handler/NoopHandlerTest.php b/tests/Monolog/Handler/NoopHandlerTest.php new file mode 100644 index 0000000..768f5e3 --- /dev/null +++ b/tests/Monolog/Handler/NoopHandlerTest.php @@ -0,0 +1,49 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Test\TestCase; +use Monolog\Logger; + +/** + * @covers Monolog\Handler\NoopHandler::handle + */ +class NoopHandlerTest extends TestCase +{ + /** + * @dataProvider logLevelsProvider + */ + public function testIsHandling($level) + { + $handler = new NoopHandler(); + $this->assertTrue($handler->isHandling($this->getRecord($level))); + } + + /** + * @dataProvider logLevelsProvider + */ + public function testHandle($level) + { + $handler = new NoopHandler(); + $this->assertFalse($handler->handle($this->getRecord($level))); + } + + public function logLevelsProvider() + { + return array_map( + function ($level) { + return [$level]; + }, + array_values(Logger::getLevels()) + ); + } +} diff --git a/tests/Monolog/Handler/NullHandlerTest.php b/tests/Monolog/Handler/NullHandlerTest.php index 292df78..b7e482b 100644 --- a/tests/Monolog/Handler/NullHandlerTest.php +++ b/tests/Monolog/Handler/NullHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** diff --git a/tests/Monolog/Handler/PHPConsoleHandlerTest.php b/tests/Monolog/Handler/PHPConsoleHandlerTest.php index 152573e..0836b99 100644 --- a/tests/Monolog/Handler/PHPConsoleHandlerTest.php +++ b/tests/Monolog/Handler/PHPConsoleHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -14,11 +14,11 @@ namespace Monolog\Handler; use Exception; use Monolog\ErrorHandler; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; use PhpConsole\Connector; use PhpConsole\Dispatcher\Debug as DebugDispatcher; use PhpConsole\Dispatcher\Errors as ErrorDispatcher; -use PhpConsole\Handler; +use PhpConsole\Handler as VendorPhpConsoleHandler; use PHPUnit_Framework_MockObject_MockObject; /** @@ -52,8 +52,8 @@ class PHPConsoleHandlerTest extends TestCase { return $this->getMockBuilder('PhpConsole\Dispatcher\Debug') ->disableOriginalConstructor() - ->setMethods(array('dispatchDebug')) - ->setConstructorArgs(array($connector, $connector->getDumper())) + ->setMethods(['dispatchDebug']) + ->setConstructorArgs([$connector, $connector->getDumper()]) ->getMock(); } @@ -61,8 +61,8 @@ class PHPConsoleHandlerTest extends TestCase { return $this->getMockBuilder('PhpConsole\Dispatcher\Errors') ->disableOriginalConstructor() - ->setMethods(array('dispatchError', 'dispatchException')) - ->setConstructorArgs(array($connector, $connector->getDumper())) + ->setMethods(['dispatchError', 'dispatchException']) + ->setConstructorArgs([$connector, $connector->getDumper()]) ->getMock(); } @@ -70,7 +70,7 @@ class PHPConsoleHandlerTest extends TestCase { $connector = $this->getMockBuilder('PhpConsole\Connector') ->disableOriginalConstructor() - ->setMethods(array( + ->setMethods([ 'sendMessage', 'onShutDown', 'isActiveClient', @@ -81,7 +81,7 @@ class PHPConsoleHandlerTest extends TestCase 'setAllowedIpMasks', 'setHeadersLimit', 'startEvalRequestsListener', - )) + ]) ->getMock(); $connector->expects($this->any()) @@ -93,17 +93,17 @@ class PHPConsoleHandlerTest extends TestCase protected function getHandlerDefaultOption($name) { - $handler = new PHPConsoleHandler(array(), $this->connector); + $handler = new PHPConsoleHandler([], $this->connector); $options = $handler->getOptions(); return $options[$name]; } - protected function initLogger($handlerOptions = array(), $level = Logger::DEBUG) + protected function initLogger($handlerOptions = [], $level = Logger::DEBUG) { - return new Logger('test', array( + return new Logger('test', [ new PHPConsoleHandler($handlerOptions, $this->connector, $level), - )); + ]); } public function testInitWithDefaultConnector() @@ -114,33 +114,33 @@ class PHPConsoleHandlerTest extends TestCase public function testInitWithCustomConnector() { - $handler = new PHPConsoleHandler(array(), $this->connector); + $handler = new PHPConsoleHandler([], $this->connector); $this->assertEquals(spl_object_hash($this->connector), spl_object_hash($handler->getConnector())); } public function testDebug() { $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with($this->equalTo('test')); - $this->initLogger()->addDebug('test'); + $this->initLogger()->debug('test'); } public function testDebugContextInMessage() { $message = 'test'; $tag = 'tag'; - $context = array($tag, 'custom' => mt_rand()); + $context = [$tag, 'custom' => mt_rand()]; $expectedMessage = $message . ' ' . json_encode(array_slice($context, 1)); $this->debugDispatcher->expects($this->once())->method('dispatchDebug')->with( $this->equalTo($expectedMessage), $this->equalTo($tag) ); - $this->initLogger()->addDebug($message, $context); + $this->initLogger()->debug($message, $context); } public function testDebugTags($tagsContextKeys = null) { $expectedTags = mt_rand(); - $logger = $this->initLogger($tagsContextKeys ? array('debugTagsKeysInContext' => $tagsContextKeys) : array()); + $logger = $this->initLogger($tagsContextKeys ? ['debugTagsKeysInContext' => $tagsContextKeys] : []); if (!$tagsContextKeys) { $tagsContextKeys = $this->getHandlerDefaultOption('debugTagsKeysInContext'); } @@ -151,7 +151,7 @@ class PHPConsoleHandlerTest extends TestCase $this->equalTo($expectedTags) ); $this->connector->setDebugDispatcher($debugDispatcher); - $logger->addDebug('test', array($key => $expectedTags)); + $logger->debug('test', [$key => $expectedTags]); } } @@ -168,8 +168,8 @@ class PHPConsoleHandlerTest extends TestCase $this->equalTo($line), $classesPartialsTraceIgnore ?: $this->equalTo($this->getHandlerDefaultOption('classesPartialsTraceIgnore')) ); - $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? array('classesPartialsTraceIgnore' => $classesPartialsTraceIgnore) : array()), false); - $errorHandler->registerErrorHandler(array(), false, E_USER_WARNING); + $errorHandler = ErrorHandler::register($this->initLogger($classesPartialsTraceIgnore ? ['classesPartialsTraceIgnore' => $classesPartialsTraceIgnore] : []), false); + $errorHandler->registerErrorHandler([], false, E_USER_WARNING); $errorHandler->handleError($code, $message, $file, $line); } @@ -183,7 +183,7 @@ class PHPConsoleHandlerTest extends TestCase $handler->log( \Psr\Log\LogLevel::ERROR, sprintf('Uncaught Exception %s: "%s" at %s line %s', get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()), - array('exception' => $e) + ['exception' => $e] ); } @@ -192,45 +192,45 @@ class PHPConsoleHandlerTest extends TestCase */ public function testWrongOptionsThrowsException() { - new PHPConsoleHandler(array('xxx' => 1)); + new PHPConsoleHandler(['xxx' => 1]); } public function testOptionEnabled() { $this->debugDispatcher->expects($this->never())->method('dispatchDebug'); - $this->initLogger(array('enabled' => false))->addDebug('test'); + $this->initLogger(['enabled' => false])->debug('test'); } public function testOptionClassesPartialsTraceIgnore() { - $this->testError(array('Class', 'Namespace\\')); + $this->testError(['Class', 'Namespace\\']); } public function testOptionDebugTagsKeysInContext() { - $this->testDebugTags(array('key1', 'key2')); + $this->testDebugTags(['key1', 'key2']); } public function testOptionUseOwnErrorsAndExceptionsHandler() { - $this->initLogger(array('useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true)); - $this->assertEquals(array(Handler::getInstance(), 'handleError'), set_error_handler(function () { + $this->initLogger(['useOwnErrorsHandler' => true, 'useOwnExceptionsHandler' => true]); + $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleError'], set_error_handler(function () { })); - $this->assertEquals(array(Handler::getInstance(), 'handleException'), set_exception_handler(function () { + $this->assertEquals([VendorPhpConsoleHandler::getInstance(), 'handleException'], set_exception_handler(function () { })); } public static function provideConnectorMethodsOptionsSets() { - return array( - array('sourcesBasePath', 'setSourcesBasePath', __DIR__), - array('serverEncoding', 'setServerEncoding', 'cp1251'), - array('password', 'setPassword', '******'), - array('enableSslOnlyMode', 'enableSslOnlyMode', true, false), - array('ipMasks', 'setAllowedIpMasks', array('127.0.0.*')), - array('headersLimit', 'setHeadersLimit', 2500), - array('enableEvalListener', 'startEvalRequestsListener', true, false), - ); + return [ + ['sourcesBasePath', 'setSourcesBasePath', __DIR__], + ['serverEncoding', 'setServerEncoding', 'cp1251'], + ['password', 'setPassword', '******'], + ['enableSslOnlyMode', 'enableSslOnlyMode', true, false], + ['ipMasks', 'setAllowedIpMasks', ['127.0.0.*']], + ['headersLimit', 'setHeadersLimit', 2500], + ['enableEvalListener', 'startEvalRequestsListener', true, false], + ]; } /** @@ -242,24 +242,24 @@ class PHPConsoleHandlerTest extends TestCase if ($isArgument) { $expectCall->with($value); } - new PHPConsoleHandler(array($option => $value), $this->connector); + new PHPConsoleHandler([$option => $value], $this->connector); } public function testOptionDetectDumpTraceAndSource() { - new PHPConsoleHandler(array('detectDumpTraceAndSource' => true), $this->connector); + new PHPConsoleHandler(['detectDumpTraceAndSource' => true], $this->connector); $this->assertTrue($this->connector->getDebugDispatcher()->detectTraceAndSource); } public static function provideDumperOptionsValues() { - return array( - array('dumperLevelLimit', 'levelLimit', 1001), - array('dumperItemsCountLimit', 'itemsCountLimit', 1002), - array('dumperItemSizeLimit', 'itemSizeLimit', 1003), - array('dumperDumpSizeLimit', 'dumpSizeLimit', 1004), - array('dumperDetectCallbacks', 'detectCallbacks', true), - ); + return [ + ['dumperLevelLimit', 'levelLimit', 1001], + ['dumperItemsCountLimit', 'itemsCountLimit', 1002], + ['dumperItemSizeLimit', 'itemSizeLimit', 1003], + ['dumperDumpSizeLimit', 'dumpSizeLimit', 1004], + ['dumperDetectCallbacks', 'detectCallbacks', true], + ]; } /** @@ -267,7 +267,7 @@ class PHPConsoleHandlerTest extends TestCase */ public function testDumperOptions($option, $dumperProperty, $value) { - new PHPConsoleHandler(array($option => $value), $this->connector); + new PHPConsoleHandler([$option => $value], $this->connector); $this->assertEquals($value, $this->connector->getDumper()->$dumperProperty); } } diff --git a/tests/Monolog/Handler/ProcessHandlerTest.php b/tests/Monolog/Handler/ProcessHandlerTest.php new file mode 100644 index 0000000..dc2a427 --- /dev/null +++ b/tests/Monolog/Handler/ProcessHandlerTest.php @@ -0,0 +1,195 @@ +<?php declare(strict_types=1); + +/* + * This file is part of the Monolog package. + * + * (c) Jordi Boggiano <j.boggiano@seld.be> + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Monolog\Handler; + +use Monolog\Test\TestCase; +use Monolog\Logger; + +class ProcessHandlerTest extends TestCase +{ + /** + * Dummy command to be used by tests that should not fail due to the command. + * + * @var string + */ + const DUMMY_COMMAND = 'echo'; + + /** + * @covers Monolog\Handler\ProcessHandler::__construct + * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand + * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd + * @covers Monolog\Handler\ProcessHandler::write + * @covers Monolog\Handler\ProcessHandler::ensureProcessIsStarted + * @covers Monolog\Handler\ProcessHandler::startProcess + * @covers Monolog\Handler\ProcessHandler::handleStartupErrors + */ + public function testWriteOpensProcessAndWritesToStdInOfProcess() + { + $fixtures = [ + 'chuck norris', + 'foobar1337', + ]; + + $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); + $mockBuilder->setMethods(['writeProcessInput']); + // using echo as command, as it is most probably available + $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]); + + $handler = $mockBuilder->getMock(); + + $handler->expects($this->exactly(2)) + ->method('writeProcessInput') + ->withConsecutive($this->stringContains($fixtures[0]), $this->stringContains($fixtures[1])); + + /** @var ProcessHandler $handler */ + $handler->handle($this->getRecord(Logger::WARNING, $fixtures[0])); + $handler->handle($this->getRecord(Logger::ERROR, $fixtures[1])); + } + + /** + * Data provider for invalid commands. + * + * @return array + */ + public function invalidCommandProvider() + { + return [ + [1337, 'TypeError'], + ['', 'InvalidArgumentException'], + [null, 'TypeError'], + [fopen('php://input', 'r'), 'TypeError'], + ]; + } + + /** + * @dataProvider invalidCommandProvider + * @param mixed $invalidCommand + * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCommand + */ + public function testConstructWithInvalidCommandThrowsInvalidArgumentException($invalidCommand, $expectedExcep) + { + $this->setExpectedException($expectedExcep); + new ProcessHandler($invalidCommand, Logger::DEBUG); + } + + /** + * Data provider for invalid CWDs. + * + * @return array + */ + public function invalidCwdProvider() + { + return [ + [1337, 'TypeError'], + ['', 'InvalidArgumentException'], + [fopen('php://input', 'r'), 'TypeError'], + ]; + } + + /** + * @dataProvider invalidCwdProvider + * @param mixed $invalidCwd + * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd + */ + public function testConstructWithInvalidCwdThrowsInvalidArgumentException($invalidCwd, $expectedExcep) + { + $this->setExpectedException($expectedExcep); + new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, $invalidCwd); + } + + /** + * @covers Monolog\Handler\ProcessHandler::__construct + * @covers Monolog\Handler\ProcessHandler::guardAgainstInvalidCwd + */ + public function testConstructWithValidCwdWorks() + { + $handler = new ProcessHandler(self::DUMMY_COMMAND, Logger::DEBUG, true, sys_get_temp_dir()); + $this->assertInstanceOf( + 'Monolog\Handler\ProcessHandler', + $handler, + 'Constructed handler is not a ProcessHandler.' + ); + } + + /** + * @covers Monolog\Handler\ProcessHandler::handleStartupErrors + */ + public function testStartupWithFailingToSelectErrorStreamThrowsUnexpectedValueException() + { + $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); + $mockBuilder->setMethods(['selectErrorStream']); + $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]); + + $handler = $mockBuilder->getMock(); + + $handler->expects($this->once()) + ->method('selectErrorStream') + ->will($this->returnValue(false)); + + $this->setExpectedException('\UnexpectedValueException'); + /** @var ProcessHandler $handler */ + $handler->handle($this->getRecord(Logger::WARNING, 'stream failing, whoops')); + } + + /** + * @covers Monolog\Handler\ProcessHandler::handleStartupErrors + * @covers Monolog\Handler\ProcessHandler::selectErrorStream + */ + public function testStartupWithErrorsThrowsUnexpectedValueException() + { + $handler = new ProcessHandler('>&2 echo "some fake error message"'); + $this->setExpectedException('\UnexpectedValueException'); + $handler->handle($this->getRecord(Logger::WARNING, 'some warning in the house')); + } + + /** + * @covers Monolog\Handler\ProcessHandler::write + */ + public function testWritingWithErrorsOnStdOutOfProcessThrowsInvalidArgumentException() + { + $mockBuilder = $this->getMockBuilder('Monolog\Handler\ProcessHandler'); + $mockBuilder->setMethods(['readProcessErrors']); + // using echo as command, as it is most probably available + $mockBuilder->setConstructorArgs([self::DUMMY_COMMAND]); + + $handler = $mockBuilder->getMock(); + + $handler->expects($this->exactly(2)) + ->method('readProcessErrors') + ->willReturnOnConsecutiveCalls('', $this->returnValue('some fake error message here')); + + $this->setExpectedException('\UnexpectedValueException'); + /** @var ProcessHandler $handler */ + $handler->handle($this->getRecord(Logger::WARNING, 'some test stuff')); + } + + /** + * @covers Monolog\Handler\ProcessHandler::close + */ + public function testCloseClosesProcess() + { + $class = new \ReflectionClass('Monolog\Handler\ProcessHandler'); + $property = $class->getProperty('process'); + $property->setAccessible(true); + + $handler = new ProcessHandler(self::DUMMY_COMMAND); + $handler->handle($this->getRecord(Logger::WARNING, '21 is only the half truth')); + + $process = $property->getValue($handler); + $this->assertTrue(is_resource($process), 'Process is not running although it should.'); + + $handler->close(); + + $process = $property->getValue($handler); + $this->assertFalse(is_resource($process), 'Process is still running although it should not.'); + } +} diff --git a/tests/Monolog/Handler/PsrHandlerTest.php b/tests/Monolog/Handler/PsrHandlerTest.php index 64eaab1..e371512 100644 --- a/tests/Monolog/Handler/PsrHandlerTest.php +++ b/tests/Monolog/Handler/PsrHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -21,11 +21,11 @@ class PsrHandlerTest extends TestCase { public function logLevelProvider() { - $levels = array(); + $levels = []; $monologLogger = new Logger(''); foreach ($monologLogger->getLevels() as $levelName => $level) { - $levels[] = array($levelName, $level); + $levels[] = [$levelName, $level]; } return $levels; @@ -37,14 +37,14 @@ class PsrHandlerTest extends TestCase public function testHandlesAllLevels($levelName, $level) { $message = 'Hello, world! ' . $level; - $context = array('foo' => 'bar', 'level' => $level); + $context = ['foo' => 'bar', 'level' => $level]; - $psrLogger = $this->getMock('Psr\Log\NullLogger'); + $psrLogger = $this->createMock('Psr\Log\NullLogger'); $psrLogger->expects($this->once()) ->method('log') ->with(strtolower($levelName), $message, $context); $handler = new PsrHandler($psrLogger); - $handler->handle(array('level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context)); + $handler->handle(['level' => $level, 'level_name' => $levelName, 'message' => $message, 'context' => $context]); } } diff --git a/tests/Monolog/Handler/PushoverHandlerTest.php b/tests/Monolog/Handler/PushoverHandlerTest.php index 56df474..6a295c9 100644 --- a/tests/Monolog/Handler/PushoverHandlerTest.php +++ b/tests/Monolog/Handler/PushoverHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -103,7 +103,7 @@ class PushoverHandlerTest extends TestCase public function testWriteToMultipleUsers() { - $this->createHandler('myToken', array('userA', 'userB')); + $this->createHandler('myToken', ['userA', 'userB']); $this->handler->handle($this->getRecord(Logger::EMERGENCY, 'test1')); fseek($this->res, 0); $content = fread($this->res, 1024); @@ -114,15 +114,14 @@ class PushoverHandlerTest extends TestCase private function createHandler($token = 'myToken', $user = 'myUser', $title = 'Monolog') { - $constructorArgs = array($token, $user, $title); + $constructorArgs = [$token, $user, $title]; $this->res = fopen('php://memory', 'a'); - $this->handler = $this->getMock( - '\Monolog\Handler\PushoverHandler', - array('fsockopen', 'streamSetTimeout', 'closeSocket'), - $constructorArgs - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\PushoverHandler') + ->setConstructorArgs($constructorArgs) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); - $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); diff --git a/tests/Monolog/Handler/RavenHandlerTest.php b/tests/Monolog/Handler/RavenHandlerTest.php index 26d212b..082042f 100644 --- a/tests/Monolog/Handler/RavenHandlerTest.php +++ b/tests/Monolog/Handler/RavenHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,19 +11,24 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\LineFormatter; +use Raven_Client; class RavenHandlerTest extends TestCase { public function setUp() { if (!class_exists('Raven_Client')) { - $this->markTestSkipped('raven/raven not installed'); + $this->markTestSkipped('sentry/sentry not installed'); } - require_once __DIR__ . '/MockRavenClient.php'; + if (version_compare(Raven_Client::VERSION, '0.16.0', '>=')) { + require_once __DIR__ . '/MockRavenClient-gte-0-16-0.php'; + } else { + require_once __DIR__ . '/MockRavenClient.php'; + } } /** @@ -78,8 +83,8 @@ class RavenHandlerTest extends TestCase $ravenClient = $this->getRavenClient(); $handler = $this->getHandler($ravenClient); - $tags = array(1, 2, 'foo'); - $record = $this->getRecord(Logger::INFO, 'test', array('tags' => $tags)); + $tags = [1, 2, 'foo']; + $record = $this->getRecord(Logger::INFO, 'test', ['tags' => $tags]); $handler->handle($record); $this->assertEquals($tags, $ravenClient->lastData['tags']); @@ -93,7 +98,7 @@ class RavenHandlerTest extends TestCase $checksum = '098f6bcd4621d373cade4e832627b4f6'; $release = '05a671c66aefea124cc08b76ea6d30bb'; $eventId = '31423'; - $record = $this->getRecord(Logger::INFO, 'test', array('checksum' => $checksum, 'release' => $release, 'event_id' => $eventId)); + $record = $this->getRecord(Logger::INFO, 'test', ['checksum' => $checksum, 'release' => $release, 'event_id' => $eventId]); $handler->handle($record); $this->assertEquals($checksum, $ravenClient->lastData['checksum']); @@ -106,8 +111,8 @@ class RavenHandlerTest extends TestCase $ravenClient = $this->getRavenClient(); $handler = $this->getHandler($ravenClient); - $fingerprint = array('{{ default }}', 'other value'); - $record = $this->getRecord(Logger::INFO, 'test', array('fingerprint' => $fingerprint)); + $fingerprint = ['{{ default }}', 'other value']; + $record = $this->getRecord(Logger::INFO, 'test', ['fingerprint' => $fingerprint]); $handler->handle($record); $this->assertEquals($fingerprint, $ravenClient->lastData['fingerprint']); @@ -121,14 +126,14 @@ class RavenHandlerTest extends TestCase $recordWithNoContext = $this->getRecord(Logger::INFO, 'test with default user context'); // set user context 'externally' - $user = array( + $user = [ 'id' => '123', 'email' => 'test@test.com', - ); + ]; - $recordWithContext = $this->getRecord(Logger::INFO, 'test', array('user' => $user)); + $recordWithContext = $this->getRecord(Logger::INFO, 'test', ['user' => $user]); - $ravenClient->user_context(array('id' => 'test_user_id')); + $ravenClient->user_context(['id' => 'test_user_id']); // handle context $handler->handle($recordWithContext); $this->assertEquals($user, $ravenClient->lastData['user']); @@ -156,7 +161,7 @@ class RavenHandlerTest extends TestCase try { $this->methodThatThrowsAnException(); } catch (\Exception $e) { - $record = $this->getRecord(Logger::ERROR, $e->getMessage(), array('exception' => $e)); + $record = $this->getRecord(Logger::ERROR, $e->getMessage(), ['exception' => $e]); $handler->handle($record); } @@ -169,10 +174,10 @@ class RavenHandlerTest extends TestCase $records[] = $this->getRecord(Logger::WARNING, 'warning'); $records[] = $this->getRecord(Logger::WARNING, 'warning'); - $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $logFormatter->expects($this->once())->method('formatBatch'); - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $formatter->expects($this->once())->method('format')->with($this->callback(function ($record) { return $record['level'] == 400; })); @@ -185,13 +190,16 @@ class RavenHandlerTest extends TestCase public function testHandleBatchDoNothingIfRecordsAreBelowLevel() { - $records = array( + $records = [ $this->getRecord(Logger::DEBUG, 'debug message 1'), $this->getRecord(Logger::DEBUG, 'debug message 2'), $this->getRecord(Logger::INFO, 'information'), - ); + ]; - $handler = $this->getMock('Monolog\Handler\RavenHandler', null, array($this->getRavenClient())); + $handler = $this->getMockBuilder('Monolog\Handler\RavenHandler') + ->setMethods(['handle']) + ->setConstructorArgs([$this->getRavenClient()]) + ->getMock(); $handler->expects($this->never())->method('handle'); $handler->setLevel(Logger::ERROR); $handler->handleBatch($records); @@ -209,10 +217,10 @@ class RavenHandlerTest extends TestCase $this->getRecord(Logger::INFO, 'information 2'), ); - $logFormatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $logFormatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $logFormatter->expects($this->once())->method('formatBatch'); - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $formatter->expects($this->once())->method('format')->with($this->callback(function ($record) use ($records) { return $record['message'] == 'error 1'; })); @@ -243,7 +251,7 @@ class RavenHandlerTest extends TestCase $this->assertEquals($release, $ravenClient->lastData['release']); $localRelease = 'v41.41.41'; - $record = $this->getRecord(Logger::INFO, 'test', array('release' => $localRelease)); + $record = $this->getRecord(Logger::INFO, 'test', ['release' => $localRelease]); $handler->handle($record); $this->assertEquals($localRelease, $ravenClient->lastData['release']); } diff --git a/tests/Monolog/Handler/RedisHandlerTest.php b/tests/Monolog/Handler/RedisHandlerTest.php index 689d527..a0260e1 100644 --- a/tests/Monolog/Handler/RedisHandlerTest.php +++ b/tests/Monolog/Handler/RedisHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\LineFormatter; @@ -27,26 +27,30 @@ class RedisHandlerTest extends TestCase public function testConstructorShouldWorkWithPredis() { - $redis = $this->getMock('Predis\Client'); + $redis = $this->createMock('Predis\Client'); $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key')); } public function testConstructorShouldWorkWithRedis() { - $redis = $this->getMock('Redis'); + if (!class_exists('Redis')) { + $this->markTestSkipped('The redis ext is required to run this test'); + } + + $redis = $this->createMock('Redis'); $this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key')); } public function testPredisHandle() { - $redis = $this->getMock('Predis\Client', array('rpush')); + $redis = $this->createPartialMock('Predis\Client', ['rpush']); // Predis\Client uses rpush $redis->expects($this->once()) ->method('rpush') ->with('key', 'test'); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); @@ -55,14 +59,18 @@ class RedisHandlerTest extends TestCase public function testRedisHandle() { - $redis = $this->getMock('Redis', array('rpush')); + if (!class_exists('Redis')) { + $this->markTestSkipped('The redis ext is required to run this test'); + } + + $redis = $this->createPartialMock('Redis', ['rpush']); // Redis uses rPush $redis->expects($this->once()) - ->method('rPush') + ->method('rpush') ->with('key', 'test'); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key'); $handler->setFormatter(new LineFormatter("%message%")); @@ -71,7 +79,11 @@ class RedisHandlerTest extends TestCase public function testRedisHandleCapped() { - $redis = $this->getMock('Redis', array('multi', 'rpush', 'ltrim', 'exec')); + if (!class_exists('Redis')) { + $this->markTestSkipped('The redis ext is required to run this test'); + } + + $redis = $this->createPartialMock('Redis', ['multi', 'rpush', 'ltrim', 'exec']); // Redis uses multi $redis->expects($this->once()) @@ -90,7 +102,7 @@ class RedisHandlerTest extends TestCase ->method('exec') ->will($this->returnSelf()); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); $handler->setFormatter(new LineFormatter("%message%")); @@ -99,9 +111,9 @@ class RedisHandlerTest extends TestCase public function testPredisHandleCapped() { - $redis = $this->getMock('Predis\Client', array('transaction')); + $redis = $this->createPartialMock('Predis\Client', ['transaction']); - $redisTransaction = $this->getMock('Predis\Client', array('rpush', 'ltrim')); + $redisTransaction = $this->createPartialMock('Predis\Client', ['rpush', 'ltrim']); $redisTransaction->expects($this->once()) ->method('rpush') @@ -118,7 +130,7 @@ class RedisHandlerTest extends TestCase $cb($redisTransaction); })); - $record = $this->getRecord(Logger::WARNING, 'test', array('data' => new \stdClass, 'foo' => 34)); + $record = $this->getRecord(Logger::WARNING, 'test', ['data' => new \stdClass, 'foo' => 34]); $handler = new RedisHandler($redis, 'key', Logger::DEBUG, true, 10); $handler->setFormatter(new LineFormatter("%message%")); diff --git a/tests/Monolog/Handler/RollbarHandlerTest.php b/tests/Monolog/Handler/RollbarHandlerTest.php index f302e91..89fc9cb 100644 --- a/tests/Monolog/Handler/RollbarHandlerTest.php +++ b/tests/Monolog/Handler/RollbarHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Exception; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use PHPUnit_Framework_MockObject_MockObject as MockObject; @@ -32,7 +32,7 @@ class RollbarHandlerTest extends TestCase /** * @var array */ - public $reportedExceptionArguments = null; + private $reportedExceptionArguments = null; protected function setUp() { @@ -60,25 +60,23 @@ class RollbarHandlerTest extends TestCase ->setMethods(array('report_message', 'report_exception', 'flush')) ->getMock(); - $that = $this; - $this->rollbarNotifier ->expects($this->any()) ->method('report_exception') - ->willReturnCallback(function ($exception, $context, $payload) use ($that) { - $that->reportedExceptionArguments = compact('exception', 'context', 'payload'); + ->willReturnCallback(function ($exception, $context, $payload) { + $this->reportedExceptionArguments = compact('exception', 'context', 'payload'); }); } - private function createHandler() + private function createHandler(): RollbarHandler { return new RollbarHandler($this->rollbarNotifier, Logger::DEBUG); } - private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null) + private function createExceptionRecord($level = Logger::DEBUG, $message = 'test', $exception = null): array { - return $this->getRecord($level, $message, array( - 'exception' => $exception ?: new Exception() - )); + return $this->getRecord($level, $message, [ + 'exception' => $exception ?: new Exception(), + ]); } } diff --git a/tests/Monolog/Handler/RotatingFileHandlerTest.php b/tests/Monolog/Handler/RotatingFileHandlerTest.php index f1feb22..f2d61db 100644 --- a/tests/Monolog/Handler/RotatingFileHandlerTest.php +++ b/tests/Monolog/Handler/RotatingFileHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,21 +11,15 @@ namespace Monolog\Handler; -use Monolog\TestCase; -use PHPUnit_Framework_Error_Deprecated; +use InvalidArgumentException; +use Monolog\Test\TestCase; /** * @covers Monolog\Handler\RotatingFileHandler */ class RotatingFileHandlerTest extends TestCase { - /** - * This var should be private but then the anonymous function - * in the `setUp` method won't be able to set it. `$this` cant't - * be used in the anonymous function in `setUp` because PHP 5.3 - * does not support it. - */ - public $lastError; + private $lastError; public function setUp() { @@ -35,13 +29,11 @@ class RotatingFileHandlerTest extends TestCase $this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.'); } $this->lastError = null; - $self = $this; - // workaround with &$self used for PHP 5.3 - set_error_handler(function($code, $message) use (&$self) { - $self->lastError = array( + set_error_handler(function ($code, $message) { + $this->lastError = [ 'code' => $code, 'message' => $message, - ); + ]; }); } @@ -107,32 +99,32 @@ class RotatingFileHandlerTest extends TestCase public function rotationTests() { $now = time(); - $dayCallback = function($ago) use ($now) { + $dayCallback = function ($ago) use ($now) { return $now + 86400 * $ago; }; $monthCallback = function($ago) { - return gmmktime(0, 0, 0, date('n') + $ago, 1, date('Y')); + return gmmktime(0, 0, 0, (int) (date('n') + $ago), 1, (int) date('Y')); }; $yearCallback = function($ago) { - return gmmktime(0, 0, 0, 1, 1, date('Y') + $ago); + return gmmktime(0, 0, 0, 1, 1, (int) (date('Y') + $ago)); }; - return array( + return [ 'Rotation is triggered when the file of the current day is not present' - => array(true, RotatingFileHandler::FILE_PER_DAY, $dayCallback), + => [true, RotatingFileHandler::FILE_PER_DAY, $dayCallback], 'Rotation is not triggered when the file of the current day is already present' - => array(false, RotatingFileHandler::FILE_PER_DAY, $dayCallback), + => [false, RotatingFileHandler::FILE_PER_DAY, $dayCallback], 'Rotation is triggered when the file of the current month is not present' - => array(true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), + => [true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback], 'Rotation is not triggered when the file of the current month is already present' - => array(false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback), + => [false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback], 'Rotation is triggered when the file of the current year is not present' - => array(true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), + => [true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback], 'Rotation is not triggered when the file of the current year is already present' - => array(false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback), - ); + => [false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback], + ]; } /** @@ -141,26 +133,38 @@ class RotatingFileHandlerTest extends TestCase public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid) { $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2); - $handler->setFilenameFormat('{filename}-{date}', $dateFormat); if (!$valid) { - $this->assertErrorWasTriggered( - E_USER_DEPRECATED, - 'Invalid date format - format must be one of RotatingFileHandler::FILE_PER_DAY ("Y-m-d"), '. - 'RotatingFileHandler::FILE_PER_MONTH ("Y-m") or RotatingFileHandler::FILE_PER_YEAR ("Y"), '. - 'or you can set one of the date formats using slashes, underscores and/or dots instead of dashes.' - ); + $this->setExpectedExceptionRegExp(InvalidArgumentException::class, '~^Invalid date format~'); } + $handler->setFilenameFormat('{filename}-{date}', $dateFormat); + $this->assertTrue(true); } public function dateFormatProvider() { - return array( - array(RotatingFileHandler::FILE_PER_DAY, true), - array(RotatingFileHandler::FILE_PER_MONTH, true), - array(RotatingFileHandler::FILE_PER_YEAR, true), - array('m-d-Y', false), - array('Y-m-d-h-i', false) - ); + return [ + [RotatingFileHandler::FILE_PER_DAY, true], + [RotatingFileHandler::FILE_PER_MONTH, true], + [RotatingFileHandler::FILE_PER_YEAR, true], + ['Y/m/d', true], + ['Y.m.d', true], + ['Y_m_d', true], + ['Ymd', true], + ['Ym/d', true], + ['Y/m', true], + ['Ym', true], + ['Y.m', true], + ['Y_m', true], + ['Y/md', true], + ['', false], + ['m-d-Y', false], + ['Y-m-d-h-i', false], + ['Y-', false], + ['Y-m-', false], + ['Y--', false], + ['m-d', false], + ['Y-d', false], + ]; } /** @@ -169,26 +173,24 @@ class RotatingFileHandlerTest extends TestCase public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid) { $handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2); - $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY); if (!$valid) { - $this->assertErrorWasTriggered( - E_USER_DEPRECATED, - 'Invalid filename format - format should contain at least `{date}`, because otherwise rotating is impossible.' - ); + $this->setExpectedExceptionRegExp(InvalidArgumentException::class, '~^Invalid filename format~'); } + + $handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY); } public function filenameFormatProvider() { - return array( - array('{filename}', false), - array('{filename}-{date}', true), - array('{date}', true), - array('foobar-{date}', true), - array('foo-{date}-bar', true), - array('{date}-foobar', true), - array('foobar', false), - ); + return [ + ['{filename}', false], + ['{filename}-{date}', true], + ['{date}', true], + ['foobar-{date}', true], + ['foo-{date}-bar', true], + ['{date}-foobar', true], + ['foobar', false], + ]; } public function testReuseCurrentFile() diff --git a/tests/Monolog/Handler/SamplingHandlerTest.php b/tests/Monolog/Handler/SamplingHandlerTest.php index b354cee..90f5c9b 100644 --- a/tests/Monolog/Handler/SamplingHandlerTest.php +++ b/tests/Monolog/Handler/SamplingHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; /** * @covers Monolog\Handler\SamplingHandler::handle diff --git a/tests/Monolog/Handler/Slack/SlackRecordTest.php b/tests/Monolog/Handler/Slack/SlackRecordTest.php index e1aa96d..aa5787f 100644 --- a/tests/Monolog/Handler/Slack/SlackRecordTest.php +++ b/tests/Monolog/Handler/Slack/SlackRecordTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler\Slack; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; /** * @coversDefaultClass Monolog\Handler\Slack\SlackRecord @@ -42,8 +42,8 @@ class SlackRecordTest extends TestCase /** * @dataProvider dataGetAttachmentColor - * @param int $logLevel - * @param string $expectedColour RGB hex color or name of Slack color + * @param int $logLevel + * @param string $expectedColour RGB hex color or name of Slack color * @covers ::getAttachmentColor */ public function testGetAttachmentColor($logLevel, $expectedColour) @@ -88,7 +88,7 @@ class SlackRecordTest extends TestCase array(array(), '[]'), array($multipleDimensions, json_encode($multipleDimensions, $jsonPrettyPrintFlag)), array($numericKeys, json_encode($numericKeys, $jsonPrettyPrintFlag)), - array($singleDimension, json_encode($singleDimension)) + array($singleDimension, json_encode($singleDimension)), ); } @@ -172,17 +172,21 @@ class SlackRecordTest extends TestCase public function testTextEqualsFormatterOutput() { - $formatter = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $formatter ->expects($this->any()) ->method('format') - ->will($this->returnCallback(function ($record) { return $record['message'] . 'test'; })); + ->will($this->returnCallback(function ($record) { + return $record['message'] . 'test'; + })); - $formatter2 = $this->getMock('Monolog\\Formatter\\FormatterInterface'); + $formatter2 = $this->createMock('Monolog\\Formatter\\FormatterInterface'); $formatter2 ->expects($this->any()) ->method('format') - ->will($this->returnCallback(function ($record) { return $record['message'] . 'test1'; })); + ->will($this->returnCallback(function ($record) { + return $record['message'] . 'test1'; + })); $message = 'Test message'; $record = new SlackRecord(null, null, false, null, false, false, array(), $formatter); @@ -268,13 +272,13 @@ class SlackRecordTest extends TestCase array( 'title' => 'Extra', 'value' => sprintf('```%s```', json_encode($extra, $this->jsonPrettyPrintFlag)), - 'short' => false + 'short' => false, ), array( 'title' => 'Context', 'value' => sprintf('```%s```', json_encode($context, $this->jsonPrettyPrintFlag)), - 'short' => false - ) + 'short' => false, + ), ), $attachment['fields'] ); @@ -296,7 +300,7 @@ class SlackRecordTest extends TestCase array(array( 'title' => 'Level', 'value' => $levelName, - 'short' => false + 'short' => false, )), $attachment['fields'] ); @@ -322,13 +326,13 @@ class SlackRecordTest extends TestCase array( 'title' => 'tags', 'value' => sprintf('```%s```', json_encode($extra['tags'])), - 'short' => false + 'short' => false, ), array( 'title' => 'test', 'value' => $context['test'], - 'short' => false - ) + 'short' => false, + ), ); $attachment = $data['attachments'][0]; @@ -370,12 +374,12 @@ class SlackRecordTest extends TestCase array( 'title' => 'info', 'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), $this->jsonPrettyPrintFlag)), - 'short' => false + 'short' => false, ), array( 'title' => 'tags', 'value' => sprintf('```%s```', json_encode(array('web'))), - 'short' => false + 'short' => false, ), ); diff --git a/tests/Monolog/Handler/SlackHandlerTest.php b/tests/Monolog/Handler/SlackHandlerTest.php index b12b01f..e8abd15 100644 --- a/tests/Monolog/Handler/SlackHandlerTest.php +++ b/tests/Monolog/Handler/SlackHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\LineFormatter; use Monolog\Handler\Slack\SlackRecord; @@ -46,7 +46,7 @@ class SlackHandlerTest extends TestCase fseek($this->res, 0); $content = fread($this->res, 1024); - $this->assertRegexp('/POST \/api\/chat.postMessage HTTP\/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application\/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n/', $content); + $this->assertRegexp('{POST /api/chat.postMessage HTTP/1.1\\r\\nHost: slack.com\\r\\nContent-Type: application/x-www-form-urlencoded\\r\\nContent-Length: \d{2,4}\\r\\n\\r\\n}', $content); } public function testWriteContent() @@ -128,15 +128,14 @@ class SlackHandlerTest extends TestCase private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false) { - $constructorArgs = array($token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra); + $constructorArgs = [$token, $channel, $username, $useAttachment, $iconEmoji, Logger::DEBUG, true, $useShortAttachment, $includeExtra]; $this->res = fopen('php://memory', 'a'); - $this->handler = $this->getMock( - '\Monolog\Handler\SlackHandler', - array('fsockopen', 'streamSetTimeout', 'closeSocket'), - $constructorArgs - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\SlackHandler') + ->setConstructorArgs($constructorArgs) + ->setMethods(['fsockopen', 'streamSetTimeout', 'closeSocket']) + ->getMock(); - $reflectionProperty = new \ReflectionProperty('\Monolog\Handler\SocketHandler', 'connectionString'); + $reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString'); $reflectionProperty->setAccessible(true); $reflectionProperty->setValue($this->handler, 'localhost:1234'); diff --git a/tests/Monolog/Handler/SlackWebhookHandlerTest.php b/tests/Monolog/Handler/SlackWebhookHandlerTest.php index c9229e2..8ce7210 100644 --- a/tests/Monolog/Handler/SlackWebhookHandlerTest.php +++ b/tests/Monolog/Handler/SlackWebhookHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; use Monolog\Formatter\LineFormatter; use Monolog\Handler\Slack\SlackRecord; diff --git a/tests/Monolog/Handler/SlackbotHandlerTest.php b/tests/Monolog/Handler/SlackbotHandlerTest.php index b1b02bd..340c4c6 100644 --- a/tests/Monolog/Handler/SlackbotHandlerTest.php +++ b/tests/Monolog/Handler/SlackbotHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** diff --git a/tests/Monolog/Handler/SocketHandlerTest.php b/tests/Monolog/Handler/SocketHandlerTest.php index 1f9c1f2..c0080e8 100644 --- a/tests/Monolog/Handler/SocketHandlerTest.php +++ b/tests/Monolog/Handler/SocketHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -88,7 +88,7 @@ class SocketHandlerTest extends TestCase */ public function testExceptionIsThrownOnFsockopenError() { - $this->setMockHandler(array('fsockopen')); + $this->setMockHandler(['fsockopen']); $this->handler->expects($this->once()) ->method('fsockopen') ->will($this->returnValue(false)); @@ -100,7 +100,7 @@ class SocketHandlerTest extends TestCase */ public function testExceptionIsThrownOnPfsockopenError() { - $this->setMockHandler(array('pfsockopen')); + $this->setMockHandler(['pfsockopen']); $this->handler->expects($this->once()) ->method('pfsockopen') ->will($this->returnValue(false)); @@ -113,7 +113,7 @@ class SocketHandlerTest extends TestCase */ public function testExceptionIsThrownIfCannotSetTimeout() { - $this->setMockHandler(array('streamSetTimeout')); + $this->setMockHandler(['streamSetTimeout']); $this->handler->expects($this->once()) ->method('streamSetTimeout') ->will($this->returnValue(false)); @@ -125,13 +125,13 @@ class SocketHandlerTest extends TestCase */ public function testWriteFailsOnIfFwriteReturnsFalse() { - $this->setMockHandler(array('fwrite')); + $this->setMockHandler(['fwrite']); $callback = function ($arg) { - $map = array( + $map = [ 'Hello world' => 6, 'world' => false, - ); + ]; return $map[$arg]; }; @@ -148,13 +148,13 @@ class SocketHandlerTest extends TestCase */ public function testWriteFailsIfStreamTimesOut() { - $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + $this->setMockHandler(['fwrite', 'streamGetMetadata']); $callback = function ($arg) { - $map = array( + $map = [ 'Hello world' => 6, 'world' => 5, - ); + ]; return $map[$arg]; }; @@ -164,7 +164,7 @@ class SocketHandlerTest extends TestCase ->will($this->returnCallback($callback)); $this->handler->expects($this->exactly(1)) ->method('streamGetMetadata') - ->will($this->returnValue(array('timed_out' => true))); + ->will($this->returnValue(['timed_out' => true])); $this->writeRecord('Hello world'); } @@ -174,7 +174,7 @@ class SocketHandlerTest extends TestCase */ public function testWriteFailsOnIncompleteWrite() { - $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + $this->setMockHandler(['fwrite', 'streamGetMetadata']); $res = $this->res; $callback = function ($string) use ($res) { @@ -188,7 +188,7 @@ class SocketHandlerTest extends TestCase ->will($this->returnCallback($callback)); $this->handler->expects($this->exactly(1)) ->method('streamGetMetadata') - ->will($this->returnValue(array('timed_out' => false))); + ->will($this->returnValue(['timed_out' => false])); $this->writeRecord('Hello world'); } @@ -205,13 +205,13 @@ class SocketHandlerTest extends TestCase public function testWriteWithMock() { - $this->setMockHandler(array('fwrite')); + $this->setMockHandler(['fwrite']); $callback = function ($arg) { - $map = array( + $map = [ 'Hello world' => 6, 'world' => 5, - ); + ]; return $map[$arg]; }; @@ -247,7 +247,7 @@ class SocketHandlerTest extends TestCase */ public function testAvoidInfiniteLoopWhenNoDataIsWrittenForAWritingTimeoutSeconds() { - $this->setMockHandler(array('fwrite', 'streamGetMetadata')); + $this->setMockHandler(['fwrite', 'streamGetMetadata']); $this->handler->expects($this->any()) ->method('fwrite') @@ -255,7 +255,7 @@ class SocketHandlerTest extends TestCase $this->handler->expects($this->any()) ->method('streamGetMetadata') - ->will($this->returnValue(array('timed_out' => false))); + ->will($this->returnValue(['timed_out' => false])); $this->handler->setWritingTimeout(1); @@ -273,18 +273,19 @@ class SocketHandlerTest extends TestCase $this->handler->handle($this->getRecord(Logger::WARNING, $string)); } - private function setMockHandler(array $methods = array()) + private function setMockHandler(array $methods = []) { $this->res = fopen('php://memory', 'a'); - $defaultMethods = array('fsockopen', 'pfsockopen', 'streamSetTimeout'); + $defaultMethods = ['fsockopen', 'pfsockopen', 'streamSetTimeout']; $newMethods = array_diff($methods, $defaultMethods); $finalMethods = array_merge($defaultMethods, $newMethods); - $this->handler = $this->getMock( - '\Monolog\Handler\SocketHandler', $finalMethods, array('localhost:1234') - ); + $this->handler = $this->getMockBuilder('Monolog\Handler\SocketHandler') + ->setMethods($finalMethods) + ->setConstructorArgs(['localhost:1234']) + ->getMock(); if (!in_array('fsockopen', $methods)) { $this->handler->expects($this->any()) diff --git a/tests/Monolog/Handler/StreamHandlerTest.php b/tests/Monolog/Handler/StreamHandlerTest.php index 487030f..377e296 100644 --- a/tests/Monolog/Handler/StreamHandlerTest.php +++ b/tests/Monolog/Handler/StreamHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class StreamHandlerTest extends TestCase @@ -51,13 +51,38 @@ class StreamHandlerTest extends TestCase { $handler = new StreamHandler('php://memory'); $handler->handle($this->getRecord(Logger::WARNING, 'test')); - $streamProp = new \ReflectionProperty('Monolog\Handler\StreamHandler', 'stream'); - $streamProp->setAccessible(true); - $handle = $streamProp->getValue($handler); + $stream = $handler->getStream(); - $this->assertTrue(is_resource($handle)); + $this->assertTrue(is_resource($stream)); $handler->close(); - $this->assertFalse(is_resource($handle)); + $this->assertFalse(is_resource($stream)); + } + + /** + * @covers Monolog\Handler\StreamHandler::close + * @covers Monolog\Handler\Handler::__sleep + */ + public function testSerialization() + { + $handler = new StreamHandler('php://memory'); + $handler->handle($this->getRecord(Logger::WARNING, 'testfoo')); + $stream = $handler->getStream(); + + $this->assertTrue(is_resource($stream)); + fseek($stream, 0); + $this->assertContains('testfoo', stream_get_contents($stream)); + $serialized = serialize($handler); + $this->assertFalse(is_resource($stream)); + + $handler = unserialize($serialized); + $handler->handle($this->getRecord(Logger::WARNING, 'testbar')); + $stream = $handler->getStream(); + + $this->assertTrue(is_resource($stream)); + fseek($stream, 0); + $contents = stream_get_contents($stream); + $this->assertNotContains('testfoo', $contents); + $this->assertContains('testbar', $contents); } /** @@ -93,11 +118,11 @@ class StreamHandlerTest extends TestCase public function invalidArgumentProvider() { - return array( - array(1), - array(array()), - array(array('bogus://url')), - ); + return [ + [1], + [[]], + [['bogus://url']], + ]; } /** diff --git a/tests/Monolog/Handler/SwiftMailerHandlerTest.php b/tests/Monolog/Handler/SwiftMailerHandlerTest.php index 1d62940..3c77127 100644 --- a/tests/Monolog/Handler/SwiftMailerHandlerTest.php +++ b/tests/Monolog/Handler/SwiftMailerHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -12,7 +12,7 @@ namespace Monolog\Handler; use Monolog\Logger; -use Monolog\TestCase; +use Monolog\Test\TestCase; class SwiftMailerHandlerTest extends TestCase { @@ -37,10 +37,10 @@ class SwiftMailerHandlerTest extends TestCase }; $handler = new SwiftMailerHandler($this->mailer, $callback); - $records = array( + $records = [ $this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO), - ); + ]; $handler->handleBatch($records); } @@ -66,9 +66,9 @@ class SwiftMailerHandlerTest extends TestCase $handler = new SwiftMailerHandler($this->mailer, $callback); // Logging 1 record makes this an Emergency - $records = array( + $records = [ $this->getRecord(Logger::EMERGENCY), - ); + ]; $handler->handleBatch($records); } @@ -83,14 +83,15 @@ class SwiftMailerHandlerTest extends TestCase ->method('send') ->with($this->callback(function ($value) use (&$receivedMessage) { $receivedMessage = $value; + return true; })); $handler = new SwiftMailerHandler($this->mailer, $messageTemplate); - $records = array( + $records = [ $this->getRecord(Logger::EMERGENCY), - ); + ]; $handler->handleBatch($records); $this->assertEquals('Alert: EMERGENCY test', $receivedMessage->getSubject()); @@ -103,10 +104,10 @@ class SwiftMailerHandlerTest extends TestCase $method = new \ReflectionMethod('Monolog\Handler\SwiftMailerHandler', 'buildMessage'); $method->setAccessible(true); - $method->invokeArgs($handler, array($messageTemplate, array())); + $method->invokeArgs($handler, [$messageTemplate, []]); - $builtMessage1 = $method->invoke($handler, $messageTemplate, array()); - $builtMessage2 = $method->invoke($handler, $messageTemplate, array()); + $builtMessage1 = $method->invoke($handler, $messageTemplate, []); + $builtMessage2 = $method->invoke($handler, $messageTemplate, []); $this->assertFalse($builtMessage1->getId() === $builtMessage2->getId(), 'Two different messages have the same id'); } diff --git a/tests/Monolog/Handler/SyslogHandlerTest.php b/tests/Monolog/Handler/SyslogHandlerTest.php index 8f9e46b..550e210 100644 --- a/tests/Monolog/Handler/SyslogHandlerTest.php +++ b/tests/Monolog/Handler/SyslogHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -13,7 +13,7 @@ namespace Monolog\Handler; use Monolog\Logger; -class SyslogHandlerTest extends \PHPUnit_Framework_TestCase +class SyslogHandlerTest extends \PHPUnit\Framework\TestCase { /** * @covers Monolog\Handler\SyslogHandler::__construct @@ -38,7 +38,7 @@ class SyslogHandlerTest extends \PHPUnit_Framework_TestCase */ public function testConstructInvalidFacility() { - $this->setExpectedException('UnexpectedValueException'); + $this->expectException('UnexpectedValueException'); $handler = new SyslogHandler('test', 'unknown'); } } diff --git a/tests/Monolog/Handler/SyslogUdpHandlerTest.php b/tests/Monolog/Handler/SyslogUdpHandlerTest.php index 7ee8a98..9f32d91 100644 --- a/tests/Monolog/Handler/SyslogUdpHandlerTest.php +++ b/tests/Monolog/Handler/SyslogUdpHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; /** * @requires extension sockets @@ -42,7 +42,10 @@ class SyslogUdpHandlerTest extends TestCase $handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter()); - $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol')); + $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket') + ->setMethods(['write']) + ->setConstructorArgs(['lol', 'lol']) + ->getMock(); $socket->expects($this->at(0)) ->method('write') ->with("lol", "<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "); @@ -60,7 +63,10 @@ class SyslogUdpHandlerTest extends TestCase $handler = new SyslogUdpHandler("127.0.0.1", 514, "authpriv"); $handler->setFormatter($this->getIdentityFormatter()); - $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('write'), array('lol', 'lol')); + $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket') + ->setMethods(['write']) + ->setConstructorArgs(['lol', 'lol']) + ->getMock(); $socket->expects($this->never()) ->method('write'); @@ -71,6 +77,6 @@ class SyslogUdpHandlerTest extends TestCase protected function getRecordWithMessage($msg) { - return array('message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => array(), 'channel' => 'lol'); + return ['message' => $msg, 'level' => \Monolog\Logger::WARNING, 'context' => null, 'extra' => [], 'channel' => 'lol']; } } diff --git a/tests/Monolog/Handler/TestHandlerTest.php b/tests/Monolog/Handler/TestHandlerTest.php index bfb8d3d..db3f01f 100644 --- a/tests/Monolog/Handler/TestHandlerTest.php +++ b/tests/Monolog/Handler/TestHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; /** @@ -51,20 +51,20 @@ class TestHandlerTest extends TestCase $records = $handler->getRecords(); unset($records[0]['formatted']); - $this->assertEquals(array($record), $records); + $this->assertEquals([$record], $records); } public function methodProvider() { - return array( - array('Emergency', Logger::EMERGENCY), - array('Alert' , Logger::ALERT), - array('Critical' , Logger::CRITICAL), - array('Error' , Logger::ERROR), - array('Warning' , Logger::WARNING), - array('Info' , Logger::INFO), - array('Notice' , Logger::NOTICE), - array('Debug' , Logger::DEBUG), - ); + return [ + ['Emergency', Logger::EMERGENCY], + ['Alert' , Logger::ALERT], + ['Critical' , Logger::CRITICAL], + ['Error' , Logger::ERROR], + ['Warning' , Logger::WARNING], + ['Info' , Logger::INFO], + ['Notice' , Logger::NOTICE], + ['Debug' , Logger::DEBUG], + ]; } } diff --git a/tests/Monolog/Handler/UdpSocketTest.php b/tests/Monolog/Handler/UdpSocketTest.php index fa524d0..1adf79a 100644 --- a/tests/Monolog/Handler/UdpSocketTest.php +++ b/tests/Monolog/Handler/UdpSocketTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Handler\SyslogUdp\UdpSocket; /** @@ -21,7 +21,10 @@ class UdpSocketTest extends TestCase { public function testWeDoNotTruncateShortMessages() { - $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol')); + $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket') + ->setMethods(['send']) + ->setConstructorArgs(['lol', 'lol']) + ->getMock(); $socket->expects($this->at(0)) ->method('send') @@ -32,7 +35,10 @@ class UdpSocketTest extends TestCase public function testLongMessagesAreTruncated() { - $socket = $this->getMock('\Monolog\Handler\SyslogUdp\UdpSocket', array('send'), array('lol', 'lol')); + $socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket') + ->setMethods(['send']) + ->setConstructorArgs(['lol', 'lol']) + ->getMock(); $truncatedString = str_repeat("derp", 16254).'d'; @@ -53,7 +59,7 @@ class UdpSocketTest extends TestCase } /** - * @expectedException LogicException + * @expectedException RuntimeException */ public function testWriteAfterCloseErrors() { diff --git a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php index 8d37a1f..60f5175 100644 --- a/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php +++ b/tests/Monolog/Handler/WhatFailureGroupHandlerTest.php @@ -1,4 +1,4 @@ -<?php +<?php declare(strict_types=1); /* * This file is part of the Monolog package. @@ -11,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; use Monolog\Logger; class WhatFailureGroupHandlerTest extends TestCase @@ -22,7 +22,7 @@ class WhatFailureGroupHandlerTest extends TestCase */ public function testConstructorOnlyTakesHandler() { - new WhatFailureGroupHandler(array(new TestHandler(), "foo")); + new WhatFailureGroupHandler([new TestHandler(), "foo"]); } /** @@ -31,7 +31,7 @@ class WhatFailureGroupHandlerTest extends TestCase */ public function testHandle() { - $testHandlers = array(new TestHandler(), new TestHandler()); + $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new WhatFailureGroupHandler($testHandlers); $handler->handle($this->getRecord(Logger::DEBUG)); $handler->handle($this->getRecord(Logger::INFO)); @@ -47,9 +47,9 @@ class WhatFailureGroupHandlerTest extends TestCase */ public function testHandleBatch() { - $testHandlers = array(new TestHandler(), new TestHandler()); + $testHandlers = [new TestHandler(), new TestHandler()]; $handler = new WhatFailureGroupHandler($testHandlers); - $handler->handleBatch(array($this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO))); + $handler->handleBatch([$this->getRecord(Logger::DEBUG), $this->getRecord(Logger::INFO)]); foreach ($testHandlers as $test) { $this->assertTrue($test->hasDebugRecords()); $this->assertTrue($test->hasInfoRecords()); @@ -62,7 +62,7 @@ class WhatFailureGroupHandlerTest extends TestCase */ public function testIsHandling() { - $testHandlers = array(new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)); + $testHandlers = [new TestHandler(Logger::ERROR), new TestHandler(Logger::WARNING)]; $handler = new WhatFailureGroupHandler($testHandlers); $this->assertTrue($handler->isHandling($this->getRecord(Logger::ERROR))); $this->assertTrue($handler->isHandling($this->getRecord(Logger::WARNING))); @@ -75,7 +75,7 @@ class WhatFailureGroupHandlerTest extends TestCase public function testHandleUsesProcessors() { $test = new TestHandler(); - $handler = new WhatFailureGroupHandler(array($test)); + $handler = new WhatFailureGroupHandler([$test]); $handler->pushProcessor(function ($record) { $record['extra']['foo'] = true; @@ -94,7 +94,7 @@ class WhatFailureGroupHandlerTest extends TestCase { $test = new TestHandler(); $exception = new ExceptionTestHandler(); - $handler = new WhatFailureGroupHandler(array($exception, $test, $exception)); + $handler = new WhatFailureGroupHandler([$exception, $test, $exception]); $handler->pushProcessor(function ($record) { $record['extra']['foo'] = true; @@ -112,7 +112,7 @@ class ExceptionTestHandler extends TestHandler /** * {@inheritdoc} */ - public function handle(array $record) + public function handle(array $record): bool { parent::handle($record); diff --git a/tests/Monolog/Handler/ZendMonitorHandlerTest.php b/tests/Monolog/Handler/ZendMonitorHandlerTest.php index 69b001e..4879ebe 100644 --- a/tests/Monolog/Handler/ZendMonitorHandlerTest.php +++ b/tests/Monolog/Handler/ZendMonitorHandlerTest.php @@ -1,4 +1,5 @@ -<?php +<?php declare(strict_types=1); + /* * This file is part of the Monolog package. * @@ -10,7 +11,7 @@ namespace Monolog\Handler; -use Monolog\TestCase; +use Monolog\Test\TestCase; class ZendMonitorHandlerTest extends TestCase { @@ -29,12 +30,12 @@ class ZendMonitorHandlerTest extends TestCase public function testWrite() { $record = $this->getRecord(); - $formatterResult = array( + $formatterResult = [ 'message' => $record['message'], - ); + ]; $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler') - ->setMethods(array('writeZendMonitorCustomEvent', 'getDefaultFormatter')) + ->setMethods(['writeZendMonitorCustomEvent', 'getDefaultFormatter']) ->getMock(); $formatterMock = $this->getMockBuilder('Monolog\Formatter\NormalizerFormatter') |