NormalizerFormatterTest.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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 tearDown()
  17. {
  18. \PHPUnit_Framework_Error_Warning::$enabled = true;
  19. return parent::tearDown();
  20. }
  21. public function testFormat()
  22. {
  23. $formatter = new NormalizerFormatter('Y-m-d');
  24. $formatted = $formatter->format(array(
  25. 'level_name' => 'ERROR',
  26. 'channel' => 'meh',
  27. 'message' => 'foo',
  28. 'datetime' => new \DateTimeImmutable,
  29. 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
  30. 'context' => array(
  31. 'foo' => 'bar',
  32. 'baz' => 'qux',
  33. 'inf' => INF,
  34. '-inf' => -INF,
  35. 'nan' => acos(4),
  36. ),
  37. ));
  38. $this->assertEquals(array(
  39. 'level_name' => 'ERROR',
  40. 'channel' => 'meh',
  41. 'message' => 'foo',
  42. 'datetime' => date('Y-m-d'),
  43. 'extra' => array(
  44. 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
  45. 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
  46. 'baz' => array(),
  47. 'res' => '[resource(stream)]',
  48. ),
  49. 'context' => array(
  50. 'foo' => 'bar',
  51. 'baz' => 'qux',
  52. 'inf' => 'INF',
  53. '-inf' => '-INF',
  54. 'nan' => 'NaN',
  55. ),
  56. ), $formatted);
  57. }
  58. public function testFormatExceptions()
  59. {
  60. $formatter = new NormalizerFormatter('Y-m-d');
  61. $e = new \LogicException('bar');
  62. $e2 = new \RuntimeException('foo', 0, $e);
  63. $formatted = $formatter->format(array(
  64. 'exception' => $e2,
  65. ));
  66. $this->assertGreaterThan(5, count($formatted['exception']['trace']));
  67. $this->assertTrue(isset($formatted['exception']['previous']));
  68. unset($formatted['exception']['trace'], $formatted['exception']['previous']);
  69. $this->assertEquals(array(
  70. 'exception' => array(
  71. 'class' => get_class($e2),
  72. 'message' => $e2->getMessage(),
  73. 'code' => $e2->getCode(),
  74. 'file' => $e2->getFile().':'.$e2->getLine(),
  75. ),
  76. ), $formatted);
  77. }
  78. public function testFormatToStringExceptionHandle()
  79. {
  80. $formatter = new NormalizerFormatter('Y-m-d');
  81. $this->setExpectedException('RuntimeException', 'Could not convert to string');
  82. $formatter->format(array(
  83. 'myObject' => new TestToStringError(),
  84. ));
  85. }
  86. public function testBatchFormat()
  87. {
  88. $formatter = new NormalizerFormatter('Y-m-d');
  89. $formatted = $formatter->formatBatch(array(
  90. array(
  91. 'level_name' => 'CRITICAL',
  92. 'channel' => 'test',
  93. 'message' => 'bar',
  94. 'context' => array(),
  95. 'datetime' => new \DateTimeImmutable,
  96. 'extra' => array(),
  97. ),
  98. array(
  99. 'level_name' => 'WARNING',
  100. 'channel' => 'log',
  101. 'message' => 'foo',
  102. 'context' => array(),
  103. 'datetime' => new \DateTimeImmutable,
  104. 'extra' => array(),
  105. ),
  106. ));
  107. $this->assertEquals(array(
  108. array(
  109. 'level_name' => 'CRITICAL',
  110. 'channel' => 'test',
  111. 'message' => 'bar',
  112. 'context' => array(),
  113. 'datetime' => date('Y-m-d'),
  114. 'extra' => array(),
  115. ),
  116. array(
  117. 'level_name' => 'WARNING',
  118. 'channel' => 'log',
  119. 'message' => 'foo',
  120. 'context' => array(),
  121. 'datetime' => date('Y-m-d'),
  122. 'extra' => array(),
  123. ),
  124. ), $formatted);
  125. }
  126. /**
  127. * Test issue #137
  128. */
  129. public function testIgnoresRecursiveObjectReferences()
  130. {
  131. // set up the recursion
  132. $foo = new \stdClass();
  133. $bar = new \stdClass();
  134. $foo->bar = $bar;
  135. $bar->foo = $foo;
  136. // set an error handler to assert that the error is not raised anymore
  137. $that = $this;
  138. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  139. if (error_reporting() & $level) {
  140. restore_error_handler();
  141. $that->fail("$message should not be raised");
  142. }
  143. });
  144. $formatter = new NormalizerFormatter();
  145. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  146. $reflMethod->setAccessible(true);
  147. $res = $reflMethod->invoke($formatter, array($foo, $bar), true);
  148. restore_error_handler();
  149. $this->assertEquals(@json_encode(array($foo, $bar)), $res);
  150. }
  151. public function testIgnoresInvalidTypes()
  152. {
  153. // set up the recursion
  154. $resource = fopen(__FILE__, 'r');
  155. // set an error handler to assert that the error is not raised anymore
  156. $that = $this;
  157. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  158. if (error_reporting() & $level) {
  159. restore_error_handler();
  160. $that->fail("$message should not be raised");
  161. }
  162. });
  163. $formatter = new NormalizerFormatter();
  164. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  165. $reflMethod->setAccessible(true);
  166. $res = $reflMethod->invoke($formatter, array($resource), true);
  167. restore_error_handler();
  168. $this->assertEquals(@json_encode(array($resource)), $res);
  169. }
  170. /**
  171. * @expectedException RuntimeException
  172. */
  173. public function testThrowsOnInvalidEncoding()
  174. {
  175. $formatter = new NormalizerFormatter();
  176. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  177. $reflMethod->setAccessible(true);
  178. // send an invalid unicode sequence as a object that can't be cleaned
  179. $record = new \stdClass;
  180. $record->message = "\xB1\x31";
  181. $reflMethod->invoke($formatter, $record);
  182. }
  183. public function testConvertsInvalidEncodingAsLatin9()
  184. {
  185. $formatter = new NormalizerFormatter();
  186. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  187. $reflMethod->setAccessible(true);
  188. $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
  189. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  190. }
  191. /**
  192. * @param mixed $in Input
  193. * @param mixed $expect Expected output
  194. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  195. * @dataProvider providesDetectAndCleanUtf8
  196. */
  197. public function testDetectAndCleanUtf8($in, $expect)
  198. {
  199. $formatter = new NormalizerFormatter();
  200. $formatter->detectAndCleanUtf8($in);
  201. $this->assertSame($expect, $in);
  202. }
  203. public function providesDetectAndCleanUtf8()
  204. {
  205. $obj = new \stdClass;
  206. return array(
  207. 'null' => array(null, null),
  208. 'int' => array(123, 123),
  209. 'float' => array(123.45, 123.45),
  210. 'bool false' => array(false, false),
  211. 'bool true' => array(true, true),
  212. 'ascii string' => array('abcdef', 'abcdef'),
  213. 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
  214. 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
  215. 'empty array' => array(array(), array()),
  216. 'array' => array(array('abcdef'), array('abcdef')),
  217. 'object' => array($obj, $obj),
  218. );
  219. }
  220. /**
  221. * @param int $code
  222. * @param string $msg
  223. * @dataProvider providesHandleJsonErrorFailure
  224. */
  225. public function testHandleJsonErrorFailure($code, $msg)
  226. {
  227. $formatter = new NormalizerFormatter();
  228. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  229. $reflMethod->setAccessible(true);
  230. $this->setExpectedException('RuntimeException', $msg);
  231. $reflMethod->invoke($formatter, $code, 'faked');
  232. }
  233. public function providesHandleJsonErrorFailure()
  234. {
  235. return array(
  236. 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
  237. 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
  238. 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
  239. 'default' => array(-1, 'Unknown error'),
  240. );
  241. }
  242. public function testExceptionTraceWithArgs()
  243. {
  244. if (defined('HHVM_VERSION')) {
  245. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  246. }
  247. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  248. // and no file or line are included in the trace because it's treated as internal function
  249. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  250. throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  251. });
  252. try {
  253. // This will contain $resource and $wrappedResource as arguments in the trace item
  254. $resource = fopen('php://memory', 'rw+');
  255. fwrite($resource, 'test_resource');
  256. $wrappedResource = new TestFooNorm;
  257. $wrappedResource->foo = $resource;
  258. // Just do something stupid with a resource/wrapped resource as argument
  259. array_keys($wrappedResource);
  260. } catch (\Throwable $e) {
  261. restore_error_handler();
  262. }
  263. $formatter = new NormalizerFormatter();
  264. $record = array('context' => array('exception' => $e));
  265. $result = $formatter->format($record);
  266. $this->assertRegExp(
  267. '%"resource":"\[resource\(stream\)\]"%',
  268. $result['context']['exception']['trace'][0]
  269. );
  270. $pattern = '%"wrappedResource":\{"Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm":"JSON_ERROR"\}%';
  271. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  272. $this->assertRegExp(
  273. $pattern,
  274. $result['context']['exception']['trace'][0]
  275. );
  276. }
  277. }
  278. class TestFooNorm
  279. {
  280. public $foo = 'fooValue';
  281. }
  282. class TestBarNorm
  283. {
  284. public function __toString()
  285. {
  286. return 'bar';
  287. }
  288. }
  289. class TestStreamFoo
  290. {
  291. public $foo;
  292. public $resource;
  293. public function __construct($resource)
  294. {
  295. $this->resource = $resource;
  296. $this->foo = 'BAR';
  297. }
  298. public function __toString()
  299. {
  300. fseek($this->resource, 0);
  301. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  302. }
  303. }
  304. class TestToStringError
  305. {
  306. public function __toString()
  307. {
  308. throw new \RuntimeException('Could not convert to string');
  309. }
  310. }