GarbageCollectionTest.php in Drupal 9
File
core/tests/Drupal/KernelTests/Core/KeyValueStore/GarbageCollectionTest.php
View source
<?php
namespace Drupal\KernelTests\Core\KeyValueStore;
use Drupal\Component\Serialization\PhpSerialize;
use Drupal\Core\Database\Database;
use Drupal\Core\KeyValueStore\DatabaseStorageExpirable;
use Drupal\KernelTests\KernelTestBase;
class GarbageCollectionTest extends KernelTestBase {
protected static $modules = [
'system',
];
public function testGarbageCollection() {
$collection = $this
->randomMachineName();
$connection = Database::getConnection();
$store = new DatabaseStorageExpirable($collection, new PhpSerialize(), $connection);
for ($i = 0; $i <= 3; $i++) {
$store
->setWithExpire('key_' . $i, $this
->randomObject(), rand(500, 100000));
}
$this
->assertCount(4, $store
->getAll(), 'Four items were written to the storage.');
for ($i = 0; $i <= 3; $i++) {
$connection
->merge('key_value_expire')
->keys([
'name' => 'key_' . $i,
'collection' => $collection,
])
->fields([
'expire' => REQUEST_TIME - 1,
])
->execute();
}
$store
->setWithExpire('autumn', 'winter', rand(500, 1000000));
system_cron();
$result = $connection
->select('key_value_expire', 'kvp')
->fields('kvp', [
'name',
])
->condition('collection', $collection)
->execute()
->fetchAll();
$this
->assertCount(1, $result, 'Only one item remains after garbage collection');
}
}