2
0

MemoryHandlerTest.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. namespace Test\Michel\Log;
  3. use Michel\Log\Handler\MemoryHandler;
  4. use Michel\UniTester\TestCase;
  5. use Psr\Log\LogLevel;
  6. class MemoryHandlerTest extends TestCase
  7. {
  8. protected function setUp(): void {}
  9. protected function tearDown(): void {}
  10. protected function execute(): void
  11. {
  12. $storage = [];
  13. $handler = new MemoryHandler($storage);
  14. $vars = [
  15. 'message' => 'is a test',
  16. 'level' => strtoupper(LogLevel::INFO),
  17. 'timestamp' => (new \DateTimeImmutable())->format('c'),
  18. ];
  19. $handler->handle($vars);
  20. $this->assertEquals(1, count($storage));
  21. $this->assertEquals($storage[0], sprintf('%s [%s]: %s', $vars['timestamp'], $vars['level'], $vars['message']));
  22. $this->testLogLevel();
  23. $this->testCustomFormat();
  24. }
  25. private function testLogLevel()
  26. {
  27. $storage = [];
  28. $handler = new MemoryHandler($storage, LogLevel::ERROR);
  29. // Should not log INFO
  30. $handler->handle([
  31. 'level' => LogLevel::INFO,
  32. 'message' => 'info message',
  33. 'timestamp' => '2023-01-01 00:00:00'
  34. ]);
  35. $this->assertEquals(0, count($storage));
  36. // Should log ERROR
  37. $handler->handle([
  38. 'level' => LogLevel::ERROR,
  39. 'message' => 'error message',
  40. 'timestamp' => '2023-01-01 00:00:00'
  41. ]);
  42. $this->assertEquals(1, count($storage));
  43. }
  44. private function testCustomFormat()
  45. {
  46. $storage = [];
  47. $handler = new MemoryHandler($storage);
  48. $handler->setFormat('[%level%] %message%');
  49. $handler->handle([
  50. 'level' => LogLevel::INFO,
  51. 'message' => 'custom format',
  52. 'timestamp' => '2023-01-01 00:00:00'
  53. ]);
  54. $this->assertEquals('[INFO] custom format', $storage[0]);
  55. }
  56. }