NormalizerFormatterTest.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 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, array($resource), true);
  167. restore_error_handler();
  168. $this->assertEquals(@json_encode(array($resource)), $res);
  169. }
  170. /**
  171. * @expectedException RuntimeException
  172. */
  173. public function testThrowsOnInvalidEncoding()
  174. {
  175. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  176. // Ignore the warning that will be emitted by PHP <5.5.0
  177. \PHPUnit_Framework_Error_Warning::$enabled = false;
  178. }
  179. $formatter = new NormalizerFormatter();
  180. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  181. $reflMethod->setAccessible(true);
  182. // send an invalid unicode sequence as a object that can't be cleaned
  183. $record = new \stdClass;
  184. $record->message = "\xB1\x31";
  185. $res = $reflMethod->invoke($formatter, $record);
  186. if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
  187. throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
  188. }
  189. }
  190. public function testConvertsInvalidEncodingAsLatin9()
  191. {
  192. if (version_compare(PHP_VERSION, '5.5.0', '<')) {
  193. // Ignore the warning that will be emitted by PHP <5.5.0
  194. \PHPUnit_Framework_Error_Warning::$enabled = false;
  195. }
  196. $formatter = new NormalizerFormatter();
  197. $reflMethod = new \ReflectionMethod($formatter, 'toJson');
  198. $reflMethod->setAccessible(true);
  199. $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
  200. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  201. $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
  202. } else {
  203. // PHP <5.5 does not return false for an element encoding failure,
  204. // instead it emits a warning (possibly) and nulls the value.
  205. $this->assertSame('{"message":null}', $res);
  206. }
  207. }
  208. /**
  209. * @param mixed $in Input
  210. * @param mixed $expect Expected output
  211. * @covers Monolog\Formatter\NormalizerFormatter::detectAndCleanUtf8
  212. * @dataProvider providesDetectAndCleanUtf8
  213. */
  214. public function testDetectAndCleanUtf8($in, $expect)
  215. {
  216. $formatter = new NormalizerFormatter();
  217. $formatter->detectAndCleanUtf8($in);
  218. $this->assertSame($expect, $in);
  219. }
  220. public function providesDetectAndCleanUtf8()
  221. {
  222. $obj = new \stdClass;
  223. return array(
  224. 'null' => array(null, null),
  225. 'int' => array(123, 123),
  226. 'float' => array(123.45, 123.45),
  227. 'bool false' => array(false, false),
  228. 'bool true' => array(true, true),
  229. 'ascii string' => array('abcdef', 'abcdef'),
  230. 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
  231. 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
  232. 'empty array' => array(array(), array()),
  233. 'array' => array(array('abcdef'), array('abcdef')),
  234. 'object' => array($obj, $obj),
  235. );
  236. }
  237. /**
  238. * @param int $code
  239. * @param string $msg
  240. * @dataProvider providesHandleJsonErrorFailure
  241. */
  242. public function testHandleJsonErrorFailure($code, $msg)
  243. {
  244. $formatter = new NormalizerFormatter();
  245. $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
  246. $reflMethod->setAccessible(true);
  247. $this->setExpectedException('RuntimeException', $msg);
  248. $reflMethod->invoke($formatter, $code, 'faked');
  249. }
  250. public function providesHandleJsonErrorFailure()
  251. {
  252. return array(
  253. 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
  254. 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
  255. 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
  256. 'default' => array(-1, 'Unknown error'),
  257. );
  258. }
  259. public function testExceptionTraceWithArgs()
  260. {
  261. if (defined('HHVM_VERSION')) {
  262. $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
  263. }
  264. // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
  265. // and no file or line are included in the trace because it's treated as internal function
  266. set_error_handler(function ($errno, $errstr, $errfile, $errline) {
  267. throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
  268. });
  269. try {
  270. // This will contain $resource and $wrappedResource as arguments in the trace item
  271. $resource = fopen('php://memory', 'rw+');
  272. fwrite($resource, 'test_resource');
  273. $wrappedResource = new TestFooNorm;
  274. $wrappedResource->foo = $resource;
  275. // Just do something stupid with a resource/wrapped resource as argument
  276. array_keys($wrappedResource);
  277. } catch (\Exception $e) {
  278. restore_error_handler();
  279. }
  280. $formatter = new NormalizerFormatter();
  281. $record = array('context' => array('exception' => $e));
  282. $result = $formatter->format($record);
  283. $this->assertRegExp(
  284. '%"resource":"\[resource\] \(stream\)"%',
  285. $result['context']['exception']['trace'][0]
  286. );
  287. if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
  288. $pattern = '%"wrappedResource":"\[object\] \(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \)"%';
  289. } else {
  290. $pattern = '%\\\\"foo\\\\":null%';
  291. }
  292. // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
  293. $this->assertRegExp(
  294. $pattern,
  295. $result['context']['exception']['trace'][0]
  296. );
  297. }
  298. }
  299. class TestFooNorm
  300. {
  301. public $foo = 'foo';
  302. }
  303. class TestBarNorm
  304. {
  305. public function __toString()
  306. {
  307. return 'bar';
  308. }
  309. }
  310. class TestStreamFoo
  311. {
  312. public $foo;
  313. public $resource;
  314. public function __construct($resource)
  315. {
  316. $this->resource = $resource;
  317. $this->foo = 'BAR';
  318. }
  319. public function __toString()
  320. {
  321. fseek($this->resource, 0);
  322. return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
  323. }
  324. }
  325. class TestToStringError
  326. {
  327. public function __toString()
  328. {
  329. throw new \RuntimeException('Could not convert to string');
  330. }
  331. }