ILIAS  release_5-4 Revision v5.4.26-12-gabc799a52e6
NormalizerFormatterTest.php
Go to the documentation of this file.
1<?php
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog\Formatter;
13
18{
19 public function tearDown()
20 {
21 \PHPUnit_Framework_Error_Warning::$enabled = true;
22
23 return parent::tearDown();
24 }
25
26 public function testFormat()
27 {
28 $formatter = new NormalizerFormatter('Y-m-d');
29 $formatted = $formatter->format(array(
30 'level_name' => 'ERROR',
31 'channel' => 'meh',
32 'message' => 'foo',
33 'datetime' => new \DateTime,
34 'extra' => array('foo' => new TestFooNorm, 'bar' => new TestBarNorm, 'baz' => array(), 'res' => fopen('php://memory', 'rb')),
35 'context' => array(
36 'foo' => 'bar',
37 'baz' => 'qux',
38 'inf' => INF,
39 '-inf' => -INF,
40 'nan' => acos(4),
41 ),
42 ));
43
44 $this->assertEquals(array(
45 'level_name' => 'ERROR',
46 'channel' => 'meh',
47 'message' => 'foo',
48 'datetime' => date('Y-m-d'),
49 'extra' => array(
50 'foo' => '[object] (Monolog\\Formatter\\TestFooNorm: {"foo":"foo"})',
51 'bar' => '[object] (Monolog\\Formatter\\TestBarNorm: bar)',
52 'baz' => array(),
53 'res' => '[resource] (stream)',
54 ),
55 'context' => array(
56 'foo' => 'bar',
57 'baz' => 'qux',
58 'inf' => 'INF',
59 '-inf' => '-INF',
60 'nan' => 'NaN',
61 ),
62 ), $formatted);
63 }
64
65 public function testFormatExceptions()
66 {
67 $formatter = new NormalizerFormatter('Y-m-d');
68 $e = new \LogicException('bar');
69 $e2 = new \RuntimeException('foo', 0, $e);
70 $formatted = $formatter->format(array(
71 'exception' => $e2,
72 ));
73
74 $this->assertGreaterThan(5, count($formatted['exception']['trace']));
75 $this->assertTrue(isset($formatted['exception']['previous']));
76 unset($formatted['exception']['trace'], $formatted['exception']['previous']);
77
78 $this->assertEquals(array(
79 'exception' => array(
80 'class' => get_class($e2),
81 'message' => $e2->getMessage(),
82 'code' => $e2->getCode(),
83 'file' => $e2->getFile().':'.$e2->getLine(),
84 ),
85 ), $formatted);
86 }
87
89 {
90 if (!class_exists('SoapFault')) {
91 $this->markTestSkipped('Requires the soap extension');
92 }
93
94 $formatter = new NormalizerFormatter('Y-m-d');
95 $e = new \SoapFault('foo', 'bar', 'hello', 'world');
96 $formatted = $formatter->format(array(
97 'exception' => $e,
98 ));
99
100 unset($formatted['exception']['trace']);
101
102 $this->assertEquals(array(
103 'exception' => array(
104 'class' => 'SoapFault',
105 'message' => 'bar',
106 'code' => 0,
107 'file' => $e->getFile().':'.$e->getLine(),
108 'faultcode' => 'foo',
109 'faultactor' => 'hello',
110 'detail' => 'world',
111 ),
112 ), $formatted);
113 }
114
116 {
117 $formatter = new NormalizerFormatter('Y-m-d');
118 $this->setExpectedException('RuntimeException', 'Could not convert to string');
119 $formatter->format(array(
120 'myObject' => new TestToStringError(),
121 ));
122 }
123
124 public function testBatchFormat()
125 {
126 $formatter = new NormalizerFormatter('Y-m-d');
127 $formatted = $formatter->formatBatch(array(
128 array(
129 'level_name' => 'CRITICAL',
130 'channel' => 'test',
131 'message' => 'bar',
132 'context' => array(),
133 'datetime' => new \DateTime,
134 'extra' => array(),
135 ),
136 array(
137 'level_name' => 'WARNING',
138 'channel' => 'log',
139 'message' => 'foo',
140 'context' => array(),
141 'datetime' => new \DateTime,
142 'extra' => array(),
143 ),
144 ));
145 $this->assertEquals(array(
146 array(
147 'level_name' => 'CRITICAL',
148 'channel' => 'test',
149 'message' => 'bar',
150 'context' => array(),
151 'datetime' => date('Y-m-d'),
152 'extra' => array(),
153 ),
154 array(
155 'level_name' => 'WARNING',
156 'channel' => 'log',
157 'message' => 'foo',
158 'context' => array(),
159 'datetime' => date('Y-m-d'),
160 'extra' => array(),
161 ),
162 ), $formatted);
163 }
164
169 {
170 // set up the recursion
171 $foo = new \stdClass();
172 $bar = new \stdClass();
173
174 $foo->bar = $bar;
175 $bar->foo = $foo;
176
177 // set an error handler to assert that the error is not raised anymore
178 $that = $this;
179 set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
180 if (error_reporting() & $level) {
181 restore_error_handler();
182 $that->fail("$message should not be raised");
183 }
184 });
185
186 $formatter = new NormalizerFormatter();
187 $reflMethod = new \ReflectionMethod($formatter, 'toJson');
188 $reflMethod->setAccessible(true);
189 $res = $reflMethod->invoke($formatter, array($foo, $bar), true);
190
191 restore_error_handler();
192
193 $this->assertEquals(@json_encode(array($foo, $bar)), $res);
194 }
195
197 {
198 $formatter = new NormalizerFormatter();
199 $x = array('foo' => 'bar');
200 $y = array('x' => &$x);
201 $x['y'] = &$y;
202 $formatter->format($y);
203 }
204
205 public function testIgnoresInvalidTypes()
206 {
207 // set up the recursion
208 $resource = fopen(__FILE__, 'r');
209
210 // set an error handler to assert that the error is not raised anymore
211 $that = $this;
212 set_error_handler(function ($level, $message, $file, $line, $context) use ($that) {
213 if (error_reporting() & $level) {
214 restore_error_handler();
215 $that->fail("$message should not be raised");
216 }
217 });
218
219 $formatter = new NormalizerFormatter();
220 $reflMethod = new \ReflectionMethod($formatter, 'toJson');
221 $reflMethod->setAccessible(true);
222 $res = $reflMethod->invoke($formatter, array($resource), true);
223
224 restore_error_handler();
225
226 $this->assertEquals(@json_encode(array($resource)), $res);
227 }
228
230 {
231 $formatter = new NormalizerFormatter();
232 $largeArray = range(1, 1000);
233
234 $res = $formatter->format(array(
235 'level_name' => 'CRITICAL',
236 'channel' => 'test',
237 'message' => 'bar',
238 'context' => array($largeArray),
239 'datetime' => new \DateTime,
240 'extra' => array(),
241 ));
242
243 $this->assertCount(1000, $res['context'][0]);
244 $this->assertArrayNotHasKey('...', $res['context'][0]);
245 }
246
248 {
249 $formatter = new NormalizerFormatter();
250 $largeArray = range(1, 2000);
251
252 $res = $formatter->format(array(
253 'level_name' => 'CRITICAL',
254 'channel' => 'test',
255 'message' => 'bar',
256 'context' => array($largeArray),
257 'datetime' => new \DateTime,
258 'extra' => array(),
259 ));
260
261 $this->assertCount(1001, $res['context'][0]);
262 $this->assertEquals('Over 1000 items (2000 total), aborting normalization', $res['context'][0]['...']);
263 }
264
269 {
270 if (version_compare(PHP_VERSION, '5.5.0', '<')) {
271 // Ignore the warning that will be emitted by PHP <5.5.0
272 \PHPUnit_Framework_Error_Warning::$enabled = false;
273 }
274 $formatter = new NormalizerFormatter();
275 $reflMethod = new \ReflectionMethod($formatter, 'toJson');
276 $reflMethod->setAccessible(true);
277
278 // send an invalid unicode sequence as a object that can't be cleaned
279 $record = new \stdClass;
280 $record->message = "\xB1\x31";
281 $res = $reflMethod->invoke($formatter, $record);
282 if (PHP_VERSION_ID < 50500 && $res === '{"message":null}') {
283 throw new \RuntimeException('PHP 5.3/5.4 throw a warning and null the value instead of returning false entirely');
284 }
285 }
286
288 {
289 if (version_compare(PHP_VERSION, '5.5.0', '<')) {
290 // Ignore the warning that will be emitted by PHP <5.5.0
291 \PHPUnit_Framework_Error_Warning::$enabled = false;
292 }
293 $formatter = new NormalizerFormatter();
294 $reflMethod = new \ReflectionMethod($formatter, 'toJson');
295 $reflMethod->setAccessible(true);
296
297 $res = $reflMethod->invoke($formatter, array('message' => "\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE"));
298
299 if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
300 $this->assertSame('{"message":"€ŠšŽžŒœŸ"}', $res);
301 } else {
302 // PHP <5.5 does not return false for an element encoding failure,
303 // instead it emits a warning (possibly) and nulls the value.
304 $this->assertSame('{"message":null}', $res);
305 }
306 }
307
314 public function testDetectAndCleanUtf8($in, $expect)
315 {
316 $formatter = new NormalizerFormatter();
317 $formatter->detectAndCleanUtf8($in);
318 $this->assertSame($expect, $in);
319 }
320
322 {
323 $obj = new \stdClass;
324
325 return array(
326 'null' => array(null, null),
327 'int' => array(123, 123),
328 'float' => array(123.45, 123.45),
329 'bool false' => array(false, false),
330 'bool true' => array(true, true),
331 'ascii string' => array('abcdef', 'abcdef'),
332 'latin9 string' => array("\xB1\x31\xA4\xA6\xA8\xB4\xB8\xBC\xBD\xBE\xFF", '±1€ŠšŽžŒœŸÿ'),
333 'unicode string' => array('¤¦¨´¸¼½¾€ŠšŽžŒœŸ', '¤¦¨´¸¼½¾€ŠšŽžŒœŸ'),
334 'empty array' => array(array(), array()),
335 'array' => array(array('abcdef'), array('abcdef')),
336 'object' => array($obj, $obj),
337 );
338 }
339
345 public function testHandleJsonErrorFailure($code, $msg)
346 {
347 $formatter = new NormalizerFormatter();
348 $reflMethod = new \ReflectionMethod($formatter, 'handleJsonError');
349 $reflMethod->setAccessible(true);
350
351 $this->setExpectedException('RuntimeException', $msg);
352 $reflMethod->invoke($formatter, $code, 'faked');
353 }
354
356 {
357 return array(
358 'depth' => array(JSON_ERROR_DEPTH, 'Maximum stack depth exceeded'),
359 'state' => array(JSON_ERROR_STATE_MISMATCH, 'Underflow or the modes mismatch'),
360 'ctrl' => array(JSON_ERROR_CTRL_CHAR, 'Unexpected control character found'),
361 'default' => array(-1, 'Unknown error'),
362 );
363 }
364
366 {
367 if (defined('HHVM_VERSION')) {
368 $this->markTestSkipped('Not supported in HHVM since it detects errors differently');
369 }
370
371 // This happens i.e. in React promises or Guzzle streams where stream wrappers are registered
372 // and no file or line are included in the trace because it's treated as internal function
373 set_error_handler(function ($errno, $errstr, $errfile, $errline) {
374 throw new \ErrorException($errstr, 0, $errno, $errfile, $errline);
375 });
376
377 try {
378 // This will contain $resource and $wrappedResource as arguments in the trace item
379 $resource = fopen('php://memory', 'rw+');
380 fwrite($resource, 'test_resource');
381 $wrappedResource = new TestFooNorm;
382 $wrappedResource->foo = $resource;
383 // Just do something stupid with a resource/wrapped resource as argument
384 array_keys($wrappedResource);
385 } catch (\Exception $e) {
386 restore_error_handler();
387 }
388
389 $formatter = new NormalizerFormatter();
390 $record = array('context' => array('exception' => $e));
391 $result = $formatter->format($record);
392
393 $this->assertRegExp(
394 '%"resource":"\[resource\] \‍(stream\‍)"%',
395 $result['context']['exception']['trace'][0]
396 );
397
398 if (version_compare(PHP_VERSION, '5.5.0', '>=')) {
399 $pattern = '%"wrappedResource":"\[object\] \‍(Monolog\\\\\\\\Formatter\\\\\\\\TestFooNorm: \‍)"%';
400 } else {
401 $pattern = '%\\\\"foo\\\\":null%';
402 }
403
404 // Tests that the wrapped resource is ignored while encoding, only works for PHP <= 5.4
405 $this->assertRegExp(
406 $pattern,
407 $result['context']['exception']['trace'][0]
408 );
409 }
410
412 {
413 try {
414 $arg = new TestInfoLeak;
415 call_user_func(array($this, 'throwHelper'), $arg, $dt = new \DateTime());
416 } catch (\Exception $e) {
417 }
418
419 $formatter = new NormalizerFormatter();
420 $record = array('context' => array('exception' => $e));
421 $result = $formatter->format($record);
422
423 $this->assertSame(
424 '{"function":"throwHelper","class":"Monolog\\\\Formatter\\\\NormalizerFormatterTest","type":"->","args":["[object] (Monolog\\\\Formatter\\\\TestInfoLeak)","'.$dt->format('Y-m-d H:i:s').'"]}',
425 $result['context']['exception']['trace'][0]
426 );
427 }
428
429 private function throwHelper($arg)
430 {
431 throw new \RuntimeException('Thrown');
432 }
433}
434
436{
437 public $foo = 'foo';
438}
439
441{
442 public function __toString()
443 {
444 return 'bar';
445 }
446}
447
449{
450 public $foo;
451 public $resource;
452
453 public function __construct($resource)
454 {
455 $this->resource = $resource;
456 $this->foo = 'BAR';
457 }
458
459 public function __toString()
460 {
461 fseek($this->resource, 0);
462
463 return $this->foo . ' - ' . (string) stream_get_contents($this->resource);
464 }
465}
466
468{
469 public function __toString()
470 {
471 throw new \RuntimeException('Could not convert to string');
472 }
473}
474
476{
477 public function __toString()
478 {
479 return 'Sensitive information';
480 }
481}
$result
if(php_sapi_name() !='cli') $in
Definition: Utf8Test.php:37
An exception for terminatinating execution or to throw for unit testing.
@covers Monolog\Formatter\NormalizerFormatter
testThrowsOnInvalidEncoding()
@expectedException RuntimeException
Normalizes incoming records to remove objects/resources so it's easier to dump to various targets.
$x
Definition: complexTest.php:9
$y
Definition: example_007.php:83
$code
Definition: example_050.php:99
catch(Exception $e) $message
foreach($_POST as $key=> $value) $res
$context
Definition: webdav.php:25