NormalizerFormatterTest.php 17 KB

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