You are here

public function ResultCacheTest::testContext in GraphQL 8.3

Same name and namespace in other branches
  1. 8.4 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 127

Class

ResultCacheTest
Test query result caching.

Namespace

Drupal\Tests\graphql\Kernel\Framework

Code

public function testContext() {

  // 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
    ->mockField('root', [
    'id' => 'root',
    'name' => 'root',
    'type' => 'String',
    'response_cache_contexts' => [
      'context',
    ],
  ], NULL, function ($field) {
    $field
      ->expects(static::exactly(2))
      ->method('resolveValues')
      ->willReturnCallback(function () {
      (yield 'test');
    });
  });

  // 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 }');
}