Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / vendor / symfony / http-kernel / Tests / Log / LoggerTest.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\HttpKernel\Tests\Log;
13
14 use PHPUnit\Framework\TestCase;
15 use Psr\Log\LoggerInterface;
16 use Psr\Log\LogLevel;
17 use Symfony\Component\HttpKernel\Log\Logger;
18
19 /**
20  * @author Kévin Dunglas <dunglas@gmail.com>
21  * @author Jordi Boggiano <j.boggiano@seld.be>
22  */
23 class LoggerTest extends TestCase
24 {
25     /**
26      * @var LoggerInterface
27      */
28     private $logger;
29
30     /**
31      * @var string
32      */
33     private $tmpFile;
34
35     protected function setUp()
36     {
37         $this->tmpFile = sys_get_temp_dir().DIRECTORY_SEPARATOR.'log';
38         $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile);
39     }
40
41     protected function tearDown()
42     {
43         if (!@unlink($this->tmpFile)) {
44             file_put_contents($this->tmpFile, '');
45         }
46     }
47
48     public static function assertLogsMatch(array $expected, array $given)
49     {
50         foreach ($given as $k => $line) {
51             self::assertThat(1 === preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}[\+-][0-9]{2}:[0-9]{2} '.preg_quote($expected[$k]).'/', $line), self::isTrue(), "\"$line\" do not match expected pattern \"$expected[$k]\"");
52         }
53     }
54
55     /**
56      * Return the log messages in order.
57      *
58      * @return string[]
59      */
60     public function getLogs()
61     {
62         return file($this->tmpFile, FILE_IGNORE_NEW_LINES);
63     }
64
65     public function testImplements()
66     {
67         $this->assertInstanceOf(LoggerInterface::class, $this->logger);
68     }
69
70     /**
71      * @dataProvider provideLevelsAndMessages
72      */
73     public function testLogsAtAllLevels($level, $message)
74     {
75         $this->logger->{$level}($message, array('user' => 'Bob'));
76         $this->logger->log($level, $message, array('user' => 'Bob'));
77
78         $expected = array(
79             "[$level] message of level $level with context: Bob",
80             "[$level] message of level $level with context: Bob",
81         );
82         $this->assertLogsMatch($expected, $this->getLogs());
83     }
84
85     public function provideLevelsAndMessages()
86     {
87         return array(
88             LogLevel::EMERGENCY => array(LogLevel::EMERGENCY, 'message of level emergency with context: {user}'),
89             LogLevel::ALERT => array(LogLevel::ALERT, 'message of level alert with context: {user}'),
90             LogLevel::CRITICAL => array(LogLevel::CRITICAL, 'message of level critical with context: {user}'),
91             LogLevel::ERROR => array(LogLevel::ERROR, 'message of level error with context: {user}'),
92             LogLevel::WARNING => array(LogLevel::WARNING, 'message of level warning with context: {user}'),
93             LogLevel::NOTICE => array(LogLevel::NOTICE, 'message of level notice with context: {user}'),
94             LogLevel::INFO => array(LogLevel::INFO, 'message of level info with context: {user}'),
95             LogLevel::DEBUG => array(LogLevel::DEBUG, 'message of level debug with context: {user}'),
96         );
97     }
98
99     public function testLogLevelDisabled()
100     {
101         $this->logger = new Logger(LogLevel::INFO, $this->tmpFile);
102
103         $this->logger->debug('test', array('user' => 'Bob'));
104         $this->logger->log(LogLevel::DEBUG, 'test', array('user' => 'Bob'));
105
106         // Will always be true, but asserts than an exception isn't thrown
107         $this->assertSame(array(), $this->getLogs());
108     }
109
110     /**
111      * @expectedException \Psr\Log\InvalidArgumentException
112      */
113     public function testThrowsOnInvalidLevel()
114     {
115         $this->logger->log('invalid level', 'Foo');
116     }
117
118     /**
119      * @expectedException \Psr\Log\InvalidArgumentException
120      */
121     public function testThrowsOnInvalidMinLevel()
122     {
123         new Logger('invalid');
124     }
125
126     /**
127      * @expectedException \Psr\Log\InvalidArgumentException
128      */
129     public function testInvalidOutput()
130     {
131         new Logger(LogLevel::DEBUG, '/');
132     }
133
134     public function testContextReplacement()
135     {
136         $logger = $this->logger;
137         $logger->info('{Message {nothing} {user} {foo.bar} a}', array('user' => 'Bob', 'foo.bar' => 'Bar'));
138
139         $expected = array('[info] {Message {nothing} Bob Bar a}');
140         $this->assertLogsMatch($expected, $this->getLogs());
141     }
142
143     public function testObjectCastToString()
144     {
145         if (method_exists($this, 'createPartialMock')) {
146             $dummy = $this->createPartialMock(DummyTest::class, array('__toString'));
147         } else {
148             $dummy = $this->getMock(DummyTest::class, array('__toString'));
149         }
150         $dummy->expects($this->atLeastOnce())
151             ->method('__toString')
152             ->will($this->returnValue('DUMMY'));
153
154         $this->logger->warning($dummy);
155
156         $expected = array('[warning] DUMMY');
157         $this->assertLogsMatch($expected, $this->getLogs());
158     }
159
160     public function testContextCanContainAnything()
161     {
162         $context = array(
163             'bool' => true,
164             'null' => null,
165             'string' => 'Foo',
166             'int' => 0,
167             'float' => 0.5,
168             'nested' => array('with object' => new DummyTest()),
169             'object' => new \DateTime(),
170             'resource' => fopen('php://memory', 'r'),
171         );
172
173         $this->logger->warning('Crazy context data', $context);
174
175         $expected = array('[warning] Crazy context data');
176         $this->assertLogsMatch($expected, $this->getLogs());
177     }
178
179     public function testContextExceptionKeyCanBeExceptionOrOtherValues()
180     {
181         $logger = $this->logger;
182         $logger->warning('Random message', array('exception' => 'oops'));
183         $logger->critical('Uncaught Exception!', array('exception' => new \LogicException('Fail')));
184
185         $expected = array(
186             '[warning] Random message',
187             '[critical] Uncaught Exception!',
188         );
189         $this->assertLogsMatch($expected, $this->getLogs());
190     }
191
192     public function testFormatter()
193     {
194         $this->logger = new Logger(LogLevel::DEBUG, $this->tmpFile, function ($level, $message, $context) {
195             return json_encode(array('level' => $level, 'message' => $message, 'context' => $context)).\PHP_EOL;
196         });
197
198         $this->logger->error('An error', array('foo' => 'bar'));
199         $this->logger->warning('A warning', array('baz' => 'bar'));
200         $this->assertSame(array(
201             '{"level":"error","message":"An error","context":{"foo":"bar"}}',
202             '{"level":"warning","message":"A warning","context":{"baz":"bar"}}',
203         ), $this->getLogs());
204     }
205 }
206
207 class DummyTest
208 {
209     public function __toString()
210     {
211     }
212 }