NormalizerFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 testIgnoresInvalidEncoding()
  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->assertsame('{"message":"�1"}', $reflMethod->invoke($formatter, $record));
  247. }
  248. public function testConvertsInvalidEncodingAsLatin9()
  249. {
  250. $formatter = new NormalizerFormatter();
  251. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  252. $reflMethod->setAccessible(true);
  253. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  254. $this->assertSame('{"message":"��������"}', $res);
  255. }
  256. public function testMaxNormalizeDepth()
  257. {
  258. $formatter = new NormalizerFormatter();
  259. $formatter->setMaxNormalizeDepth(1);
  260. $throwable = new \Error('Foo');
  261. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  262. $this->assertEquals(
  263. 'Over 1 levels deep, aborting normalization',
  264. $message['context']['exception']
  265. );
  266. }
  267. public function testMaxNormalizeItemCountWith0ItemsMax()
  268. {
  269. $formatter = new NormalizerFormatter();
  270. $formatter->setMaxNormalizeDepth(9);
  271. $formatter->setMaxNormalizeItemCount(0);
  272. $throwable = new \Error('Foo');
  273. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  274. $this->assertEquals(
  275. ["..." => "Over 0 items (6 total), aborting normalization"],
  276. $message
  277. );
  278. }
  279. public function testMaxNormalizeItemCountWith3ItemsMax()
  280. {
  281. $formatter = new NormalizerFormatter();
  282. $formatter->setMaxNormalizeDepth(9);
  283. $formatter->setMaxNormalizeItemCount(2);
  284. $throwable = new \Error('Foo');
  285. $message = $this->formatRecordWithExceptionInContext($formatter, $throwable);
  286. $this->assertEquals(
  287. ["level_name" => "CRITICAL", "channel" => "core", "..." => "Over 2 items (6 total), aborting normalization"],
  288. $message
  289. );
  290. }
  291. public function testExceptionTraceWithArgs()
  292. {
  293. try {
  294. // This will contain $resource and $wrappedResource as arguments in the trace item
  295. $resource = fopen('php://memory', 'rw+');
  296. fwrite($resource, 'test_resource');
  297. $wrappedResource = new TestFooNorm;
  298. $wrappedResource->foo = $resource;
  299. // Just do something stupid with a resource/wrapped resource as argument
  300. $arr = [$wrappedResource, $resource];
  301. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  302. usort($arr, function ($a, $b) {
  303. throw new \ErrorException('Foo');
  304. });
  305. } catch (\Throwable $e) {
  306. }
  307. $formatter = new NormalizerFormatter();
  308. $record = ['context' => ['exception' => $e]];
  309. $result = $formatter->format($record);
  310. $this->assertSame(
  311. __FILE__.':'.(__LINE__-9),
  312. $result['context']['exception']['trace'][0]
  313. );
  314. }
  315. /**
  316. * @param NormalizerFormatter $formatter
  317. * @param \Throwable $exception
  318. *
  319. * @return string
  320. */
  321. private function formatRecordWithExceptionInContext(NormalizerFormatter $formatter, \Throwable $exception)
  322. {
  323. $message = $formatter->format([
  324. 'level_name' => 'CRITICAL',
  325. 'channel' => 'core',
  326. 'context' => ['exception' => $exception],
  327. 'datetime' => null,
  328. 'extra' => [],
  329. 'message' => 'foobar',
  330. ]);
  331. return $message;
  332. }
  333. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  334. {
  335. try {
  336. $arg = new TestInfoLeak;
  337. call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
  338. } catch (\Exception $e) {
  339. }
  340. $formatter = new NormalizerFormatter();
  341. $record = array('context' => array('exception' => $e));
  342. $result = $formatter->format($record);
  343. $this->assertSame(
  344. __FILE__ .':'.(__LINE__-9),
  345. $result['context']['exception']['trace'][0]
  346. );
  347. }
  348. private function throwHelper($arg)
  349. {
  350. throw new \RuntimeException('Thrown');
  351. }
  352. }
  353. class TestFooNorm
  354. {
  355. public $foo = 'fooValue';
  356. }
  357. class TestBarNorm
  358. {
  359. public function __toString()
  360. {
  361. return 'bar';
  362. }
  363. }
  364. class TestStreamFoo
  365. {
  366. public $foo;
  367. public $resource;
  368. public function __construct($resource)
  369. {
  370. $this->resource = $resource;
  371. $this->foo = 'BAR';
  372. }
  373. public function __toString()
  374. {
  375. fseek($this->resource, 0);
  376. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  377. }
  378. }
  379. class TestToStringError
  380. {
  381. public function __toString()
  382. {
  383. throw new \RuntimeException('Could not convert to string');
  384. }
  385. }
  386. class TestInfoLeak
  387. {
  388. public function __toString()
  389. {
  390. return 'Sensitive information';
  391. }
  392. }