beste/psr-testlogger

PSR-3兼容的测试日志记录器,适用于喜欢测试并希望检查其应用程序是否按预期记录消息的开发者。

1.0.0 2022-09-24 15:52 UTC

This package is auto-updated.

Last update: 2024-08-26 03:08:27 UTC


README

PSR-3兼容的测试日志记录器,适用于喜欢测试并希望检查其应用程序是否按预期记录消息的开发者。

Current version Packagist PHP Version Support Monthly Downloads Total Downloads Tests Sponsor

安装

composer require --dev beste/psr-testlogger

用法

在你的单元测试中,将Beste\Psr\Log\TestLogger类注入到期望Prs\Log\LoggerInterface的测试主题中。

测试日志记录器记录所有日志消息,并通过records属性暴露,该属性是Beste\Psr\Log\Records的实例。

use Beste\Psr\Log\Record;
use Beste\Psr\Log\TestLogger;
use Psr\Log\LoggerInterface;
use Psr\Log\LogLevel;

final class Subject
{
    public function __construct(
        public readonly LoggerInterface $logger
    ) {}
    
    public function doSomething(): void
    {
        $this->logger->info('Doing something');
        $this->logger->warning('1st problem');
        $this->logger->warning('2nd problem');
        $this->logger->critical('Uh oh!');
    }
}

final class SubjectTest extends \PHPUnit\Framework\TestCase
{
    private TestLogger $logger;
    private Subject $subject;
    
    protected function setUp() : void{
        $this->logger = TestLogger::create();
    }
    
    /** @test */
    public function it_does_something(): void
    {
        $this->subject->doSomething();
        
        self::assertCount(4, $this->logger->records);
        
        self::assertEqualsCanonicalizing(
            [LogLevel::INFO, LogLevel::WARNING, LogLevel::CRITICAL],
            $this->logger->records->levels()
        );
        
        self::assertTrue($this->logger->records->includeMessagesWithLevel('info'));
        self::assertCount(1, $this->logger->records->filteredByLevel('info'));
        self::assertCount(3, $this->logger->records->filteredByLevel('info', 'warning'));
        
        self::assertTrue($this->logger->records->includeMessagesContaining('problem'));
        self::assertCount(2, $this->logger->records->filteredByMessageContaining('problem'));
        
        self::assertTrue($this->logger->records->includeMessagesMatching('/^\d{1,}(st|nd)/i'));
        self::assertCount(2, $this->logger->records->filteredByMessageMatching('/^\d{1,}(st|nd)/i'));
        
        // You can filter by your own criteria. If you discover criteria not natively
        // covered by the test logger, please consider a pull request.
        self::assertTrue($this->logger->records->includeMessagesBy(fn (Record $r) => str_contains($r->level, 'n')));
        self::assertCount(3, $this->logger->records->filteredBy(fn (Record $r) => str_contains($r->level, 'n')));  
    }
}

许可证

本项目发布在MIT许可证下。