You are here

public function FileLogRotationTest::testRotation in File Log 2.0.x

Same name and namespace in other branches
  1. 8 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(int $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);
  $state = $this
    ->createMock(StateInterface::class);
  $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) {
    static::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);
    static::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) {
      static::assertStringEqualsFile($path, '');
    }
    else {
      static::assertDirectoryExists($path);
    }
  }
}