ScalarFormatterTest.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. array_shift($trace);
  14. foreach ($trace as $frame) {
  15. if (isset($frame['file'])) {
  16. $data[] = $frame['file'].':'.$frame['line'];
  17. } else {
  18. $data[] = json_encode($frame);
  19. }
  20. }
  21. return $data;
  22. }
  23. public function encodeJson($data)
  24. {
  25. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  26. return json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  27. }
  28. return json_encode($data);
  29. }
  30. public function testFormat()
  31. {
  32. $exception = new \Exception('foo');
  33. $formatted = $this->formatter->format(array(
  34. 'foo' => 'string',
  35. 'bar' => 1,
  36. 'baz' => false,
  37. 'bam' => array(1,2,3),
  38. 'bat' => array('foo' => 'bar'),
  39. 'bap' => \DateTime::createFromFormat(\DateTime::ISO8601, '1970-01-01T00:00:00+0000'),
  40. 'ban' => $exception
  41. ));
  42. $this->assertSame(array(
  43. 'foo' => 'string',
  44. 'bar' => 1,
  45. 'baz' => false,
  46. 'bam' => $this->encodeJson(array(1,2,3)),
  47. 'bat' => $this->encodeJson(array('foo' => 'bar')),
  48. 'bap' => '1970-01-01 00:00:00',
  49. 'ban' => $this->encodeJson(array(
  50. 'class' => get_class($exception),
  51. 'message' => $exception->getMessage(),
  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. 'file' => $exception->getFile() . ':' . $exception->getLine(),
  81. 'trace' => $this->buildTrace($exception)
  82. )
  83. ))
  84. ), $formatted);
  85. }
  86. }