1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-10 23:24:02 +02:00
This commit is contained in:
Jordi Boggiano
2022-04-19 22:10:02 +02:00
parent e4bb5c5cf3
commit 2695fa86cd
85 changed files with 350 additions and 398 deletions

View File

@@ -30,4 +30,4 @@ final class AsMonologProcessorTest extends TestCase
$this->assertNull($asMonologProcessor->handler);
$this->assertNull($asMonologProcessor->method);
}
}
}

View File

@@ -12,7 +12,6 @@
namespace Monolog\Formatter;
use Monolog\Level;
use Monolog\LogRecord;
use Monolog\Test\TestCase;
class ElasticaFormatterTest extends TestCase

View File

@@ -219,7 +219,7 @@ class GelfMessageFormatterTest extends TestCase
$length = 200;
foreach ($messageArray as $key => $value) {
if (!in_array($key, array('level', 'timestamp'))) {
if (!in_array($key, ['level', 'timestamp'])) {
$length += strlen($value);
}
}

View File

@@ -205,9 +205,6 @@ class JsonFormatterTest extends TestCase
}
/**
* @param JsonFormatter $formatter
* @param \Throwable $exception
*
* @return string
*/
private function formatRecordWithExceptionInContext(JsonFormatter $formatter, \Throwable $exception)
@@ -265,7 +262,7 @@ class JsonFormatterTest extends TestCase
Level::Critical,
'bar',
channel: 'test',
context: array($largeArray),
context: [$largeArray],
));
$this->assertCount(1000, $res['context'][0]);
@@ -281,7 +278,7 @@ class JsonFormatterTest extends TestCase
Level::Critical,
'bar',
channel: 'test',
context: array($largeArray),
context: [$largeArray],
));
$this->assertCount(1001, $res['context'][0]);

View File

@@ -274,6 +274,5 @@ class MongoDBFormatterTest extends TestCase
$this->assertInstanceOf(ObjectId::class, $formattedRecord['context']['objectid']);
$this->assertInstanceOf(UTCDateTime::class, $formattedRecord['context']['nest']['timestamp']);
$this->assertInstanceOf(Regex::class, $formattedRecord['context']['nest']['regex']);
}
}

View File

@@ -338,7 +338,7 @@ class NormalizerFormatterTest extends TestCase
'message' => 'Foo',
'code' => 0,
]],
"..." => "Over 2 items (7 total), aborting normalization"
"..." => "Over 2 items (7 total), aborting normalization",
],
$message
);
@@ -372,9 +372,6 @@ class NormalizerFormatterTest extends TestCase
}
/**
* @param NormalizerFormatter $formatter
* @param \Throwable $exception
*
* @return string
*/
private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
@@ -393,7 +390,7 @@ class NormalizerFormatterTest extends TestCase
{
try {
$arg = new TestInfoLeak;
call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
call_user_func([$this, 'throwHelper'], $arg, $dt = new \DateTime());
} catch (\Exception $e) {
}

View File

@@ -95,7 +95,7 @@ class ScalarFormatterTest extends TestCase
'code' => $exception->getCode(),
'file' => $exception->getFile() . ':' . $exception->getLine(),
'trace' => $this->buildTrace($exception),
]
],
]), $formatted['context']);
}
}

View File

@@ -54,12 +54,12 @@ class ChromePHPHandlerTest extends TestCase
public static function agentsProvider()
{
return array(
array('Monolog Test; Chrome/1.0'),
array('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'),
array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'),
array('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'),
);
return [
['Monolog Test; Chrome/1.0'],
['Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/56.0.2924.76 Chrome/56.0.2924.76 Safari/537.36'],
['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome Safari/537.36'],
];
}
public function testHeadersOverflow()

View File

@@ -70,7 +70,7 @@ class DynamoDbHandlerTest extends TestCase
$handler->setFormatter($formatter);
if ($this->isV3) {
$expFormatted = array('foo' => array('N' => 1), 'bar' => array('N' => 2));
$expFormatted = ['foo' => ['N' => 1], 'bar' => ['N' => 2]];
} else {
$expFormatted = $formatted;
}

View File

@@ -15,7 +15,6 @@ use Monolog\Formatter\ElasticaFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Test\TestCase;
use Monolog\Level;
use Monolog\LogRecord;
use Elastica\Client;
use Elastica\Request;
use Elastica\Response;

View File

@@ -178,8 +178,8 @@ class FilterHandlerTest extends TestCase
{
$test = new TestHandler();
$handler = new FilterHandler($test);
$handler->handleBatch(array());
$this->assertSame(array(), $test->getRecords());
$handler->handleBatch([]);
$this->assertSame([], $test->getRecords());
}
/**
@@ -202,6 +202,6 @@ class FilterHandlerTest extends TestCase
$this->assertFalse($test->hasInfoRecords());
$this->assertFalse($test->hasInfoRecords());
$this->assertSame(array(), $test->getRecords());
$this->assertSame([], $test->getRecords());
}
}

View File

@@ -55,10 +55,10 @@ class InsightOpsHandlerTest extends TestCase
private function createHandler()
{
$useSSL = extension_loaded('openssl');
$args = array('testToken', 'us', $useSSL, Level::Debug, true);
$args = ['testToken', 'us', $useSSL, Level::Debug, true];
$this->resource = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder(InsightOpsHandler::class)
->onlyMethods(array('fsockopen', 'streamSetTimeout', 'closeSocket'))
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->setConstructorArgs($args)
->getMock();

View File

@@ -24,7 +24,7 @@ class PsrHandlerTest extends TestCase
public function logLevelProvider()
{
return array_map(
fn(Level $level) => [$level->toLevelName(), $level],
fn (Level $level) => [$level->toLevelName(), $level],
Level::cases()
);
}

View File

@@ -59,14 +59,14 @@ class RollbarHandlerTest extends TestCase
private function setupRollbarLoggerMock()
{
$config = array(
$config = [
'access_token' => 'ad865e76e7fb496fab096ac07b1dbabb',
'environment' => 'test',
);
];
$this->rollbarLogger = $this->getMockBuilder(RollbarLogger::class)
->setConstructorArgs(array($config))
->onlyMethods(array('log'))
->setConstructorArgs([$config])
->onlyMethods(['log'])
->getMock();
$this->rollbarLogger

View File

@@ -218,16 +218,16 @@ class RotatingFileHandlerTest extends TestCase
public function rotationWhenSimilarFilesExistTests()
{
return array(
return [
'Rotation is triggered when the file of the current day is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_DAY),
=> [RotatingFileHandler::FILE_PER_DAY],
'Rotation is triggered when the file of the current month is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_MONTH),
=> [RotatingFileHandler::FILE_PER_MONTH],
'Rotation is triggered when the file of the current year is not present but similar exists'
=> array(RotatingFileHandler::FILE_PER_YEAR),
);
=> [RotatingFileHandler::FILE_PER_YEAR],
];
}
public function testReuseCurrentFile()

View File

@@ -22,16 +22,16 @@ class SlackRecordTest extends TestCase
{
public function dataGetAttachmentColor()
{
return array(
array(Level::Debug, SlackRecord::COLOR_DEFAULT),
array(Level::Info, SlackRecord::COLOR_GOOD),
array(Level::Notice, SlackRecord::COLOR_GOOD),
array(Level::Warning, SlackRecord::COLOR_WARNING),
array(Level::Error, SlackRecord::COLOR_DANGER),
array(Level::Critical, SlackRecord::COLOR_DANGER),
array(Level::Alert, SlackRecord::COLOR_DANGER),
array(Level::Emergency, SlackRecord::COLOR_DANGER),
);
return [
[Level::Debug, SlackRecord::COLOR_DEFAULT],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency, SlackRecord::COLOR_DANGER],
];
}
/**
@@ -70,16 +70,16 @@ class SlackRecordTest extends TestCase
*/
public function dataStringify()
{
$multipleDimensions = array(array(1, 2));
$numericKeys = array('library' => 'monolog');
$singleDimension = array(1, 'Hello', 'Jordi');
$multipleDimensions = [[1, 2]];
$numericKeys = ['library' => 'monolog'];
$singleDimension = [1, 'Hello', 'Jordi'];
return array(
array(array(), '[]'),
array($multipleDimensions, json_encode($multipleDimensions, JSON_PRETTY_PRINT)),
array($numericKeys, json_encode($numericKeys, JSON_PRETTY_PRINT)),
array($singleDimension, json_encode($singleDimension)),
);
return [
[[], '[]'],
[$multipleDimensions, json_encode($multipleDimensions, JSON_PRETTY_PRINT)],
[$numericKeys, json_encode($numericKeys, JSON_PRETTY_PRINT)],
[$singleDimension, json_encode($singleDimension)],
];
}
/**
@@ -179,7 +179,7 @@ class SlackRecordTest extends TestCase
}));
$message = 'Test message';
$record = new SlackRecord(null, null, false, null, false, false, array(), $formatter);
$record = new SlackRecord(null, null, false, null, false, false, [], $formatter);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertArrayHasKey('text', $data);
@@ -232,21 +232,21 @@ class SlackRecordTest extends TestCase
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$record = new SlackRecord(null, null, true, null, true);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame(array(), $attachment['fields']);
$this->assertSame([], $attachment['fields']);
}
public function testAddsShortAttachmentWithContextAndExtra()
{
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$context = array('test' => 1);
$extra = array('tags' => array('web'));
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, true, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
@@ -258,18 +258,18 @@ class SlackRecordTest extends TestCase
$this->assertCount(2, $attachment['fields']);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame(
array(
array(
[
[
'title' => 'Extra',
'value' => sprintf('```%s```', json_encode($extra, JSON_PRETTY_PRINT)),
'short' => false,
),
array(
],
[
'title' => 'Context',
'value' => sprintf('```%s```', json_encode($context, JSON_PRETTY_PRINT)),
'short' => false,
),
),
],
],
$attachment['fields']
);
}
@@ -279,7 +279,7 @@ class SlackRecordTest extends TestCase
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$record = new SlackRecord(null, null, true, null);
$data = $record->getSlackData($this->getRecord($level, 'test', array('test' => 1)));
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
@@ -287,11 +287,11 @@ class SlackRecordTest extends TestCase
$this->assertCount(1, $attachment['fields']);
$this->assertSame('Message', $attachment['title']);
$this->assertSame(
array(array(
[[
'title' => 'Level',
'value' => $levelName,
'short' => false,
)),
]],
$attachment['fields']
);
}
@@ -300,30 +300,30 @@ class SlackRecordTest extends TestCase
{
$level = Level::Error;
$levelName = LevelName::fromLevel($level)->value;
$context = array('test' => 1);
$extra = array('tags' => array('web'));
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, false, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord);
$expectedFields = array(
array(
$expectedFields = [
[
'title' => 'Level',
'value' => $levelName,
'short' => false,
),
array(
],
[
'title' => 'Tags',
'value' => sprintf('```%s```', json_encode($extra['tags'])),
'short' => false,
),
array(
],
[
'title' => 'Test',
'value' => $context['test'],
'short' => false,
),
);
],
];
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
@@ -349,7 +349,7 @@ class SlackRecordTest extends TestCase
public function testContextHasException()
{
$record = $this->getRecord(Level::Critical, 'This is a critical message.', array('exception' => new \Exception()));
$record = $this->getRecord(Level::Critical, 'This is a critical message.', ['exception' => new \Exception()]);
$slackRecord = new SlackRecord(null, null, true, null, false, true);
$data = $slackRecord->getSlackData($record);
$this->assertIsString($data['attachments'][0]['fields'][1]['value']);
@@ -360,26 +360,26 @@ class SlackRecordTest extends TestCase
$record = $this->getRecord(
Level::Warning,
'test',
context: array('info' => array('library' => 'monolog', 'author' => 'Jordi')),
extra: array('tags' => array('web', 'cli')),
context: ['info' => ['library' => 'monolog', 'author' => 'Jordi']],
extra: ['tags' => ['web', 'cli']],
);
$slackRecord = new SlackRecord(null, null, true, null, false, true, array('context.info.library', 'extra.tags.1'));
$slackRecord = new SlackRecord(null, null, true, null, false, true, ['context.info.library', 'extra.tags.1']);
$data = $slackRecord->getSlackData($record);
$attachment = $data['attachments'][0];
$expected = array(
array(
$expected = [
[
'title' => 'Info',
'value' => sprintf('```%s```', json_encode(array('author' => 'Jordi'), JSON_PRETTY_PRINT)),
'value' => sprintf('```%s```', json_encode(['author' => 'Jordi'], JSON_PRETTY_PRINT)),
'short' => false,
),
array(
],
[
'title' => 'Tags',
'value' => sprintf('```%s```', json_encode(array('web'))),
'value' => sprintf('```%s```', json_encode(['web'])),
'short' => false,
),
);
],
];
foreach ($expected as $field) {
$this->assertNotFalse(array_search($field, $attachment['fields']));

View File

@@ -114,16 +114,16 @@ class SlackHandlerTest extends TestCase
public function provideLevelColors()
{
return array(
array(Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)),
array(Level::Info, SlackRecord::COLOR_GOOD),
array(Level::Notice, SlackRecord::COLOR_GOOD),
array(Level::Warning, SlackRecord::COLOR_WARNING),
array(Level::Error, SlackRecord::COLOR_DANGER),
array(Level::Critical, SlackRecord::COLOR_DANGER),
array(Level::Alert, SlackRecord::COLOR_DANGER),
array(Level::Emergency,SlackRecord::COLOR_DANGER),
);
return [
[Level::Debug, urlencode(SlackRecord::COLOR_DEFAULT)],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency,SlackRecord::COLOR_DANGER],
];
}
private function createHandler($token = 'myToken', $channel = 'channel1', $username = 'Monolog', $useAttachment = true, $iconEmoji = null, $useShortAttachment = false, $includeExtra = false)

View File

@@ -36,27 +36,27 @@ class SlackWebhookHandlerTest extends TestCase
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
'attachments' => array(
array(
$this->assertEquals([
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => array(
array(
'fields' => [
[
'title' => 'Level',
'value' => 'WARNING',
'short' => false,
),
),
],
],
'title' => 'Message',
'mrkdwn_in' => array('fields'),
'mrkdwn_in' => ['fields'],
'ts' => $record->datetime->getTimestamp(),
'footer' => null,
'footer_icon' => null,
),
),
), $slackRecord->getSlackData($record));
],
],
], $slackRecord->getSlackData($record));
}
/**
@@ -79,12 +79,12 @@ class SlackWebhookHandlerTest extends TestCase
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
$this->assertEquals([
'username' => 'test-username',
'text' => 'test',
'channel' => 'test-channel',
'icon_emoji' => ':ghost:',
), $slackRecord->getSlackData($this->getRecord()));
], $slackRecord->getSlackData($this->getRecord()));
}
/**
@@ -108,30 +108,30 @@ class SlackWebhookHandlerTest extends TestCase
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals(array(
$this->assertEquals([
'username' => 'test-username-with-attachment',
'channel' => 'test-channel-with-attachment',
'attachments' => array(
array(
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => array(
array(
'fields' => [
[
'title' => 'Level',
'value' => LevelName::Warning->value,
'short' => false,
),
),
'mrkdwn_in' => array('fields'),
],
],
'mrkdwn_in' => ['fields'],
'ts' => $record['datetime']->getTimestamp(),
'footer' => 'test-username-with-attachment',
'footer_icon' => 'https://www.example.com/example.png',
'title' => 'Message',
),
),
],
],
'icon_url' => 'https://www.example.com/example.png',
), $slackRecord->getSlackData($record));
], $slackRecord->getSlackData($record));
}
/**

View File

@@ -128,7 +128,7 @@ class SocketHandlerTest extends TestCase
public function testExceptionIsThrownIfCannotSetChunkSize()
{
$this->setMockHandler(array('streamSetChunkSize'));
$this->setMockHandler(['streamSetChunkSize']);
$this->handler->setChunkSize(8192);
$this->handler->expects($this->once())
->method('streamSetChunkSize')

View File

@@ -11,7 +11,6 @@
namespace Monolog\Handler;
use Monolog\Handler\StreamHandler;
use Monolog\Test\TestCase;
use Monolog\Level;

View File

@@ -75,15 +75,15 @@ class SyslogUdpHandlerTest extends TestCase
$host = gethostname();
$handler = $this->getMockBuilder('\Monolog\Handler\SyslogUdpHandler')
->setConstructorArgs(array("127.0.0.1", 514, "authpriv", 'debug', true, "php", \Monolog\Handler\SyslogUdpHandler::RFC3164))
->setConstructorArgs(["127.0.0.1", 514, "authpriv", 'debug', true, "php", \Monolog\Handler\SyslogUdpHandler::RFC3164])
->onlyMethods([])
->getMock();
$handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());
$socket = $this->getMockBuilder('\Monolog\Handler\SyslogUdp\UdpSocket')
->setConstructorArgs(array('lol', 999))
->onlyMethods(array('write'))
->setConstructorArgs(['lol', 999])
->onlyMethods(['write'])
->getMock();
$socket->expects($this->atLeast(2))
->method('write')

View File

@@ -32,8 +32,6 @@ class TelegramBotHandlerTest extends TestCase
}
/**
* @param string $apiKey
* @param string $channel
*/
private function createHandler(
string $apiKey = 'testKey',

View File

@@ -93,7 +93,7 @@ class WhatFailureGroupHandlerTest extends TestCase
*/
public function testHandleBatchUsesProcessors()
{
$testHandlers = array(new TestHandler(), new TestHandler());
$testHandlers = [new TestHandler(), new TestHandler()];
$handler = new WhatFailureGroupHandler($testHandlers);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
@@ -105,7 +105,7 @@ class WhatFailureGroupHandlerTest extends TestCase
return $record;
});
$handler->handleBatch(array($this->getRecord(Level::Debug), $this->getRecord(Level::Info)));
$handler->handleBatch([$this->getRecord(Level::Debug), $this->getRecord(Level::Info)]);
foreach ($testHandlers as $test) {
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());

View File

@@ -12,7 +12,6 @@
namespace Monolog\Handler;
use Monolog\Test\TestCase;
use Monolog\Level;
class ZendMonitorHandlerTest extends TestCase
{

View File

@@ -276,7 +276,7 @@ class LoggerTest extends TestCase
public function testHandlersNotCalledBeforeFirstHandlingWhenProcessorsPresent()
{
$logger = new Logger(__METHOD__);
$logger->pushProcessor(fn($record) => $record);
$logger->pushProcessor(fn ($record) => $record);
$handler1 = $this->createMock('Monolog\Handler\HandlerInterface');
$handler1->expects($this->never())
@@ -348,7 +348,7 @@ class LoggerTest extends TestCase
;
$logger = new Logger(__METHOD__, ['last' => $handler3, 'second' => $handler2, 'first' => $handler1]);
$logger->pushProcessor(fn($record) => $record);
$logger->pushProcessor(fn ($record) => $record);
$logger->debug('test');
}
@@ -652,7 +652,7 @@ class LoggerTest extends TestCase
$testHandler = new Handler\TestHandler();
$testHandler->setSkipReset(true);
$bufferHandler = new Handler\BufferHandler($testHandler);
$groupHandler = new Handler\GroupHandler(array($bufferHandler));
$groupHandler = new Handler\GroupHandler([$bufferHandler]);
$fingersCrossedHandler = new Handler\FingersCrossedHandler($groupHandler);
$logger->pushHandler($fingersCrossedHandler);

View File

@@ -90,15 +90,15 @@ class WebProcessorTest extends TestCase
public function testProcessorAddsOnlyRequestedExtraFieldsIncludingOptionalFields()
{
$server = array(
$server = [
'REQUEST_URI' => 'A',
'UNIQUE_ID' => 'X',
);
];
$processor = new WebProcessor($server, array('url'));
$processor = new WebProcessor($server, ['url']);
$record = $processor($this->getRecord());
$this->assertSame(array('url' => 'A'), $record->extra);
$this->assertSame(['url' => 'A'], $record->extra);
}
public function testProcessorConfiguringOfExtraFields()

View File

@@ -19,7 +19,6 @@ use PHPUnit\Framework\TestCase;
use Psr\Log\InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;
use Psr\Log\Test\LoggerInterfaceTest;
class PsrLogCompatTest extends TestCase
{
@@ -61,28 +60,28 @@ class PsrLogCompatTest extends TestCase
public function testLogsAtAllLevels($level, $message)
{
$logger = $this->getLogger();
$logger->{$level}($message, array('user' => 'Bob'));
$logger->log($level, $message, array('user' => 'Bob'));
$logger->{$level}($message, ['user' => 'Bob']);
$logger->log($level, $message, ['user' => 'Bob']);
$expected = array(
$expected = [
"$level message of level $level with context: Bob",
"$level message of level $level with context: Bob",
);
];
$this->assertEquals($expected, $this->getLogs());
}
public function provideLevelsAndMessages()
{
return array(
LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
);
return [
LogLevel::EMERGENCY => [LogLevel::EMERGENCY, 'message of level emergency with context: {user}'],
LogLevel::ALERT => [LogLevel::ALERT, 'message of level alert with context: {user}'],
LogLevel::CRITICAL => [LogLevel::CRITICAL, 'message of level critical with context: {user}'],
LogLevel::ERROR => [LogLevel::ERROR, 'message of level error with context: {user}'],
LogLevel::WARNING => [LogLevel::WARNING, 'message of level warning with context: {user}'],
LogLevel::NOTICE => [LogLevel::NOTICE, 'message of level notice with context: {user}'],
LogLevel::INFO => [LogLevel::INFO, 'message of level info with context: {user}'],
LogLevel::DEBUG => [LogLevel::DEBUG, 'message of level debug with context: {user}'],
];
}
public function testThrowsOnInvalidLevel()
@@ -96,9 +95,9 @@ class PsrLogCompatTest extends TestCase
public function testContextReplacement()
{
$logger = $this->getLogger();
$logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
$logger->info('{Message {nothing} {user} {foo.bar} a}', ['user' => 'Bob', 'foo.bar' => 'Bar']);
$expected = array('info {Message {nothing} Bob Bar a}');
$expected = ['info {Message {nothing} Bob Bar a}'];
$this->assertEquals($expected, $this->getLogs());
}
@@ -111,7 +110,7 @@ class PsrLogCompatTest extends TestCase
$this->getLogger()->warning($dummy);
$expected = array("warning $string");
$expected = ["warning $string"];
$this->assertEquals($expected, $this->getLogs());
}
@@ -120,47 +119,47 @@ class PsrLogCompatTest extends TestCase
$closed = fopen('php://memory', 'r');
fclose($closed);
$context = array(
$context = [
'bool' => true,
'null' => null,
'string' => 'Foo',
'int' => 0,
'float' => 0.5,
'nested' => array('with object' => $this->createStringable()),
'nested' => ['with object' => $this->createStringable()],
'object' => new \DateTime('now', new DateTimeZone('Europe/London')),
'resource' => fopen('php://memory', 'r'),
'closed' => $closed,
);
];
$this->getLogger()->warning('Crazy context data', $context);
$expected = array('warning Crazy context data');
$expected = ['warning Crazy context data'];
$this->assertEquals($expected, $this->getLogs());
}
public function testContextExceptionKeyCanBeExceptionOrOtherValues()
{
$logger = $this->getLogger();
$logger->warning('Random message', array('exception' => 'oops'));
$logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
$logger->warning('Random message', ['exception' => 'oops']);
$logger->critical('Uncaught Exception!', ['exception' => new \LogicException('Fail')]);
$expected = array(
$expected = [
'warning Random message',
'critical Uncaught Exception!'
);
'critical Uncaught Exception!',
];
$this->assertEquals($expected, $this->getLogs());
}
/**
* Creates a mock of a `Stringable`.
*
* @param string $string The string that must be represented by the stringable.
* @param string $string The string that must be represented by the stringable.
* @return \PHPUnit_Framework_MockObject_MockObject A mock of an object that has a `__toString()` method.
*/
protected function createStringable($string = '')
{
$mock = $this->getMockBuilder('Stringable')
->setMethods(array('__toString'))
->setMethods(['__toString'])
->getMock();
$mock->method('__toString')

View File

@@ -28,13 +28,13 @@ class SignalHandlerTest extends TestCase
protected function setUp(): void
{
$this->signalHandlers = array();
$this->signalHandlers = [];
if (extension_loaded('pcntl')) {
if (function_exists('pcntl_async_signals')) {
$this->asyncSignalHandling = pcntl_async_signals();
}
if (function_exists('pcntl_sigprocmask')) {
pcntl_sigprocmask(SIG_BLOCK, array(), $this->blockedSignals);
pcntl_sigprocmask(SIG_BLOCK, [], $this->blockedSignals);
}
}
}
@@ -67,10 +67,10 @@ class SignalHandlerTest extends TestCase
public function testHandleSignal()
{
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$signo = 2; // SIGINT.
$siginfo = array('signo' => $signo, 'errno' => 0, 'code' => 0);
$siginfo = ['signo' => $signo, 'errno' => 0, 'code' => 0];
$errHandler->handleSignal($signo, $siginfo);
$this->assertCount(1, $handler->getRecords());
$this->assertTrue($handler->hasCriticalRecords());
@@ -97,7 +97,7 @@ class SignalHandlerTest extends TestCase
$this->setSignalHandler(SIGCONT, SIG_IGN);
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$pid = posix_getpid();
@@ -135,14 +135,14 @@ class SignalHandlerTest extends TestCase
if ($pid === 0) { // Child.
$streamHandler = new StreamHandler($path);
$streamHandler->setFormatter($this->getIdentityFormatter());
$logger = new Logger('test', array($streamHandler));
$logger = new Logger('test', [$streamHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler($signo, LogLevel::INFO, $callPrevious, false, false);
pcntl_sigprocmask(SIG_SETMASK, array(SIGCONT));
pcntl_sigprocmask(SIG_SETMASK, [SIGCONT]);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
// If $callPrevious is true, SIGINT should terminate by this line.
pcntl_sigprocmask(SIG_BLOCK, array(), $oldset);
pcntl_sigprocmask(SIG_BLOCK, [], $oldset);
file_put_contents($path, implode(' ', $oldset), FILE_APPEND);
posix_kill(posix_getpid(), $signo);
pcntl_signal_dispatch();
@@ -158,15 +158,15 @@ class SignalHandlerTest extends TestCase
public function defaultPreviousProvider()
{
if (!defined('SIGCONT') || !defined('SIGINT') || !defined('SIGURG')) {
return array();
return [];
}
return array(
array(SIGINT, false, 'Program received signal SIGINT'.SIGCONT.'Program received signal SIGINT'),
array(SIGINT, true, 'Program received signal SIGINT'),
array(SIGURG, false, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'),
array(SIGURG, true, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'),
);
return [
[SIGINT, false, 'Program received signal SIGINT'.SIGCONT.'Program received signal SIGINT'],
[SIGINT, true, 'Program received signal SIGINT'],
[SIGURG, false, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
[SIGURG, true, 'Program received signal SIGURG'.SIGCONT.'Program received signal SIGURG'],
];
}
/**
@@ -178,7 +178,7 @@ class SignalHandlerTest extends TestCase
{
$this->setSignalHandler(SIGURG, SIG_IGN);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$previousCalled = 0;
pcntl_signal(SIGURG, function ($signo, array $siginfo = null) use (&$previousCalled) {
@@ -194,10 +194,10 @@ class SignalHandlerTest extends TestCase
public function callablePreviousProvider()
{
return array(
array(false),
array(true),
);
return [
[false],
[true],
];
}
/**
@@ -222,7 +222,7 @@ class SignalHandlerTest extends TestCase
}
$this->assertNotSame(-1, $pid);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, $restartSyscalls, false);
if ($restartSyscalls) {
@@ -246,12 +246,12 @@ class SignalHandlerTest extends TestCase
public function restartSyscallsProvider()
{
return array(
array(false),
array(true),
array(false),
array(true),
);
return [
[false],
[true],
[false],
[true],
];
}
/**
@@ -264,7 +264,7 @@ class SignalHandlerTest extends TestCase
$this->setSignalHandler(SIGURG, SIG_IGN);
pcntl_async_signals($initialAsync);
$logger = new Logger('test', array($handler = new TestHandler));
$logger = new Logger('test', [$handler = new TestHandler]);
$errHandler = new SignalHandler($logger);
$errHandler->registerSignalHandler(SIGURG, LogLevel::INFO, false, false, $desiredAsync);
$this->assertTrue(posix_kill(posix_getpid(), SIGURG));
@@ -275,13 +275,13 @@ class SignalHandlerTest extends TestCase
public function asyncProvider()
{
return array(
array(false, false, 0, 1),
array(false, null, 0, 1),
array(false, true, 1, 1),
array(true, false, 0, 1),
array(true, null, 1, 1),
array(true, true, 1, 1),
);
return [
[false, false, 0, 1],
[false, null, 0, 1],
[false, true, 1, 1],
[true, false, 0, 1],
[true, null, 1, 1],
[true, true, 1, 1],
];
}
}

View File

@@ -27,8 +27,10 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
{
return [
['stdClass', new \stdClass()],
['class@anonymous', new class {}],
['stdClass@anonymous', new class extends \stdClass {}],
['class@anonymous', new class {
}],
['stdClass@anonymous', new class extends \stdClass {
}],
];
}
@@ -44,15 +46,15 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
public function providePathsToCanonicalize()
{
return array(
array('/foo/bar', '/foo/bar'),
array('file://'.getcwd().'/bla', 'file://bla'),
array(getcwd().'/bla', 'bla'),
array(getcwd().'/./bla', './bla'),
array('file:///foo/bar', 'file:///foo/bar'),
array('any://foo', 'any://foo'),
array('\\\\network\path', '\\\\network\path'),
);
return [
['/foo/bar', '/foo/bar'],
['file://'.getcwd().'/bla', 'file://bla'],
[getcwd().'/bla', 'bla'],
[getcwd().'/./bla', './bla'],
['file:///foo/bar', 'file:///foo/bar'],
['any://foo', 'any://foo'],
['\\\\network\path', '\\\\network\path'],
];
}
/**
@@ -112,13 +114,14 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider providesPcreLastErrorMessage
* @param int $code
* @param int $code
* @param string $msg
*/
public function testPcreLastErrorMessage($code, $msg)
{
if (PHP_VERSION_ID >= 80000) {
$this->assertSame('No error', Utils::pcreLastErrorMessage($code));
return;
}
@@ -178,7 +181,7 @@ class UtilsTest extends \PHPUnit_Framework_TestCase
/**
* @dataProvider provideIniValuesToConvertToBytes
* @param mixed $input
* @param mixed $input
* @param int|false $expected
*/
public function testExpandIniShorthandBytes($input, $expected)