NormalizerFormatterTest.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. return true;
  168. });
  169. $formatter = new NormalizerFormatter();
  170. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  171. $reflMethod->setAccessible(true);
  172. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  173. restore_error_handler();
  174. $this->assertEquals(@json_encode([$foo, $bar]), $res);
  175. }
  176. public function testCanNormalizeReferences()
  177. {
  178. $formatter = new NormalizerFormatter();
  179. $x = ['foo' => 'bar'];
  180. $y = ['x' => &$x];
  181. $x['y'] = &$y;
  182. $formatter->format($y);
  183. }
  184. public function testIgnoresInvalidTypes()
  185. {
  186. // set up the recursion
  187. $resource = fopen(__FILE__, 'r');
  188. // set an error handler to assert that the error is not raised anymore
  189. $that = $this;
  190. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  191. if (error_reporting() & $level) {
  192. restore_error_handler();
  193. $that->fail("$message should not be raised");
  194. }
  195. return true;
  196. });
  197. $formatter = new NormalizerFormatter();
  198. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  199. $reflMethod->setAccessible(true);
  200. $res = $reflMethod->invoke($formatter, [$resource], true);
  201. restore_error_handler();
  202. $this->assertEquals(@json_encode([$resource]), $res);
  203. }
  204. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  205. {
  206. $formatter = new NormalizerFormatter();
  207. $largeArray = range(1, 1000);
  208. $res = $formatter->format(array(
  209. 'level_name' => 'CRITICAL',
  210. 'channel' => 'test',
  211. 'message' => 'bar',
  212. 'context' => array($largeArray),
  213. 'datetime' => new \DateTime,
  214. 'extra' => array(),
  215. ));
  216. $this->assertCount(1000, $res['context'][0]);
  217. $this->assertArrayNotHasKey('...', $res['context'][0]);
  218. }
  219. public function testNormalizeHandleLargeArrays()
  220. {
  221. $formatter = new NormalizerFormatter();
  222. $largeArray = range(1, 2000);
  223. $res = $formatter->format(array(
  224. 'level_name' => 'CRITICAL',
  225. 'channel' => 'test',
  226. 'message' => 'bar',
  227. 'context' => array($largeArray),
  228. 'datetime' => new \DateTime,
  229. 'extra' => array(),
  230. ));
  231. $this->assertCount(1001, $res['context'][0]);
  232. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  233. }
  234. /**
  235. * @expectedException RuntimeException
  236. */
  237. public function testThrowsOnInvalidEncoding()
  238. {
  239. $formatter = new NormalizerFormatter();
  240. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  241. $reflMethod->setAccessible(true);
  242. // send an invalid unicode sequence as a object that can't be cleaned
  243. $record = new \stdClass;
  244. $record->message = "\xB1\x31";
  245. $reflMethod->invoke($formatter, $record);
  246. }
  247. public function testConvertsInvalidEncodingAsLatin9()
  248. {
  249. $formatter = new NormalizerFormatter();
  250. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  251. $reflMethod->setAccessible(true);
  252. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  253. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  254. }
  255. public function testMaxNormalizeDepth()
  256. {
  257. $formatter = new NormalizerFormatter();
  258. $formatter->setMaxNormalizeDepth(1);
  259. $throwable = new \Error('Foo');
  260. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  261. $this->assertEquals(
  262. 'Over 1 levels deep, aborting normalization',
  263. $message['context']['exception']
  264. );
  265. }
  266. public function testMaxNormalizeItemCountWith0ItemsMax()
  267. {
  268. $formatter = new NormalizerFormatter();
  269. $formatter->setMaxNormalizeDepth(9);
  270. $formatter->setMaxNormalizeItemCount(0);
  271. $throwable = new \Error('Foo');
  272. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  273. $this->assertEquals(
  274. ["..." => "Over 0 items (6 total), aborting normalization"],
  275. $message
  276. );
  277. }
  278. public function testMaxNormalizeItemCountWith3ItemsMax()
  279. {
  280. $formatter = new NormalizerFormatter();
  281. $formatter->setMaxNormalizeDepth(9);
  282. $formatter->setMaxNormalizeItemCount(2);
  283. $throwable = new \Error('Foo');
  284. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  285. $this->assertEquals(
  286. ["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"],
  287. $message
  288. );
  289. }
  290. /**
  291. * @param mixed $in Input
  292. * @param mixed $expect Expected output
  293. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  294. * @dataProvider providesDetectAndCleanUtf8
  295. */
  296. public function testDetectAndCleanUtf8($in, $expect)
  297. {
  298. $formatter = new NormalizerFormatter();
  299. $formatter->detectAndCleanUtf8($in);
  300. $this->assertSame($expect, $in);
  301. }
  302. public function providesDetectAndCleanUtf8()
  303. {
  304. $obj = new \stdClass;
  305. return [
  306. 'null' => [null, null],
  307. 'int' => [123, 123],
  308. 'float' => [123.45, 123.45],
  309. 'bool false' => [false, false],
  310. 'bool true' => [true, true],
  311. 'ascii string' => ['abcdef', 'abcdef'],
  312. 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
  313. 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
  314. 'empty array' => [[], []],
  315. 'array' => [['abcdef'], ['abcdef']],
  316. 'object' => [$obj, $obj],
  317. ];
  318. }
  319. /**
  320. * @param int $code
  321. * @param string $msg
  322. * @dataProvider providesHandleJsonErrorFailure
  323. */
  324. public function testHandleJsonErrorFailure($code, $msg)
  325. {
  326. $formatter = new NormalizerFormatter();
  327. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  328. $reflMethod->setAccessible(true);
  329. $this->expectException('RuntimeException');
  330. $this->expectExceptionMessage($msg);
  331. $reflMethod->invoke($formatter, $code, 'faked');
  332. }
  333. public function providesHandleJsonErrorFailure()
  334. {
  335. return [
  336. 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
  337. 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
  338. 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
  339. 'default' => [-1, 'Unknown error'],
  340. ];
  341. }
  342. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  343. // and no file or line are included in the trace because it's treated as internal function
  344. public function testExceptionTraceWithArgs()
  345. {
  346. try {
  347. // This will contain $resource and $wrappedResource as arguments in the trace item
  348. $resource = fopen('php://memory', 'rw+');
  349. fwrite($resource, 'test_resource');
  350. $wrappedResource = new TestFooNorm;
  351. $wrappedResource->foo = $resource;
  352. // Just do something stupid with a resource/wrapped resource as argument
  353. $arr = [$wrappedResource, $resource];
  354. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  355. usort($arr, function ($a, $b) {
  356. throw new \ErrorException('Foo');
  357. });
  358. } catch (\Throwable $e) {
  359. }
  360. $formatter = new NormalizerFormatter();
  361. $record = ['context' => ['exception' => $e]];
  362. $result = $formatter->format($record);
  363. $this->assertSame(
  364. '{"function":"Monolog\\\\Formatter\\\\{closure}","class":"Monolog\\\\Formatter\\\\NormalizerFormatterTest","type":"->","args":["[object] (Monolog\\\\Formatter\\\\TestFooNorm)","[resource(stream)]"]}',
  365. $result['context']['exception']['trace'][0]
  366. );
  367. }
  368. /**
  369. * This test was copied from `testExceptionTraceWithArgs` in order to ensure that pretty prints works
  370. */
  371. public function testPrettyPrint()
  372. {
  373. try {
  374. // This will contain $resource and $wrappedResource as arguments in the trace item
  375. $resource = fopen('php://memory', 'rw+');
  376. fwrite($resource, 'test_resource');
  377. $wrappedResource = new TestFooNorm;
  378. $wrappedResource->foo = $resource;
  379. // Just do something stupid with a resource/wrapped resource as argument
  380. $arr = [$wrappedResource, $resource];
  381. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  382. usort($arr, function ($a, $b) {
  383. throw new \ErrorException('Foo');
  384. });
  385. } catch (\Throwable $e) {
  386. }
  387. $formatter = new NormalizerFormatter();
  388. $record = ['context' => ['exception' => $e]];
  389. $formatter->setJsonPrettyPrint(true);
  390. $result = $formatter->format($record);
  391. $this->assertSame(
  392. '{
  393. "function": "Monolog\\\\Formatter\\\\{closure}",
  394. "class": "Monolog\\\\Formatter\\\\NormalizerFormatterTest",
  395. "type": "->",
  396. "args": [
  397. "[object] (Monolog\\\\Formatter\\\\TestFooNorm)",
  398. "[resource(stream)]"
  399. ]
  400. }',
  401. $result['context']['exception']['trace'][0]
  402. );
  403. }
  404. /**
  405. * @param NormalizerFormatter $formatter
  406. * @param \Throwable $exception
  407. *
  408. * @return string
  409. */
  410. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
  411. {
  412. $message = $formatter->format([
  413. 'level_name' => 'CRITICAL',
  414. 'channel' => 'core',
  415. 'context' => ['exception' => $exception],
  416. 'datetime' => null,
  417. 'extra' => [],
  418. 'message' => 'foobar',
  419. ]);
  420. return $message;
  421. }
  422. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  423. {
  424. try {
  425. $arg = new TestInfoLeak;
  426. call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
  427. } catch (\Exception $e) {
  428. }
  429. $formatter = new NormalizerFormatter();
  430. $record = array('context' => array('exception' => $e));
  431. $result = $formatter->format($record);
  432. $this->assertSame(
  433. '{"function":"throwHelper","class":"Monolog\\\\Formatter\\\\NormalizerFormatterTest","type":"->","args":["[object] (Monolog\\\\Formatter\\\\TestInfoLeak)","'.$dt->format('Y-m-d\TH:i:sP').'"]}',
  434. $result['context']['exception']['trace'][0]
  435. );
  436. }
  437. private function throwHelper($arg)
  438. {
  439. throw new \RuntimeException('Thrown');
  440. }
  441. }
  442. class TestFooNorm
  443. {
  444. public $foo = 'fooValue';
  445. }
  446. class TestBarNorm
  447. {
  448. public function __toString()
  449. {
  450. return 'bar';
  451. }
  452. }
  453. class TestStreamFoo
  454. {
  455. public $foo;
  456. public $resource;
  457. public function __construct($resource)
  458. {
  459. $this->resource = $resource;
  460. $this->foo = 'BAR';
  461. }
  462. public function __toString()
  463. {
  464. fseek($this->resource, 0);
  465. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  466. }
  467. }
  468. class TestToStringError
  469. {
  470. public function __toString()
  471. {
  472. throw new \RuntimeException('Could not convert to string');
  473. }
  474. }
  475. class TestInfoLeak
  476. {
  477. public function __toString()
  478. {
  479. return 'Sensitive information';
  480. }
  481. }