ScalarFormatterTest.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog\Formatter;
  11. use Monolog\DateTimeImmutable;
  12. use Monolog\Test\TestCase;
  13. class ScalarFormatterTest extends TestCase
  14. {
  15. private ScalarFormatter $formatter;
  16. public function setUp(): void
  17. {
  18. $this->formatter = new ScalarFormatter();
  19. }
  20. public function buildTrace(\Exception $e)
  21. {
  22. $data = [];
  23. $trace = $e->getTrace();
  24. foreach ($trace as $frame) {
  25. if (isset($frame['file'])) {
  26. $data[] = $frame['file'].':'.$frame['line'];
  27. }
  28. }
  29. return $data;
  30. }
  31. public function encodeJson($data)
  32. {
  33. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  34. }
  35. public function testFormat()
  36. {
  37. $exception = new \Exception('foo');
  38. $formatted = $this->formatter->format($this->getRecord(context: [
  39. 'foo' => 'string',
  40. 'bar' => 1,
  41. 'baz' => false,
  42. 'bam' => [1, 2, 3],
  43. 'bat' => ['foo' => 'bar'],
  44. 'bap' => $dt = new DateTimeImmutable(true),
  45. 'ban' => $exception,
  46. ]));
  47. $this->assertSame($this->encodeJson([
  48. 'foo' => 'string',
  49. 'bar' => 1,
  50. 'baz' => false,
  51. 'bam' => [1, 2, 3],
  52. 'bat' => ['foo' => 'bar'],
  53. 'bap' => (string) $dt,
  54. 'ban' => [
  55. 'class' => get_class($exception),
  56. 'message' => $exception->getMessage(),
  57. 'code' => $exception->getCode(),
  58. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  59. 'trace' => $this->buildTrace($exception),
  60. ],
  61. ]), $formatted['context']);
  62. }
  63. public function testFormatWithErrorContext()
  64. {
  65. $context = ['file' => 'foo', 'line' => 1];
  66. $formatted = $this->formatter->format($this->getRecord(
  67. context: $context,
  68. ));
  69. $this->assertSame($this->encodeJson($context), $formatted['context']);
  70. }
  71. public function testFormatWithExceptionContext()
  72. {
  73. $exception = new \Exception('foo');
  74. $formatted = $this->formatter->format($this->getRecord(context: [
  75. 'exception' => $exception,
  76. ]));
  77. $this->assertSame($this->encodeJson([
  78. 'exception' => [
  79. 'class' => get_class($exception),
  80. 'message' => $exception->getMessage(),
  81. 'code' => $exception->getCode(),
  82. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  83. 'trace' => $this->buildTrace($exception),
  84. ],
  85. ]), $formatted['context']);
  86. }
  87. }