You are here

public function DatabaseBackendTest::testGarbageCollection in Drupal 9

Same name and namespace in other branches
  1. 8 core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php \Drupal\KernelTests\Core\Cache\DatabaseBackendTest::testGarbageCollection()

Tests the row count limiting of cache bin database tables.

File

core/tests/Drupal/KernelTests/Core/Cache/DatabaseBackendTest.php, line 61

Class

DatabaseBackendTest
Unit test of the database backend using the generic cache unit test base.

Namespace

Drupal\KernelTests\Core\Cache

Code

public function testGarbageCollection() {
  $backend = $this
    ->getCacheBackend();
  $max_rows = static::$maxRows;
  $this
    ->assertSame(0, (int) $this
    ->getNumRows());

  // Fill to just the limit.
  for ($i = 0; $i < $max_rows; $i++) {

    // Ensure that each cache item created happens in a different millisecond,
    // by waiting 1 ms (1000 microseconds). The garbage collection might
    // otherwise keep less than exactly 100 records (which is acceptable for
    // real-world cases, but not for this test).
    usleep(1000);
    $backend
      ->set("test{$i}", $i);
  }
  $this
    ->assertSame($max_rows, $this
    ->getNumRows());

  // Garbage collection has no effect.
  $backend
    ->garbageCollection();
  $this
    ->assertSame($max_rows, $this
    ->getNumRows());

  // Go one row beyond the limit.
  $backend
    ->set('test' . ($max_rows + 1), $max_rows + 1);
  $this
    ->assertSame($max_rows + 1, $this
    ->getNumRows());

  // Garbage collection removes one row: the oldest.
  $backend
    ->garbageCollection();
  $this
    ->assertSame($max_rows, $this
    ->getNumRows());
  $this
    ->assertFalse($backend
    ->get('test0'));
}