ScalarFormatterTest.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  52. 'trace' => $this->buildTrace($exception)
  53. ))
  54. ), $formatted);
  55. }
  56. public function testFormatWithErrorContext()
  57. {
  58. $context = array('file' => 'foo', 'line' => 1);
  59. $formatted = $this->formatter->format(array(
  60. 'context' => $context
  61. ));
  62. $this->assertSame(array(
  63. 'context' => $this->encodeJson($context)
  64. ), $formatted);
  65. }
  66. public function testFormatWithExceptionContext()
  67. {
  68. $exception = new \Exception('foo');
  69. $formatted = $this->formatter->format(array(
  70. 'context' => array(
  71. 'exception' => $exception
  72. )
  73. ));
  74. $this->assertSame(array(
  75. 'context' => $this->encodeJson(array(
  76. 'exception' => array(
  77. 'class' => get_class($exception),
  78. 'message' => $exception->getMessage(),
  79. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  80. 'trace' => $this->buildTrace($exception)
  81. )
  82. ))
  83. ), $formatted);
  84. }
  85. }