NormalizerFormatterTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. <?php
  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(array(
  25. 'level_name' => 'ERROR',
  26. 'channel' => 'meh',
  27. 'message' => 'foo',
  28. 'datetime' => new \DateTime,
  29. 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
  30. 'context' => array(
  31. 'foo' => 'bar',
  32. 'baz' => 'qux',
  33. 'inf' => INF,
  34. '-inf' => -INF,
  35. 'nan' => acos(4),
  36. ),
  37. ));
  38. $this->assertEquals(array(
  39. 'level_name' => 'ERROR',
  40. 'channel' => 'meh',
  41. 'message' => 'foo',
  42. 'datetime' => date('Y-m-d'),
  43. 'extra' => array(
  44. 'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})',
  45. 'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)',
  46. 'baz' => array(),
  47. 'res' => '[resource] (stream)',
  48. ),
  49. 'context' => array(
  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(array(
  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(array(
  70. 'exception' => array(
  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(array(
  83. 'myObject' => new TestToStringError(),
  84. ));
  85. }
  86. public function testBatchFormat()
  87. {
  88. $formatter = new NormalizerFormatter('Y-m-d');
  89. $formatted = $formatter->formatBatch(array(
  90. array(
  91. 'level_name' => 'CRITICAL',
  92. 'channel' => 'test',
  93. 'message' => 'bar',
  94. 'context' => array(),
  95. 'datetime' => new \DateTime,
  96. 'extra' => array(),
  97. ),
  98. array(
  99. 'level_name' => 'WARNING',
  100. 'channel' => 'log',
  101. 'message' => 'foo',
  102. 'context' => array(),
  103. 'datetime' => new \DateTime,
  104. 'extra' => array(),
  105. ),
  106. ));
  107. $this->assertEquals(array(
  108. array(
  109. 'level_name' => 'CRITICAL',
  110. 'channel' => 'test',
  111. 'message' => 'bar',
  112. 'context' => array(),
  113. 'datetime' => date('Y-m-d'),
  114. 'extra' => array(),
  115. ),
  116. array(
  117. 'level_name' => 'WARNING',
  118. 'channel' => 'log',
  119. 'message' => 'foo',
  120. 'context' => array(),
  121. 'datetime' => date('Y-m-d'),
  122. 'extra' => array(),
  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, array($foo, $bar), true);
  148. restore_error_handler();
  149. $this->assertEquals(@json_encode(array($foo, $bar)), $res);
  150. }
  151. public function testCanNormalizeReferences()
  152. {
  153. $formatter = new NormalizerFormatter();
  154. $x = ['foo' => 'bar'];
  155. $y = ['x' => &$x];
  156. $x['y'] = &$y;
  157. $formatter->format($y);
  158. }
  159. public function testIgnoresInvalidTypes()
  160. {
  161. // set up the recursion
  162. $resource = fopen(__FILE__, 'r');
  163. // set an error handler to assert that the error is not raised anymore
  164. $that = $this;
  165. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  166. if (error_reporting() & $level) {
  167. restore_error_handler();
  168. $that->fail("$message should not be raised");
  169. }
  170. });
  171. $formatter = new NormalizerFormatter();
  172. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  173. $reflMethod->setAccessible(true);
  174. $res = $reflMethod->invoke($formatter, array($resource), true);
  175. restore_error_handler();
  176. $this->assertEquals(@json_encode(array($resource)), $res);
  177. }
  178. /**
  179. * @expectedException RuntimeException
  180. */
  181. public function testThrowsOnInvalidEncoding()
  182. {
  183. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  184. // Ignore the warning that will be emitted by PHP <5.5.0
  185. \PHPUnit_Framework_Error_Warning::$enabled = false;
  186. }
  187. $formatter = new NormalizerFormatter();
  188. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  189. $reflMethod->setAccessible(true);
  190. // send an invalid unicode sequence as a object that can't be cleaned
  191. $record = new \stdClass;
  192. $record->message = "\xB1\x31";
  193. $res = $reflMethod->invoke($formatter, $record);
  194. if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
  195. throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
  196. }
  197. }
  198. public function testConvertsInvalidEncodingAsLatin9()
  199. {
  200. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  201. // Ignore the warning that will be emitted by PHP <5.5.0
  202. \PHPUnit_Framework_Error_Warning::$enabled = false;
  203. }
  204. $formatter = new NormalizerFormatter();
  205. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  206. $reflMethod->setAccessible(true);
  207. $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
  208. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  209. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  210. } else {
  211. // PHP <5.5 does not return false for an element encoding failure,
  212. // instead it emits a warning (possibly) and nulls the value.
  213. $this->assertSame('{"message":null}', $res);
  214. }
  215. }
  216. /**
  217. * @param mixed $in Input
  218. * @param mixed $expect Expected output
  219. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  220. * @dataProvider providesDetectAndCleanUtf8
  221. */
  222. public function testDetectAndCleanUtf8($in, $expect)
  223. {
  224. $formatter = new NormalizerFormatter();
  225. $formatter->detectAndCleanUtf8($in);
  226. $this->assertSame($expect, $in);
  227. }
  228. public function providesDetectAndCleanUtf8()
  229. {
  230. $obj = new \stdClass;
  231. return array(
  232. 'null' => array(null, null),
  233. 'int' => array(123, 123),
  234. 'float' => array(123.45, 123.45),
  235. 'bool false' => array(false, false),
  236. 'bool true' => array(true, true),
  237. 'ascii string' => array('abcdef', 'abcdef'),
  238. 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
  239. 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
  240. 'empty array' => array(array(), array()),
  241. 'array' => array(array('abcdef'), array('abcdef')),
  242. 'object' => array($obj, $obj),
  243. );
  244. }
  245. /**
  246. * @param int $code
  247. * @param string $msg
  248. * @dataProvider providesHandleJsonErrorFailure
  249. */
  250. public function testHandleJsonErrorFailure($code, $msg)
  251. {
  252. $formatter = new NormalizerFormatter();
  253. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  254. $reflMethod->setAccessible(true);
  255. $this->setExpectedException('RuntimeException', $msg);
  256. $reflMethod->invoke($formatter, $code, 'faked');
  257. }
  258. public function providesHandleJsonErrorFailure()
  259. {
  260. return array(
  261. 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
  262. 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
  263. 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
  264. 'default' => array(-1, 'Unknown error'),
  265. );
  266. }
  267. public function testExceptionTraceWithArgs()
  268. {
  269. if (defined('HHVM_VERSION')) {
  270. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  271. }
  272. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  273. // and no file or line are included in the trace because it's treated as internal function
  274. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  275. throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  276. });
  277. try {
  278. // This will contain $resource and $wrappedResource as arguments in the trace item
  279. $resource = fopen('php://memory', 'rw+');
  280. fwrite($resource, 'test_resource');
  281. $wrappedResource = new TestFooNorm;
  282. $wrappedResource->foo = $resource;
  283. // Just do something stupid with a resource/wrapped resource as argument
  284. array_keys($wrappedResource);
  285. } catch (\Exception $e) {
  286. restore_error_handler();
  287. }
  288. $formatter = new NormalizerFormatter();
  289. $record = array('context' => array('exception' => $e));
  290. $result = $formatter->format($record);
  291. $this->assertRegExp(
  292. '%"resource":"\[resource\] \(stream\)"%',
  293. $result['context']['exception']['trace'][0]
  294. );
  295. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  296. $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%';
  297. } else {
  298. $pattern = '%\\\\"foo\\\\":null%';
  299. }
  300. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  301. $this->assertRegExp(
  302. $pattern,
  303. $result['context']['exception']['trace'][0]
  304. );
  305. }
  306. }
  307. class TestFooNorm
  308. {
  309. public $foo = 'foo';
  310. }
  311. class TestBarNorm
  312. {
  313. public function __toString()
  314. {
  315. return 'bar';
  316. }
  317. }
  318. class TestStreamFoo
  319. {
  320. public $foo;
  321. public $resource;
  322. public function __construct($resource)
  323. {
  324. $this->resource = $resource;
  325. $this->foo = 'BAR';
  326. }
  327. public function __toString()
  328. {
  329. fseek($this->resource, 0);
  330. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  331. }
  332. }
  333. class TestToStringError
  334. {
  335. public function __toString()
  336. {
  337. throw new \RuntimeException('Could not convert to string');
  338. }
  339. }