ScalarFormatterTest.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Monolog\Formatter;
  3. class ScalarFormatterTest extends \PHPUnit_Framework_TestCase
  4. {
  5. public function setUp()
  6. {
  7. $this->formatter = new ScalarFormatter();
  8. }
  9. public function buildTrace(\Exception $e)
  10. {
  11. $data = array();
  12. $trace = $e->getTrace();
  13. foreach ($trace as $frame) {
  14. if (isset($frame['file'])) {
  15. $data[] = $frame['file'].':'.$frame['line'];
  16. } else {
  17. $data[] = json_encode($frame);
  18. }
  19. }
  20. return $data;
  21. }
  22. public function encodeJson($data)
  23. {
  24. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  25. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  26. }
  27. return json_encode($data);
  28. }
  29. public function testFormat()
  30. {
  31. $exception = new \Exception('foo');
  32. $formatted = $this->formatter->format(array(
  33. 'foo' => 'string',
  34. 'bar' => 1,
  35. 'baz' => false,
  36. 'bam' => array(1, 2, 3),
  37. 'bat' => array('foo' => 'bar'),
  38. 'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'),
  39. 'ban' => $exception
  40. ));
  41. $this->assertSame(array(
  42. 'foo' => 'string',
  43. 'bar' => 1,
  44. 'baz' => false,
  45. 'bam' => $this->encodeJson(array(1, 2, 3)),
  46. 'bat' => $this->encodeJson(array('foo' => 'bar')),
  47. 'bap' => '1970-01-01 00:00:00',
  48. 'ban' => $this->encodeJson(array(
  49. 'class' => get_class($exception),
  50. 'message' => $exception->getMessage(),
  51. 'code' => $exception->getCode(),
  52. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  53. 'trace' => $this->buildTrace($exception)
  54. ))
  55. ), $formatted);
  56. }
  57. public function testFormatWithErrorContext()
  58. {
  59. $context = array('file' => 'foo', 'line' => 1);
  60. $formatted = $this->formatter->format(array(
  61. 'context' => $context
  62. ));
  63. $this->assertSame(array(
  64. 'context' => $this->encodeJson($context)
  65. ), $formatted);
  66. }
  67. public function testFormatWithExceptionContext()
  68. {
  69. $exception = new \Exception('foo');
  70. $formatted = $this->formatter->format(array(
  71. 'context' => array(
  72. 'exception' => $exception
  73. )
  74. ));
  75. $this->assertSame(array(
  76. 'context' => $this->encodeJson(array(
  77. 'exception' => array(
  78. 'class' => get_class($exception),
  79. 'message' => $exception->getMessage(),
  80. 'code' => $exception->getCode(),
  81. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  82. 'trace' => $this->buildTrace($exception)
  83. )
  84. ))
  85. ), $formatted);
  86. }
  87. }