NormalizerFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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', (object) ['foo' => '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. if (PHP_VERSION_ID < 50500) {
  171. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  172. } else {
  173. $this->assertEquals('null', $res);
  174. }
  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. if (PHP_VERSION_ID < 50500) {
  203. $this->assertEquals('[null]', $res);
  204. } else {
  205. $this->assertEquals('null', $res);
  206. }
  207. }
  208. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  209. {
  210. $formatter = new NormalizerFormatter();
  211. $largeArray = range(1, 1000);
  212. $res = $formatter->format(array(
  213. 'level_name' => 'CRITICAL',
  214. 'channel' => 'test',
  215. 'message' => 'bar',
  216. 'context' => array($largeArray),
  217. 'datetime' => new \DateTime,
  218. 'extra' => array(),
  219. ));
  220. $this->assertCount(1000, $res['context'][0]);
  221. $this->assertArrayNotHasKey('...', $res['context'][0]);
  222. }
  223. public function testNormalizeHandleLargeArrays()
  224. {
  225. $formatter = new NormalizerFormatter();
  226. $largeArray = range(1, 2000);
  227. $res = $formatter->format(array(
  228. 'level_name' => 'CRITICAL',
  229. 'channel' => 'test',
  230. 'message' => 'bar',
  231. 'context' => array($largeArray),
  232. 'datetime' => new \DateTime,
  233. 'extra' => array(),
  234. ));
  235. $this->assertCount(1001, $res['context'][0]);
  236. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  237. }
  238. public function testThrowsOnInvalidEncoding()
  239. {
  240. $formatter = new NormalizerFormatter();
  241. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  242. $reflMethod->setAccessible(true);
  243. // send an invalid unicode sequence as a object that can't be cleaned
  244. $record = new \stdClass;
  245. $record->message = "\xB1\x31";
  246. $this->expectException(\RuntimeException::class);
  247. $reflMethod->invoke($formatter, $record);
  248. }
  249. public function testConvertsInvalidEncodingAsLatin9()
  250. {
  251. $formatter = new NormalizerFormatter();
  252. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  253. $reflMethod->setAccessible(true);
  254. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  255. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  256. }
  257. public function testMaxNormalizeDepth()
  258. {
  259. $formatter = new NormalizerFormatter();
  260. $formatter->setMaxNormalizeDepth(1);
  261. $throwable = new \Error('Foo');
  262. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  263. $this->assertEquals(
  264. 'Over 1 levels deep, aborting normalization',
  265. $message['context']['exception']
  266. );
  267. }
  268. public function testMaxNormalizeItemCountWith0ItemsMax()
  269. {
  270. $formatter = new NormalizerFormatter();
  271. $formatter->setMaxNormalizeDepth(9);
  272. $formatter->setMaxNormalizeItemCount(0);
  273. $throwable = new \Error('Foo');
  274. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  275. $this->assertEquals(
  276. ["..." => "Over 0 items (6 total), aborting normalization"],
  277. $message
  278. );
  279. }
  280. public function testMaxNormalizeItemCountWith3ItemsMax()
  281. {
  282. $formatter = new NormalizerFormatter();
  283. $formatter->setMaxNormalizeDepth(9);
  284. $formatter->setMaxNormalizeItemCount(2);
  285. $throwable = new \Error('Foo');
  286. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  287. $this->assertEquals(
  288. ["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"],
  289. $message
  290. );
  291. }
  292. public function testExceptionTraceWithArgs()
  293. {
  294. try {
  295. // This will contain $resource and $wrappedResource as arguments in the trace item
  296. $resource = fopen('php://memory', 'rw+');
  297. fwrite($resource, 'test_resource');
  298. $wrappedResource = new TestFooNorm;
  299. $wrappedResource->foo = $resource;
  300. // Just do something stupid with a resource/wrapped resource as argument
  301. $arr = [$wrappedResource, $resource];
  302. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  303. usort($arr, function ($a, $b) {
  304. throw new \ErrorException('Foo');
  305. });
  306. } catch (\Throwable $e) {
  307. }
  308. $formatter = new NormalizerFormatter();
  309. $record = ['context' => ['exception' => $e]];
  310. $result = $formatter->format($record);
  311. $this->assertSame(
  312. __FILE__.':'.(__LINE__-9),
  313. $result['context']['exception']['trace'][0]
  314. );
  315. }
  316. /**
  317. * @param NormalizerFormatter $formatter
  318. * @param \Throwable $exception
  319. *
  320. * @return string
  321. */
  322. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
  323. {
  324. $message = $formatter->format([
  325. 'level_name' => 'CRITICAL',
  326. 'channel' => 'core',
  327. 'context' => ['exception' => $exception],
  328. 'datetime' => null,
  329. 'extra' => [],
  330. 'message' => 'foobar',
  331. ]);
  332. return $message;
  333. }
  334. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  335. {
  336. try {
  337. $arg = new TestInfoLeak;
  338. call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
  339. } catch (\Exception $e) {
  340. }
  341. $formatter = new NormalizerFormatter();
  342. $record = array('context' => array('exception' => $e));
  343. $result = $formatter->format($record);
  344. $this->assertSame(
  345. __FILE__ .':'.(__LINE__-9),
  346. $result['context']['exception']['trace'][0]
  347. );
  348. }
  349. private function throwHelper($arg)
  350. {
  351. throw new \RuntimeException('Thrown');
  352. }
  353. }
  354. class TestFooNorm
  355. {
  356. public $foo = 'fooValue';
  357. }
  358. class TestBarNorm
  359. {
  360. public function __toString()
  361. {
  362. return 'bar';
  363. }
  364. }
  365. class TestStreamFoo
  366. {
  367. public $foo;
  368. public $resource;
  369. public function __construct($resource)
  370. {
  371. $this->resource = $resource;
  372. $this->foo = 'BAR';
  373. }
  374. public function __toString()
  375. {
  376. fseek($this->resource, 0);
  377. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  378. }
  379. }
  380. class TestToStringError
  381. {
  382. public function __toString()
  383. {
  384. throw new \RuntimeException('Could not convert to string');
  385. }
  386. }
  387. class TestInfoLeak
  388. {
  389. public function __toString()
  390. {
  391. return 'Sensitive information';
  392. }
  393. }