CacheContextsTest.php 2.41 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
<?php

/**
 * @file
 * Contains \Drupal\Tests\Core\Cache\CacheContextsTest.
 */

namespace Drupal\Tests\Core\Cache;

use Drupal\Core\Cache\CacheContexts;
use Drupal\Core\Cache\CacheContextInterface;
12
use Drupal\Tests\UnitTestCase;
13 14 15 16 17 18 19 20

/**
 * Tests the CacheContexts service.
 *
 * @group Cache
 *
 * @see \Drupal\Core\Cache\CacheContexts
 */
21
class CacheContextsTest extends UnitTestCase {
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

  public static function getInfo() {
    return array(
      'name' => 'CacheContext test',
      'description' => 'Tests cache contexts.',
      'group' => 'Cache',
    );
  }

  public function testContextPlaceholdersAreReplaced() {
    $container = $this->getMockContainer();
    $container->expects($this->once())
              ->method("get")
              ->with("cache_context.foo")
              ->will($this->returnValue(new FooCacheContext()));

    $cache_contexts = new CacheContexts($container, $this->getContextsFixture());

    $new_keys = $cache_contexts->convertTokensToKeys(
      array("non-cache-context", "cache_context.foo")
    );

    $expected = array("non-cache-context", "bar");
    $this->assertEquals($expected, $new_keys);
  }

  public function testAvailableContextStrings() {
    $cache_contexts = new CacheContexts($this->getMockContainer(), $this->getContextsFixture());
    $contexts = $cache_contexts->getAll();
    $this->assertEquals(array("cache_context.foo"), $contexts);
  }

  public function testAvailableContextLabels() {
    $container = $this->getMockContainer();
    $container->expects($this->once())
              ->method("get")
              ->with("cache_context.foo")
              ->will($this->returnValue(new FooCacheContext()));

    $cache_contexts = new CacheContexts($container, $this->getContextsFixture());
    $labels = $cache_contexts->getLabels();
    $expected = array("cache_context.foo" => "Foo");
    $this->assertEquals($expected, $labels);
  }

  protected function getContextsFixture() {
    return array('cache_context.foo');
  }

  protected function getMockContainer() {
    return $this->getMockBuilder('Drupal\Core\DependencyInjection\Container')
                ->disableOriginalConstructor()
                ->getMock();
  }
}
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98

/**
 * Fake cache context class.
 */
class FooCacheContext implements CacheContextInterface {

  /**
   * {@inheritdoc}
   */
  public static function getLabel() {
    return 'Foo';
  }

  /**
   * {@inheritdoc}
   */
  public function getContext() {
    return 'bar';
  }

}