3 namespace Drupal\KernelTests\Core\KeyValueStore;
5 use Drupal\Component\Serialization\PhpSerialize;
6 use Drupal\Core\Database\Database;
7 use Drupal\Core\KeyValueStore\DatabaseStorageExpirable;
8 use Drupal\KernelTests\KernelTestBase;
11 * Tests garbage collection for the expirable key-value database storage.
13 * @group KeyValueStore
15 class GarbageCollectionTest extends KernelTestBase {
22 public static $modules = ['system'];
24 protected function setUp() {
27 // These additional tables are necessary due to the call to system_cron().
28 $this->installSchema('system', ['key_value_expire']);
32 * Tests garbage collection.
34 public function testGarbageCollection() {
35 $collection = $this->randomMachineName();
36 $store = new DatabaseStorageExpirable($collection, new PhpSerialize(), Database::getConnection());
38 // Insert some items and confirm that they're set.
39 for ($i = 0; $i <= 3; $i++) {
40 $store->setWithExpire('key_' . $i, $this->randomObject(), rand(500, 100000));
42 $this->assertIdentical(sizeof($store->getAll()), 4, 'Four items were written to the storage.');
44 // Manually expire the data.
45 for ($i = 0; $i <= 3; $i++) {
46 db_merge('key_value_expire')
48 'name' => 'key_' . $i,
49 'collection' => $collection,
52 'expire' => REQUEST_TIME - 1,
58 // Perform a new set operation and then trigger garbage collection.
59 $store->setWithExpire('autumn', 'winter', rand(500, 1000000));
62 // Query the database and confirm that the stale records were deleted.
64 'SELECT name, value FROM {key_value_expire} WHERE collection = :collection',
66 ':collection' => $collection,
68 $this->assertIdentical(count($result), 1, 'Only one item remains after garbage collection');