NormalizerFormatterTest.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 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', (object) array('foo' => 'world'));
  85. $formatted = $formatter->format(array(
  86. 'exception' => $e,
  87. ));
  88. unset($formatted['exception']['trace']);
  89. $this->assertEquals(array(
  90. 'exception' => array(
  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->setExpectedException('RuntimeException', 'Could not convert to string');
  105. $formatter->format(array(
  106. 'myObject' => new TestToStringError(),
  107. ));
  108. }
  109. public function testBatchFormat()
  110. {
  111. $formatter = new NormalizerFormatter('Y-m-d');
  112. $formatted = $formatter->formatBatch(array(
  113. array(
  114. 'level_name' => 'CRITICAL',
  115. 'channel' => 'test',
  116. 'message' => 'bar',
  117. 'context' => array(),
  118. 'datetime' => new \DateTime,
  119. 'extra' => array(),
  120. ),
  121. array(
  122. 'level_name' => 'WARNING',
  123. 'channel' => 'log',
  124. 'message' => 'foo',
  125. 'context' => array(),
  126. 'datetime' => new \DateTime,
  127. 'extra' => array(),
  128. ),
  129. ));
  130. $this->assertEquals(array(
  131. array(
  132. 'level_name' => 'CRITICAL',
  133. 'channel' => 'test',
  134. 'message' => 'bar',
  135. 'context' => array(),
  136. 'datetime' => date('Y-m-d'),
  137. 'extra' => array(),
  138. ),
  139. array(
  140. 'level_name' => 'WARNING',
  141. 'channel' => 'log',
  142. 'message' => 'foo',
  143. 'context' => array(),
  144. 'datetime' => date('Y-m-d'),
  145. 'extra' => array(),
  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, array($foo, $bar), true);
  171. restore_error_handler();
  172. if (PHP_VERSION_ID < 50500) {
  173. $this->assertEquals('[{"bar":{"foo":null}},{"foo":{"bar":null}}]', $res);
  174. } else {
  175. $this->assertEquals('null', $res);
  176. }
  177. }
  178. public function testCanNormalizeReferences()
  179. {
  180. $formatter = new NormalizerFormatter();
  181. $x = array('foo' => 'bar');
  182. $y = array('x' => &$x);
  183. $x['y'] = &$y;
  184. $formatter->format($y);
  185. }
  186. public function testIgnoresInvalidTypes()
  187. {
  188. // set up the recursion
  189. $resource = fopen(__FILE__, 'r');
  190. // set an error handler to assert that the error is not raised anymore
  191. $that = $this;
  192. set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
  193. if (error_reporting() & $level) {
  194. restore_error_handler();
  195. $that->fail("$message should not be raised");
  196. }
  197. });
  198. $formatter = new NormalizerFormatter();
  199. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  200. $reflMethod->setAccessible(true);
  201. $res = $reflMethod->invoke($formatter, array($resource), true);
  202. restore_error_handler();
  203. if (PHP_VERSION_ID < 50500) {
  204. $this->assertEquals('[null]', $res);
  205. } else {
  206. $this->assertEquals('null', $res);
  207. }
  208. }
  209. public function testNormalizeHandleLargeArraysWithExactly1000Items()
  210. {
  211. $formatter = new NormalizerFormatter();
  212. $largeArray = range(1, 1000);
  213. $res = $formatter->format(array(
  214. 'level_name' => 'CRITICAL',
  215. 'channel' => 'test',
  216. 'message' => 'bar',
  217. 'context' => array($largeArray),
  218. 'datetime' => new \DateTime,
  219. 'extra' => array(),
  220. ));
  221. $this->assertCount(1000, $res['context'][0]);
  222. $this->assertArrayNotHasKey('...', $res['context'][0]);
  223. }
  224. public function testNormalizeHandleLargeArrays()
  225. {
  226. $formatter = new NormalizerFormatter();
  227. $largeArray = range(1, 2000);
  228. $res = $formatter->format(array(
  229. 'level_name' => 'CRITICAL',
  230. 'channel' => 'test',
  231. 'message' => 'bar',
  232. 'context' => array($largeArray),
  233. 'datetime' => new \DateTime,
  234. 'extra' => array(),
  235. ));
  236. $this->assertCount(1001, $res['context'][0]);
  237. $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
  238. }
  239. /**
  240. * @expectedException RuntimeException
  241. */
  242. public function testThrowsOnInvalidEncoding()
  243. {
  244. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  245. // Ignore the warning that will be emitted by PHP <5.5.0
  246. \PHPUnit_Framework_Error_Warning::$enabled = false;
  247. }
  248. $formatter = new NormalizerFormatter();
  249. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  250. $reflMethod->setAccessible(true);
  251. // send an invalid unicode sequence as a object that can't be cleaned
  252. $record = new \stdClass;
  253. $record->message = "\xB1\x31";
  254. $res = $reflMethod->invoke($formatter, $record);
  255. if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
  256. throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
  257. }
  258. }
  259. public function testConvertsInvalidEncodingAsLatin9()
  260. {
  261. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  262. // Ignore the warning that will be emitted by PHP <5.5.0
  263. \PHPUnit_Framework_Error_Warning::$enabled = false;
  264. }
  265. $formatter = new NormalizerFormatter();
  266. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  267. $reflMethod->setAccessible(true);
  268. $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
  269. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  270. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  271. } else {
  272. // PHP <5.5 does not return false for an element encoding failure,
  273. // instead it emits a warning (possibly) and nulls the value.
  274. $this->assertSame('{"message":null}', $res);
  275. }
  276. }
  277. public function testExceptionTraceWithArgs()
  278. {
  279. if (defined('HHVM_VERSION')) {
  280. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  281. }
  282. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  283. // and no file or line are included in the trace because it's treated as internal function
  284. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  285. throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  286. });
  287. try {
  288. // This will contain $resource and $wrappedResource as arguments in the trace item
  289. $resource = fopen('php://memory', 'rw+');
  290. fwrite($resource, 'test_resource');
  291. $wrappedResource = new TestFooNorm;
  292. $wrappedResource->foo = $resource;
  293. // Just do something stupid with a resource/wrapped resource as argument
  294. array_keys($wrappedResource);
  295. } catch (\Exception $e) {
  296. restore_error_handler();
  297. }
  298. $formatter = new NormalizerFormatter();
  299. $record = array('context' => array('exception' => $e));
  300. $result = $formatter->format($record);
  301. $this->assertSame(
  302. __FILE__.':'.(__LINE__-10),
  303. $result['context']['exception']['trace'][0]
  304. );
  305. }
  306. public function testExceptionTraceDoesNotLeakCallUserFuncArgs()
  307. {
  308. try {
  309. $arg = new TestInfoLeak;
  310. call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
  311. } catch (\Exception $e) {
  312. }
  313. $formatter = new NormalizerFormatter();
  314. $record = array('context' => array('exception' => $e));
  315. $result = $formatter->format($record);
  316. $this->assertSame(
  317. __FILE__ .':'.(__LINE__-9),
  318. $result['context']['exception']['trace'][0]
  319. );
  320. }
  321. private function throwHelper($arg)
  322. {
  323. throw new \RuntimeException('Thrown');
  324. }
  325. }
  326. class TestFooNorm
  327. {
  328. public $foo = 'foo';
  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. }
  359. class TestInfoLeak
  360. {
  361. public function __toString()
  362. {
  363. return 'Sensitive information';
  364. }
  365. }