You are here

public function FileLogRotationTest::testRotation in File Log 8

Same name and namespace in other branches
  1. 2.0.x tests/src/Unit/FileLogRotationTest.php \Drupal\Tests\filelog\Unit\FileLogRotationTest::testRotation()

Test the log rotator with a variety of configurations and states.

@dataProvider provideRotationConfig

Parameters

int $timestamp: The time of the previous log rotation.

array $config: The filelog settings.

array $files: The files that are expected to exist after the test.

File

tests/src/Unit/FileLogRotationTest.php, line 101

Class

FileLogRotationTest
Tests the log rotation of the file logger.

Namespace

Drupal\Tests\filelog\Unit

Code

public function testRotation($timestamp, array $config, array $files) : void {
  $root = 'vfs://filelog';
  $logFile = $root . '/' . LogFileManager::FILENAME;
  $data = "This is the log file content.\n";
  $configs = [
    'filelog.settings' => [
      'rotation' => $config,
      'location' => $root,
    ],
  ];

  /** @var \Drupal\Core\Config\ConfigFactoryInterface $configFactory */
  $configFactory = $this
    ->getConfigFactoryStub($configs);

  /** @var \Drupal\Core\State\StateInterface|\PHPUnit_Framework_MockObject_MockObject $state */
  $state = $this
    ->createMock(StateInterface::class);

  // InvocationMocker::with(...$arguments) incorrectly documented.
  // Suppress until phpunit/phpunit:8.2.1.

  /* @noinspection PhpParamsInspection */
  $state
    ->method('get')
    ->with('filelog.rotation')
    ->willReturn($timestamp);
  file_put_contents($logFile, $data);
  $rotator = new LogRotator($configFactory, $state, $this->token, $this->time, $this->fileManager, $this->fileSystem);
  try {
    $rotator
      ->run();
  } catch (FileLogException $exception) {
    $this
      ->fail("Log rotation caused an exception: {$exception}");
  }

  // Check that all the expected files have the correct content.
  foreach ($files as $name) {
    $path = "{$root}/{$name}";
    $compressed = preg_match('/\\.gz$/', $name) === 1;
    $expected = $compressed ? gzencode($data) : $data;
    $content = file_get_contents($path);
    $this
      ->assertEquals($expected, $content);

    // Delete the file after checking.
    unlink($path);
  }

  // Check that no other files exist.
  foreach (scandir('vfs://filelog', 0) as $name) {
    if ($name === '.htaccess') {
      continue;
    }
    $path = "{$root}/{$name}";

    // The log file itself may persist, but must be empty.
    if ($name === LogFileManager::FILENAME) {
      $this
        ->assertStringEqualsFile($path, '');
    }
    else {
      $this
        ->assertDirectoryExists($path);
    }
  }
}