summaryrefslogtreecommitdiffstats
path: root/core/modules/system/lib/Drupal/system/Tests/Cache/GenericCacheBackendUnitTestBase.php
blob: 95805d7205eefe3dc3822f25eb8150f9ebb59139 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
<?php

/**
 * @file
 * Definition of Drupal\system\Tests\Cache\GenericCacheBackendUnitTestBase.
 */

namespace Drupal\system\Tests\Cache;

use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\simpletest\UnitTestBase;

use stdClass;

/**
 * Tests any cache backend.
 *
 * Full generic unit test suite for any cache backend. In order to use it for a
 * cache backend implementation, extend this class and override the
 * createBackendInstace() method to return an object.
 *
 * @see DatabaseBackendUnitTestCase
 *   For a full working implementation.
 */
abstract class GenericCacheBackendUnitTestBase extends UnitTestBase {

  /**
   * Array of objects implementing Drupal\Core\Cache\CacheBackendInterface.
   *
   * @var array
   */
  protected $cachebackends;

  /**
   * Cache bin to use for testing.
   *
   * @var string
   */
  protected $testBin;

  /**
   * Random value to use in tests.
   *
   * @var string
   */
  protected $defaultValue;

  /**
   * Gets the testing bin.
   *
   * Override this method if you want to work on a different bin than the
   * default one.
   *
   * @return string
   *   Bin name.
   */
  protected function getTestBin() {
    if (!isset($this->testBin)) {
      $this->testBin = 'page';
    }
    return $this->testBin;
  }

  /**
   * Creates a cache backend to test.
   *
   * Override this method to test a CacheBackend.
   *
   * @param string $bin
   *   Bin name to use for this backend instance.
   *
   * @return Drupal\Core\Cache\CacheBackendInterface
   *   Cache backend to test.
   */
  protected abstract function createCacheBackend($bin);

  /**
   * Allows specific implementation to change the environment before a test run.
   */
  public function setUpCacheBackend() {
  }

  /**
   * Allows alteration of environment after a test run but before tear down.
   *
   * Used before the real tear down because the tear down will change things
   * such as the database prefix.
   */
  public function tearDownCacheBackend() {
  }

  /**
   * Gets a backend to test; this will get a shared instance set in the object.
   *
   * @return Drupal\Core\Cache\CacheBackendInterface
   *   Cache backend to test.
   */
  final function getCacheBackend($bin = null) {
    if (!isset($bin)) {
      $bin = $this->getTestBin();
    }
    if (!isset($this->cachebackends[$bin])) {
      $this->cachebackends[$bin] = $this->createCacheBackend($bin);
      // Ensure the backend is empty.
      $this->cachebackends[$bin]->flush();
    }
    return $this->cachebackends[$bin];
  }

  public function setUp() {
    $this->cachebackends = array();
    $this->defaultValue = $this->randomName(10);

    parent::setUp();

    $this->setUpCacheBackend();
  }

  public function tearDown() {
    // Destruct the registered backend, each test will get a fresh instance,
    // properly flushing it here ensure that on persistant data backends they
    // will come up empty the next test.
    foreach ($this->cachebackends as $bin => $cachebackend) {
      $this->cachebackends[$bin]->flush();
    }
    unset($this->cachebackends);

    $this->tearDownCacheBackend();

    parent::tearDown();
  }

  /**
   * Tests the get and set methods of Drupal\Core\Cache\CacheBackendInterface.
   */
  public function testSetGet() {
    $backend = $this->getCacheBackend();

    $data = 7;
    $this->assertIdentical(FALSE, $backend->get('test1'), "Backend does not contain data for cache id test1.");
    $backend->set('test1', $data);
    $cached = $backend->get('test1');
    $this->assert(is_object($cached), "Backend returned an object for cache id test1.");
    $this->assertIdentical($data, $cached->data);

    $data = array('value' => 3);
    $this->assertIdentical(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2.");
    $backend->set('test2', $data);
    $cached = $backend->get('test2');
    $this->assert(is_object($cached), "Backend returned an object for cache id test2.");
    $this->assertIdentical($data, $cached->data);
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::delete().
   */
  public function testDelete() {
    $backend = $this->getCacheBackend();

    $this->assertIdentical(FALSE, $backend->get('test1'), "Backend does not contain data for cache id test1.");
    $backend->set('test1', 7);
    $this->assert(is_object($backend->get('test1')), "Backend returned an object for cache id test1.");

    $this->assertIdentical(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2.");
    $backend->set('test2', 3);
    $this->assert(is_object($backend->get('test2')), "Backend returned an object for cache id %cid.");

    $backend->delete('test1');
    $this->assertIdentical(FALSE, $backend->get('test1'), "Backend does not contain data for cache id test1 after deletion.");

    $cached = $backend->get('test2');
    $this->assert(is_object($backend->get('test2')), "Backend still has an object for cache id test2.");

    $backend->delete('test2');
    $this->assertIdentical(FALSE, $backend->get('test2'), "Backend does not contain data for cache id test2 after deletion.");
  }

  /**
   * Tests data type preservation.
   */
  public function testValueTypeIsKept() {
    $backend = $this->getCacheBackend();

    $variables = array(
      'test1' => 1,
      'test2' => '0',
      'test3' => '',
      'test4' => 12.64,
      'test5' => false,
      'test6' => array(1,2,3),
    );

    // Create cache entries.
    foreach ($variables as $cid => $data) {
      $backend->set($cid, $data);
    }

    // Retrieve and test cache objects.
    foreach ($variables as $cid => $value) {
      $object = $backend->get($cid);
      $this->assert(is_object($object), sprintf("Backend returned an object for cache id %s.", $cid));
      $this->assertIdentical($value, $object->data, sprintf("Data of cached id %s kept is identical in type and value", $cid));
    }
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::getMultiple().
   */
  public function testGetMultiple() {
    $backend = $this->getCacheBackend();

    // Set numerous testing keys.
    $backend->set('test1', 1);
    $backend->set('test2', 3);
    $backend->set('test3', 5);
    $backend->set('test4', 7);
    $backend->set('test5', 11);
    $backend->set('test6', 13);
    $backend->set('test7', 17);

    // Mismatch order for harder testing.
    $reference = array(
      'test3',
      'test7',
      'test21', // Cid does not exist.
      'test6',
      'test19', // Cid does not exist until added before second getMulitple().
      'test2',
    );

    $cids = $reference;
    $ret = $backend->getMultiple($cids);
    // Test return - ensure it contains existing cache ids.
    $this->assert(isset($ret['test2']), "Existing cache id test2 is set.");
    $this->assert(isset($ret['test3']), "Existing cache id test3 is set.");
    $this->assert(isset($ret['test6']), "Existing cache id test6 is set.");
    $this->assert(isset($ret['test7']), "Existing cache id test7 is set.");
    // Test return - ensure it does not contain nonexistent cache ids.
    $this->assertFalse(isset($ret['test19']), "Nonexistent cache id test19 is not set.");
    $this->assertFalse(isset($ret['test21']), "Nonexistent cache id test21 is not set.");
    // Test values.
    $this->assertIdentical($ret['test2']->data, 3, "Existing cache id test2 has the correct value.");
    $this->assertIdentical($ret['test3']->data, 5, "Existing cache id test3 has the correct value.");
    $this->assertIdentical($ret['test6']->data, 13, "Existing cache id test6 has the correct value.");
    $this->assertIdentical($ret['test7']->data, 17, "Existing cache id test7 has the correct value.");
    // Test $cids array - ensure it contains cache id's that do not exist.
    $this->assert(in_array('test19', $cids), "Nonexistent cache id test19 is in cids array.");
    $this->assert(in_array('test21', $cids), "Nonexistent cache id test21 is in cids array.");
    // Test $cids array - ensure it does not contain cache id's that exist.
    $this->assertFalse(in_array('test2', $cids), "Existing cache id test2 is not in cids array.");
    $this->assertFalse(in_array('test3', $cids), "Existing cache id test3 is not in cids array.");
    $this->assertFalse(in_array('test6', $cids), "Existing cache id test6 is not in cids array.");
    $this->assertFalse(in_array('test7', $cids), "Existing cache id test7 is not in cids array.");

    // Test a second time after deleting and setting new keys which ensures that
    // if the backend uses statics it does not cause unexpected results.
    $backend->delete('test3');
    $backend->delete('test6');
    $backend->set('test19', 57);

    $cids = $reference;
    $ret = $backend->getMultiple($cids);
    // Test return - ensure it contains existing cache ids.
    $this->assert(isset($ret['test2']), "Existing cache id test2 is set");
    $this->assert(isset($ret['test7']), "Existing cache id test7 is set");
    $this->assert(isset($ret['test19']), "Added cache id test19 is set");
    // Test return - ensure it does not contain nonexistent cache ids.
    $this->assertFalse(isset($ret['test3']), "Deleted cache id test3 is not set");
    $this->assertFalse(isset($ret['test6']), "Deleted cache id test6 is not set");
    $this->assertFalse(isset($ret['test21']), "Nonexistent cache id test21 is not set");
    // Test values.
    $this->assertIdentical($ret['test2']->data, 3, "Existing cache id test2 has the correct value.");
    $this->assertIdentical($ret['test7']->data, 17, "Existing cache id test7 has the correct value.");
    $this->assertIdentical($ret['test19']->data, 57, "Added cache id test19 has the correct value.");
    // Test $cids array - ensure it contains cache id's that do not exist.
    $this->assert(in_array('test3', $cids), "Deleted cache id test3 is in cids array.");
    $this->assert(in_array('test6', $cids), "Deleted cache id test6 is in cids array.");
    $this->assert(in_array('test21', $cids), "Nonexistent cache id test21 is in cids array.");
    // Test $cids array - ensure it does not contain cache id's that exist.
    $this->assertFalse(in_array('test2', $cids), "Existing cache id test2 is not in cids array.");
    $this->assertFalse(in_array('test7', $cids), "Existing cache id test7 is not in cids array.");
    $this->assertFalse(in_array('test19', $cids), "Added cache id test19 is not in cids array.");
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::isEmpty().
   */
  public function testIsEmpty() {
    $backend = $this->getCacheBackend();

    $this->assertTrue($backend->isEmpty(), "Backend is empty.");

    $backend->set('pony', "Shetland");
    $this->assertFalse($backend->isEmpty(), "Backend is not empty.");

    $backend->delete('pony');
    $this->assertTrue($backend->isEmpty(), "Backend is empty.");
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::deleteMultiple().
   */
  public function testDeleteMultiple() {
    $backend = $this->getCacheBackend();

    // Set numerous testing keys.
    $backend->set('test1', 1);
    $backend->set('test2', 3);
    $backend->set('test3', 5);
    $backend->set('test4', 7);
    $backend->set('test5', 11);
    $backend->set('test6', 13);
    $backend->set('test7', 17);

    $backend->deleteMultiple(array(
      'test1',
      'test3',
      'test5',
      'test7',
      'test19', // Nonexistent key should not cause an error.
      'test21', // Nonexistent key should not cause an error.
    ));

    // Test if expected keys have been deleted.
    $this->assertIdentical(FALSE, $backend->get('test1'), "Cache id test1 deleted.");
    $this->assertIdentical(FALSE, $backend->get('test3'), "Cache id test3 deleted.");
    $this->assertIdentical(FALSE, $backend->get('test5'), "Cache id test5 deleted.");
    $this->assertIdentical(FALSE, $backend->get('test7'), "Cache id test7 deleted.");

    // Test if expected keys exist.
    $this->assertNotIdentical(FALSE, $backend->get('test2'), "Cache id test2 exists.");
    $this->assertNotIdentical(FALSE, $backend->get('test4'), "Cache id test4 exists.");
    $this->assertNotIdentical(FALSE, $backend->get('test6'), "Cache id test6 exists.");

    // Test if that expected keys do not exist.
    $this->assertIdentical(FALSE, $backend->get('test19'), "Cache id test19 does not exist.");
    $this->assertIdentical(FALSE, $backend->get('test21'), "Cache id test21 does not exist.");
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::flush().
   */
  public function testFlush() {
    $backend = $this->getCacheBackend();

    // Set both expiring and permanent keys.
    $backend->set('test1', 1, CacheBackendInterface::CACHE_PERMANENT);
    $backend->set('test2', 3, time() + 1000);

    $backend->flush();

    $this->assertTrue($backend->isEmpty(), "Backend is empty after flush.");

    $this->assertIdentical(FALSE, $backend->get('test1'), "First key has been flushed.");
    $this->assertIdentical(FALSE, $backend->get('test2'), "Second key has been flushed.");
  }

  /**
   * Checks whether or not a cache entry exists.
   *
   * @param $cid
   *   The cache id.
   * @param $bin
   *   The cache bin to use. If not provided the default test bin wil be used.
   *
   * @return
   *   TRUE on pass, FALSE on fail.
   */
  protected function checkCacheExists($cid, $bin = null) {
    $cached = $this->getCacheBackend($bin)->get($cid);
    return isset($cached->data);
  }

  /**
   * Tests Drupal\Core\Cache\CacheBackendInterface::invalidateTags().
   */
  function testClearTags() {
    $backend = $this->getCacheBackend();

    // Create two cache entries with the same tag and tag value.
    $backend->set('test_cid_clear1', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => 2));
    $backend->set('test_cid_clear2', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => 2));
    $this->assertTrue($this->checkCacheExists('test_cid_clear1')
                      && $this->checkCacheExists('test_cid_clear2'),
                      'Two cache items were created.');
    // Invalidate test_tag of value 1. This should invalidate both entries.
    $backend->invalidateTags(array('test_tag' => 2));
    $this->assertFalse($this->checkCacheExists('test_cid_clear1')
                      || $this->checkCacheExists('test_cid_clear2'),
                      'Two caches removed after clearing a cache tag.');

    // Create two cache entries with the same tag and an array tag value.
    $backend->set('test_cid_clear1', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => array(1)));
    $backend->set('test_cid_clear2', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => array(1)));
    $this->assertTrue($this->checkCacheExists('test_cid_clear1')
                      && $this->checkCacheExists('test_cid_clear2'),
                      'Two cache items were created.');
    // Invalidate test_tag of value 1. This should invalidate both entries.
    $backend->invalidateTags(array('test_tag' => array(1)));
    $this->assertFalse($this->checkCacheExists('test_cid_clear1')
                      || $this->checkCacheExists('test_cid_clear2'),
                      'Two caches removed after clearing a cache tag.');

    // Create three cache entries with a mix of tags and tag values.
    $backend->set('test_cid_clear1', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => array(1)));
    $backend->set('test_cid_clear2', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag' => array(2)));
    $backend->set('test_cid_clear3', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, array('test_tag_foo' => array(3)));
    $this->assertTrue($this->checkCacheExists('test_cid_clear1')
                      && $this->checkCacheExists('test_cid_clear2')
                      && $this->checkCacheExists('test_cid_clear3'),
                      'Two cached items were created.');
    $backend->invalidateTags(array('test_tag_foo' => array(3)));
    $this->assertTrue($this->checkCacheExists('test_cid_clear1')
                      && $this->checkCacheExists('test_cid_clear2'),
                      'Cached items not matching the tag were not cleared.');

    $this->assertFalse($this->checkCacheExists('test_cid_clear3'),
                      'Cached item matching the tag was removed.');

    // Create cache entry in multiple bins. Two cache entries (test_cid_clear1
    // and test_cid_clear2) still exist from previous tests.
    $tags = array('test_tag' => array(1, 2, 3));
    $bins = array('path', 'bootstrap', 'page');
    foreach ($bins as $bin) {
      $this->getCacheBackend($bin)->set('test', $this->defaultValue, CacheBackendInterface::CACHE_PERMANENT, $tags);
      $this->assertTrue($this->checkCacheExists('test', $bin), 'Cache item was set in bin.');
    }

    // Invalidate tag in mulitple bins.
    foreach ($bins as $bin) {
      $this->getCacheBackend($bin)->invalidateTags(array('test_tag' => array(2)));
    }

    // Test that cache entry has been invalidated in multple bins.
    foreach ($bins as $bin) {
      $this->assertFalse($this->checkCacheExists('test', $bin), 'Tag expire affected item in bin.');
    }
    // Test that the cache entry with a matching tag has been invalidated.
    $this->assertFalse($this->checkCacheExists('test_cid_clear2', $bin), 'Cached items matching tag were cleared.');
    // Test that the cache entry with without a matching tag still exists.
    $this->assertTrue($this->checkCacheExists('test_cid_clear1', $bin), 'Cached items not matching tag were not cleared.');
  }
}