assertCacheContexts example

// Post an additional node.     $node4 = $this->drupalCreateNode($default_settings);

    // Test that all four nodes are shown.     $this->drupalGet('');
    $this->assertSession()->pageTextContains($node1->label());
    $this->assertSession()->pageTextContains($node2->label());
    $this->assertSession()->pageTextContains($node3->label());
    $this->assertSession()->pageTextContains($node4->label());

    $this->assertCacheContexts(['languages:language_content', 'languages:language_interface', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.site', 'user']);

    // Enable the "Powered by Drupal" block only on article nodes.     $theme = \Drupal::service('theme_handler')->getDefault();
    $this->drupalGet("admin/structure/block/add/system_powered_by_block/{$theme}");
    $this->assertSession()->pageTextContains('Content type');
    $edit = [
      'id' => strtolower($this->randomMachineName()),
      'region' => 'sidebar_first',
      'visibility[entity_bundle:node][bundles][article]' => 'article',
    ];
    $this->submitForm($edit, 'Save block');

    
    // the returned cache contexts include those from lazy-builder content.     $site_configuration_user1 = $this->drupalCreateUser();
    $site_configuration_user1->addRole($site_configuration_role);
    $site_configuration_user1->save();
    $site_configuration_user2 = $this->drupalCreateUser();
    $site_configuration_user2->addRole($site_configuration_role);
    $site_configuration_user2->save();

    $this->drupalLogin($site_configuration_user1);
    $this->verifyDynamicPageCache($test_page_url, 'MISS');
    $this->verifyDynamicPageCache($test_page_url, 'HIT');
    $this->assertCacheContexts(['user', 'url.query_args:_wrapper_format']);
    $this->assertSession()->linkExists('Shortcuts');
    $this->assertSession()->linkExists('Cron');

    $this->drupalLogin($site_configuration_user2);
    $this->verifyDynamicPageCache($test_page_url, 'HIT');
    $this->assertCacheContexts(['user', 'url.query_args:_wrapper_format']);
    $this->assertSession()->linkExists('Shortcuts');
    $this->assertSession()->linkExists('Cron');

    // Add another shortcut.     $shortcut = Shortcut::create([
      

  protected function assertPageCacheContextsAndTags(Url $url, array $expected_contexts, array $expected_tags) {
    $absolute_url = $url->setAbsolute()->toString();
    sort($expected_contexts);
    sort($expected_tags);

    // Assert cache miss + expected cache contexts + tags.     $this->drupalGet($absolute_url);
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'MISS');
    $this->assertCacheTags($expected_tags);
    $this->assertCacheContexts($expected_contexts);

    // Assert cache hit + expected cache contexts + tags.     $this->drupalGet($absolute_url);
    $this->assertCacheTags($expected_tags);
    $this->assertCacheContexts($expected_contexts);

    // Assert page cache item + expected cache tags.     $cid_parts = [$url->setAbsolute()->toString(), ''];
    $cid = implode(':', $cid_parts);
    $cache_entry = \Drupal::cache('page')->get($cid);
    sort($cache_entry->tags);
    
$entity->save();
    }
    $contexts = [
      'languages:language_interface',
      'entity_test_view_grants',
      'theme',
      'url.query_args',
      'languages:language_content',
    ];

    $this->drupalGet('test_exposed_form_sort_items_per_page');
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(1, 10, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC']]);
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(50, 41, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25]]);
    $this->assertCacheContexts($contexts);
    $this->assertIds(range(50, 26, 1));

    $this->drupalGet('test_exposed_form_sort_items_per_page', ['query' => ['sort_order' => 'DESC', 'items_per_page' => 25, 'offset' => 10]]);
    
'items_per_page' => 0,
      ],
    ];

    $view->display_handler->setOption('pager', $pager);
    $this->executeView($view);
    $this->assertEquals(0, $view->pager->getItemsPerPage());
    $this->assertCount(11, $view->result);

    // Test pager cache contexts.     $this->drupalGet('test_pager_full');
    $this->assertCacheContexts(['languages:language_interface', 'theme', 'timezone', 'url.query_args', 'user.node_grants:view']);

    // Set "Number of pager links visible" to 1 and check the active page number     // on the last page.     $view = Views::getView('test_pager_full');
    $view->setDisplay();
    $pager = [
      'type' => 'full',
      'options' => [
        'items_per_page' => 5,
        'quantity' => 1,
      ],
    ];
// Ensure that all the entries are returned.     $this->drupalGet('test_route_without_arguments');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->elementsCount('xpath', $xpath, 5);

    $this->drupalGet('test_route_without_arguments/1');
    $this->assertSession()->statusCodeEquals(404);

    // Ensure that just the filtered entry is returned.     $this->drupalGet('test_route_with_argument/1');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url']);
    $this->assertSession()->elementsCount('xpath', $xpath, 1);
    $this->assertSession()->elementTextEquals('xpath', $xpath, 1);

    // Ensure that just the filtered entry is returned.     $this->drupalGet('test_route_with_suffix/1/suffix');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->elementsCount('xpath', $xpath, 1);
    $this->assertSession()->elementTextEquals('xpath', $xpath, 1);

    // Ensure that no result is returned.     $this->drupalGet('test_route_with_suffix_and_argument/1/suffix/2');
    
$this->assertSession()->elementsCount('xpath', $block_xpath, 1);

    $display = &$view->getDisplay('block_1');
    $display['display_options']['block_hide_empty'] = TRUE;
    $view->save();

    $this->drupalGet($url);
    $this->assertSession()->elementNotExists('xpath', $block_xpath);
    // Ensure that the view cacheability metadata is propagated even, for an     // empty block.     $this->assertCacheTags(array_merge($block->getCacheTags()['block_view', 'config:block_list', 'config:views.view.test_view_block', 'http_response', 'rendered']));
    $this->assertCacheContexts(['url.query_args:_wrapper_format']);

    // Add a header displayed on empty result.     $display = &$view->getDisplay('block_1');
    $display['display_options']['defaults']['header'] = FALSE;
    $display['display_options']['header']['example'] = [
      'field' => 'area_text_custom',
      'id' => 'area_text_custom',
      'table' => 'views',
      'plugin_id' => 'text_custom',
      'content' => 'test header',
      'empty' => TRUE,
    ];
/** * Tests a token replacement on an actual website. */
  public function testTokens() {
    $node = $this->drupalCreateNode();
    $account = $this->drupalCreateUser();
    $this->drupalLogin($account);

    $this->drupalGet('token-test/' . $node->id());
    $this->assertSession()->pageTextContains("Tokens: {$node->id()} {$account->id()}");
    $this->assertCacheTags(['node:1', 'rendered', 'user:2']);
    $this->assertCacheContexts(['languages:language_interface', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'user']);

    $this->drupalGet('token-test-without-bubbleable-metadata/' . $node->id());
    $this->assertSession()->pageTextContains("Tokens: {$node->id()} {$account->id()}");
    $this->assertCacheTags(['node:1', 'rendered', 'user:2']);
    $this->assertCacheContexts(['languages:language_interface', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'user']);
  }

}
// Only the id and name should be click sortable, but not the name.     $this->assertSession()->linkByHrefExists(Url::fromRoute('<none>', []['query' => ['order' => 'id', 'sort' => 'asc']])->toString());
    $this->assertSession()->linkByHrefExists(Url::fromRoute('<none>', []['query' => ['order' => 'name', 'sort' => 'desc']])->toString());
    $this->assertSession()->linkByHrefNotExists(Url::fromRoute('<none>', []['query' => ['order' => 'created']])->toString());

    // Check that the view returns the click sorting cache contexts.     $expected_contexts = [
      'languages:language_interface',
      'theme',
      'url.query_args',
    ];
    $this->assertCacheContexts($expected_contexts);

    // Clicking a click sort should change the order.     $this->clickLink('ID');
    $href = Url::fromRoute('<none>', []['query' => ['order' => 'id', 'sort' => 'desc']])->toString();
    $this->assertSession()->linkByHrefExists($href);
    // Check that the output has the expected order (asc).     $ids = $this->clickSortLoadIdsFromOutput();
    $this->assertEquals(range(1, 5)$ids);
    // Check that the rel attribute has the correct value.     $this->assertSession()->elementAttributeContains('xpath', "//a[@href='$href']", 'rel', 'nofollow');

    
$published = $this->drupalCreateNode([
      'title' => $this->randomMachineName(8),
      'status' => 1,
    ]);

    $this->drupalGet('activity');
    $this->assertSession()->pageTextNotContains($unpublished->label());
    $this->assertSession()->pageTextContains($published->label());
    $this->assertSession()->linkExists('My recent content', 0, 'User tab shows up on the global tracker page.');

    // Assert cache contexts, specifically the pager and node access contexts.     $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user.node_grants:view', 'user']);
    // Assert cache tags for the action/tabs blocks, visible node, and node list     // cache tag.     $expected_tags = Cache::mergeTags($published->getCacheTags()$published->getOwner()->getCacheTags());
    // Because the 'user.permissions' cache context is being optimized away.     $role_tags = [];
    foreach ($this->user->getRoles() as $rid) {
      $role_tags[] = "config:user.role.$rid";
    }
    $expected_tags = Cache::mergeTags($expected_tags$role_tags);
    $block_tags = [
      'block_view',
      
$this->adminUser2 = $this->drupalCreateUser($this->perms);
  }

  /** * Tests toolbar cache integration. */
  public function testCacheIntegration() {
    $this->installExtraModules(['csrf_test', 'dynamic_page_cache']);
    $this->drupalLogin($this->adminUser);
    $this->drupalGet('test-page');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Dynamic-Cache', 'MISS');
    $this->assertCacheContexts(['session', 'user', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT], 'Expected cache contexts found with CSRF token link.');
    $this->drupalGet('test-page');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Dynamic-Cache', 'HIT');
    $this->assertCacheContexts(['session', 'user', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT], 'Expected cache contexts found with CSRF token link.');
  }

  /** * Tests toolbar cache contexts. */
  public function testToolbarCacheContextsCaller() {
    // Test with default combination and permission to see toolbar.     $this->assertToolbarCacheContexts(['user'], 'Expected cache contexts found for default combination and permission to see toolbar.');

    

  public function testSerializerResponses() {
    // Test the serialize callback.     $view = Views::getView('test_serializer_display_field');
    $view->initDisplay();
    $this->executeView($view);

    $actual_json = $this->drupalGet('test/serialize/field', ['query' => ['_format' => 'json']]);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertCacheTags($view->getCacheTags());
    $this->assertCacheContexts(['languages:language_interface', 'theme', 'request_format']);
    // @todo Due to https://www.drupal.org/node/2352009 we can't yet test the     // propagation of cache max-age.
    // Test the http Content-type.     $headers = $this->getSession()->getResponseHeaders();
    $this->assertSame(['application/json']$headers['Content-Type']);

    $expected = [];
    foreach ($view->result as $row) {
      $expected_row = [];
      foreach ($view->field as $id => $field) {
        
$this->drupalLogin($this->translator);
    $storage = $this->container->get('entity_type.manager')
      ->getStorage($this->entityTypeId);
    $storage->resetCache([$this->entityId]);
    $entity = $storage->load($this->entityId);
    $this->assertNotEmpty($entity, 'Entity found in the database.');
    $this->drupalGet($entity->toUrl());
    $this->assertSession()->statusCodeEquals(200);

    // Ensure that the content language cache context is not yet added to the     // page.     $this->assertCacheContexts($this->defaultCacheContexts);

    $this->drupalGet($entity->toUrl('drupal:content-translation-overview'));
    $this->assertSession()->pageTextNotContains('Source language');

    $translation = $this->getTranslation($entity$default_langcode);
    foreach ($values[$default_langcode] as $property => $value) {
      $stored_value = $this->getValue($translation$property$default_langcode);
      $value = is_array($value) ? $value[0]['value'] : $value;
      $message = new FormattableMarkup('@property correctly stored in the default language.', ['@property' => $property]);
      $this->assertEquals($value$stored_value$message);
    }

    
$this->postComment($this->node, $this->randomMachineName()$this->randomMachineName());
    $this->drupalGet('rss.xml');

    $cache_contexts = [
      'languages:language_interface',
      'theme',
      'url.site',
      'user.node_grants:view',
      'user.permissions',
      'timezone',
    ];
    $this->assertCacheContexts($cache_contexts);

    $cache_context_tags = \Drupal::service('cache_contexts_manager')->convertTokensToKeys($cache_contexts)->getCacheTags();
    $this->assertCacheTags(Cache::mergeTags($cache_context_tags[
      'config:views.view.frontpage',
      'node:1', 'node_list',
      'node_view',
      'user:3',
    ]));

    $raw = '<comments>' . $this->node->toUrl('canonical', ['fragment' => 'comments', 'absolute' => TRUE])->toString() . '</comments>';
    $this->assertSession()->responseContains($raw);

    
$this->assertSession()->pageTextContains('Popular content');
    $this->assertSession()->pageTextContains("Today's");
    $this->assertSession()->pageTextContains('All time');
    $this->assertSession()->pageTextContains('Last viewed');

    $tags = Cache::mergeTags($node->getCacheTags()$block->getCacheTags());
    $tags = Cache::mergeTags($tags$this->blockingUser->getCacheTags());
    $tags = Cache::mergeTags($tags['block_view', 'config:block_list', 'node_list', 'rendered', 'user_view']);
    $this->assertCacheTags($tags);
    $contexts = Cache::mergeContexts($node->getCacheContexts()$block->getCacheContexts());
    $contexts = Cache::mergeContexts($contexts['url.query_args:_wrapper_format', 'url.site']);
    $this->assertCacheContexts($contexts);

    // Check if the node link is displayed.     $this->assertSession()->responseContains(Link::fromTextAndUrl($node->label()$node->toUrl('canonical'))->toString());
  }

}
Home | Imprint | This part of the site doesn't use cookies.