NormalizerFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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', 'Could not convert to string');
  105. $formatter->format([
  106. 'myObject' => new TestToStringError(),
  107. ]);
  108. }
  109. public function testBatchFormat()
  110. {
  111. $formatter = new NormalizerFormatter('Y-m-d');
  112. $formatted = $formatter->formatBatch([
  113. [
  114. 'level_name' => 'CRITICAL',
  115. 'channel' => 'test',
  116. 'message' => 'bar',
  117. 'context' => [],
  118. 'datetime' => new \DateTimeImmutable,
  119. 'extra' => [],
  120. ],
  121. [
  122. 'level_name' => 'WARNING',
  123. 'channel' => 'log',
  124. 'message' => 'foo',
  125. 'context' => [],
  126. 'datetime' => new \DateTimeImmutable,
  127. 'extra' => [],
  128. ],
  129. ]);
  130. $this->assertEquals([
  131. [
  132. 'level_name' => 'CRITICAL',
  133. 'channel' => 'test',
  134. 'message' => 'bar',
  135. 'context' => [],
  136. 'datetime' => date('Y-m-d'),
  137. 'extra' => [],
  138. ],
  139. [
  140. 'level_name' => 'WARNING',
  141. 'channel' => 'log',
  142. 'message' => 'foo',
  143. 'context' => [],
  144. 'datetime' => date('Y-m-d'),
  145. 'extra' => [],
  146. ],
  147. ], $formatted);
  148. }
  149. /**
  150. * Test issue #137
  151. */
  152. public function testIgnoresRecursiveObjectReferences()
  153. {
  154. // set up the recursion
  155. $foo = new \stdClass();
  156. $bar = new \stdClass();
  157. $foo->bar = $bar;
  158. $bar->foo = $foo;
  159. // set an error handler to assert that the error is not raised anymore
  160. $that = $this;
  161. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  162. if (error_reporting() & $level) {
  163. restore_error_handler();
  164. $that->fail("$message should not be raised");
  165. }
  166. });
  167. $formatter = new NormalizerFormatter();
  168. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  169. $reflMethod->setAccessible(true);
  170. $res = $reflMethod->invoke($formatter, [$foo, $bar], true);
  171. restore_error_handler();
  172. $this->assertEquals(@json_encode([$foo, $bar]), $res);
  173. }
  174. public function testCanNormalizeReferences()
  175. {
  176. $formatter = new NormalizerFormatter();
  177. $x = ['foo' => 'bar'];
  178. $y = ['x' => &$x];
  179. $x['y'] = &$y;
  180. $formatter->format($y);
  181. }
  182. public function testIgnoresInvalidTypes()
  183. {
  184. // set up the recursion
  185. $resource = fopen(__FILE__, 'r');
  186. // set an error handler to assert that the error is not raised anymore
  187. $that = $this;
  188. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  189. if (error_reporting() & $level) {
  190. restore_error_handler();
  191. $that->fail("$message should not be raised");
  192. }
  193. });
  194. $formatter = new NormalizerFormatter();
  195. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  196. $reflMethod->setAccessible(true);
  197. $res = $reflMethod->invoke($formatter, [$resource], true);
  198. restore_error_handler();
  199. $this->assertEquals(@json_encode([$resource]), $res);
  200. }
  201. public function testNormalizeHandleLargeArrays()
  202. {
  203. $formatter = new NormalizerFormatter();
  204. $largeArray = range(1, 2000);
  205. $res = $formatter->format(array(
  206. 'level_name' => 'CRITICAL',
  207. 'channel' => 'test',
  208. 'message' => 'bar',
  209. 'context' => array($largeArray),
  210. 'datetime' => new \DateTime,
  211. 'extra' => array(),
  212. ));
  213. $this->assertCount(1000, $res['context'][0]);
  214. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  215. }
  216. /**
  217. * @expectedException RuntimeException
  218. */
  219. public function testThrowsOnInvalidEncoding()
  220. {
  221. $formatter = new NormalizerFormatter();
  222. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  223. $reflMethod->setAccessible(true);
  224. // send an invalid unicode sequence as a object that can't be cleaned
  225. $record = new \stdClass;
  226. $record->message = "\xB1\x31";
  227. $reflMethod->invoke($formatter, $record);
  228. }
  229. public function testConvertsInvalidEncodingAsLatin9()
  230. {
  231. $formatter = new NormalizerFormatter();
  232. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  233. $reflMethod->setAccessible(true);
  234. $res = $reflMethod->invoke($formatter, ['message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"]);
  235. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  236. }
  237. /**
  238. * @param mixed $in Input
  239. * @param mixed $expect Expected output
  240. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  241. * @dataProvider providesDetectAndCleanUtf8
  242. */
  243. public function testDetectAndCleanUtf8($in, $expect)
  244. {
  245. $formatter = new NormalizerFormatter();
  246. $formatter->detectAndCleanUtf8($in);
  247. $this->assertSame($expect, $in);
  248. }
  249. public function providesDetectAndCleanUtf8()
  250. {
  251. $obj = new \stdClass;
  252. return [
  253. 'null' => [null, null],
  254. 'int' => [123, 123],
  255. 'float' => [123.45, 123.45],
  256. 'bool false' => [false, false],
  257. 'bool true' => [true, true],
  258. 'ascii string' => ['abcdef', 'abcdef'],
  259. 'latin9 string' => ["\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'],
  260. 'unicode string' => ['¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'],
  261. 'empty array' => [[], []],
  262. 'array' => [['abcdef'], ['abcdef']],
  263. 'object' => [$obj, $obj],
  264. ];
  265. }
  266. /**
  267. * @param int $code
  268. * @param string $msg
  269. * @dataProvider providesHandleJsonErrorFailure
  270. */
  271. public function testHandleJsonErrorFailure($code, $msg)
  272. {
  273. $formatter = new NormalizerFormatter();
  274. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  275. $reflMethod->setAccessible(true);
  276. $this->expectException('RuntimeException', $msg);
  277. $reflMethod->invoke($formatter, $code, 'faked');
  278. }
  279. public function providesHandleJsonErrorFailure()
  280. {
  281. return [
  282. 'depth' => [JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'],
  283. 'state' => [JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'],
  284. 'ctrl' => [JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'],
  285. 'default' => [-1, 'Unknown error'],
  286. ];
  287. }
  288. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  289. // and no file or line are included in the trace because it's treated as internal function
  290. public function testExceptionTraceWithArgs()
  291. {
  292. if (defined('HHVM_VERSION')) {
  293. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  294. }
  295. try {
  296. // This will contain $resource and $wrappedResource as arguments in the trace item
  297. $resource = fopen('php://memory', 'rw+');
  298. fwrite($resource, 'test_resource');
  299. $wrappedResource = new TestFooNorm;
  300. $wrappedResource->foo = $resource;
  301. // Just do something stupid with a resource/wrapped resource as argument
  302. $arr = [$wrappedResource, $resource];
  303. // modifying the array inside throws a "usort(): Array was modified by the user comparison function"
  304. usort($arr, function ($a, $b) {
  305. throw new \ErrorException('Foo');
  306. });
  307. } catch (\Throwable $e) {
  308. }
  309. $formatter = new NormalizerFormatter();
  310. $record = ['context' => ['exception' => $e]];
  311. $result = $formatter->format($record);
  312. $this->assertRegExp(
  313. '%\[resource\(stream\)\]%',
  314. $result['context']['exception']['trace'][0]
  315. );
  316. $pattern = '%\[\{"Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm":"JSON_ERROR"\}%';
  317. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  318. $this->assertRegExp(
  319. $pattern,
  320. $result['context']['exception']['trace'][0]
  321. );
  322. }
  323. }
  324. class TestFooNorm
  325. {
  326. public $foo = 'fooValue';
  327. }
  328. class TestBarNorm
  329. {
  330. public function __toString()
  331. {
  332. return 'bar';
  333. }
  334. }
  335. class TestStreamFoo
  336. {
  337. public $foo;
  338. public $resource;
  339. public function __construct($resource)
  340. {
  341. $this->resource = $resource;
  342. $this->foo = 'BAR';
  343. }
  344. public function __toString()
  345. {
  346. fseek($this->resource, 0);
  347. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  348. }
  349. }
  350. class TestToStringError
  351. {
  352. public function __toString()
  353. {
  354. throw new \RuntimeException('Could not convert to string');
  355. }
  356. }