NormalizerFormatterTest.php 11 KB

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