PageRenderTime 26ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/Streaming-Safe-for-Kids/vendor/monolog/monolog/tests/Monolog/Formatter/NormalizerFormatterTest.php

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