1
0
mirror of https://github.com/Seldaek/monolog.git synced 2025-08-14 00:54:01 +02:00

Merge branch '2.x' into main

This commit is contained in:
Jordi Boggiano
2022-05-08 23:03:49 +02:00
31 changed files with 697 additions and 182 deletions

View File

@@ -78,7 +78,7 @@ class AmqpHandlerTest extends TestCase
public function testHandlePhpAmqpLib()
{
if (!class_exists('PhpAmqpLib\Connection\AMQPConnection')) {
if (!class_exists('PhpAmqpLib\Channel\AMQPChannel')) {
$this->markTestSkipped("php-amqplib not installed");
}

View File

@@ -47,6 +47,13 @@ class DynamoDbHandlerTest extends TestCase
$this->client = $clientMockBuilder->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->client);
}
public function testGetFormatter()
{
$handler = new DynamoDbHandler($this->client, 'foo');

View File

@@ -19,6 +19,9 @@ use Elastica\Client;
use Elastica\Request;
use Elastica\Response;
/**
* @group Elastica
*/
class ElasticaHandlerTest extends TestCase
{
/**
@@ -48,6 +51,13 @@ class ElasticaHandlerTest extends TestCase
->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->client);
}
/**
* @covers Monolog\Handler\ElasticaHandler::write
* @covers Monolog\Handler\ElasticaHandler::handleBatch
@@ -144,52 +154,6 @@ class ElasticaHandlerTest extends TestCase
];
}
/**
* Integration test using localhost Elastic Search server version <7
*
* @covers Monolog\Handler\ElasticaHandler::__construct
* @covers Monolog\Handler\ElasticaHandler::handleBatch
* @covers Monolog\Handler\ElasticaHandler::bulkSend
* @covers Monolog\Handler\ElasticaHandler::getDefaultFormatter
*/
public function testHandleIntegration()
{
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
$expected = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ISO8601);
$expected['context'] = [
'class' => '[object] (stdClass: {})',
'foo' => 7,
0 => 'bar',
];
$client = new Client();
$handler = new ElasticaHandler($client, $this->options);
try {
$handler->handleBatch([$msg]);
} catch (\RuntimeException $e) {
$this->markTestSkipped("Cannot connect to Elastic Search server on localhost");
}
// check document id from ES server response
$documentId = $this->getCreatedDocId($client->getLastResponse());
$this->assertNotEmpty($documentId, 'No elastic document id received');
// retrieve document source from ES and validate
$document = $this->getDocSourceFromElastic(
$client,
$this->options['index'],
$this->options['type'],
$documentId
);
$this->assertEquals($expected, $document);
// remove test index from ES
$client->request("/{$this->options['index']}", Request::DELETE);
}
/**
* Integration test using localhost Elastic Search server version 7+
*
@@ -210,7 +174,9 @@ class ElasticaHandlerTest extends TestCase
0 => 'bar',
];
$client = new Client();
$clientOpts = ['url' => 'http://elastic:changeme@127.0.0.1:9200'];
$client = new Client($clientOpts);
$handler = new ElasticaHandler($client, $this->options);
try {
@@ -243,9 +209,14 @@ class ElasticaHandlerTest extends TestCase
protected function getCreatedDocId(Response $response): ?string
{
$data = $response->getData();
if (!empty($data['items'][0]['create']['_id'])) {
return $data['items'][0]['create']['_id'];
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
var_dump('Unexpected response: ', $data);
return null;
}
/**

View File

@@ -11,17 +11,22 @@
namespace Monolog\Handler;
use Elasticsearch\ClientBuilder;
use Monolog\Formatter\ElasticsearchFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Test\TestCase;
use Monolog\Level;
use Elasticsearch\Client;
use Elastic\Elasticsearch\Client as Client8;
use Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\ClientBuilder as ClientBuilder8;
/**
* @group Elasticsearch
*/
class ElasticsearchHandlerTest extends TestCase
{
/**
* @var Client mock
* @var Client|Client8 mock
*/
protected Client $client;
@@ -35,55 +40,23 @@ class ElasticsearchHandlerTest extends TestCase
public function setUp(): void
{
// Elasticsearch lib required
if (!class_exists('Elasticsearch\Client')) {
$this->markTestSkipped('elasticsearch/elasticsearch not installed');
}
$hosts = ['http://elastic:changeme@127.0.0.1:9200'];
$this->client = $this->getClientBuilder()
->setHosts($hosts)
->build();
// base mock Elasticsearch Client object
$this->client = $this->getMockBuilder('Elasticsearch\Client')
->onlyMethods(['bulk'])
->disableOriginalConstructor()
->getMock();
try {
$this->client->info();
} catch (\Throwable $e) {
$this->markTestSkipped('Could not connect to Elasticsearch on 127.0.0.1:9200');
}
}
/**
* @covers Monolog\Handler\ElasticsearchHandler::write
* @covers Monolog\Handler\ElasticsearchHandler::handleBatch
* @covers Monolog\Handler\ElasticsearchHandler::bulkSend
* @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
*/
public function testHandle()
public function tearDown(): void
{
// log message
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
parent::tearDown();
// format expected result
$formatter = new ElasticsearchFormatter($this->options['index'], $this->options['type']);
$data = $formatter->format($msg);
unset($data['_index'], $data['_type']);
$expected = [
'body' => [
[
'index' => [
'_index' => $this->options['index'],
'_type' => $this->options['type'],
],
],
$data,
],
];
// setup ES client mock
$this->client->expects($this->any())
->method('bulk')
->with($expected);
// perform tests
$handler = new ElasticsearchHandler($this->client, $this->options);
$handler->handle($msg);
$handler->handleBatch([$msg]);
unset($this->client);
}
/**
@@ -100,7 +73,7 @@ class ElasticsearchHandlerTest extends TestCase
}
/**
* @covers Monolog\Handler\ElasticsearchHandler::setFormatter
* @covers Monolog\Handler\ElasticsearchHandler::setFormatter
*/
public function testSetFormatterInvalid()
{
@@ -124,6 +97,11 @@ class ElasticsearchHandlerTest extends TestCase
'type' => $this->options['type'],
'ignore_error' => false,
];
if ($this->client instanceof Client8 || $this->client::VERSION[0] === '7') {
$expected['type'] = '_doc';
}
$handler = new ElasticsearchHandler($this->client, $this->options);
$this->assertEquals($expected, $handler->getOptions());
}
@@ -134,10 +112,10 @@ class ElasticsearchHandlerTest extends TestCase
*/
public function testConnectionErrors($ignore, $expectedError)
{
$hosts = [['host' => '127.0.0.1', 'port' => 1]];
$client = ClientBuilder::create()
->setHosts($hosts)
->build();
$hosts = ['http://127.0.0.1:1'];
$client = $this->getClientBuilder()
->setHosts($hosts)
->build();
$handlerOpts = ['ignore_error' => $ignore];
$handler = new ElasticsearchHandler($client, $handlerOpts);
@@ -167,7 +145,7 @@ class ElasticsearchHandlerTest extends TestCase
* @covers Monolog\Handler\ElasticsearchHandler::bulkSend
* @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
*/
public function testHandleIntegration()
public function testHandleBatchIntegration()
{
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
@@ -179,21 +157,26 @@ class ElasticsearchHandlerTest extends TestCase
0 => 'bar',
];
$hosts = [['host' => '127.0.0.1', 'port' => 9200]];
$client = ClientBuilder::create()
$hosts = ['http://elastic:changeme@127.0.0.1:9200'];
$client = $this->getClientBuilder()
->setHosts($hosts)
->build();
$handler = new ElasticsearchHandler($client, $this->options);
try {
$handler->handleBatch([$msg]);
} catch (\RuntimeException $e) {
$this->markTestSkipped('Cannot connect to Elasticsearch server on localhost');
}
$handler->handleBatch([$msg]);
// check document id from ES server response
$documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
$this->assertNotEmpty($documentId, 'No elastic document id received');
if ($client instanceof Client8) {
$messageBody = $client->getTransport()->getLastResponse()->getBody();
$info = json_decode((string) $messageBody, true);
$this->assertNotNull($info, 'Decoding failed');
$documentId = $this->getCreatedDocIdV8($info);
$this->assertNotEmpty($documentId, 'No elastic document id received');
} else {
$documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
$this->assertNotEmpty($documentId, 'No elastic document id received');
}
// retrieve document source from ES and validate
$document = $this->getDocSourceFromElastic(
@@ -221,21 +204,41 @@ class ElasticsearchHandlerTest extends TestCase
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
return null;
}
/**
* Return last created document id from ES response
*
* @param array $data Elasticsearch last request info
* @return string|null
*/
protected function getCreatedDocIdV8(array $data)
{
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
return null;
}
/**
* Retrieve document by id from Elasticsearch
*
* @param Client $client Elasticsearch client
* @return array<mixed>
*/
protected function getDocSourceFromElastic(Client $client, string $index, string $type, string $documentId): array
protected function getDocSourceFromElastic(Client|Client8 $client, string $index, string $type, string $documentId): array
{
$params = [
'index' => $index,
'type' => $type,
'id' => $documentId,
];
if (!$client instanceof Client8 && $client::VERSION[0] !== '7') {
$params['type'] = $type;
}
$data = $client->get($params);
if (!empty($data['_source'])) {
@@ -244,4 +247,16 @@ class ElasticsearchHandlerTest extends TestCase
return [];
}
/**
* @return ClientBuilder|ClientBuilder8
*/
private function getClientBuilder()
{
if (class_exists(ClientBuilder8::class)) {
return ClientBuilder8::create();
}
return ClientBuilder::create();
}
}

View File

@@ -35,6 +35,13 @@ class FlowdockHandlerTest extends TestCase
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testWriteHeader()
{
$this->createHandler();

View File

@@ -30,6 +30,13 @@ class HandlerWrapperTest extends TestCase
$this->wrapper = new HandlerWrapper($this->handler);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->wrapper);
}
public function trueFalseDataProvider(): array
{
return [

View File

@@ -28,6 +28,13 @@ class InsightOpsHandlerTest extends TestCase
private InsightOpsHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->resource);
}
public function testWriteContent()
{
$this->createHandler();

View File

@@ -27,6 +27,13 @@ class LogEntriesHandlerTest extends TestCase
private LogEntriesHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testWriteContent()
{
$this->createHandler();

View File

@@ -27,6 +27,13 @@ class LogmaticHandlerTest extends TestCase
private LogmaticHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testWriteContent()
{
$this->createHandler();

View File

@@ -54,6 +54,13 @@ class PHPConsoleHandlerTest extends TestCase
$this->connector->setErrorsDispatcher($this->errorDispatcher);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->connector, $this->debugDispatcher, $this->errorDispatcher);
}
protected function initDebugDispatcherMock(Connector $connector)
{
return $this->getMockBuilder('PhpConsole\Dispatcher\Debug')

View File

@@ -27,6 +27,13 @@ class PushoverHandlerTest extends TestCase
private $res;
private PushoverHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testWriteHeader()
{
$this->createHandler();

View File

@@ -38,6 +38,13 @@ class RollbarHandlerTest extends TestCase
$this->setupRollbarLoggerMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->rollbarLogger, $this->reportedExceptionArguments);
}
/**
* When reporting exceptions to Rollbar the
* level has to be set in the payload data

View File

@@ -39,6 +39,18 @@ class RotatingFileHandlerTest extends TestCase
});
}
public function tearDown(): void
{
parent::tearDown();
foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
unlink($file);
}
restore_error_handler();
unset($this->lastError);
}
private function assertErrorWasTriggered($code, $message)
{
if (empty($this->lastError)) {
@@ -239,12 +251,4 @@ class RotatingFileHandlerTest extends TestCase
$handler->handle($this->getRecord());
$this->assertEquals('footest', file_get_contents($log));
}
public function tearDown(): void
{
foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
unlink($file);
}
restore_error_handler();
}
}

View File

@@ -36,6 +36,13 @@ class SlackHandlerTest extends TestCase
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testWriteHeader()
{
$this->createHandler();

View File

@@ -27,6 +27,13 @@ class SocketHandlerTest extends TestCase
*/
private $res;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
}
public function testInvalidHostname()
{
$this->expectException(\UnexpectedValueException::class);

View File

@@ -270,20 +270,20 @@ STRING;
$this->markTestSkipped('We could not set a memory limit that would trigger the error.');
}
$stream = tmpfile();
try {
$stream = tmpfile();
if ($stream === false) {
$this->markTestSkipped('We could not create a temp file to be use as a stream.');
if ($stream === false) {
$this->markTestSkipped('We could not create a temp file to be use as a stream.');
}
$handler = new StreamHandler($stream);
stream_get_contents($stream, 1024);
$this->assertEquals($expectedChunkSize, $handler->getStreamChunkSize());
} finally {
ini_set('memory_limit', $previousValue);
}
$exceptionRaised = false;
$handler = new StreamHandler($stream);
stream_get_contents($stream, 1024);
ini_set('memory_limit', $previousValue);
$this->assertEquals($expectedChunkSize, $handler->getStreamChunkSize());
}
public function testSimpleOOMPrevention(): void
@@ -294,10 +294,13 @@ STRING;
$this->markTestSkipped('We could not set a memory limit that would trigger the error.');
}
$stream = tmpfile();
new StreamHandler($stream);
stream_get_contents($stream);
ini_set('memory_limit', $previousValue);
$this->assertTrue(true);
try {
$stream = tmpfile();
new StreamHandler($stream);
stream_get_contents($stream);
$this->assertTrue(true);
} finally {
ini_set('memory_limit', $previousValue);
}
}
}

View File

@@ -0,0 +1,107 @@
<?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\Logger;
use Monolog\Test\TestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
class SymfonyMailerHandlerTest extends TestCase
{
/** @var MailerInterface&MockObject */
private $mailer;
public function setUp(): void
{
$this->mailer = $this
->getMockBuilder(MailerInterface::class)
->disableOriginalConstructor()
->getMock();
}
public function tearDown(): void
{
parent::tearDown();
unset($this->mailer);
}
public function testMessageCreationIsLazyWhenUsingCallback()
{
$this->mailer->expects($this->never())
->method('send');
$callback = function () {
throw new \RuntimeException('Email creation callback should not have been called in this test');
};
$handler = new SymfonyMailerHandler($this->mailer, $callback);
$records = [
$this->getRecord(Logger::DEBUG),
$this->getRecord(Logger::INFO),
];
$handler->handleBatch($records);
}
public function testMessageCanBeCustomizedGivenLoggedData()
{
// Wire Mailer to expect a specific Email with a customized Subject
$expectedMessage = new Email();
$this->mailer->expects($this->once())
->method('send')
->with($this->callback(function ($value) use ($expectedMessage) {
return $value instanceof Email
&& $value->getSubject() === 'Emergency'
&& $value === $expectedMessage;
}));
// Callback dynamically changes subject based on number of logged records
$callback = function ($content, array $records) use ($expectedMessage) {
$subject = count($records) > 0 ? 'Emergency' : 'Normal';
return $expectedMessage->subject($subject);
};
$handler = new SymfonyMailerHandler($this->mailer, $callback);
// Logging 1 record makes this an Emergency
$records = [
$this->getRecord(Logger::EMERGENCY),
];
$handler->handleBatch($records);
}
public function testMessageSubjectFormatting()
{
// Wire Mailer to expect a specific Email with a customized Subject
$messageTemplate = new Email();
$messageTemplate->subject('Alert: %level_name% %message%');
$receivedMessage = null;
$this->mailer->expects($this->once())
->method('send')
->with($this->callback(function ($value) use (&$receivedMessage) {
$receivedMessage = $value;
return true;
}));
$handler = new SymfonyMailerHandler($this->mailer, $messageTemplate);
$records = [
$this->getRecord(Logger::EMERGENCY),
];
$handler->handleBatch($records);
$this->assertEquals('Alert: EMERGENCY test', $receivedMessage->getSubject());
}
}

View File

@@ -22,6 +22,13 @@ class ZendMonitorHandlerTest extends TestCase
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->zendMonitorHandler);
}
/**
* @covers Monolog\Handler\ZendMonitorHandler::write
*/