2
0

FileHandlerTest.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Test\Michel\Log;
  3. use Michel\UniTester\TestCase;
  4. use Psr\Log\LogLevel;
  5. class FileHandlerTest extends TestCase
  6. {
  7. private ?string $tmpFile = null;
  8. protected function setUp(): void
  9. {
  10. $this->tmpFile = sys_get_temp_dir() . '/log/' . date('Y-m-d') . '.log';
  11. if (file_exists($this->tmpFile)) {
  12. unlink($this->tmpFile);
  13. }
  14. }
  15. protected function tearDown(): void
  16. {
  17. if (file_exists($this->tmpFile)) {
  18. unlink($this->tmpFile);
  19. }
  20. if (is_dir(dirname($this->tmpFile))) {
  21. rmdir(dirname($this->tmpFile));
  22. }
  23. }
  24. protected function execute(): void
  25. {
  26. $this->testCreateDir();
  27. $this->testWriteInFile();
  28. }
  29. public function testCreateDir()
  30. {
  31. $tmp_dir = dirname($this->tmpFile);
  32. if (is_dir($tmp_dir)) {
  33. rmdir($tmp_dir);
  34. }
  35. new \Michel\Log\Handler\FileHandler($this->tmpFile);
  36. $this->assertTrue(is_dir($tmp_dir));
  37. }
  38. public function testWriteInFile()
  39. {
  40. $handler = new \Michel\Log\Handler\FileHandler($this->tmpFile);
  41. $vars = [
  42. 'message' => 'is a test',
  43. 'level' => strtoupper(LogLevel::INFO),
  44. 'timestamp' => (new \DateTimeImmutable())->format('c'),
  45. ];
  46. $handler->handle($vars);
  47. $this->assertTrue(file_exists($this->tmpFile));
  48. $fileObject = new \SplFileObject($this->tmpFile);
  49. $line = $fileObject->current();
  50. $this->assertEquals($line, sprintf('%s [%s]: %s' . PHP_EOL, $vars['timestamp'], $vars['level'], $vars['message']));
  51. }
  52. }