NormalizerFormatterTest.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. <?php
  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. /**
  12. * @covers Monolog\Formatter\NormalizerFormatter
  13. */
  14. class NormalizerFormatterTest extends \PHPUnit_Framework_TestCase
  15. {
  16. public function testFormat()
  17. {
  18. $formatter = new NormalizerFormatter('Y-m-d');
  19. $formatted = $formatter->format(array(
  20. 'level_name' => 'ERROR',
  21. 'channel' => 'meh',
  22. 'message' => 'foo',
  23. 'datetime' => new \DateTime,
  24. 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
  25. 'context' => array(
  26. 'foo' => 'bar',
  27. 'baz' => 'qux',
  28. 'inf' => INF,
  29. '-inf' => -INF,
  30. 'nan' => acos(4),
  31. ),
  32. ));
  33. $this->assertEquals(array(
  34. 'level_name' => 'ERROR',
  35. 'channel' => 'meh',
  36. 'message' => 'foo',
  37. 'datetime' => date('Y-m-d'),
  38. 'extra' => array(
  39. 'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})',
  40. 'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)',
  41. 'baz' => array(),
  42. 'res' => '[resource] (stream)',
  43. ),
  44. 'context' => array(
  45. 'foo' => 'bar',
  46. 'baz' => 'qux',
  47. 'inf' => 'INF',
  48. '-inf' => '-INF',
  49. 'nan' => 'NaN',
  50. )
  51. ), $formatted);
  52. }
  53. public function testFormatExceptions()
  54. {
  55. $formatter = new NormalizerFormatter('Y-m-d');
  56. $e = new \LogicException('bar');
  57. $e2 = new \RuntimeException('foo', 0, $e);
  58. $formatted = $formatter->format(array(
  59. 'exception' => $e2,
  60. ));
  61. $this->assertGreaterThan(5, count($formatted['exception']['trace']));
  62. $this->assertTrue(isset($formatted['exception']['previous']));
  63. unset($formatted['exception']['trace'], $formatted['exception']['previous']);
  64. $this->assertEquals(array(
  65. 'exception' => array(
  66. 'class' => get_class($e2),
  67. 'message' => $e2->getMessage(),
  68. 'code' => $e2->getCode(),
  69. 'file' => $e2->getFile().':'.$e2->getLine(),
  70. )
  71. ), $formatted);
  72. }
  73. public function testFormatToStringExceptionHandle()
  74. {
  75. $formatter = new NormalizerFormatter('Y-m-d');
  76. $this->setExpectedException('RuntimeException', 'Could not convert to string');
  77. $formatter->format(array(
  78. 'myObject' => new TestToStringError(),
  79. ));
  80. }
  81. public function testBatchFormat()
  82. {
  83. $formatter = new NormalizerFormatter('Y-m-d');
  84. $formatted = $formatter->formatBatch(array(
  85. array(
  86. 'level_name' => 'CRITICAL',
  87. 'channel' => 'test',
  88. 'message' => 'bar',
  89. 'context' => array(),
  90. 'datetime' => new \DateTime,
  91. 'extra' => array(),
  92. ),
  93. array(
  94. 'level_name' => 'WARNING',
  95. 'channel' => 'log',
  96. 'message' => 'foo',
  97. 'context' => array(),
  98. 'datetime' => new \DateTime,
  99. 'extra' => array(),
  100. ),
  101. ));
  102. $this->assertEquals(array(
  103. array(
  104. 'level_name' => 'CRITICAL',
  105. 'channel' => 'test',
  106. 'message' => 'bar',
  107. 'context' => array(),
  108. 'datetime' => date('Y-m-d'),
  109. 'extra' => array(),
  110. ),
  111. array(
  112. 'level_name' => 'WARNING',
  113. 'channel' => 'log',
  114. 'message' => 'foo',
  115. 'context' => array(),
  116. 'datetime' => date('Y-m-d'),
  117. 'extra' => array(),
  118. ),
  119. ), $formatted);
  120. }
  121. /**
  122. * Test issue #137
  123. */
  124. public function testIgnoresRecursiveObjectReferences()
  125. {
  126. // set up the recursion
  127. $foo = new \stdClass();
  128. $bar = new \stdClass();
  129. $foo->bar = $bar;
  130. $bar->foo = $foo;
  131. // set an error handler to assert that the error is not raised anymore
  132. $that = $this;
  133. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  134. if (error_reporting() & $level) {
  135. restore_error_handler();
  136. $that->fail("$message should not be raised");
  137. }
  138. });
  139. $formatter = new NormalizerFormatter();
  140. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  141. $reflMethod->setAccessible(true);
  142. $res = $reflMethod->invoke($formatter, array($foo, $bar), true);
  143. restore_error_handler();
  144. $this->assertEquals(@json_encode(array($foo, $bar)), $res);
  145. }
  146. public function testIgnoresInvalidTypes()
  147. {
  148. // set up the recursion
  149. $resource = fopen(__FILE__, 'r');
  150. // set an error handler to assert that the error is not raised anymore
  151. $that = $this;
  152. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  153. if (error_reporting() & $level) {
  154. restore_error_handler();
  155. $that->fail("$message should not be raised");
  156. }
  157. });
  158. $formatter = new NormalizerFormatter();
  159. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  160. $reflMethod->setAccessible(true);
  161. $res = $reflMethod->invoke($formatter, array($resource), true);
  162. restore_error_handler();
  163. $this->assertEquals(@json_encode(array($resource)), $res);
  164. }
  165. /**
  166. * @expectedException RuntimeException
  167. */
  168. public function testThrowsOnInvalidEncoding()
  169. {
  170. $formatter = new NormalizerFormatter();
  171. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  172. $reflMethod->setAccessible(true);
  173. // send an invalid unicode sequence
  174. $res = $reflMethod->invoke($formatter, array('message' => "\xB1\x31"));
  175. if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
  176. throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
  177. }
  178. }
  179. public function testExceptionTraceWithArgs()
  180. {
  181. if (defined('HHVM_VERSION')) {
  182. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  183. }
  184. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  185. // and no file or line are included in the trace because it's treated as internal function
  186. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  187. throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  188. });
  189. try {
  190. // This will contain $resource and $wrappedResource as arguments in the trace item
  191. $resource = fopen('php://memory', 'rw+');
  192. fwrite($resource, 'test_resource');
  193. $wrappedResource = new TestFooNorm;
  194. $wrappedResource->foo = $resource;
  195. // Just do something stupid with a resource/wrapped resource as argument
  196. array_keys($wrappedResource);
  197. } catch (\Exception $e) {
  198. restore_error_handler();
  199. }
  200. $formatter = new NormalizerFormatter();
  201. $record = array('context' => array('exception' => $e));
  202. $result = $formatter->format($record);
  203. $this->assertRegExp(
  204. '%"resource":"\[resource\] \(stream\)"%',
  205. $result['context']['exception']['trace'][0]
  206. );
  207. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  208. $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%';
  209. } else {
  210. $pattern = '%\\\\"foo\\\\":null%';
  211. }
  212. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  213. $this->assertRegExp(
  214. $pattern,
  215. $result['context']['exception']['trace'][0]
  216. );
  217. }
  218. }
  219. class TestFooNorm
  220. {
  221. public $foo = 'foo';
  222. }
  223. class TestBarNorm
  224. {
  225. public function __toString()
  226. {
  227. return 'bar';
  228. }
  229. }
  230. class TestStreamFoo
  231. {
  232. public $foo;
  233. public $resource;
  234. public function __construct($resource)
  235. {
  236. $this->resource = $resource;
  237. $this->foo = 'BAR';
  238. }
  239. public function __toString()
  240. {
  241. fseek($this->resource, 0);
  242. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  243. }
  244. }
  245. class TestToStringError
  246. {
  247. public function __toString()
  248. {
  249. throw new \RuntimeException('Could not convert to string');
  250. }
  251. }