NormalizerFormatterTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. $formatter = new NormalizerFormatter('Y-m-d');
  97. $e = new \SoapFault('foo', 'bar', 'hello', (object) ['bar' => (object) ['biz' => 'baz'], 'foo' => 'world']);
  98. $formatted = $formatter->format([
  99. 'exception' => $e,
  100. ]);
  101. unset($formatted['exception']['trace']);
  102. $this->assertEquals([
  103. 'exception' => [
  104. 'class' => 'SoapFault',
  105. 'message' => 'bar',
  106. 'code' => 0,
  107. 'file' => $e->getFile().':'.$e->getLine(),
  108. 'faultcode' => 'foo',
  109. 'faultactor' => 'hello',
  110. 'detail' => '{"bar":{"biz":"baz"},"foo":"world"}',
  111. ],
  112. ], $formatted);
  113. }
  114. public function testFormatToStringExceptionHandle()
  115. {
  116. $formatter = new NormalizerFormatter('Y-m-d');
  117. $this->expectException('RuntimeException');
  118. $this->expectExceptionMessage('Could not convert to string');
  119. $formatter->format([
  120. 'myObject' => new TestToStringError(),
  121. ]);
  122. }
  123. public function testBatchFormat()
  124. {
  125. $formatter = new NormalizerFormatter('Y-m-d');
  126. $formatted = $formatter->formatBatch([
  127. [
  128. 'level_name' => 'CRITICAL',
  129. 'channel' => 'test',
  130. 'message' => 'bar',
  131. 'context' => [],
  132. 'datetime' => new \DateTimeImmutable,
  133. 'extra' => [],
  134. ],
  135. [
  136. 'level_name' => 'WARNING',
  137. 'channel' => 'log',
  138. 'message' => 'foo',
  139. 'context' => [],
  140. 'datetime' => new \DateTimeImmutable,
  141. 'extra' => [],
  142. ],
  143. ]);
  144. $this->assertEquals([
  145. [
  146. 'level_name' => 'CRITICAL',
  147. 'channel' => 'test',
  148. 'message' => 'bar',
  149. 'context' => [],
  150. 'datetime' => date('Y-m-d'),
  151. 'extra' => [],
  152. ],
  153. [
  154. 'level_name' => 'WARNING',
  155. 'channel' => 'log',
  156. 'message' => 'foo',
  157. 'context' => [],
  158. 'datetime' => date('Y-m-d'),
  159. 'extra' => [],
  160. ],
  161. ], $formatted);
  162. }
  163. /**
  164. * Test issue #137
  165. */
  166. public function testIgnoresRecursiveObjectReferences()
  167. {
  168. // set up the recursion
  169. $foo = new \stdClass();
  170. $bar = new \stdClass();
  171. $foo->bar = $bar;
  172. $bar->foo = $foo;
  173. // set an error handler to assert that the error is not raised anymore
  174. $that = $this;
  175. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  176. if (error_reporting() & $level) {
  177. restore_error_handler();
  178. $that->fail("$message should not be raised");
  179. }
  180. return true;
  181. });
  182. $formatter = new NormalizerFormatter();
  183. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  184. $reflMethod->setAccessible(true);
  185. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  186. restore_error_handler();
  187. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  188. }
  189. public function testCanNormalizeReferences()
  190. {
  191. $formatter = new NormalizerFormatter();
  192. $x = ['foo' => 'bar'];
  193. $y = ['x' => &$x];
  194. $x['y'] = &$y;
  195. $formatter->format($y);
  196. }
  197. public function testToJsonIgnoresInvalidTypes()
  198. {
  199. // set up the invalid data
  200. $resource = fopen(__FILE__, 'r');
  201. // set an error handler to assert that the error is not raised anymore
  202. $that = $this;
  203. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  204. if (error_reporting() & $level) {
  205. restore_error_handler();
  206. $that->fail("$message should not be raised");
  207. }
  208. return true;
  209. });
  210. $formatter = new NormalizerFormatter();
  211. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  212. $reflMethod->setAccessible(true);
  213. $res = $reflMethod->invoke($formatter, [$resource], true);
  214. restore_error_handler();
  215. $this->assertEquals('[null]', $res);
  216. }
  217. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  218. {
  219. $formatter = new NormalizerFormatter();
  220. $largeArray = range(1, 1000);
  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(1000, $res['context'][0]);
  230. $this->assertArrayNotHasKey('...', $res['context'][0]);
  231. }
  232. public function testNormalizeHandleLargeArrays()
  233. {
  234. $formatter = new NormalizerFormatter();
  235. $largeArray = range(1, 2000);
  236. $res = $formatter->format(array(
  237. 'level_name' => 'CRITICAL',
  238. 'channel' => 'test',
  239. 'message' => 'bar',
  240. 'context' => array($largeArray),
  241. 'datetime' => new \DateTime,
  242. 'extra' => array(),
  243. ));
  244. $this->assertCount(1001, $res['context'][0]);
  245. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  246. }
  247. public function testIgnoresInvalidEncoding()
  248. {
  249. $formatter = new NormalizerFormatter();
  250. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  251. $reflMethod->setAccessible(true);
  252. // send an invalid unicode sequence as a object that can't be cleaned
  253. $record = new \stdClass;
  254. $record->message = "\xB1\x31";
  255. $this->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  256. }
  257. public function testConvertsInvalidEncodingAsLatin9()
  258. {
  259. $formatter = new NormalizerFormatter();
  260. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  261. $reflMethod->setAccessible(true);
  262. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  263. $this->assertSame('{"message":"��������"}', $res);
  264. }
  265. public function testMaxNormalizeDepth()
  266. {
  267. $formatter = new NormalizerFormatter();
  268. $formatter->setMaxNormalizeDepth(1);
  269. $throwable = new \Error('Foo');
  270. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  271. $this->assertEquals(
  272. 'Over 1 levels deep, aborting normalization',
  273. $message['context']['exception']
  274. );
  275. }
  276. public function testMaxNormalizeItemCountWith0ItemsMax()
  277. {
  278. $formatter = new NormalizerFormatter();
  279. $formatter->setMaxNormalizeDepth(9);
  280. $formatter->setMaxNormalizeItemCount(0);
  281. $throwable = new \Error('Foo');
  282. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  283. $this->assertEquals(
  284. ["..." => "Over 0 items (6 total), aborting normalization"],
  285. $message
  286. );
  287. }
  288. public function testMaxNormalizeItemCountWith3ItemsMax()
  289. {
  290. $formatter = new NormalizerFormatter();
  291. $formatter->setMaxNormalizeDepth(9);
  292. $formatter->setMaxNormalizeItemCount(2);
  293. $throwable = new \Error('Foo');
  294. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  295. $this->assertEquals(
  296. ["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"],
  297. $message
  298. );
  299. }
  300. public function testExceptionTraceWithArgs()
  301. {
  302. try {
  303. // This will contain $resource and $wrappedResource as arguments in the trace item
  304. $resource = fopen('php://memory', 'rw+');
  305. fwrite($resource, 'test_resource');
  306. $wrappedResource = new TestFooNorm;
  307. $wrappedResource->foo = $resource;
  308. // Just do something stupid with a resource/wrapped resource as argument
  309. $arr = [$wrappedResource, $resource];
  310. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  311. usort($arr, function ($a, $b) {
  312. throw new \ErrorException('Foo');
  313. });
  314. } catch (\Throwable $e) {
  315. }
  316. $formatter = new NormalizerFormatter();
  317. $record = ['context' => ['exception' => $e]];
  318. $result = $formatter->format($record);
  319. $offset = PHP_VERSION_ID >= 80200 ? 12 : 10;
  320. $this->assertSame(
  321. __FILE__.':'.(__LINE__ - $offset),
  322. $result['context']['exception']['trace'][0]
  323. );
  324. }
  325. /**
  326. * @param NormalizerFormatter $formatter
  327. * @param \Throwable $exception
  328. *
  329. * @return string
  330. */
  331. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
  332. {
  333. $message = $formatter->format([
  334. 'level_name' => 'CRITICAL',
  335. 'channel' => 'core',
  336. 'context' => ['exception' => $exception],
  337. 'datetime' => null,
  338. 'extra' => [],
  339. 'message' => 'foobar',
  340. ]);
  341. return $message;
  342. }
  343. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  344. {
  345. try {
  346. $arg = new TestInfoLeak;
  347. call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
  348. } catch (\Exception $e) {
  349. }
  350. $formatter = new NormalizerFormatter();
  351. $record = array('context' => array('exception' => $e));
  352. $result = $formatter->format($record);
  353. $this->assertSame(
  354. __FILE__ .':'.(__LINE__-9),
  355. $result['context']['exception']['trace'][0]
  356. );
  357. }
  358. private function throwHelper($arg)
  359. {
  360. throw new \RuntimeException('Thrown');
  361. }
  362. }
  363. class TestFooNorm
  364. {
  365. public $foo = 'fooValue';
  366. }
  367. class TestBarNorm
  368. {
  369. public function __toString()
  370. {
  371. return 'bar';
  372. }
  373. }
  374. class TestStreamFoo
  375. {
  376. public $foo;
  377. public $resource;
  378. public function __construct($resource)
  379. {
  380. $this->resource = $resource;
  381. $this->foo = 'BAR';
  382. }
  383. public function __toString()
  384. {
  385. fseek($this->resource, 0);
  386. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  387. }
  388. }
  389. class TestToStringError
  390. {
  391. public function __toString()
  392. {
  393. throw new \RuntimeException('Could not convert to string');
  394. }
  395. }
  396. class TestInfoLeak
  397. {
  398. public function __toString()
  399. {
  400. return 'Sensitive information';
  401. }
  402. }