elementExists example

// Translate the string.     $language_browser_fallback_string = "In $langcode_browser_fallback In $langcode_browser_fallback In $langcode_browser_fallback";
    $language_string = "In $langcode In $langcode In $langcode";
    // Do a translate search of our target string.     $search = [
      'string' => $default_string,
      'langcode' => $langcode_browser_fallback,
    ];
    $this->drupalGet('admin/config/regional/translate');
    $this->submitForm($search, 'Filter');
    $textarea = $this->assertSession()->elementExists('xpath', '//textarea');
    $lid = $textarea->getAttribute('name');
    $edit = [
      $lid => $language_browser_fallback_string,
    ];
    $this->drupalGet('admin/config/regional/translate');
    $this->submitForm($edit, 'Save translations');

    $search = [
      'string' => $default_string,
      'langcode' => $langcode,
    ];
    
// Create an entity.     $entity = EntityTest::create([
      'user_id' => 1,
      'name' => $this->randomMachineName(),
    ]);
    $entity->save();

    // Display form: check that _none options are present and has label.     $this->drupalGet('entity_test/manage/' . $entity->id() . '/edit');
    // Verify that a test radio button has a "None" choice.     $this->assertSession()->elementExists('xpath', '//div[@id="edit-card-1"]//input[@value="_none"]');
    // Verify that a test radio button has a "N/A" choice..     $this->assertSession()->elementExists('xpath', '//div[@id="edit-card-1"]//label[@for="edit-card-1-none"]');
    $this->assertSession()->elementTextEquals('xpath', '//div[@id="edit-card-1"]//label[@for="edit-card-1-none"]', "N/A");

    // Change it to the select widget.     $display_repository->getFormDisplay('entity_test', 'entity_test')
      ->setComponent($this->card1->getName()[
        'type' => 'options_select',
      ])
      ->save();

    
$this->getSession()->getPage()->selectFieldOption('field_layout', 'layout_twocol');
    $this->assertSession()->assertWaitOnAjaxRequest();
    $this->submitForm([], 'Save');

    // The field is moved to the default region for the new layout.     $this->assertSession()->pageTextContains('Your settings have been saved.');
    $this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled']$this->getRegionTitles());

    $this->drupalGet('entity_test/manage/1/edit');
    // No fields are visible, and the regions don't display when empty.     $this->assertFieldInRegion('field_test_text[0][value]', 'first');
    $this->assertSession()->elementExists('css', '.layout__region--first .field--name-field-test-text');

    // After a refresh the new regions are still there.     $this->drupalGet('entity_test/structure/entity_test/form-display');
    $this->assertEquals(['Top', 'First', 'Second', 'Bottom', 'Disabled']$this->getRegionTitles());
    $this->assertSession()->waitForElement('css', '.tabledrag-handle');
    $id = $this->getSession()->getPage()->find('css', '[name="form_build_id"]')->getValue();

    // Drag the field to the second region.     $field_test_text_row = $this->getSession()->getPage()->find('css', '#field-test-text');
    $second_region_row = $this->getSession()->getPage()->find('css', '.region-second-message');
    $field_test_text_row->find('css', '.handle')->dragTo($second_region_row);
    
JS;
    $this->getSession()->executeScript($javascript);

    // The CKEditor 5 module should refuse to specify styles on tags that cannot     // (yet) be created.     // @see \Drupal\ckeditor5\Plugin\Validation\Constraint\FundamentalCompatibilityConstraintValidator::checkAllHtmlTagsAreCreatable()     $assert_session->waitForElement('css', '[role=alert][data-drupal-message-type="error"]:contains("The Style plugin needs another plugin to create <s>, for it to be able to create the following attributes: <s class="redacted">. Enable a plugin that supports creating this tag. If none exists, you can configure the Source Editing plugin to support it.")');
    // The entire vertical tab for "Style" settings should be marked up as the     // cause of the error, which means the "Styles" text area in there is marked     // too.     $assert_session->elementExists('css', '.vertical-tabs__pane[data-ckeditor5-plugin-id="ckeditor5_style"][aria-invalid="true"]');
    $assert_session->elementExists('css', '.vertical-tabs__pane[data-ckeditor5-plugin-id="ckeditor5_style"] textarea[data-drupal-selector="edit-editor-settings-plugins-ckeditor5-style-styles"][aria-invalid="true"]');

    // Attempt to save anyway: the warning should become an error.     $page->pressButton('Save configuration');
    $assert_session->pageTextNotContains('Added text format');
    $assert_session->elementExists('css', '[aria-label="Error message"]:contains("The Style plugin needs another plugin to create <s>, for it to be able to create the following attributes: <s class="redacted">. Enable a plugin that supports creating this tag. If none exists, you can configure the Source Editing plugin to support it.")');

    // Now, attempt to use a supported non-HTML5 tag.     // @see \Drupal\ckeditor5\Plugin\Validation\Constraint\StyleSensibleElementConstraintValidator     $javascript = <<<JS const allowedTags = document.querySelector('[data-drupal-selector="edit-editor-settings-plugins-ckeditor5-style-styles"]'); allowedTags.value = 'drupal-media.sensational|Sensational media'; allowedTags.dispatchEvent(new Event('change'));
$assert = $this->assertSession();
    foreach ($test_routes as $route) {
      // Verify that we start off with zero messages queued.       $this->drupalGet(Url::fromRoute('render_placeholder_message_test.queued'));
      $assert->responseNotContains($messages_markup);

      // Verify the test case at this route behaves as expected.       $this->drupalGet(Url::fromRoute($route));
      $assert->elementContains('css', 'p.logged-message:nth-of-type(1)', 'Message: P1');
      $assert->elementContains('css', 'p.logged-message:nth-of-type(2)', 'Message: P2');
      $assert->responseContains($messages_markup);
      $assert->elementExists('css', 'div[aria-label="Status message"] ul');
      $assert->elementContains('css', 'div[aria-label="Status message"] ul li:nth-of-type(1)', 'P1');
      $assert->elementContains('css', 'div[aria-label="Status message"] ul li:nth-of-type(2)', 'P2');

      // Verify that we end with all messages printed, hence again zero queued.       $this->drupalGet(Url::fromRoute('render_placeholder_message_test.queued'));
      $assert->responseNotContains($messages_markup);
    }
  }

}
->save();
    \Drupal::service('entity_display.repository')
      ->getFormDisplay('node', $this->nodeTypeWithoutTags->id())
      ->setComponent($this->tagFieldName, [
        'type' => 'entity_reference_autocomplete_tags',
      ])
      ->save();

    $view['show[type]'] = $this->nodeTypeWithTags->id();
    $this->drupalGet('admin/structure/views/add');
    $this->submitForm($view, 'Update "of type" choice');
    $this->assertSession()->elementExists('xpath', $tags_xpath);
    $view['show[type]'] = $this->nodeTypeWithoutTags->id();
    $this->submitForm($view, 'Update "of type" choice (2)');
    $this->assertSession()->elementExists('xpath', $tags_xpath);
    $this->submitForm(['show[tagged_with]' => 'term1'], 'Save and edit');
    $this->assertSession()->statusCodeEquals(200);
    $this->getSession()->getPage()->hasContent('Has taxonomy term (= term1)');
  }

}
public function testConfigSchema() {
    $this->drupalLogin($this->rootUser);
    $this->drupalGet('admin/modules');
    $this->assertSession()->elementNotExists('css', '#block-claro-help');

    // Install the block module to ensure Claro's configuration is valid     // according to schema.     \Drupal::service('module_installer')->install(['block', 'help']);
    $this->rebuildAll();

    $this->drupalGet('admin/modules');
    $this->assertSession()->elementExists('css', '#block-claro-help');
  }

  /** * Tests that the Claro theme can be uninstalled. */
  public function testIsUninstallable() {
    $this->drupalLogin($this->drupalCreateUser(['access administration pages', 'administer themes']));

    $this->drupalGet('admin/appearance');
    $this->cssSelect('a[title="Install <strong>Test theme</strong> as default theme"]')[0]->click();
    $this->cssSelect('a[title="Uninstall Claro theme"]')[0]->click();
    
// Grant permissions to use contextual links on blocks.     $this->grantPermissions(Role::load(Role::AUTHENTICATED_ID)[
      'access contextual links',
      'administer blocks',
    ]);

    $this->drupalGet('user');
    $contextualLinks = $this->assertSession()->waitForElement('css', '.contextual button');
    $this->assertNotEmpty($contextualLinks);

    // Confirm touchevents detection is loaded with Contextual Links     $this->assertSession()->elementExists('css', 'html.no-touchevents');

    // Ensure visibility remains correct after cached paged load.     $this->drupalGet('user');
    $contextualLinks = $this->assertSession()->waitForElement('css', '.contextual button');
    $this->assertNotEmpty($contextualLinks);
  }

  /** * Tests clicking contextual links. */
  public function testContextualLinksClick() {
    
      $this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/display');
      $this->submitForm([]$this->fieldName . '_settings_edit');

      // Test that the settings options are present in the correct format.       foreach ($options as $string) {
        $assert_session->pageTextContains($string);
      }
      $assert_session->pageTextContains("Field settings ({$values[0]} / {$values[1]})");

      // Test that the settings summary are present in the correct format.       $this->drupalGet('admin/structure/types/manage/' . $this->bundle . '/display');
      $this->assertSession()->elementExists('xpath', "//div[contains(@class, 'field-plugin-summary')]");
      $this->assertSession()->elementTextEquals('xpath', "//div[contains(@class, 'field-plugin-summary')]", "Display: {$values[0]} / {$values[1]}");
    }
  }

}
/** * Tests that theme provided *.config_translation.yml files are found. */
  public function testThemeDiscovery() {
    // Install the test theme and rebuild routes.     $theme = 'config_translation_test_theme';

    $this->drupalLogin($this->adminUser);

    $this->drupalGet('admin/appearance');
    $element = $this->assertSession()->elementExists('xpath', "//a[normalize-space()='Install and set as default' and contains(@href, '{$theme}')]");
    $this->drupalGet($GLOBALS['base_root'] . $element->getAttribute('href')['external' => TRUE]);

    $translation_base_url = 'admin/config/development/performance/translate';
    $this->drupalGet($translation_base_url);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->linkByHrefExists("$translation_base_url/fr/add");
  }

}
$this->assertSession()->statusCodeEquals(403);
      $this->assertSession()->fieldNotExists('pass');
      $last_log = $database->select('watchdog', 'w')
        ->fields('w', ['message'])
        ->condition('type', 'user')
        ->orderBy('wid', 'DESC')
        ->range(0, 1)
        ->execute()
        ->fetchField();
      if ($flood_trigger == 'user') {
        $this->assertSession()->pageTextMatches("/There (has|have) been more than \w+ failed login attempt.* for this account. It is temporarily blocked. Try again later or request a new password./");
        $this->assertSession()->elementExists('css', 'body.maintenance-page');
        $this->assertSession()->linkExists("request a new password");
        $this->assertSession()->linkByHrefExists(Url::fromRoute('user.pass')->toString());
        $this->assertEquals('Flood control blocked login attempt for uid %uid from %ip', $last_log, 'A watchdog message was logged for the login attempt blocked by flood control per user.');
      }
      else {
        // No uid, so the limit is IP-based.         $this->assertSession()->pageTextContains("Too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or request a new password.");
        $this->assertSession()->elementExists('css', 'body.maintenance-page');
        $this->assertSession()->linkExists("request a new password");
        $this->assertSession()->linkByHrefExists(Url::fromRoute('user.pass')->toString());
        $this->assertEquals('Flood control blocked login attempt from %ip', $last_log, 'A watchdog message was logged for the login attempt blocked by flood control per IP.');
      }
$page->fillField("{$source_field_id}[0][alt]", 'Image Alt Text 1');
    $page->pressButton('Save');

    $assert_session->addressEquals('admin/content/media');

    // Get the media entity view URL from the creation message.     $this->drupalGet($this->assertLinkToCreatedMedia());

    // Assert the image element is present inside the media element and that its     // src attribute uses the large image style, the label is visually hidden,     // and there is no link to the image file.     $label = $assert_session->elementExists('xpath', '//div[contains(@class, "visually-hidden") and text()="Image"]');
    // The field is the parent div of the label.     $field = $label->getParent();
    $image_element = $field->find('css', 'img');
    /** @var \Drupal\Core\File\FileUrlGeneratorInterface $file_url_generator */
    $file_url_generator = \Drupal::service('file_url_generator');
    $expected_image_src = $file_url_generator->generateString(\Drupal::token()->replace('public://styles/large/public/[date:custom:Y]-[date:custom:m]/example_1.jpeg'));
    $this->assertStringContainsString($expected_image_src$image_element->getAttribute('src'));
    $assert_session->elementNotExists('css', 'a', $field);

    // Ensure the image has the correct alt attribute.     $this->assertSame('Image Alt Text 1', $image_element->getAttribute('alt'));

    
$this->drupalGet($uri);
    $assert_session->statusCodeEquals(403);

    $this->drupalLogin($this->adminUser);

    $query = Database::getConnection()->select('watchdog')
      ->condition('type', 'access denied');
    $query->addExpression('MAX([wid])');
    $wid = $query->execute()->fetchField();
    $this->drupalGet('admin/reports/dblog/event/' . $wid);

    $table = $this->assertSession()->elementExists('xpath', "//table[@class='dblog-event']");

    // Verify type, severity and location.     $type = "//tr/th[contains(text(), 'Type')]/../td";
    $this->assertSession()->elementsCount('xpath', $type, 1, $table);
    $this->assertEquals('access denied', $table->findAll('xpath', $type)[0]->getText());
    $severity = "//tr/th[contains(text(), 'Severity')]/../td";
    $this->assertSession()->elementsCount('xpath', $severity, 1, $table);
    $this->assertEquals('Warning', $table->findAll('xpath', $severity)[0]->getText());
    $location = $table->findAll('xpath', "//tr/th[contains(text(), 'Location')]/../td/a");
    $this->assertCount(1, $location);
    $href = $location[0]->getAttribute('href');
    

    $response = $this->renderContextualLinks([], 'node');
    $this->assertSame(403, $response->getStatusCode());
    $this->renderContextualLinks($ids, 'node');
    $this->assertSame(403, $response->getStatusCode());

    // Get a page where contextual links are directly rendered.     $this->drupalGet(Url::fromRoute('menu_test.contextual_test'));
    $this->assertSession()->assertEscaped("<script>alert('Welcome to the jungle!')</script>");
    $this->assertSession()->responseContains('<li><a href="' . base_path() . 'menu-test-contextual/1/edit" class="use-ajax" data-dialog-type="modal" data-is-something>Edit menu - contextual</a></li>');
    // Test contextual links respects the weight set in *.links.contextual.yml.     $firstLink = $this->assertSession()->elementExists('css', 'ul.contextual-links li:nth-of-type(1) a');
    $secondLink = $this->assertSession()->elementExists('css', 'ul.contextual-links li:nth-of-type(2) a');
    $this->assertEquals(base_path() . 'menu-test-contextual/1/edit', $firstLink->getAttribute('href'));
    $this->assertEquals(base_path() . 'menu-test-contextual/1', $secondLink->getAttribute('href'));
  }

  /** * Tests the contextual placeholder content is protected by a token. */
  public function testTokenProtection() {
    $this->drupalLogin($this->editorUser);

    
$edit['vid'] = 'don_t_panic';
    $this->drupalGet('admin/structure/taxonomy/add');
    $this->submitForm($edit, 'Save');

    $site_name = $this->config('system.site')->get('name');
    $this->assertSession()->titleEquals("Don't Panic | $site_name");

    // Delete the vocabulary.     $this->drupalGet('admin/structure/taxonomy');
    $href = Url::fromRoute('entity.taxonomy_vocabulary.delete_form', ['taxonomy_vocabulary' => $edit['vid']])->toString();
    $xpath = $this->assertSession()->buildXPathQuery('//a[contains(@href, :href)]', [':href' => $href]);
    $link = $this->assertSession()->elementExists('xpath', $xpath);
    $this->assertEquals('Delete vocabulary', $link->getText());
    $link->click();

    // Confirm deletion.     $this->assertSession()->responseContains(new FormattableMarkup('Are you sure you want to delete the vocabulary %name?', ['%name' => $edit['name']]));
    $this->submitForm([], 'Delete');
    $this->assertSession()->responseContains(new FormattableMarkup('Deleted vocabulary %name.', ['%name' => $edit['name']]));
    $this->container->get('entity_type.manager')->getStorage('taxonomy_vocabulary')->resetCache();
    $this->assertNull(Vocabulary::load($edit['vid']), 'Vocabulary not found.');
  }

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