buildXPathQuery example


  protected function xpath($xpath, array $arguments = []) {
    if ($this->parse()) {
      $xpath = $this->buildXPathQuery($xpath$arguments);
      $result = $this->elements->xpath($xpath);
      // Some combinations of PHP / libxml versions return an empty array       // instead of the documented FALSE. Forcefully convert any falsish values       // to an empty array to allow foreach(...) constructions.       return $result ?: [];
    }
    return FALSE;
  }

  /** * Searches elements using a CSS selector in the raw content. * * The search is relative to the root element (HTML tag normally) of the page. * * @param string $selector * CSS selector to use in the search. * * @return \SimpleXMLElement[] * The return value of the XPath search performed after converting the CSS * selector to an XPath selector. */


  /** * Asserts that exactly one link exists with the given text. * * @param string $label * Link label to assert. * * @internal */
  protected function assertOneLink(string $label): void {
    $xpath = $this->assertSession()->buildXPathQuery('//a[normalize-space(text())=:label]', [
      ':label' => $label,
    ]);
    $this->assertSession()->elementsCount('xpath', $xpath, 1);
  }

}
throw new \InvalidArgumentException(sprintf("If a status message type is specified, the allowed values are 'status', 'error', 'warning'. The value provided was '%s'.", $type));
    }

    if ($type) {
      $class = 'messages--' . $type;
    }
    else {
      $class = 'messages__wrapper';
    }

    if ($message) {
      $js_selector = $this->buildXPathQuery('//div[contains(@class, :class) and contains(., :message)]', [
        ':class' => $class,
        ':message' => $message,
      ]);
    }
    else {
      $js_selector = $this->buildXPathQuery('//div[contains(@class, :class)]', [
        ':class' => $class,
      ]);
    }

    // We select based on WebAssert::buildStatusMessageSelector() or the
$edit['description'] = $this->randomMachineName();
    $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.');
  }

  
$xpath = '';
    if ($tree) {
      $i = 0;
      foreach ($tree as $link_path => $link_title) {
        $part_xpath = (!$i ? '//' : '/following-sibling::ul/descendant::');
        $part_xpath .= 'li[contains(@class, :class-trail)]/a[contains(@href, :href) and contains(text(), :title)]';
        $part_args = [
          ':class-trail' => $active_trail_class,
          ':href' => Url::fromUri('base:' . $link_path)->toString(),
          ':title' => $link_title,
        ];
        $xpath .= $this->assertSession()->buildXPathQuery($part_xpath$part_args);
        $i++;
      }
      $this->assertSession()->elementExists('xpath', $xpath);

      // Append prefix for active link asserted below.       $xpath .= '/following-sibling::ul/descendant::';
    }
    else {
      $xpath .= '//';
    }
    $xpath_last_active = ($last_active ? 'and contains(@class, :class-active)' : '');
    
"comment_bulk_form[0]" => $comments[1]->id(),
    ];
    $this->submitForm($edit, 'Apply to selected items');
    $this->assertSession()->pageTextContains('Unapproved comments (0)');

    // Test message when no comments selected.     $this->drupalGet('admin/content/comment');
    $this->submitForm([], 'Apply to selected items');
    $this->assertSession()->pageTextContains('Select one or more comments to perform the update on.');

    // Test that comment listing shows the correct subject link.     $this->assertSession()->elementExists('xpath', $this->assertSession()->buildXPathQuery('//table/tbody/tr/td/a[contains(@href, :href) and contains(@title, :title) and text()=:text]', [
      ':href' => $comments[0]->permalink()->toString(),
      ':title' => Unicode::truncate($comments[0]->get('comment_body')->value, 128),
      ':text' => $comments[0]->getSubject(),
    ]));

    // Verify that anonymous author name is displayed correctly.     $this->assertSession()->pageTextContains($author_name . ' (not verified)');

    // Test that comment listing shows the correct subject link.     $this->assertSession()->elementExists('xpath', $this->assertSession()->buildXPathQuery('//table/tbody/tr/td/a[contains(@href, :href) and contains(@title, :title) and text()=:text]', [
      ':href' => $anonymous_comment4->permalink()->toString(),
      

  protected function helperButtonHasLabel($id$expected_label$message = 'Label has the expected value: %label.') {
    $xpath = $this->assertSession()->buildXPathQuery('//button[@id=:value]|//input[@id=:value]', [':value' => $id]);
    $field = $this->getSession()->getPage()->find('xpath', $xpath);

    if (empty($field)) {
      throw new ElementNotFoundException($this->getSession()->getDriver(), 'form field', 'id', $field);
    }

    $this->assertEquals($expected_label$field->getValue());
  }

  /** * Executes a view. * * @param \Drupal\views\ViewExecutable $view * The view object. * @param array $args * (optional) An array of the view arguments to use for the view. */

  }

  /** * Tests that elements are rendered properly. * * @internal */
  protected function assertRenderedElement(array $element, string $xpath, array $xpath_args = []): void {
    $this->render($element);

    $xpath = $this->buildXPathQuery($xpath$xpath_args);
    $element += ['#value' => NULL];
    $this->assertFieldByXPath($xpath$element['#value']new FormattableMarkup('#type @type was properly rendered.', [
      '@type' => var_export($element['#type'], TRUE),
    ]));
  }

}

  protected function assertDisabledTextarea(string $id): void {
    $textarea = $this->assertSession()->fieldDisabled($id);
    $this->assertSame('textarea', $textarea->getTagName());
    $this->assertSame('This field has been disabled because you do not have sufficient permissions to edit it.', $textarea->getText());
    // Make sure the text format select is not shown.     $select_id = str_replace('value', 'format--2', $id);
    $xpath = $this->assertSession()->buildXPathQuery('//select[@id=:id]', [':id' => $select_id]);
    $this->assertSession()->elementNotExists('xpath', $xpath);
  }

  /** * Helper function that returns a .po file with a given number of plural forms. */
  public function getPoFile($plurals) {
    $po_file = [];

    $po_file[1] = <<< EOF msgid "" msgstr "" "Project-Id-Version: Drupal 8\\n" "MIME-Version: 1.0\\n" "Content-Type: text/plain; charset=UTF-8\\n" "Content-Transfer-Encoding: 8bit\\n" "Plural-Forms: nplurals=1; plural=0;\\n"

  protected function xpathContent($content$xpath, array $arguments = []) {
    if ($elements = $this->parseContent($content)) {
      $xpath = $this->assertSession()->buildXPathQuery($xpath$arguments);
      $result = $elements->xpath($xpath);
      // Some combinations of PHP / libxml versions return an empty array       // instead of the documented FALSE. Forcefully convert any falsish values       // to an empty array to allow foreach(...) constructions.       return $result ? $result : [];
    }
    else {
      return FALSE;
    }
  }

  

      ];
      $this->drupalGet(Url::fromRoute('block.admin_library', ['theme' => $default_theme]$options));

      $block_name = 'system_powered_by_block';
      $add_url = Url::fromRoute('block.admin_add', [
        'plugin_id' => $block_name,
        'theme' => $default_theme,
      ]);

      // Verify that one link is found, with the expected link text.       $xpath = $this->assertSession()->buildXPathQuery('//a[contains(@href, :href)]', [':href' => $add_url->toString()]);
      $this->assertSession()->elementsCount('xpath', $xpath, 1);
      $this->assertSession()->elementTextEquals('xpath', $xpath, 'Place block');

      $link = $this->getSession()->getPage()->find('xpath', $xpath);
      [$path$query_string] = explode('?', $link->getAttribute('href'), 2);
      parse_str($query_string$query_parts);
      $this->assertEquals($weight$query_parts['weight'], 'Found the expected weight query string.');

      // Create a random title for the block.       $title = $this->randomMachineName(8);
      $block_id = strtolower($this->randomMachineName(8));
      
$this->clickLink('Edit');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->fieldValueEquals('label', $label);

    // Verify contact "View" tab exists.     $this->assertSession()->linkExists('View');

    // Test field UI and field integration.     $this->drupalGet('admin/structure/contact');

    // Test contact listing links to contact form.     $this->assertSession()->elementExists('xpath', $this->assertSession()->buildXPathQuery('//table/tbody/tr/td/a[contains(@href, :href) and text()=:text]', [
      ':href' => Url::fromRoute('entity.contact_form.canonical', ['contact_form' => $contact_form])->toString(),
      ':text' => $label,
    ]));

    // Find out in which row the form we want to add a field to is.     foreach ($this->xpath('//table/tbody/tr') as $row) {
      if ($row->findLink($label)) {
        $row->clickLink('Manage fields');
        break;
      }
    }

    
$char = mb_strtolower(substr($term->label(), 0, 1));
      $initials += [$char => 0];
      $initials[$char]++;
    }

    $this->drupalGet('test_taxonomy_glossary');
    $assert_session = $this->assertSession();

    foreach ($initials as $char => $count) {
      $href = Url::fromUserInput('/test_taxonomy_glossary/' . $char)->toString();

      $xpath = $assert_session->buildXPathQuery('//a[@href=:href and normalize-space(text())=:label]', [
        ':href' => $href,
        ':label' => $char,
      ]);
      $link = $assert_session->elementExists('xpath', $xpath);

      // Assert that the expected number of results is indicated in the link.       preg_match("/{$char} \(([0-9]+)\)/", $link->getParent()->getText()$matches);
      $this->assertEquals($count$matches[1]);
    }

    // Check that no other glossary links but the expected ones have been

  public function testPreviewContextual() {
    \Drupal::service('module_installer')->install(['contextual']);
    $this->resetAll();

    $this->drupalGet('admin/structure/views/view/test_preview/edit');
    $this->assertSession()->statusCodeEquals(200);
    $this->submitForm($edit = [], 'Update preview');

    // Verify that the contextual link to add a new field is shown.     $selector = $this->assertSession()->buildXPathQuery('//div[@id="views-live-preview"]//ul[contains(@class, :ul-class)]/li/a[contains(@href, :href)]', [
      ':ul-class' => 'contextual-links',
      ':href' => '/admin/structure/views/nojs/add-handler/test_preview/default/filter',
    ]);
    $this->assertSession()->elementsCount('xpath', $selector, 1);

    $this->submitForm(['view_args' => '100'], 'Update preview');

    // Test that area text and exposed filters are present and rendered.     $this->assertSession()->fieldExists('id');
    $this->assertSession()->pageTextContains('Test header text');
    $this->assertSession()->pageTextContains('Test footer text');
    

  public function linkByHrefExists($href$index = 0, $message = '') {
    $xpath = $this->buildXPathQuery('//a[contains(@href, :href)]', [':href' => $href]);
    $message = ($message ? $message : strtr('No link containing href %href found.', ['%href' => $href]));
    $links = $this->session->getPage()->findAll('xpath', $xpath);
    $this->assert(!empty($links[$index])$message);
  }

  /** * Passes if a link containing a given href (part) is not found. * * @param string $href * The full or partial value of the 'href' attribute of the anchor tag. * @param string $message * (optional) A message to display with the assertion. Do not translate * messages: use \Drupal\Component\Render\FormattableMarkup to embed * variables in the message text, not t(). If left blank, a default message * will be displayed. * * @throws \Behat\Mink\Exception\ExpectationException * Thrown when element doesn't exist, or the link label is a different one. */
Home | Imprint | This part of the site doesn't use cookies.