PageRenderTime 50ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/src/Symfony/Component/HttpKernel/Tests/Log/LoggerTest.php

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