NormalizerFormatterTest.php 14 KB

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