WebAssert.php 20.8 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Tests;

5
use Behat\Mink\Exception\ExpectationException;
6
use Behat\Mink\Exception\ResponseTextException;
7 8 9
use Behat\Mink\WebAssert as MinkWebAssert;
use Behat\Mink\Element\TraversableElement;
use Behat\Mink\Exception\ElementNotFoundException;
10
use Behat\Mink\Session;
11
use Drupal\Component\Utility\Html;
12
use Drupal\Core\Url;
13 14 15 16 17 18

/**
 * Defines a class with methods for asserting presence of elements during tests.
 */
class WebAssert extends MinkWebAssert {

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
  /**
   * The absolute URL of the site under test.
   *
   * @var string
   */
  protected $baseUrl = '';

  /**
   * Constructor.
   *
   * @param \Behat\Mink\Session $session
   *   The Behat session object;
   * @param string $base_url
   *   The base URL of the site under test.
   */
  public function __construct(Session $session, $base_url = '') {
    parent::__construct($session);
    $this->baseUrl = $base_url;
  }

  /**
   * {@inheritdoc}
   */
  protected function cleanUrl($url) {
43 44 45
    if ($url instanceof Url) {
      $url = $url->setAbsolute()->toString();
    }
46 47 48 49 50 51 52 53 54 55 56 57
    // Strip the base URL from the beginning for absolute URLs.
    if ($this->baseUrl !== '' && strpos($url, $this->baseUrl) === 0) {
      $url = substr($url, strlen($this->baseUrl));
    }
    // Make sure there is a forward slash at the beginning of relative URLs for
    // consistency.
    if (parse_url($url, PHP_URL_HOST) === NULL && strpos($url, '/') !== 0) {
      $url = "/$url";
    }
    return parent::cleanUrl($url);
  }

58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  /**
   * Checks that specific button exists on the current page.
   *
   * @param string $button
   *   One of id|name|label|value for the button.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @return \Behat\Mink\Element\NodeElement
   *   The matching element.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   *   When the element doesn't exist.
   */
  public function buttonExists($button, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
    $node = $container->findButton($button);

    if ($node === NULL) {
      throw new ElementNotFoundException($this->session, 'button', 'id|name|label|value', $button);
    }

    return $node;
  }

83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  /**
   * Checks that the specific button does NOT exist on the current page.
   *
   * @param string $button
   *   One of id|name|label|value for the button.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @throws \Behat\Mink\Exception\ExpectationException
   *   When the button exists.
   */
  public function buttonNotExists($button, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
    $node = $container->findButton($button);

    $this->assert(NULL === $node, sprintf('A button "%s" appears on this page, but it should not.', $button));
  }

101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  /**
   * Checks that specific select field exists on the current page.
   *
   * @param string $select
   *   One of id|name|label|value for the select field.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @return \Behat\Mink\Element\NodeElement
   *   The matching element
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   *   When the element doesn't exist.
   */
  public function selectExists($select, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
117
    $node = $container->find('named', [
118
      'select',
119
      $select,
120
    ]);
121 122 123 124 125 126 127 128

    if ($node === NULL) {
      throw new ElementNotFoundException($this->session, 'select', 'id|name|label|value', $select);
    }

    return $node;
  }

129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
  /**
   * Checks that specific option in a select field exists on the current page.
   *
   * @param string $select
   *   One of id|name|label|value for the select field.
   * @param string $option
   *   The option value.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @return \Behat\Mink\Element\NodeElement
   *   The matching option element
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   *   When the element doesn't exist.
   */
  public function optionExists($select, $option, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
147
    $select_field = $container->find('named', [
148
      'select',
149
      $select,
150
    ]);
151 152 153 154 155

    if ($select_field === NULL) {
      throw new ElementNotFoundException($this->session, 'select', 'id|name|label|value', $select);
    }

156
    $option_field = $select_field->find('named', ['option', $option]);
157 158

    if ($option_field === NULL) {
159
      throw new ElementNotFoundException($this->session->getDriver(), 'select', 'id|name|label|value', $option);
160 161 162 163 164 165 166 167 168 169 170
    }

    return $option_field;
  }

  /**
   * Checks that an option in a select field does NOT exist on the current page.
   *
   * @param string $select
   *   One of id|name|label|value for the select field.
   * @param string $option
171
   *   The option value that should not exist.
172 173 174 175 176 177 178 179
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   *   When the select element doesn't exist.
   */
  public function optionNotExists($select, $option, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
180
    $select_field = $container->find('named', [
181
      'select',
182
      $select,
183
    ]);
184 185 186 187 188

    if ($select_field === NULL) {
      throw new ElementNotFoundException($this->session, 'select', 'id|name|label|value', $select);
    }

189
    $option_field = $select_field->find('named', ['option', $option]);
190 191 192 193

    $this->assert($option_field === NULL, sprintf('An option "%s" exists in select "%s", but it should not.', $option, $select));
  }

194 195 196 197 198 199 200 201 202 203 204 205
  /**
   * Pass if the page title is the given string.
   *
   * @param string $expected_title
   *   The string the page title should be.
   *
   * @throws \Behat\Mink\Exception\ExpectationException
   *   Thrown when element doesn't exist, or the title is a different one.
   */
  public function titleEquals($expected_title) {
    $title_element = $this->session->getPage()->find('css', 'title');
    if (!$title_element) {
206
      throw new ExpectationException('No title element found on the page', $this->session->getDriver());
207 208 209 210 211 212 213 214 215 216
    }
    $actual_title = $title_element->getText();
    $this->assert($expected_title === $actual_title, 'Title found');
  }

  /**
   * Passes if a link with the specified label is found.
   *
   * An optional link index may be passed.
   *
217
   * @param string $label
218 219 220 221 222 223 224 225 226 227 228 229 230 231
   *   Text between the anchor tags.
   * @param int $index
   *   Link position counting from zero.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
   *   messages: use strtr() 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.
   */
  public function linkExists($label, $index = 0, $message = '') {
    $message = ($message ? $message : strtr('Link with label %label found.', ['%label' => $label]));
    $links = $this->session->getPage()->findAll('named', ['link', $label]);
232 233 234
    $this->assert(!empty($links[$index]), $message);
  }

235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
  /**
   * Passes if a link with the exactly specified label is found.
   *
   * An optional link index may be passed.
   *
   * @param string $label
   *   Text between the anchor tags.
   * @param int $index
   *   Link position counting from zero.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
   *   messages: use strtr() 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.
   */
  public function linkExistsExact($label, $index = 0, $message = '') {
    $message = ($message ? $message : strtr('Link with label %label found.', ['%label' => $label]));
    $links = $this->session->getPage()->findAll('named_exact', ['link', $label]);
    $this->assert(!empty($links[$index]), $message);
  }

258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  /**
   * Passes if a link with the specified label is not found.
   *
   * An optional link index may be passed.
   *
   * @param string $label
   *   Text between the anchor tags.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
   *   messages: use strtr() 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.
   */
  public function linkNotExists($label, $message = '') {
274
    $message = ($message ? $message : strtr('Link with label %label not found.', ['%label' => $label]));
275 276 277 278
    $links = $this->session->getPage()->findAll('named', ['link', $label]);
    $this->assert(empty($links), $message);
  }

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
  /**
   * Passes if a link with the exactly specified label is not found.
   *
   * An optional link index may be passed.
   *
   * @param string $label
   *   Text between the anchor tags.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
   *   messages: use strtr() 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.
   */
  public function linkNotExistsExact($label, $message = '') {
    $message = ($message ? $message : strtr('Link with label %label not found.', ['%label' => $label]));
    $links = $this->session->getPage()->findAll('named_exact', ['link', $label]);
    $this->assert(empty($links), $message);
  }

300 301 302 303 304 305 306 307 308
  /**
   * Passes if a link containing a given href (part) is found.
   *
   * @param string $href
   *   The full or partial value of the 'href' attribute of the anchor tag.
   * @param int $index
   *   Link position counting from zero.
   * @param string $message
   *   (optional) A message to display with the assertion. Do not translate
309
   *   messages: use \Drupal\Component\Render\FormattableMarkup to embed
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
   *   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.
   */
  public function linkByHrefExists($href, $index = 0, $message = '') {
    $xpath = $this->buildXPathQuery('//a[contains(@href, :href)]', [':href' => $href]);
    $message = ($message ? $message : strtr('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
330
   *   messages: use \Drupal\Component\Render\FormattableMarkup to embed
331 332 333 334 335 336 337 338
   *   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.
   */
  public function linkByHrefNotExists($href, $message = '') {
    $xpath = $this->buildXPathQuery('//a[contains(@href, :href)]', [':href' => $href]);
339
    $message = ($message ? $message : strtr('No link containing href %href found.', ['%href' => $href]));
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    $links = $this->session->getPage()->findAll('xpath', $xpath);
    $this->assert(empty($links), $message);
  }

  /**
   * Builds an XPath query.
   *
   * Builds an XPath query by replacing placeholders in the query by the value
   * of the arguments.
   *
   * XPath 1.0 (the version supported by libxml2, the underlying XML library
   * used by PHP) doesn't support any form of quotation. This function
   * simplifies the building of XPath expression.
   *
   * @param string $xpath
   *   An XPath query, possibly with placeholders in the form ':name'.
   * @param array $args
   *   An array of arguments with keys in the form ':name' matching the
   *   placeholders in the query. The values may be either strings or numeric
   *   values.
   *
   * @return string
   *   An XPath query with arguments replaced.
   */
364
  public function buildXPathQuery($xpath, array $args = []) {
365 366 367
    // Replace placeholders.
    foreach ($args as $placeholder => $value) {
      if (is_object($value)) {
368
        throw new \InvalidArgumentException('Just pass in scalar values for $args and remove all t() calls from your test.');
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
      }
      // XPath 1.0 doesn't support a way to escape single or double quotes in a
      // string literal. We split double quotes out of the string, and encode
      // them separately.
      if (is_string($value)) {
        // Explode the text at the quote characters.
        $parts = explode('"', $value);

        // Quote the parts.
        foreach ($parts as &$part) {
          $part = '"' . $part . '"';
        }

        // Return the string.
        $value = count($parts) > 1 ? 'concat(' . implode(', \'"\', ', $parts) . ')' : $parts[0];
      }

      // Use preg_replace_callback() instead of preg_replace() to prevent the
      // regular expression engine from trying to substitute backreferences.
      $replacement = function ($matches) use ($value) {
        return $value;
      };
      $xpath = preg_replace_callback('/' . preg_quote($placeholder) . '\b/', $replacement, $xpath);
392
    }
393
    return $xpath;
394 395 396 397 398 399 400 401 402 403 404
  }

  /**
   * Passes if the raw text IS NOT found escaped on the loaded page.
   *
   * Raw text refers to the raw HTML that the page generated.
   *
   * @param string $raw
   *   Raw (HTML) string to look for.
   */
  public function assertNoEscaped($raw) {
405 406 407 408 409 410 411 412 413 414 415 416 417
    $this->responseNotContains(Html::escape($raw));
  }

  /**
   * Passes if the raw text IS found escaped on the loaded page.
   *
   * Raw text refers to the raw HTML that the page generated.
   *
   * @param string $raw
   *   Raw (HTML) string to look for.
   */
  public function assertEscaped($raw) {
    $this->responseContains(Html::escape($raw));
418 419
  }

420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
  /**
   * Checks that page HTML (response content) contains text.
   *
   * @param string|object $text
   *   Text value. Any non-string value will be cast to string.
   *
   * @throws ExpectationException
   */
  public function responseContains($text) {
    parent::responseContains((string) $text);
  }

  /**
   * Checks that page HTML (response content) does not contains text.
   *
   * @param string|object $text
   *   Text value. Any non-string value will be cast to string.
   *
   * @throws ExpectationException
   */
  public function responseNotContains($text) {
    parent::responseNotContains((string) $text);
  }

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
  /**
   * Asserts a condition.
   *
   * The parent method is overridden because it is a private method.
   *
   * @param bool $condition
   *   The condition.
   * @param string $message
   *   The success message.
   *
   * @throws \Behat\Mink\Exception\ExpectationException
   *   When the condition is not fulfilled.
   */
  public function assert($condition, $message) {
    if ($condition) {
      return;
    }

    throw new ExpectationException($message, $this->session->getDriver());
  }

465 466 467 468 469 470 471 472 473 474 475 476 477 478
  /**
   * Checks that a given form field element is disabled.
   *
   * @param string $field
   *   One of id|name|label|value for the field.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @return \Behat\Mink\Element\NodeElement
   *   The matching element.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   */
479
  public function fieldDisabled($field, TraversableElement $container = NULL) {
480 481 482 483 484 485 486 487 488 489 490 491 492 493
    $container = $container ?: $this->session->getPage();
    $node = $container->findField($field);

    if ($node === NULL) {
      throw new ElementNotFoundException($this->session->getDriver(), 'field', 'id|name|label|value', $field);
    }

    if (!$node->hasAttribute('disabled')) {
      throw new ExpectationException("Field $field is disabled", $this->session->getDriver());
    }

    return $node;
  }

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
  /**
   * Checks that specific hidden field exists.
   *
   * @param string $field
   *   One of id|name|value for the hidden field.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @return \Behat\Mink\Element\NodeElement
   *   The matching element.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   */
  public function hiddenFieldExists($field, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
    if ($node = $container->find('hidden_field_selector', ['hidden_field', $field])) {
      return $node;
    }
    throw new ElementNotFoundException($this->session->getDriver(), 'form hidden field', 'id|name|value', $field);
  }

  /**
516
   * Checks that specific hidden field does not exist.
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572
   *
   * @param string $field
   *   One of id|name|value for the hidden field.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @throws \Behat\Mink\Exception\ExpectationException
   */
  public function hiddenFieldNotExists($field, TraversableElement $container = NULL) {
    $container = $container ?: $this->session->getPage();
    $node = $container->find('hidden_field_selector', ['hidden_field', $field]);
    $this->assert($node === NULL, "A hidden field '$field' exists on this page, but it should not.");
  }

  /**
   * Checks that specific hidden field have provided value.
   *
   * @param string $field
   *   One of id|name|value for the hidden field.
   * @param string $value
   *   The hidden field value that needs to be checked.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   */
  public function hiddenFieldValueEquals($field, $value, TraversableElement $container = NULL) {
    $node = $this->hiddenFieldExists($field, $container);
    $actual = $node->getValue();
    $regex = '/^' . preg_quote($value, '/') . '$/ui';
    $message = "The hidden field '$field' value is '$actual', but '$value' expected.";
    $this->assert((bool) preg_match($regex, $actual), $message);
  }

  /**
   * Checks that specific hidden field doesn't have the provided value.
   *
   * @param string $field
   *   One of id|name|value for the hidden field.
   * @param string $value
   *   The hidden field value that needs to be checked.
   * @param \Behat\Mink\Element\TraversableElement $container
   *   (optional) The document to check against. Defaults to the current page.
   *
   * @throws \Behat\Mink\Exception\ElementNotFoundException
   * @throws \Behat\Mink\Exception\ExpectationException
   */
  public function hiddenFieldValueNotEquals($field, $value, TraversableElement $container = NULL) {
    $node = $this->hiddenFieldExists($field, $container);
    $actual = $node->getValue();
    $regex = '/^' . preg_quote($value, '/') . '$/ui';
    $message = "The hidden field '$field' value is '$actual', but it should not be.";
    $this->assert(!preg_match($regex, $actual), $message);
  }

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
  /**
   * Checks that current page contains text only once.
   *
   * @param string $text
   *   The string to look for.
   *
   * @see \Behat\Mink\WebAssert::pageTextContains()
   */
  public function pageTextContainsOnce($text) {
    $actual = $this->session->getPage()->getText();
    $actual = preg_replace('/\s+/u', ' ', $actual);
    $regex = '/' . preg_quote($text, '/') . '/ui';
    $count = preg_match_all($regex, $actual);
    if ($count === 1) {
      return;
    }

    if ($count > 1) {
      $message = sprintf('The text "%s" appears in the text of this page more than once, but it should not.', $text);
    }
    else {
      $message = sprintf('The text "%s" was not found anywhere in the text of the current page.', $text);
    }

    throw new ResponseTextException($message, $this->session->getDriver());
  }

600
}