NormalizerFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. /**
  12. * @covers Monolog\Formatter\NormalizerFormatter
  13. */
  14. class NormalizerFormatterTest extends \PHPUnit\Framework\TestCase
  15. {
  16. public function tearDown()
  17. {
  18. \PHPUnit\Framework\Error\Warning::$enabled = true;
  19. return parent::tearDown();
  20. }
  21. public function testFormat()
  22. {
  23. $formatter = new NormalizerFormatter('Y-m-d');
  24. $formatted = $formatter->format([
  25. 'level_name' => 'ERROR',
  26. 'channel' => 'meh',
  27. 'message' => 'foo',
  28. 'datetime' => new \DateTimeImmutable,
  29. 'extra' => ['foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => [], 'res' => fopen('php://memory', 'rb')],
  30. 'context' => [
  31. 'foo' => 'bar',
  32. 'baz' => 'qux',
  33. 'inf' => INF,
  34. '-inf' => -INF,
  35. 'nan' => acos(4),
  36. ],
  37. ]);
  38. $this->assertEquals([
  39. 'level_name' => 'ERROR',
  40. 'channel' => 'meh',
  41. 'message' => 'foo',
  42. 'datetime' => date('Y-m-d'),
  43. 'extra' => [
  44. 'foo' => ['Monolog\\Formatter\\TestFooNorm' => ["foo" => "fooValue"]],
  45. 'bar' => ['Monolog\\Formatter\\TestBarNorm' => 'bar'],
  46. 'baz' => [],
  47. 'res' => '[resource(stream)]',
  48. ],
  49. 'context' => [
  50. 'foo' => 'bar',
  51. 'baz' => 'qux',
  52. 'inf' => 'INF',
  53. '-inf' => '-INF',
  54. 'nan' => 'NaN',
  55. ],
  56. ], $formatted);
  57. }
  58. public function testFormatExceptions()
  59. {
  60. $formatter = new NormalizerFormatter('Y-m-d');
  61. $e = new \LogicException('bar');
  62. $e2 = new \RuntimeException('foo', 0, $e);
  63. $formatted = $formatter->format([
  64. 'exception' => $e2,
  65. ]);
  66. $this->assertGreaterThan(5, count($formatted['exception']['trace']));
  67. $this->assertTrue(isset($formatted['exception']['previous']));
  68. unset($formatted['exception']['trace'], $formatted['exception']['previous']);
  69. $this->assertEquals([
  70. 'exception' => [
  71. 'class' => get_class($e2),
  72. 'message' => $e2->getMessage(),
  73. 'code' => $e2->getCode(),
  74. 'file' => $e2->getFile().':'.$e2->getLine(),
  75. ],
  76. ], $formatted);
  77. }
  78. public function testFormatSoapFaultException()
  79. {
  80. if (!class_exists('SoapFault')) {
  81. $this->markTestSkipped('Requires the soap extension');
  82. }
  83. $formatter = new NormalizerFormatter('Y-m-d');
  84. $e = new \SoapFault('foo', 'bar', 'hello', 'world');
  85. $formatted = $formatter->format([
  86. 'exception' => $e,
  87. ]);
  88. unset($formatted['exception']['trace']);
  89. $this->assertEquals([
  90. 'exception' => [
  91. 'class' => 'SoapFault',
  92. 'message' => 'bar',
  93. 'code' => 0,
  94. 'file' => $e->getFile().':'.$e->getLine(),
  95. 'faultcode' => 'foo',
  96. 'faultactor' => 'hello',
  97. 'detail' => 'world',
  98. ],
  99. ], $formatted);
  100. }
  101. public function testFormatToStringExceptionHandle()
  102. {
  103. $formatter = new NormalizerFormatter('Y-m-d');
  104. $this->expectException('RuntimeException');
  105. $this->expectExceptionMessage('Could not convert to string');
  106. $formatter->format([
  107. 'myObject' => new TestToStringError(),
  108. ]);
  109. }
  110. public function testBatchFormat()
  111. {
  112. $formatter = new NormalizerFormatter('Y-m-d');
  113. $formatted = $formatter->formatBatch([
  114. [
  115. 'level_name' => 'CRITICAL',
  116. 'channel' => 'test',
  117. 'message' => 'bar',
  118. 'context' => [],
  119. 'datetime' => new \DateTimeImmutable,
  120. 'extra' => [],
  121. ],
  122. [
  123. 'level_name' => 'WARNING',
  124. 'channel' => 'log',
  125. 'message' => 'foo',
  126. 'context' => [],
  127. 'datetime' => new \DateTimeImmutable,
  128. 'extra' => [],
  129. ],
  130. ]);
  131. $this->assertEquals([
  132. [
  133. 'level_name' => 'CRITICAL',
  134. 'channel' => 'test',
  135. 'message' => 'bar',
  136. 'context' => [],
  137. 'datetime' => date('Y-m-d'),
  138. 'extra' => [],
  139. ],
  140. [
  141. 'level_name' => 'WARNING',
  142. 'channel' => 'log',
  143. 'message' => 'foo',
  144. 'context' => [],
  145. 'datetime' => date('Y-m-d'),
  146. 'extra' => [],
  147. ],
  148. ], $formatted);
  149. }
  150. /**
  151. * Test issue #137
  152. */
  153. public function testIgnoresRecursiveObjectReferences()
  154. {
  155. // set up the recursion
  156. $foo = new \stdClass();
  157. $bar = new \stdClass();
  158. $foo->bar = $bar;
  159. $bar->foo = $foo;
  160. // set an error handler to assert that the error is not raised anymore
  161. $that = $this;
  162. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  163. if (error_reporting() & $level) {
  164. restore_error_handler();
  165. $that->fail("$message should not be raised");
  166. }
  167. });
  168. $formatter = new NormalizerFormatter();
  169. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  170. $reflMethod->setAccessible(true);
  171. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  172. restore_error_handler();
  173. $this->assertEquals(@json_encode([$foo, $bar]), $res);
  174. }
  175. public function testCanNormalizeReferences()
  176. {
  177. $formatter = new NormalizerFormatter();
  178. $x = ['foo' => 'bar'];
  179. $y = ['x' => &$x];
  180. $x['y'] = &$y;
  181. $formatter->format($y);
  182. }
  183. public function testIgnoresInvalidTypes()
  184. {
  185. // set up the recursion
  186. $resource = fopen(__FILE__, 'r');
  187. // set an error handler to assert that the error is not raised anymore
  188. $that = $this;
  189. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  190. if (error_reporting() & $level) {
  191. restore_error_handler();
  192. $that->fail("$message should not be raised");
  193. }
  194. });
  195. $formatter = new NormalizerFormatter();
  196. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  197. $reflMethod->setAccessible(true);
  198. $res = $reflMethod->invoke($formatter, [$resource], true);
  199. restore_error_handler();
  200. $this->assertEquals(@json_encode([$resource]), $res);
  201. }
  202. public function testNormalizeHandleLargeArrays()
  203. {
  204. $formatter = new NormalizerFormatter();
  205. $largeArray = range(1, 2000);
  206. $res = $formatter->format(array(
  207. 'level_name' => 'CRITICAL',
  208. 'channel' => 'test',
  209. 'message' => 'bar',
  210. 'context' => array($largeArray),
  211. 'datetime' => new \DateTime,
  212. 'extra' => array(),
  213. ));
  214. $this->assertCount(1000, $res['context'][0]);
  215. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  216. }
  217. /**
  218. * @expectedException RuntimeException
  219. */
  220. public function testThrowsOnInvalidEncoding()
  221. {
  222. $formatter = new NormalizerFormatter();
  223. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  224. $reflMethod->setAccessible(true);
  225. // send an invalid unicode sequence as a object that can't be cleaned
  226. $record = new \stdClass;
  227. $record->message = "\xB1\x31";
  228. $reflMethod->invoke($formatter, $record);
  229. }
  230. public function testConvertsInvalidEncodingAsLatin9()
  231. {
  232. $formatter = new NormalizerFormatter();
  233. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  234. $reflMethod->setAccessible(true);
  235. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  236. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  237. }
  238. /**
  239. * @param mixed $in Input
  240. * @param mixed $expect Expected output
  241. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  242. * @dataProvider providesDetectAndCleanUtf8
  243. */
  244. public function testDetectAndCleanUtf8($in, $expect)
  245. {
  246. $formatter = new NormalizerFormatter();
  247. $formatter->detectAndCleanUtf8($in);
  248. $this->assertSame($expect, $in);
  249. }
  250. public function providesDetectAndCleanUtf8()
  251. {
  252. $obj = new \stdClass;
  253. return [
  254. 'null' => [null, null],
  255. 'int' => [123, 123],
  256. 'float' => [123.45, 123.45],
  257. 'bool false' => [false, false],
  258. 'bool true' => [true, true],
  259. 'ascii string' => ['abcdef', 'abcdef'],
  260. 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
  261. 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
  262. 'empty array' => [[], []],
  263. 'array' => [['abcdef'], ['abcdef']],
  264. 'object' => [$obj, $obj],
  265. ];
  266. }
  267. /**
  268. * @param int $code
  269. * @param string $msg
  270. * @dataProvider providesHandleJsonErrorFailure
  271. */
  272. public function testHandleJsonErrorFailure($code, $msg)
  273. {
  274. $formatter = new NormalizerFormatter();
  275. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  276. $reflMethod->setAccessible(true);
  277. $this->expectException('RuntimeException');
  278. $this->expectExceptionMessage($msg);
  279. $reflMethod->invoke($formatter, $code, 'faked');
  280. }
  281. public function providesHandleJsonErrorFailure()
  282. {
  283. return [
  284. 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
  285. 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
  286. 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
  287. 'default' => [-1, 'Unknown error'],
  288. ];
  289. }
  290. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  291. // and no file or line are included in the trace because it's treated as internal function
  292. public function testExceptionTraceWithArgs()
  293. {
  294. if (defined('HHVM_VERSION')) {
  295. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  296. }
  297. try {
  298. // This will contain $resource and $wrappedResource as arguments in the trace item
  299. $resource = fopen('php://memory', 'rw+');
  300. fwrite($resource, 'test_resource');
  301. $wrappedResource = new TestFooNorm;
  302. $wrappedResource->foo = $resource;
  303. // Just do something stupid with a resource/wrapped resource as argument
  304. $arr = [$wrappedResource, $resource];
  305. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  306. usort($arr, function ($a, $b) {
  307. throw new \ErrorException('Foo');
  308. });
  309. } catch (\Throwable $e) {
  310. }
  311. $formatter = new NormalizerFormatter();
  312. $record = ['context' => ['exception' => $e]];
  313. $result = $formatter->format($record);
  314. $this->assertRegExp(
  315. '%\[resource\(stream\)\]%',
  316. $result['context']['exception']['trace'][0]
  317. );
  318. $pattern = '%\[\{"Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm":"JSON_ERROR"\}%';
  319. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  320. $this->assertRegExp(
  321. $pattern,
  322. $result['context']['exception']['trace'][0]
  323. );
  324. }
  325. }
  326. class TestFooNorm
  327. {
  328. public $foo = 'fooValue';
  329. }
  330. class TestBarNorm
  331. {
  332. public function __toString()
  333. {
  334. return 'bar';
  335. }
  336. }
  337. class TestStreamFoo
  338. {
  339. public $foo;
  340. public $resource;
  341. public function __construct($resource)
  342. {
  343. $this->resource = $resource;
  344. $this->foo = 'BAR';
  345. }
  346. public function __toString()
  347. {
  348. fseek($this->resource, 0);
  349. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  350. }
  351. }
  352. class TestToStringError
  353. {
  354. public function __toString()
  355. {
  356. throw new \RuntimeException('Could not convert to string');
  357. }
  358. }