You are here

public function VarnishCacheInvalidationCase::testVarnishCacheExpiration in Varnish 7

Test that makes sure that the varnish cache get's invalidated at the appropriate times.

File

./varnish.test, line 106
Tests the basic functionality of Varnish.

Class

VarnishCacheInvalidationCase
Tests Cache Expiration.

Code

public function testVarnishCacheExpiration() {
  $not_cached_pattern = '/[0-9]{8,9}$/';
  $cached_pattern = '/[0-9]{8,9} [0-9]{8,9}$/';

  // Tell the Varnish module that it is OK to cache.
  variable_set('varnish_cache_clear', 1);

  // Fill the cache.
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));
  $this
    ->assertRegexpPattern($this
    ->drupalGetHeader('X-Varnish'), $not_cached_pattern, t('Varnish header is indicating that it did not have this page in the cache.'));

  // Request the page again. It should be in the cache.
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));
  $this
    ->assertRegexpPattern($this
    ->drupalGetHeader('X-Varnish'), $cached_pattern, t('Varnish header is indicating that it had the page in the cache.'));
  $headers = $this
    ->drupalGetHeaders(TRUE);

  // Clear the cache_page bin. This should trigger an invalidation of the page in Varnish.
  cache_clear_all(NULL, 'cache_page');
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));
  $this
    ->assertRegexpPattern($this
    ->drupalGetHeader('X-Varnish'), $not_cached_pattern, t('Varnish header is indicating that it did not have the page in the cache after a cache purge.'));

  // Tell the Varnish module to not invalidate any pages in Varnish.
  variable_set('varnish_cache_clear', 0);
  cache_clear_all(NULL, 'cache_page');
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));
  $this
    ->assertRegexpPattern($this
    ->drupalGetHeader('X-Varnish'), $cached_pattern, t('Varnish header is indicating that it had the page in the cache, even after a cache clear'));

  // Set a minimum cache lifetime for the cache to avoid having varnish purging the cache.
  variable_set('cache_lifetime', 3600);

  // Cache the page.
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));

  // Try to invalidate the cache, it should fail.
  cache_clear_all(NULL, 'cache_page');
  $this
    ->drupalGet('system-test/set-header', array(
    'query' => array(
      'name' => 'Foo',
      'value' => 'bar',
    ),
  ));
  $this
    ->assertRegexpPattern($this
    ->drupalGetHeader('X-Varnish'), $cached_pattern, t('Varnish cache did not invalidate itself when minimum cache lifetime was set.'));
}