You are here

class JsonLogTest in JSONlog 8

Same name and namespace in other branches
  1. 8.2 tests/src/Unit/JsonLogTest.php \Drupal\Tests\jsonlog\Unit\JsonLogTest
  2. 3.x tests/src/Unit/JsonLogTest.php \Drupal\Tests\jsonlog\Unit\JsonLogTest

Unit tests for JsonLog class

@group JsonLog

Class JsonLogTest @package Drupal\Tests\jsonlog\Unit

Hierarchy

Expanded class hierarchy of JsonLogTest

File

tests/src/Unit/JsonLogTest.php, line 22

Namespace

Drupal\Tests\jsonlog\Unit
View source
class JsonLogTest extends UnitTestCase {
  const DEFAULT_THRESHOLD = 4;
  const DEFAULT_LOG_DIR = '/var/log';
  const DEFAULT_TIME_FORMAT = 'Ymd';
  const DEFAULT_SITE_ID = 'jsonlog_test';

  /**
   * @var mixed - mock of \Symfony\Component\HttpFoundation\RequestStack
   */
  private $requestStackMock;

  /**
   * @var \Drupal\jsonlog\Logger\JsonLog
   */
  private $jsonLogger;
  protected function setUp() {
    parent::setUp();
    $config_stub['jsonlog.settings'] = [
      'jsonlog_severity_threshold' => self::DEFAULT_THRESHOLD,
      'jsonlog_truncate' => 64,
      'jsonlog_siteid' => self::DEFAULT_SITE_ID,
      'jsonlog_canonical' => '',
      'jsonlog_file_time' => self::DEFAULT_TIME_FORMAT,
      'jsonlog_dir' => self::DEFAULT_LOG_DIR,
      'jsonlog_tags' => 'test',
    ];

    /** @var ConfigFactoryInterface $configFactoryMock */
    $configFactoryMock = $this
      ->getConfigFactoryStub($config_stub);

    /** @var LogMessageParserInterface $messageParserMock */
    $messageParserMock = $this
      ->getEmptyMessageParserMock();

    /** @var ModuleHandlerInterface $moduleHandlerMock */
    $moduleHandlerMock = $this
      ->createMock('Drupal\\Core\\Extension\\ModuleHandlerInterface');

    /** @var RequestStack requestStackMock */
    $this->requestStackMock = $this
      ->createMock('Symfony\\Component\\HttpFoundation\\RequestStack');
    $this->jsonLogger = new JsonLog($configFactoryMock, $messageParserMock, $moduleHandlerMock, $this->requestStackMock);
  }

  /**
   * test to see if a log file is well prepared
   */
  public function testCanPrepareLogFile() {
    $request_mock = $this
      ->createMock('Symfony\\Component\\HttpFoundation\\Request');
    $request_mock
      ->expects($this
      ->exactly(1))
      ->method('getRealMethod')
      ->willReturn('POST');

    /** @var Request $request_mock */
    $this
      ->setupContainerCurrentRequest($request_mock);
    $test_context = [
      'user' => NULL,
      'ip' => '127.0.0.9',
      'request_uri' => 'admin/help',
      'channel' => '500',
      'link' => '',
      'referer' => '',
    ];
    $level = self::DEFAULT_THRESHOLD - 1;
    $log_entry = $this->jsonLogger
      ->prepareLog($level, 'test', $test_context);
    $this
      ->assertFalse($log_entry === FALSE, 'Log entry constructed');
    $this
      ->assertEquals(JsonLogData::class, get_class($log_entry));
    $this
      ->assertEquals('500', $log_entry
      ->getData()['subtype'], 'Correct subtype logged');
    $this
      ->assertEquals('127.0.0.9', $log_entry
      ->getData()['client_ip'], 'Correct client_ip logged');
    $this
      ->assertEquals('admin/help', $log_entry
      ->getData()['request_uri'], 'Correct request_uri logged');
    $this
      ->assertEquals('POST', $log_entry
      ->getData()['method'], 'Correct method logged');
  }

  /**
   * test to see if a log file is not prepared when the log-level is too high
   */
  public function testCannotPrepareLogFileIfThresholdExceeded() {
    $level = self::DEFAULT_THRESHOLD + 1;
    $log_entry = $this->jsonLogger
      ->prepareLog($level, 'test', []);
    $this
      ->assertTrue($log_entry === FALSE, 'Log entry not built');
  }

  /**
   * test correct filename can be constructed
   */
  public function testGetCorrectFilename() {
    $time = date(self::DEFAULT_TIME_FORMAT);
    $filename = $this->jsonLogger
      ->getFileName(self::DEFAULT_TIME_FORMAT);
    $this
      ->assertEquals(self::DEFAULT_LOG_DIR . '/' . self::DEFAULT_SITE_ID . '.' . $time . '.json.log', $filename, 'Correct filename constructed.');
  }

  /**
   * @return \PHPUnit\Framework\MockObject\MockObject
   */
  private function getEmptyMessageParserMock() {
    $messageParserMock = $this
      ->createMock('Drupal\\Core\\Logger\\LogMessageParserInterface');
    $messageParserMock
      ->expects($this
      ->atMost(1))
      ->method('parseMessagePlaceholders')
      ->withAnyParameters()
      ->willReturn([]);
    return $messageParserMock;
  }

  /**
   * @param \Symfony\Component\HttpFoundation\Request $request
   */
  private function setupContainerCurrentRequest(Request $request) {
    $this->requestStackMock
      ->expects($this
      ->any())
      ->method('getCurrentRequest')
      ->willReturn($request);
    $containerMock = $this
      ->createMock('Symfony\\Component\\DependencyInjection\\ContainerInterface');
    $containerMock
      ->expects($this
      ->any())
      ->method('get')
      ->with('request_stack')
      ->willReturn($this->requestStackMock);

    /** @var \Symfony\Component\DependencyInjection\ContainerInterface $containerMock */
    \Drupal::setContainer($containerMock);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
JsonLogTest::$jsonLogger private property
JsonLogTest::$requestStackMock private property
JsonLogTest::DEFAULT_LOG_DIR constant
JsonLogTest::DEFAULT_SITE_ID constant
JsonLogTest::DEFAULT_THRESHOLD constant
JsonLogTest::DEFAULT_TIME_FORMAT constant
JsonLogTest::getEmptyMessageParserMock private function
JsonLogTest::setUp protected function Overrides UnitTestCase::setUp
JsonLogTest::setupContainerCurrentRequest private function
JsonLogTest::testCannotPrepareLogFileIfThresholdExceeded public function test to see if a log file is not prepared when the log-level is too high
JsonLogTest::testCanPrepareLogFile public function test to see if a log file is well prepared
JsonLogTest::testGetCorrectFilename public function test correct filename can be constructed
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.