You are here

public function DatabaseStorageExpirableTest::testExpiration in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/KernelTests/Core/KeyValueStore/DatabaseStorageExpirableTest.php \Drupal\KernelTests\Core\KeyValueStore\DatabaseStorageExpirableTest::testExpiration()
  2. 10 core/tests/Drupal/KernelTests/Core/KeyValueStore/DatabaseStorageExpirableTest.php \Drupal\KernelTests\Core\KeyValueStore\DatabaseStorageExpirableTest::testExpiration()

Tests data expiration.

File

core/tests/Drupal/KernelTests/Core/KeyValueStore/DatabaseStorageExpirableTest.php, line 122

Class

DatabaseStorageExpirableTest
Tests the key-value database storage.

Namespace

Drupal\KernelTests\Core\KeyValueStore

Code

public function testExpiration() {
  $stores = $this
    ->createStorage();
  $day = 604800;

  // Set an item to expire in the past and another without an expiration.
  $stores[0]
    ->setWithExpire('yesterday', 'all my troubles seemed so far away', -1 * $day);
  $stores[0]
    ->set('troubles', 'here to stay');

  // Only the non-expired item should be returned.
  $this
    ->assertFalse($stores[0]
    ->has('yesterday'));
  $this
    ->assertNull($stores[0]
    ->get('yesterday'));
  $this
    ->assertTrue($stores[0]
    ->has('troubles'));
  $this
    ->assertIdentical($stores[0]
    ->get('troubles'), 'here to stay');
  $this
    ->assertCount(1, $stores[0]
    ->getMultiple([
    'yesterday',
    'troubles',
  ]));

  // Store items set to expire in the past in various ways.
  $stores[0]
    ->setWithExpire($this
    ->randomMachineName(), $this->objects[0], -7 * $day);
  $stores[0]
    ->setWithExpireIfNotExists($this
    ->randomMachineName(), $this->objects[1], -5 * $day);
  $stores[0]
    ->setMultipleWithExpire([
    $this
      ->randomMachineName() => $this->objects[2],
    $this
      ->randomMachineName() => $this->objects[3],
  ], -3 * $day);
  $stores[0]
    ->setWithExpireIfNotExists('yesterday', "you'd forgiven me", -1 * $day);
  $stores[0]
    ->setWithExpire('still', "'til we say we're sorry", 2 * $day);

  // Ensure only non-expired items are retrieved.
  $all = $stores[0]
    ->getAll();
  $this
    ->assertCount(2, $all);
  foreach ([
    'troubles',
    'still',
  ] as $key) {
    $this
      ->assertTrue(!empty($all[$key]));
  }

  // Test DatabaseStorageExpirable::setWithExpireIfNotExists() will overwrite
  // expired items.
  $this
    ->assertNull($stores[0]
    ->get('yesterday'));
  $stores[0]
    ->setWithExpireIfNotExists('yesterday', 'Oh, yesterday came suddenly', $day);
  $this
    ->assertSame('Oh, yesterday came suddenly', $stores[0]
    ->get('yesterday'));
}