You are here

class CacheContextsManagerTest in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/Tests/Core/Cache/Context/CacheContextsManagerTest.php \Drupal\Tests\Core\Cache\Context\CacheContextsManagerTest
  2. 10 core/tests/Drupal/Tests/Core/Cache/Context/CacheContextsManagerTest.php \Drupal\Tests\Core\Cache\Context\CacheContextsManagerTest

@coversDefaultClass \Drupal\Core\Cache\Context\CacheContextsManager @group Cache

Hierarchy

Expanded class hierarchy of CacheContextsManagerTest

File

core/tests/Drupal/Tests/Core/Cache/Context/CacheContextsManagerTest.php, line 22
Contains \Drupal\Tests\Core\Cache\Context\CacheContextsManagerTest.

Namespace

Drupal\Tests\Core\Cache\Context
View source
class CacheContextsManagerTest extends UnitTestCase {

  /**
   * @covers ::optimizeTokens
   *
   * @dataProvider providerTestOptimizeTokens
   */
  public function testOptimizeTokens(array $context_tokens, array $optimized_context_tokens) {
    $container = $this
      ->getMockBuilder('Drupal\\Core\\DependencyInjection\\Container')
      ->disableOriginalConstructor()
      ->getMock();
    $container
      ->expects($this
      ->any())
      ->method('get')
      ->will($this
      ->returnValueMap([
      [
        'cache_context.a',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new FooCacheContext(),
      ],
      [
        'cache_context.a.b',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new FooCacheContext(),
      ],
      [
        'cache_context.a.b.c',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new BazCacheContext(),
      ],
      [
        'cache_context.x',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new BazCacheContext(),
      ],
      [
        'cache_context.a.b.no-optimize',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new NoOptimizeCacheContext(),
      ],
    ]));
    $cache_contexts_manager = new CacheContextsManager($container, $this
      ->getContextsFixture());
    $this
      ->assertSame($optimized_context_tokens, $cache_contexts_manager
      ->optimizeTokens($context_tokens));
  }

  /**
   * Provides a list of context token sets.
   */
  public function providerTestOptimizeTokens() {
    return [
      [
        [
          'a',
          'x',
        ],
        [
          'a',
          'x',
        ],
      ],
      [
        [
          'a.b',
          'x',
        ],
        [
          'a.b',
          'x',
        ],
      ],
      // Direct ancestor, single-level hierarchy.
      [
        [
          'a',
          'a.b',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b',
          'a',
        ],
        [
          'a',
        ],
      ],
      // Direct ancestor, multi-level hierarchy.
      [
        [
          'a.b',
          'a.b.c',
        ],
        [
          'a.b',
        ],
      ],
      [
        [
          'a.b.c',
          'a.b',
        ],
        [
          'a.b',
        ],
      ],
      // Indirect ancestor.
      [
        [
          'a',
          'a.b.c',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b.c',
          'a',
        ],
        [
          'a',
        ],
      ],
      // Direct & indirect ancestors.
      [
        [
          'a',
          'a.b',
          'a.b.c',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a',
          'a.b.c',
          'a.b',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b',
          'a',
          'a.b.c',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b',
          'a.b.c',
          'a',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b.c',
          'a.b',
          'a',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b.c',
          'a',
          'a.b',
        ],
        [
          'a',
        ],
      ],
      // Using parameters.
      [
        [
          'a',
          'a.b.c:foo',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b.c:foo',
          'a',
        ],
        [
          'a',
        ],
      ],
      [
        [
          'a.b.c:foo',
          'a.b.c',
        ],
        [
          'a.b.c',
        ],
      ],
      // max-age 0 is treated as non-optimizable.
      [
        [
          'a.b.no-optimize',
          'a.b',
          'a',
        ],
        [
          'a.b.no-optimize',
          'a',
        ],
      ],
    ];
  }

  /**
   * @covers ::convertTokensToKeys
   */
  public function testConvertTokensToKeys() {
    $container = $this
      ->getMockContainer();
    $cache_contexts_manager = new CacheContextsManager($container, $this
      ->getContextsFixture());
    $new_keys = $cache_contexts_manager
      ->convertTokensToKeys([
      'foo',
      'baz:parameterA',
      'baz:parameterB',
    ]);
    $expected = [
      '[baz:parameterA]=cnenzrgreN',
      '[baz:parameterB]=cnenzrgreO',
      '[foo]=bar',
    ];
    $this
      ->assertEquals($expected, $new_keys
      ->getKeys());
  }

  /**
   * @covers ::convertTokensToKeys
   */
  public function testInvalidContext() {
    $container = $this
      ->getMockContainer();
    $cache_contexts_manager = new CacheContextsManager($container, $this
      ->getContextsFixture());
    $this
      ->expectException(\AssertionError::class);
    $cache_contexts_manager
      ->convertTokensToKeys([
      "non-cache-context",
    ]);
  }

  /**
   * @covers ::convertTokensToKeys
   *
   * @dataProvider providerTestInvalidCalculatedContext
   */
  public function testInvalidCalculatedContext($context_token) {
    $container = $this
      ->getMockContainer();
    $cache_contexts_manager = new CacheContextsManager($container, $this
      ->getContextsFixture());
    $this
      ->expectException(\Exception::class);
    $cache_contexts_manager
      ->convertTokensToKeys([
      $context_token,
    ]);
  }

  /**
   * Provides a list of invalid 'baz' cache contexts: the parameter is missing.
   */
  public function providerTestInvalidCalculatedContext() {
    return [
      [
        'baz',
      ],
      [
        'baz:',
      ],
    ];
  }
  public function testAvailableContextStrings() {
    $cache_contexts_manager = new CacheContextsManager($this
      ->getMockContainer(), $this
      ->getContextsFixture());
    $contexts = $cache_contexts_manager
      ->getAll();
    $this
      ->assertEquals([
      "foo",
      "baz",
    ], $contexts);
  }
  public function testAvailableContextLabels() {
    $container = $this
      ->getMockContainer();
    $cache_contexts_manager = new CacheContextsManager($container, $this
      ->getContextsFixture());
    $labels = $cache_contexts_manager
      ->getLabels();
    $expected = [
      "foo" => "Foo",
    ];
    $this
      ->assertEquals($expected, $labels);
  }
  protected function getContextsFixture() {
    return [
      'foo',
      'baz',
    ];
  }
  protected function getMockContainer() {
    $container = $this
      ->getMockBuilder('Drupal\\Core\\DependencyInjection\\Container')
      ->disableOriginalConstructor()
      ->getMock();
    $container
      ->expects($this
      ->any())
      ->method('get')
      ->will($this
      ->returnValueMap([
      [
        'cache_context.foo',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new FooCacheContext(),
      ],
      [
        'cache_context.baz',
        Container::EXCEPTION_ON_INVALID_REFERENCE,
        new BazCacheContext(),
      ],
    ]));
    return $container;
  }

  /**
   * Provides a list of cache context token arrays.
   *
   * @return array
   */
  public function validateTokensProvider() {
    return [
      [
        [],
        FALSE,
      ],
      [
        [
          'foo',
        ],
        FALSE,
      ],
      [
        [
          'foo',
          'foo.bar',
        ],
        FALSE,
      ],
      [
        [
          'foo',
          'baz:llama',
        ],
        FALSE,
      ],
      // Invalid.
      [
        [
          FALSE,
        ],
        'Cache contexts must be strings, boolean given.',
      ],
      [
        [
          TRUE,
        ],
        'Cache contexts must be strings, boolean given.',
      ],
      [
        [
          'foo',
          FALSE,
        ],
        'Cache contexts must be strings, boolean given.',
      ],
      [
        [
          NULL,
        ],
        'Cache contexts must be strings, NULL given.',
      ],
      [
        [
          'foo',
          NULL,
        ],
        'Cache contexts must be strings, NULL given.',
      ],
      [
        [
          1337,
        ],
        'Cache contexts must be strings, integer given.',
      ],
      [
        [
          'foo',
          1337,
        ],
        'Cache contexts must be strings, integer given.',
      ],
      [
        [
          3.14,
        ],
        'Cache contexts must be strings, double given.',
      ],
      [
        [
          'foo',
          3.14,
        ],
        'Cache contexts must be strings, double given.',
      ],
      [
        [
          [],
        ],
        'Cache contexts must be strings, array given.',
      ],
      [
        [
          'foo',
          [],
        ],
        'Cache contexts must be strings, array given.',
      ],
      [
        [
          'foo',
          [
            'bar',
          ],
        ],
        'Cache contexts must be strings, array given.',
      ],
      [
        [
          new \stdClass(),
        ],
        'Cache contexts must be strings, object given.',
      ],
      [
        [
          'foo',
          new \stdClass(),
        ],
        'Cache contexts must be strings, object given.',
      ],
      // Non-existing.
      [
        [
          'foo.bar',
          'qux',
        ],
        '"qux" is not a valid cache context ID.',
      ],
      [
        [
          'qux',
          'baz',
        ],
        '"qux" is not a valid cache context ID.',
      ],
    ];
  }

  /**
   * @covers ::validateTokens
   *
   * @dataProvider validateTokensProvider
   */
  public function testValidateContexts(array $contexts, $expected_exception_message) {
    $container = new ContainerBuilder();
    $cache_contexts_manager = new CacheContextsManager($container, [
      'foo',
      'foo.bar',
      'baz',
    ]);
    if ($expected_exception_message !== FALSE) {
      $this
        ->expectException('LogicException');
      $this
        ->expectExceptionMessage($expected_exception_message);
    }

    // If it doesn't throw an exception, validateTokens() returns NULL.
    $this
      ->assertNull($cache_contexts_manager
      ->validateTokens($contexts));
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CacheContextsManagerTest::getContextsFixture protected function
CacheContextsManagerTest::getMockContainer protected function
CacheContextsManagerTest::providerTestInvalidCalculatedContext public function Provides a list of invalid 'baz' cache contexts: the parameter is missing.
CacheContextsManagerTest::providerTestOptimizeTokens public function Provides a list of context token sets.
CacheContextsManagerTest::testAvailableContextLabels public function
CacheContextsManagerTest::testAvailableContextStrings public function
CacheContextsManagerTest::testConvertTokensToKeys public function @covers ::convertTokensToKeys
CacheContextsManagerTest::testInvalidCalculatedContext public function @covers ::convertTokensToKeys
CacheContextsManagerTest::testInvalidContext public function @covers ::convertTokensToKeys
CacheContextsManagerTest::testOptimizeTokens public function @covers ::optimizeTokens
CacheContextsManagerTest::testValidateContexts public function @covers ::validateTokens
CacheContextsManagerTest::validateTokensProvider public function Provides a list of cache context token arrays.
PhpunitCompatibilityTrait::getMock Deprecated public function Returns a mock object for the specified class using the available method.
PhpunitCompatibilityTrait::setExpectedException Deprecated public function Compatibility layer for PHPUnit 6 to support PHPUnit 4 code.
UnitTestCase::$randomGenerator protected property The random generator.
UnitTestCase::$root protected property The app root. 1
UnitTestCase::assertArrayEquals protected function Asserts if two arrays are equal by sorting them first.
UnitTestCase::getBlockMockWithMachineName Deprecated protected function Mocks a block with a block plugin. 1
UnitTestCase::getClassResolverStub protected function Returns a stub class resolver.
UnitTestCase::getConfigFactoryStub public function Returns a stub config factory that behaves according to the passed array.
UnitTestCase::getConfigStorageStub public function Returns a stub config storage that returns the supplied configuration.
UnitTestCase::getContainerWithCacheTagsInvalidator protected function Sets up a container with a cache tags invalidator.
UnitTestCase::getRandomGenerator protected function Gets the random generator for the utility methods.
UnitTestCase::getStringTranslationStub public function Returns a stub translation manager that just returns the passed string.
UnitTestCase::randomMachineName public function Generates a unique random string containing letters and numbers.
UnitTestCase::setUp protected function 340