NormalizerFormatterTest.php 15 KB

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