NormalizerFormatterTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. <?php declare(strict_types=1);
  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([
  25. 'level_name' => 'ERROR',
  26. 'channel' => 'meh',
  27. 'message' => 'foo',
  28. 'datetime' => new \DateTimeImmutable,
  29. 'extra' => ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
  30. 'context' => [
  31. 'foo' => 'bar',
  32. 'baz' => 'qux',
  33. 'inf' => INF,
  34. '-inf' => -INF,
  35. 'nan' => acos(4),
  36. ],
  37. ]);
  38. $this->assertEquals([
  39. 'level_name' => 'ERROR',
  40. 'channel' => 'meh',
  41. 'message' => 'foo',
  42. 'datetime' => date('Y-m-d'),
  43. 'extra' => [
  44. 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
  45. 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
  46. 'baz' => [],
  47. 'res' => '[resource(stream)]',
  48. ],
  49. 'context' => [
  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([
  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([
  70. 'exception' => [
  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 testFormatSoapFaultException()
  79. {
  80. if (!class_exists('SoapFault')) {
  81. $this->markTestSkipped('Requires the soap extension');
  82. }
  83. $formatter = new NormalizerFormatter('Y-m-d');
  84. $e = new \SoapFault('foo', 'bar', 'hello', 'world');
  85. $formatted = $formatter->format([
  86. 'exception' => $e,
  87. ]);
  88. unset($formatted['exception']['trace']);
  89. $this->assertEquals([
  90. 'exception' => [
  91. 'class' => 'SoapFault',
  92. 'message' => 'bar',
  93. 'code' => 0,
  94. 'file' => $e->getFile().':'.$e->getLine(),
  95. 'faultcode' => 'foo',
  96. 'faultactor' => 'hello',
  97. 'detail' => 'world',
  98. ],
  99. ], $formatted);
  100. }
  101. public function testFormatToStringExceptionHandle()
  102. {
  103. $formatter = new NormalizerFormatter('Y-m-d');
  104. $this->expectException('RuntimeException');
  105. $this->expectExceptionMessage('Could not convert to string');
  106. $formatter->format([
  107. 'myObject' => new TestToStringError(),
  108. ]);
  109. }
  110. public function testBatchFormat()
  111. {
  112. $formatter = new NormalizerFormatter('Y-m-d');
  113. $formatted = $formatter->formatBatch([
  114. [
  115. 'level_name' => 'CRITICAL',
  116. 'channel' => 'test',
  117. 'message' => 'bar',
  118. 'context' => [],
  119. 'datetime' => new \DateTimeImmutable,
  120. 'extra' => [],
  121. ],
  122. [
  123. 'level_name' => 'WARNING',
  124. 'channel' => 'log',
  125. 'message' => 'foo',
  126. 'context' => [],
  127. 'datetime' => new \DateTimeImmutable,
  128. 'extra' => [],
  129. ],
  130. ]);
  131. $this->assertEquals([
  132. [
  133. 'level_name' => 'CRITICAL',
  134. 'channel' => 'test',
  135. 'message' => 'bar',
  136. 'context' => [],
  137. 'datetime' => date('Y-m-d'),
  138. 'extra' => [],
  139. ],
  140. [
  141. 'level_name' => 'WARNING',
  142. 'channel' => 'log',
  143. 'message' => 'foo',
  144. 'context' => [],
  145. 'datetime' => date('Y-m-d'),
  146. 'extra' => [],
  147. ],
  148. ], $formatted);
  149. }
  150. /**
  151. * Test issue #137
  152. */
  153. public function testIgnoresRecursiveObjectReferences()
  154. {
  155. // set up the recursion
  156. $foo = new \stdClass();
  157. $bar = new \stdClass();
  158. $foo->bar = $bar;
  159. $bar->foo = $foo;
  160. // set an error handler to assert that the error is not raised anymore
  161. $that = $this;
  162. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  163. if (error_reporting() & $level) {
  164. restore_error_handler();
  165. $that->fail("$message should not be raised");
  166. }
  167. });
  168. $formatter = new NormalizerFormatter();
  169. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  170. $reflMethod->setAccessible(true);
  171. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  172. restore_error_handler();
  173. $this->assertEquals(@json_encode([$foo, $bar]), $res);
  174. }
  175. public function testCanNormalizeReferences()
  176. {
  177. $formatter = new NormalizerFormatter();
  178. $x = ['foo' => 'bar'];
  179. $y = ['x' => &$x];
  180. $x['y'] = &$y;
  181. $formatter->format($y);
  182. }
  183. public function testIgnoresInvalidTypes()
  184. {
  185. // set up the recursion
  186. $resource = fopen(__FILE__, 'r');
  187. // set an error handler to assert that the error is not raised anymore
  188. $that = $this;
  189. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  190. if (error_reporting() & $level) {
  191. restore_error_handler();
  192. $that->fail("$message should not be raised");
  193. }
  194. });
  195. $formatter = new NormalizerFormatter();
  196. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  197. $reflMethod->setAccessible(true);
  198. $res = $reflMethod->invoke($formatter, [$resource], true);
  199. restore_error_handler();
  200. $this->assertEquals(@json_encode([$resource]), $res);
  201. }
  202. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  203. {
  204. $formatter = new NormalizerFormatter();
  205. $largeArray = range(1, 1000);
  206. $res = $formatter->format(array(
  207. 'level_name' => 'CRITICAL',
  208. 'channel' => 'test',
  209. 'message' => 'bar',
  210. 'context' => array($largeArray),
  211. 'datetime' => new \DateTime,
  212. 'extra' => array(),
  213. ));
  214. $this->assertCount(1000, $res['context'][0]);
  215. $this->assertArrayNotHasKey('...', $res['context'][0]);
  216. }
  217. public function testNormalizeHandleLargeArrays()
  218. {
  219. $formatter = new NormalizerFormatter();
  220. $largeArray = range(1, 2000);
  221. $res = $formatter->format(array(
  222. 'level_name' => 'CRITICAL',
  223. 'channel' => 'test',
  224. 'message' => 'bar',
  225. 'context' => array($largeArray),
  226. 'datetime' => new \DateTime,
  227. 'extra' => array(),
  228. ));
  229. $this->assertCount(1001, $res['context'][0]);
  230. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  231. }
  232. /**
  233. * @expectedException RuntimeException
  234. */
  235. public function testThrowsOnInvalidEncoding()
  236. {
  237. $formatter = new NormalizerFormatter();
  238. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  239. $reflMethod->setAccessible(true);
  240. // send an invalid unicode sequence as a object that can't be cleaned
  241. $record = new \stdClass;
  242. $record->message = "\xB1\x31";
  243. $reflMethod->invoke($formatter, $record);
  244. }
  245. public function testConvertsInvalidEncodingAsLatin9()
  246. {
  247. $formatter = new NormalizerFormatter();
  248. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  249. $reflMethod->setAccessible(true);
  250. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  251. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  252. }
  253. public function testMaxNormalizeDepth()
  254. {
  255. $formatter = new NormalizerFormatter();
  256. $formatter->setMaxNormalizeDepth(1);
  257. $throwable = new \Error('Foo');
  258. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  259. $this->assertEquals(
  260. 'Over 1 levels deep, aborting normalization',
  261. $message['context']['exception']
  262. );
  263. }
  264. public function testMaxNormalizeItemCountWith0ItemsMax()
  265. {
  266. $formatter = new NormalizerFormatter();
  267. $formatter->setMaxNormalizeDepth(9);
  268. $formatter->setMaxNormalizeItemCount(0);
  269. $throwable = new \Error('Foo');
  270. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  271. $this->assertEquals(
  272. ["..." => "Over 0 items (6 total), aborting normalization"],
  273. $message
  274. );
  275. }
  276. public function testMaxNormalizeItemCountWith3ItemsMax()
  277. {
  278. $formatter = new NormalizerFormatter();
  279. $formatter->setMaxNormalizeDepth(9);
  280. $formatter->setMaxNormalizeItemCount(2);
  281. $throwable = new \Error('Foo');
  282. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  283. $this->assertEquals(
  284. ["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"],
  285. $message
  286. );
  287. }
  288. /**
  289. * @param mixed $in Input
  290. * @param mixed $expect Expected output
  291. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  292. * @dataProvider providesDetectAndCleanUtf8
  293. */
  294. public function testDetectAndCleanUtf8($in, $expect)
  295. {
  296. $formatter = new NormalizerFormatter();
  297. $formatter->detectAndCleanUtf8($in);
  298. $this->assertSame($expect, $in);
  299. }
  300. public function providesDetectAndCleanUtf8()
  301. {
  302. $obj = new \stdClass;
  303. return [
  304. 'null' => [null, null],
  305. 'int' => [123, 123],
  306. 'float' => [123.45, 123.45],
  307. 'bool false' => [false, false],
  308. 'bool true' => [true, true],
  309. 'ascii string' => ['abcdef', 'abcdef'],
  310. 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
  311. 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
  312. 'empty array' => [[], []],
  313. 'array' => [['abcdef'], ['abcdef']],
  314. 'object' => [$obj, $obj],
  315. ];
  316. }
  317. /**
  318. * @param int $code
  319. * @param string $msg
  320. * @dataProvider providesHandleJsonErrorFailure
  321. */
  322. public function testHandleJsonErrorFailure($code, $msg)
  323. {
  324. $formatter = new NormalizerFormatter();
  325. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  326. $reflMethod->setAccessible(true);
  327. $this->expectException('RuntimeException');
  328. $this->expectExceptionMessage($msg);
  329. $reflMethod->invoke($formatter, $code, 'faked');
  330. }
  331. public function providesHandleJsonErrorFailure()
  332. {
  333. return [
  334. 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
  335. 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
  336. 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
  337. 'default' => [-1, 'Unknown error'],
  338. ];
  339. }
  340. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  341. // and no file or line are included in the trace because it's treated as internal function
  342. public function testExceptionTraceWithArgs()
  343. {
  344. if (defined('HHVM_VERSION')) {
  345. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  346. }
  347. try {
  348. // This will contain $resource and $wrappedResource as arguments in the trace item
  349. $resource = fopen('php://memory', 'rw+');
  350. fwrite($resource, 'test_resource');
  351. $wrappedResource = new TestFooNorm;
  352. $wrappedResource->foo = $resource;
  353. // Just do something stupid with a resource/wrapped resource as argument
  354. $arr = [$wrappedResource, $resource];
  355. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  356. usort($arr, function ($a, $b) {
  357. throw new \ErrorException('Foo');
  358. });
  359. } catch (\Throwable $e) {
  360. }
  361. $formatter = new NormalizerFormatter();
  362. $record = ['context' => ['exception' => $e]];
  363. $result = $formatter->format($record);
  364. $this->assertRegExp(
  365. '%\[resource\(stream\)\]%',
  366. $result['context']['exception']['trace'][0]
  367. );
  368. $pattern = '%\[\{"Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm":"JSON_ERROR"\}%';
  369. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  370. $this->assertRegExp(
  371. $pattern,
  372. $result['context']['exception']['trace'][0]
  373. );
  374. }
  375. /**
  376. * @param NormalizerFormatter $formatter
  377. * @param \Throwable $exception
  378. *
  379. * @return string
  380. */
  381. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
  382. {
  383. $message = $formatter->format([
  384. 'level_name' => 'CRITICAL',
  385. 'channel' => 'core',
  386. 'context' => ['exception' => $exception],
  387. 'datetime' => null,
  388. 'extra' => [],
  389. 'message' => 'foobar',
  390. ]);
  391. return $message;
  392. }
  393. }
  394. class TestFooNorm
  395. {
  396. public $foo = 'fooValue';
  397. }
  398. class TestBarNorm
  399. {
  400. public function __toString()
  401. {
  402. return 'bar';
  403. }
  404. }
  405. class TestStreamFoo
  406. {
  407. public $foo;
  408. public $resource;
  409. public function __construct($resource)
  410. {
  411. $this->resource = $resource;
  412. $this->foo = 'BAR';
  413. }
  414. public function __toString()
  415. {
  416. fseek($this->resource, 0);
  417. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  418. }
  419. }
  420. class TestToStringError
  421. {
  422. public function __toString()
  423. {
  424. throw new \RuntimeException('Could not convert to string');
  425. }
  426. }