assertCacheContext example

/** * Tests the 'workspace' cache context. */
  public function testWorkspaceCacheContext() {
    $renderer = \Drupal::service('renderer');
    $cache_contexts_manager = \Drupal::service("cache_contexts_manager");

    // Check that the 'workspace' cache context is present when the module is     // installed.     $this->drupalGet('<front>');
    $this->assertCacheContext('workspace');

    $cache_context = new WorkspaceCacheContext(\Drupal::service('workspaces.manager'));
    $this->assertSame('live', $cache_context->getContext());

    // Create a node and check that its render array contains the proper cache     // context.     $this->drupalCreateContentType(['type' => 'page']);
    $node = $this->createNode();

    // Get a fully built entity view render array.     $build = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'full');

    

  public function testPageNotFoundCustomPageWithAccessDenied() {
    // Sets up a 404 page not accessible by the anonymous user.     $this->config('system.site')->set('page.404', '/system-test/custom-4xx')->save();

    $this->drupalGet('/this-path-does-not-exist');
    $this->assertSession()->pageTextNotContains('Admin-only 4xx response');
    $this->assertSession()->pageTextContains('The requested page could not be found.');
    $this->assertSession()->statusCodeEquals(404);
    // Verify the access cacheability metadata for custom 404 is bubbled.     $this->assertCacheContext('user.roles');

    $this->drupalLogin($this->adminUser);
    $this->drupalGet('/this-path-does-not-exist');
    $this->assertSession()->pageTextContains('Admin-only 4xx response');
    $this->assertSession()->pageTextNotContains('The requested page could not be found.');
    $this->assertSession()->statusCodeEquals(404);
    // Verify the access cacheability metadata for custom 404 is bubbled.     $this->assertCacheContext('user.roles');
  }

}
public function testPageCacheAnonymousRolePermissions() {
    $config = $this->config('system.performance');
    $config->set('cache.page.max_age', 300);
    $config->save();

    $content_url = Url::fromRoute('system_test.permission_dependent_content');
    $route_access_url = Url::fromRoute('system_test.permission_dependent_route_access');

    // 1. anonymous user, without permission.     $this->drupalGet($content_url);
    $this->assertSession()->pageTextContains('Permission to pet llamas: no!');
    $this->assertCacheContext('user.permissions');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config:user.role.anonymous');
    $this->drupalGet($route_access_url);
    $this->assertCacheContext('user.permissions');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config:user.role.anonymous');

    // 2. anonymous user, with permission.     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, ['pet llamas']);
    $this->drupalGet($content_url);
    $this->assertSession()->pageTextContains('Permission to pet llamas: yes!');
    $this->assertCacheContext('user.permissions');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config:user.role.anonymous');
    
parent::setUp();
  }

  /** * Tests that URL bubbleable metadata is correctly bubbled. */
  public function testUrlBubbleableMetadataBubbling() {
    // Test that regular URLs bubble up bubbleable metadata when converted to     // string.     $url = Url::fromRoute('cache_test.url_bubbling');
    $this->drupalGet($url);
    $this->assertCacheContext('url.site');
    $this->assertSession()->responseContains($url->setAbsolute()->toString());
  }

}
/** * Tests if config overrides correctly set cacheability metadata. */
  public function testConfigOverride() {
    // Check the default (disabled) state of the cache context. The block label     // should not be overridden.     $this->drupalGet('<front>');
    $this->assertSession()->pageTextNotContains('Overridden block label');

    // Both the cache context and tag should be present.     $this->assertCacheContext('config_override_integration_test');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config_override_integration_test_tag');

    // Flip the state of the cache context. The block label should now be     // overridden.     \Drupal::state()->set('config_override_integration_test.enabled', TRUE);
    $this->drupalGet('<front>');
    $this->assertSession()->pageTextContains('Overridden block label');

    // Both the cache context and tag should still be present.     $this->assertCacheContext('config_override_integration_test');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config_override_integration_test_tag');
  }
$this->assertSession()->statusCodeEquals(200);

    // Create a content type via the user interface.     $web_user = $this->drupalCreateUser([
      'bypass node access',
      'administer content types',
    ]);
    $this->drupalLogin($web_user);

    $this->drupalGet('node/add');
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', 'config:node_type_list');
    $this->assertCacheContext('user.permissions');
    $elements = $this->cssSelect('dl dt');
    $this->assertCount(3, $elements);

    $edit = [
      'name' => 'foo',
      'title_label' => 'title for foo',
      'type' => 'foo',
    ];
    $this->drupalGet('admin/structure/types/add');
    $this->submitForm($edit, 'Save and manage fields');
    $type_exists = (bool) NodeType::load('foo');
    
foreach ($ops as $current_op => $item) {
      $user = $this->drupalCreateUser([
        $this->getTranslatePermission(),
        "$current_op content translations",
        'view test entity',
      ]);
      $this->drupalLogin($user);
      $this->drupalGet($translations_url);

      // Make sure that the user.permissions cache context and the cache tags       // for the entity are present.       $this->assertCacheContext('user.permissions');
      foreach ($this->entity->getCacheTags() as $cache_tag) {
        $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $cache_tag);
      }

      foreach ($ops as $op => $label) {
        if ($op != $current_op) {
          $this->assertSession()->linkNotExists($labelnew FormattableMarkup('No %op link found.', ['%op' => $label]));
        }
        else {
          $this->assertSession()->linkExists($label, 0, new FormattableMarkup('%op link found.', ['%op' => $label]));
        }
      }

  public function testAccessDeniedCustomPageWithAccessDenied() {
    // Sets up a 403 page not accessible by the anonymous user.     $this->config('system.site')->set('page.403', '/system-test/custom-4xx')->save();

    $this->drupalGet('/system-test/always-denied');
    $this->assertSession()->pageTextNotContains('Admin-only 4xx response');
    $this->assertSession()->pageTextContains('You are not authorized to access this page.');
    $this->assertSession()->statusCodeEquals(403);
    // Verify the access cacheability metadata for custom 403 is bubbled.     $this->assertCacheContext('user.roles');

    $this->drupalLogin($this->adminUser);
    $this->drupalGet('/system-test/always-denied');
    $this->assertSession()->pageTextContains('Admin-only 4xx response');
    $this->assertSession()->statusCodeEquals(403);
    // Verify the access cacheability metadata for custom 403 is bubbled.     $this->assertCacheContext('user.roles');
  }

}
'#theme' => 'image',
      '#uri' => $image_uri,
      '#width' => 40,
      '#height' => 20,
      '#alt' => $alt,
      '#attributes' => ['loading' => 'lazy'],
    ];
    $default_output = '<a href="' . $file->createFileUrl() . '">' . $renderer->renderRoot($image) . '</a>';
    $this->drupalGet('node/' . $nid);
    $this->assertSession()->responseHeaderContains('X-Drupal-Cache-Tags', $file->getCacheTags()[0]);
    // @todo Remove in https://www.drupal.org/node/2646744.     $this->assertCacheContext('url.site');
    // Verify that no image style cache tags are found.     $this->assertSession()->responseHeaderNotContains('X-Drupal-Cache-Tags', 'image_style:');
    $this->assertSession()->responseContains($default_output);
    // Verify that the image can be downloaded.     $this->assertEquals(file_get_contents($test_image->uri)$this->drupalGet($file->createFileUrl(FALSE)), 'File was downloaded successfully.');
    if ($scheme == 'private') {
      // Only verify HTTP headers when using private scheme and the headers are       // sent by Drupal.       $this->assertSession()->responseHeaderEquals('Content-Type', 'image/png');
      $this->assertSession()->responseHeaderContains('Cache-Control', 'private');

      
'-- Log out',
      '<Administration>',
      '<Footer>',
      '<Main navigation>',
      '<Tools>',
      '-- Compose tips (disabled)',
      '-- Test menu link',
    ]$menu_options);

    // The cache contexts associated with the (in)accessible menu links are     // bubbled.     $this->assertCacheContext('user.permissions');
  }

  /** * Tests the regression in https://www.drupal.org/node/2532490. */
  public function testDefaultMenuTabRegression() {
    $this->container->get('module_installer')->install(['menu_link_content', 'toolbar', 'system']);
    $this->resetAll();
    $admin_user = $this->drupalCreateUser([
      'administer views',
      'administer blocks',
      
$this->drupalCreateNode();
  }

  /** * Tests that the node grants cache context is auto-added, only when needed. * * @see node_query_node_access_alter() */
  public function testNodeAccessCacheabilitySafeguard() {
    // The node grants cache context should be added automatically.     $this->drupalGet(new Url('node_access_test_auto_bubbling'));
    $this->assertCacheContext('user.node_grants:view');

    // The root user has the 'bypass node access' permission, which means the     // node grants cache context is not necessary.     $this->drupalLogin($this->rootUser);
    $this->drupalGet(new Url('node_access_test_auto_bubbling'));
    $this->assertNoCacheContext('user.node_grants:view');
    $this->drupalLogout();

    // Uninstall the module with the only hook_node_grants() implementation.     $this->container->get('module_installer')->uninstall(['node_access_test']);
    $this->rebuildContainer();

    
$access_plugin = $executable->display_handler->getPlugin('access');
    $this->assertInstanceOf(Role::class$access_plugin);

    // Test the access() method on the access plugin.     $this->assertFalse($executable->display_handler->access($this->webUser));
    $this->assertTrue($executable->display_handler->access($this->normalUser));

    $this->drupalLogin($this->webUser);
    $this->drupalGet('test-role');
    $this->assertSession()->statusCodeEquals(403);
    $this->assertCacheContext('user.roles');

    $this->drupalLogin($this->normalUser);
    $this->drupalGet('test-role');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertCacheContext('user.roles');

    // Test allowing multiple roles.     $view = Views::getView('test_access_role')->storage;
    $display = &$view->getDisplay('default');
    $display['display_options']['access']['options']['role'] = [
      $this->normalRole => $this->normalRole,
      
$this->assertSession()->elementNotExists('css', '.pager');
  }

  /** * Tests pager query parameters and cache context. */
  public function testPagerQueryParametersAndCacheContext() {
    // First page.     $this->drupalGet('pager-test/query-parameters');
    $this->assertSession()->pageTextContains('Pager calls: 0');
    $this->assertSession()->pageTextContains('[url.query_args.pagers:0]=0.0');
    $this->assertCacheContext('url.query_args');

    // Go to last page, the count of pager calls need to go to 1.     $this->assertSession()->elementExists('xpath', '//li[contains(@class, "pager__item--last")]/a')->click();
    $this->assertSession()->pageTextContains('Pager calls: 1');
    $this->assertSession()->pageTextContains('[url.query_args.pagers:0]=0.60');
    $this->assertCacheContext('url.query_args');

    // Reset counter to 0.     $this->drupalGet('pager-test/query-parameters');
    // Go back to first page, the count of pager calls need to go to 2.     $this->assertSession()->elementExists('xpath', '//li[contains(@class, "pager__item--last")]/a')->click();
    
    $xpath = $this->assertSession()->buildXPathQuery('//div[@class="view-content"]/form/@id', [
      ':id' => Html::getUniqueId('block-' . $block->id()),
    ]);
    $this->assertSession()->elementNotExists('xpath', $xpath);

    // Test there is only one views exposed form on the page.     $xpath = '//form[@id="' . $this->getExpectedExposedFormId($view) . '"]';
    $this->assertSession()->elementsCount('xpath', $xpath, 1);
    $element = $this->assertSession()->elementExists('xpath', $xpath);

    // Test that the correct option is selected after form submission.     $this->assertCacheContext('url');
    $this->assertTrue($this->assertSession()->optionExists('Content: Type', 'All')->isSelected());
    $arguments = [
      'All' => ['article', 'page'],
      'article' => ['article'],
      'page' => ['page'],
    ];
    foreach ($arguments as $argument => $bundles) {
      $element->find('css', 'select')->selectOption($argument);
      $element->findButton('Apply')->click();
      $this->assertCacheContext('url');
      $this->assertTrue($this->assertSession()->optionExists('Content: Type', $argument)->isSelected());
      

    $media->save();
    $user_media = Media::create([
      'bundle' => $media_type->id(),
      'name' => 'Unnamed',
      'uid' => $this->nonAdminUser->id(),
    ]);
    $user_media->save();

    // We are logged in as admin, so test 'administer media' permission.     $this->drupalGet('media/add/' . $media_type->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);
    $this->drupalGet('media/' . $user_media->id());
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);
    $this->drupalGet('media/' . $user_media->id() . '/edit');
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);
    $this->drupalGet('media/' . $user_media->id() . '/delete');
    $this->assertCacheContext('user.permissions');
    $assert_session->statusCodeEquals(200);

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