You are here

public function ResultCacheTest::testContext in GraphQL 8.4

Same name and namespace in other branches
  1. 8.3 tests/src/Kernel/Framework/ResultCacheTest.php \Drupal\Tests\graphql\Kernel\Framework\ResultCacheTest::testContext()

Test if changing test context's trigger re-evaluations.

File

tests/src/Kernel/Framework/ResultCacheTest.php, line 186

Class

ResultCacheTest
Test query result caching.

Namespace

Drupal\Tests\graphql\Kernel\Framework

Code

public function testContext() : void {
  $cacheable = $this
    ->getMockBuilder(CacheableDependencyInterface::class)
    ->setMethods([
    'getCacheTags',
    'getCacheMaxAge',
    'getCacheContexts',
  ])
    ->getMock();
  $cacheable
    ->expects($this
    ->any())
    ->method('getCacheTags')
    ->willReturn([]);
  $cacheable
    ->expects($this
    ->any())
    ->method('getCacheMaxAge')
    ->willReturn(45);
  $cacheable
    ->expects($this
    ->any())
    ->method('getCacheContexts')
    ->willReturn([
    'context',
  ]);
  $dummy = $this
    ->getMockBuilder(Server::class)
    ->disableOriginalConstructor()
    ->setMethods([
    'id',
  ])
    ->getMock();
  $dummy
    ->expects($this
    ->exactly(2))
    ->method('id')
    ->willReturn('test');

  // Prepare a prophesied context manager.
  $contextManager = $this
    ->prophesize(CacheContextsManager::class);
  $this->container
    ->set('cache_contexts_manager', $contextManager
    ->reveal());

  // All tokens are valid for this test.
  $contextManager
    ->assertValidTokens(Argument::any())
    ->willReturn(TRUE);

  // Argument patterns that check if the 'context' is in the list.
  $hasContext = Argument::containing('context');
  $hasNotContext = Argument::that(function ($arg) {
    return !in_array('context', $arg);
  });

  // If 'context' is not defined, we return no cache keys.
  $contextManager
    ->convertTokensToKeys($hasNotContext)
    ->willReturn(new ContextCacheKeys([]));

  // Store the method prophecy so we can replace the result on the fly.

  /** @var \Prophecy\Prophecy\MethodProphecy $contextKeys */
  $contextKeys = $contextManager
    ->convertTokensToKeys($hasContext);
  $this
    ->mockResolver('Query', 'root', $this->builder
    ->compose($this->builder
    ->fromValue($cacheable), $this->builder
    ->callback(function () use ($dummy) {
    return $dummy
      ->id();
  })));

  // Set the context value to 'a'/.
  $contextKeys
    ->willReturn(new ContextCacheKeys([
    'a',
  ]));

  // This will be stored in the cache key for context 'a'.
  $this
    ->query('{ root }');

  // Change the context value to 'b'.
  $contextKeys
    ->willReturn(new ContextCacheKeys([
    'b',
  ]));

  // This will be stored in the cache key for context 'b'.
  $this
    ->query('{ root }');

  // Change the context value back to 'a'.
  $contextKeys
    ->willReturn(new ContextCacheKeys([
    'a',
  ]));

  // This will be retrieved from cache for context 'a'.
  $this
    ->query('{ root }');
}