xpath example

// Check that the source field is correctly assigned to media type.     $this->drupalGet("admin/structure/media/manage/{$mediaTypeMachineName}");

    $assert_session->pageTextContains('Test source field is used to store the essential information about the media item.');

    // Check that the plugin cannot be changed after it is set on type creation.     $assert_session->fieldDisabled('Media source');
    $assert_session->pageTextContains('The media source cannot be changed after the media type is created.');

    // Check that the field map options are sorted alphabetically.     $options = $this->xpath('//select[@name="field_map[attribute_1]"]/option');
    $this->assertGreaterThanOrEqual(3, count($options));
    $this->assertSame('- Skip field -', $options[0]->getText());
    $this->assertSame('Name', $options[1]->getText());
    $this->assertSame('Test source', $options[2]->getText());

    // Open up the media add form and verify that the source field is right     // after the name, and before the vertical tabs.     $this->drupalGet("/media/add/$mediaTypeMachineName");

    // Get the form element, and its HTML representation.     $form_selector = '#media-' . Html::cleanCssIdentifier($mediaTypeMachineName) . '-add-form';
    
foreach ($this->langcodes as $langcode) {
      $this->drupalGet('node', ['language' => \Drupal::languageManager()->getLanguage($langcode)]);
      $num_match_found = 0;
      if ($langcode == 'en') {
        // Site default language does not have langcode prefix in the URL.         $expected_href = $base_path . $node_href;
      }
      else {
        $expected_href = $base_path . $langcode . '/' . $node_href;
      }
      $pattern = '|^' . $expected_href . '$|';
      foreach ($this->xpath("//a[text()='Read more']") as $link) {
        if (preg_match($pattern$link->getAttribute('href')$matches) == TRUE) {
          $num_match_found++;
        }
      }
      $this->assertSame(1, $num_match_found, 'There is 1 Read more link, ' . $expected_href . ', for the ' . $langcode . ' translation of a node on the frontpage. (Found ' . $num_match_found . '.)');
    }

    // Check the frontpage for 'Add new comment' links that include the     // language.     $comment_form_href = 'node/' . $node->id() . '#comment-form';
    foreach ($this->langcodes as $langcode) {
      
// Edit the menu.     $new_label = $this->randomMachineName(16);
    $menu->set('label', $new_label);
    $menu->save();
    $this->drupalGet('admin/structure/menu/manage/' . $menu_name);
    $this->assertSession()->pageTextContains($new_label);

    // Delete the custom menu via the UI to testing destination handling.     $this->drupalGet('admin/structure/menu');
    $this->assertSession()->pageTextContains($new_label);
    // Click the "Delete menu" operation in the Tools row.     $links = $this->xpath('//*/td[contains(text(),:menu_label)]/following::a[normalize-space()=:link_label]', [':menu_label' => $new_label, ':link_label' => 'Delete menu']);
    $links[0]->click();
    $this->submitForm([], 'Delete');
    $this->assertSession()->addressEquals('admin/structure/menu');
    $this->assertSession()->responseContains("The menu <em class=\"placeholder\">$new_label</em> has been deleted.");
  }

  /** * Creates a custom menu. * * @return \Drupal\system\Entity\Menu * The custom menu that has been created. */

  protected function assertLocalTasks(array $routes, int $level = 0): void {
    $elements = $this->xpath('//*[contains(@class, :class)]//a', [
      ':class' => $level == 0 ? 'tabs primary' : 'tabs secondary',
    ]);
    $this->assertGreaterThan(0, count($elements), 'Local tasks found.');
    foreach ($routes as $index => $route_info) {
      [$route_name$route_parameters] = $route_info;
      $expected = Url::fromRoute($route_name$route_parameters)->toString();
      $this->assertEquals($expected$elements[$index]->getAttribute('href'), "Task " . ($index + 1) . "number href " . $elements[$index]->getAttribute('href') . " equals $expected.");
    }
    $this->assertEquals(count($routes)count($elements), 'Only expected local tasks are found.');
  }

  
$this->executeView($view);
    $exposed_form = $view->display_handler->getPlugin('exposed_form');
    $output = $exposed_form->renderExposedForm();
    $this->setRawContent(\Drupal::service('renderer')->renderRoot($output));

    $this->assertFieldByXpath('//form/@id', Html::cleanCssIdentifier('views-exposed-form-' . $view->storage->id() . '-' . $view->current_display), 'Expected form ID found.');

    $view->setDisplay('page_1');
    $expected_action = $view->display_handler->getUrlInfo()->toString();
    $this->assertFieldByXPath('//form/@action', $expected_action, 'The expected value for the action attribute was found.');
    // Make sure the description is shown.     $result = $this->xpath('//form//div[contains(@id, "edit-type--2--description") and normalize-space(text())="Exposed description"]');
    $this->assertCount(1, $result, 'Filter description was found.');
  }

  /** * Tests the exposed form raw input. */
  public function testExposedFormRawInput() {
    $node_type = NodeType::create(['type' => 'article']);
    $node_type->save();

    $view = Views::getView('test_exposed_form_buttons');
    

  protected function doTestLanguageBlockAuthenticated($block_label) {
    // Assert that the language switching block is displayed on the frontpage.     $this->drupalGet('');
    $this->assertSession()->pageTextContains($block_label);

    // Assert that each list item and anchor element has the appropriate data-     // attributes.     $language_switchers = $this->xpath('//div[@id=:id]/ul/li', [':id' => 'block-test-language-block']);
    $list_items = [];
    $anchors = [];
    $labels = [];
    foreach ($language_switchers as $list_item) {
      $list_items[] = [
        'hreflang' => $list_item->getAttribute('hreflang'),
        'data-drupal-link-system-path' => $list_item->getAttribute('data-drupal-link-system-path'),
      ];

      $link = $list_item->find('xpath', 'a');
      $anchors[] = [
        
$edit['options[group_info][group_items][2][title]'] = 'Not published';
    $edit['options[group_info][group_items][2][operator]'] = '=';
    $edit['options[group_info][group_items][2][value]'] = 0;
    $edit['options[group_info][group_items][3][title]'] = 'Not published2';
    $edit['options[group_info][group_items][3][operator]'] = '!=';
    $edit['options[group_info][group_items][3][value]'] = 1;

    $this->submitForm($edit, 'Apply');

    $this->drupalGet('admin/structure/views/nojs/handler/test_view/default/filter/status');

    $result = $this->xpath('//input[@name="options[group_info][group_items][1][value]"]');
    $this->assertEquals('checked', $result[1]->getAttribute('checked'));
    $result = $this->xpath('//input[@name="options[group_info][group_items][2][value]"]');
    $this->assertEquals('checked', $result[2]->getAttribute('checked'));
    $result = $this->xpath('//input[@name="options[group_info][group_items][3][value]"]');
    $this->assertEquals('checked', $result[1]->getAttribute('checked'));

    // Test that there is a remove link for each group.     $this->assertCount(3, $this->cssSelect('a.views-remove-link'));

    // Test selecting a default and removing an item.     $edit = [];
    
$checkboxes_some_disabled_element_value1 = $page->findField('checkboxes_some_disabled_when_checkbox_trigger_checked[value1]');
    $this->assertNotEmpty($checkboxes_some_disabled_element_value1);
    $checkboxes_some_disabled_element_value2 = $page->findField('checkboxes_some_disabled_when_checkbox_trigger_checked[value2]');
    $this->assertNotEmpty($checkboxes_some_disabled_element_value2);
    $checkboxes_some_disabled_element_value3 = $page->findField('checkboxes_some_disabled_when_checkbox_trigger_checked[value3]');

    $radios_checked_element = $page->findField('radios_checked_when_checkbox_trigger_checked');
    $this->assertNotEmpty($radios_checked_element);

    // We want to select the specific radio buttons, not the whole radios field itself.     $radios_all_disabled_value1 = $this->xpath('//input[@name=:name][@value=:value]', [':name' => 'radios_all_disabled_when_checkbox_trigger_checked', ':value' => 'value1']);
    $this->assertCount(1, $radios_all_disabled_value1);
    // We want to access the radio button directly for the rest of the test, so     // take it out of the array we got back from xpath().     $radios_all_disabled_value1 = reset($radios_all_disabled_value1);
    $radios_all_disabled_value2 = $this->xpath('//input[@name=:name][@value=:value]', [':name' => 'radios_all_disabled_when_checkbox_trigger_checked', ':value' => 'value2']);
    $this->assertCount(1, $radios_all_disabled_value2);
    $radios_all_disabled_value2 = reset($radios_all_disabled_value2);

    $radios_some_disabled_value1 = $this->xpath('//input[@name=:name][@value=:value]', [':name' => 'radios_some_disabled_when_checkbox_trigger_checked', ':value' => 'value1']);
    $this->assertCount(1, $radios_some_disabled_value1);
    $radios_some_disabled_value1 = reset($radios_some_disabled_value1);
    

  public function testAttributes() {

    /** @var \Drupal\Core\Form\FormBuilderInterface $form_builder */
    $form_builder = $this->container->get('form_builder');
    $form_state = new FormState();
    $elements = $form_builder->buildForm($this$form_state);
    $this->render($elements);

    $css_selector_converter = new CssSelectorConverter();
    $elements = $this->xpath($css_selector_converter->toXPath('input[name=title][maxlength=255]'));
    $this->assertCount(1, $elements, 'Text field has correct maxlength in form.');
    $elements = $this->xpath($css_selector_converter->toXPath('textarea[name=description][maxlength=255]'));
    $this->assertCount(1, $elements, 'Textarea field has correct maxlength in form.');
  }

}
$original_request = $request_stack->pop();
    // Just request some more so there is no request left.     $request_stack->pop();
    $request_stack->pop();
    $request = Request::create($original_request->getSchemeAndHttpHost() . '/test/"injected=\'attribute\'close="');
    $request_stack->push($request);

    $form = \Drupal::formBuilder()->getForm($this);
    $markup = \Drupal::service('renderer')->renderRoot($form);
    $this->setRawContent($markup);

    $elements = $this->xpath('//form');
    $action = isset($elements[0]['action']) ? (string) $elements[0]['action'] : FALSE;
    $injected = isset($elements[0]['injected']) ? (string) $elements[0]['injected'] : FALSE;

    $this->assertSame('/test/"injected=\'attribute\'close="', $action);
    $this->assertRaw('action="/test/&quot;injected=&#039;attribute&#039;close=&quot;"');
    $this->assertNotSame('attribute', $injected);
  }

}
// How many uploaded files for the current field are remaining.       $remaining = 3;
      // Test clicking each "Remove" button. For extra robustness, test them out       // of sequential order. They are 0-indexed, and get renumbered after each       // iteration, so array(1, 1, 0) means:       // - First remove the 2nd file.       // - Then remove what is then the 2nd file (was originally the 3rd file).       // - Then remove the first file.       foreach ([1, 1, 0] as $delta) {
        // Ensure we have the expected number of Remove buttons, and that they         // are numbered sequentially.         $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
        $this->assertCount($num_expected_remove_buttons$buttonsnew FormattableMarkup('There are %n "Remove" buttons displayed.', ['%n' => $num_expected_remove_buttons]));
        foreach ($buttons as $i => $button) {
          $key = $i >= $remaining ? $i - $remaining : $i;
          $check_field_name = $field_name2;
          if ($current_field_name == $field_name && $i < $remaining) {
            $check_field_name = $field_name;
          }

          $this->assertSame($check_field_name . '_' . $key . '_remove_button', $button->getAttribute('name'));
        }

        
    $edit = [
      'title[0][value]' => $this->randomString(),
    ];
    $this->submitForm($edit, 'Save');
    $this->assertSession()->pageTextContains('Test file field is required.');

    // Ensure that the form contains two items in the multi-valued field, so we     // know we're testing a form that was correctly retrieved from cache.     $this->assertSession()->elementsCount('xpath', '//form[contains(@id, "node-page-form")]//div[contains(@class, "js-form-item-field-ajax-test")]//input[@type="text"]', 2);

    // Ensure that the form's action is correct.     $forms = $this->xpath('//form[contains(@class, "node-page-form")]');
    $this->assertCount(1, $forms);
    // Strip query params off the action before asserting.     $url = parse_url($forms[0]->getAttribute('action'))['path'];
    $this->assertEquals(Url::fromRoute('node.add', ['node_type' => 'page'])->toString()$url);
  }

}
$expected[] = $form[$key]['#required_error'];
      }
      elseif (isset($form[$key]['#form_test_required_error'])) {
        $expected[] = $form[$key]['#form_test_required_error'];
      }
      else {
        $expected[] = $form[$key]['#title'] . ' field is required.';
      }
    }

    // Check the page for error messages.     $errors = $this->xpath('//div[contains(@class, "error")]//li');
    foreach ($errors as $error) {
      $expected_key = array_search($error->getText()$expected);
      // If the error message is not one of the expected messages, fail.       if ($expected_key === FALSE) {
        $this->fail(new FormattableMarkup("Unexpected error message: @error", ['@error' => $error[0]]));
      }
      // Remove the expected message from the list once it is found.       else {
        unset($expected[$expected_key]);
      }
    }

    


  /** * {@inheritdoc} */
  protected $defaultTheme = 'stark';

  /** * {@inheritdoc} */
  protected function getLogsEntriesTable() {
    return $this->xpath('.//div[contains(@class, "views-element-container")]//table/tbody/tr');
  }

  /** * {@inheritdoc} */
  protected function filterLogsEntries($type = NULL, $severity = NULL) {
    $query = [];
    if (isset($type)) {
      $query['type[]'] = $type;
    }
    if (isset($severity)) {
      

  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. */
Home | Imprint | This part of the site doesn't use cookies.