GarbageCollectionTest.php 2.0 KB

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