ea76f0a4f5ecf12d43bb1d3b69d4fb7fb0ff4200
[yaffs-website] / web / core / tests / Drupal / KernelTests / Core / KeyValueStore / GarbageCollectionTest.php
1 <?php
2
3 namespace Drupal\KernelTests\Core\KeyValueStore;
4
5 use Drupal\Component\Serialization\PhpSerialize;
6 use Drupal\Core\Database\Database;
7 use Drupal\Core\KeyValueStore\DatabaseStorageExpirable;
8 use Drupal\KernelTests\KernelTestBase;
9
10 /**
11  * Tests garbage collection for the expirable key-value database storage.
12  *
13  * @group KeyValueStore
14  */
15 class GarbageCollectionTest extends KernelTestBase {
16
17   /**
18    * Modules to enable.
19    *
20    * @var array
21    */
22   public static $modules = ['system'];
23
24   protected function setUp() {
25     parent::setUp();
26
27     // These additional tables are necessary due to the call to system_cron().
28     $this->installSchema('system', ['key_value_expire']);
29   }
30
31   /**
32    * Tests garbage collection.
33    */
34   public function testGarbageCollection() {
35     $collection = $this->randomMachineName();
36     $store = new DatabaseStorageExpirable($collection, new PhpSerialize(), Database::getConnection());
37
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));
41     }
42     $this->assertIdentical(count($store->getAll()), 4, 'Four items were written to the storage.');
43
44     // Manually expire the data.
45     for ($i = 0; $i <= 3; $i++) {
46       db_merge('key_value_expire')
47         ->keys([
48             'name' => 'key_' . $i,
49             'collection' => $collection,
50           ])
51         ->fields([
52             'expire' => REQUEST_TIME - 1,
53           ])
54         ->execute();
55     }
56
57     // Perform a new set operation and then trigger garbage collection.
58     $store->setWithExpire('autumn', 'winter', rand(500, 1000000));
59     system_cron();
60
61     // Query the database and confirm that the stale records were deleted.
62     $result = db_query(
63       'SELECT name, value FROM {key_value_expire} WHERE collection = :collection',
64       [
65         ':collection' => $collection,
66       ])->fetchAll();
67     $this->assertIdentical(count($result), 1, 'Only one item remains after garbage collection');
68
69   }
70
71 }