Chris@0: skipClasses[__CLASS__] = TRUE;
Chris@0: $this->classLoader = require DRUPAL_ROOT . '/autoload.php';
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Checks to see whether a block appears on the page.
Chris@0: *
Chris@0: * @param \Drupal\block\Entity\Block $block
Chris@0: * The block entity to find on the page.
Chris@0: */
Chris@0: protected function assertBlockAppears(Block $block) {
Chris@0: $result = $this->findBlockInstance($block);
Chris@0: $this->assertTrue(!empty($result), format_string('Ensure the block @id appears on the page', ['@id' => $block->id()]));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Checks to see whether a block does not appears on the page.
Chris@0: *
Chris@0: * @param \Drupal\block\Entity\Block $block
Chris@0: * The block entity to find on the page.
Chris@0: */
Chris@0: protected function assertNoBlockAppears(Block $block) {
Chris@0: $result = $this->findBlockInstance($block);
Chris@0: $this->assertFalse(!empty($result), format_string('Ensure the block @id does not appear on the page', ['@id' => $block->id()]));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Find a block instance on the page.
Chris@0: *
Chris@0: * @param \Drupal\block\Entity\Block $block
Chris@0: * The block entity to find on the page.
Chris@0: *
Chris@0: * @return array
Chris@0: * The result from the xpath query.
Chris@0: */
Chris@0: protected function findBlockInstance(Block $block) {
Chris@0: return $this->xpath('//div[@id = :id]', [':id' => 'block-' . $block->id()]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Log in a user with the internal browser.
Chris@0: *
Chris@0: * If a user is already logged in, then the current user is logged out before
Chris@0: * logging in the specified user.
Chris@0: *
Chris@0: * Please note that neither the current user nor the passed-in user object is
Chris@0: * populated with data of the logged in user. If you need full access to the
Chris@0: * user object after logging in, it must be updated manually. If you also need
Chris@0: * access to the plain-text password of the user (set by drupalCreateUser()),
Chris@0: * e.g. to log in the same user again, then it must be re-assigned manually.
Chris@0: * For example:
Chris@0: * @code
Chris@0: * // Create a user.
Chris@0: * $account = $this->drupalCreateUser(array());
Chris@0: * $this->drupalLogin($account);
Chris@0: * // Load real user object.
Chris@0: * $pass_raw = $account->pass_raw;
Chris@0: * $account = User::load($account->id());
Chris@0: * $account->pass_raw = $pass_raw;
Chris@0: * @endcode
Chris@0: *
Chris@0: * @param \Drupal\Core\Session\AccountInterface $account
Chris@0: * User object representing the user to log in.
Chris@0: *
Chris@0: * @see drupalCreateUser()
Chris@0: */
Chris@0: protected function drupalLogin(AccountInterface $account) {
Chris@0: if ($this->loggedInUser) {
Chris@0: $this->drupalLogout();
Chris@0: }
Chris@0:
Chris@0: $edit = [
Chris@18: 'name' => $account->getAccountName(),
Chris@17: 'pass' => $account->pass_raw,
Chris@0: ];
Chris@0: $this->drupalPostForm('user/login', $edit, t('Log in'));
Chris@0:
Chris@0: // @see WebTestBase::drupalUserIsLoggedIn()
Chris@0: if (isset($this->sessionId)) {
Chris@0: $account->session_id = $this->sessionId;
Chris@0: }
Chris@18: $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', ['%name' => $account->getAccountName()]), 'User login');
Chris@0: if ($pass) {
Chris@0: $this->loggedInUser = $account;
Chris@0: $this->container->get('current_user')->setAccount($account);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns whether a given user account is logged in.
Chris@0: *
Chris@0: * @param \Drupal\user\UserInterface $account
Chris@0: * The user account object to check.
Chris@0: */
Chris@0: protected function drupalUserIsLoggedIn($account) {
Chris@0: $logged_in = FALSE;
Chris@0:
Chris@0: if (isset($account->session_id)) {
Chris@0: $session_handler = $this->container->get('session_handler.storage');
Chris@0: $logged_in = (bool) $session_handler->read($account->session_id);
Chris@0: }
Chris@0:
Chris@0: return $logged_in;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Logs a user out of the internal browser and confirms.
Chris@0: *
Chris@0: * Confirms logout by checking the login page.
Chris@0: */
Chris@0: protected function drupalLogout() {
Chris@0: // Make a request to the logout page, and redirect to the user page, the
Chris@0: // idea being if you were properly logged out you should be seeing a login
Chris@0: // screen.
Chris@0: $this->drupalGet('user/logout', ['query' => ['destination' => 'user/login']]);
Chris@0: $this->assertResponse(200, 'User was logged out.');
Chris@0: $pass = $this->assertField('name', 'Username field found.', 'Logout');
Chris@0: $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
Chris@0:
Chris@0: if ($pass) {
Chris@0: // @see WebTestBase::drupalUserIsLoggedIn()
Chris@0: unset($this->loggedInUser->session_id);
Chris@0: $this->loggedInUser = FALSE;
Chris@0: $this->container->get('current_user')->setAccount(new AnonymousUserSession());
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Sets up a Drupal site for running functional and integration tests.
Chris@0: *
Chris@0: * Installs Drupal with the installation profile specified in
Chris@0: * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
Chris@0: *
Chris@0: * Afterwards, installs any additional modules specified in the static
Chris@0: * \Drupal\simpletest\WebTestBase::$modules property of each class in the
Chris@0: * class hierarchy.
Chris@0: *
Chris@0: * After installation all caches are flushed and several configuration values
Chris@0: * are reset to the values of the parent site executing the test, since the
Chris@0: * default values may be incompatible with the environment in which tests are
Chris@0: * being executed.
Chris@0: */
Chris@0: protected function setUp() {
Chris@0: // Set an explicit time zone to not rely on the system one, which may vary
Chris@0: // from setup to setup. The Australia/Sydney time zone is chosen so all
Chris@0: // tests are run using an edge case scenario (UTC+10 and DST). This choice
Chris@0: // is made to prevent time zone related regressions and reduce the
Chris@0: // fragility of the testing system in general. This is also set in config in
Chris@0: // \Drupal\simpletest\WebTestBase::initConfig().
Chris@0: date_default_timezone_set('Australia/Sydney');
Chris@0:
Chris@0: // Preserve original batch for later restoration.
Chris@0: $this->setBatch();
Chris@0:
Chris@0: // Initialize user 1 and session name.
Chris@0: $this->initUserSession();
Chris@0:
Chris@0: // Prepare the child site settings.
Chris@0: $this->prepareSettings();
Chris@0:
Chris@0: // Execute the non-interactive installer.
Chris@0: $this->doInstall();
Chris@0:
Chris@0: // Import new settings.php written by the installer.
Chris@0: $this->initSettings();
Chris@0:
Chris@0: // Initialize the request and container post-install.
Chris@0: $container = $this->initKernel(\Drupal::request());
Chris@0:
Chris@0: // Initialize and override certain configurations.
Chris@0: $this->initConfig($container);
Chris@0:
Chris@0: // Collect modules to install.
Chris@0: $this->installModulesFromClassProperty($container);
Chris@0:
Chris@0: // Restore the original batch.
Chris@0: $this->restoreBatch();
Chris@0:
Chris@0: // Reset/rebuild everything.
Chris@0: $this->rebuildAll();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Preserve the original batch, and instantiate the test batch.
Chris@0: */
Chris@0: protected function setBatch() {
Chris@0: // When running tests through the Simpletest UI (vs. on the command line),
Chris@0: // Simpletest's batch conflicts with the installer's batch. Batch API does
Chris@0: // not support the concept of nested batches (in which the nested is not
Chris@0: // progressive), so we need to temporarily pretend there was no batch.
Chris@0: // Backup the currently running Simpletest batch.
Chris@0: $this->originalBatch = batch_get();
Chris@0:
Chris@0: // Reset the static batch to remove Simpletest's batch operations.
Chris@0: $batch = &batch_get();
Chris@0: $batch = [];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Restore the original batch.
Chris@0: *
Chris@0: * @see ::setBatch
Chris@0: */
Chris@0: protected function restoreBatch() {
Chris@0: // Restore the original Simpletest batch.
Chris@0: $batch = &batch_get();
Chris@0: $batch = $this->originalBatch;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Queues custom translations to be written to settings.php.
Chris@0: *
Chris@0: * Use WebTestBase::writeCustomTranslations() to apply and write the queued
Chris@0: * translations.
Chris@0: *
Chris@0: * @param string $langcode
Chris@0: * The langcode to add translations for.
Chris@0: * @param array $values
Chris@0: * Array of values containing the untranslated string and its translation.
Chris@0: * For example:
Chris@0: * @code
Chris@0: * array(
Chris@0: * '' => array('Sunday' => 'domingo'),
Chris@0: * 'Long month name' => array('March' => 'marzo'),
Chris@0: * );
Chris@0: * @endcode
Chris@0: * Pass an empty array to remove all existing custom translations for the
Chris@0: * given $langcode.
Chris@0: */
Chris@0: protected function addCustomTranslations($langcode, array $values) {
Chris@0: // If $values is empty, then the test expects all custom translations to be
Chris@0: // cleared.
Chris@0: if (empty($values)) {
Chris@0: $this->customTranslations[$langcode] = [];
Chris@0: }
Chris@0: // Otherwise, $values are expected to be merged into previously passed
Chris@0: // values, while retaining keys that are not explicitly set.
Chris@0: else {
Chris@0: foreach ($values as $context => $translations) {
Chris@0: foreach ($translations as $original => $translation) {
Chris@0: $this->customTranslations[$langcode][$context][$original] = $translation;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Writes custom translations to the test site's settings.php.
Chris@0: *
Chris@0: * Use TestBase::addCustomTranslations() to queue custom translations before
Chris@0: * calling this method.
Chris@0: */
Chris@0: protected function writeCustomTranslations() {
Chris@0: $settings = [];
Chris@0: foreach ($this->customTranslations as $langcode => $values) {
Chris@0: $settings_key = 'locale_custom_strings_' . $langcode;
Chris@0:
Chris@0: // Update in-memory settings directly.
Chris@0: $this->settingsSet($settings_key, $values);
Chris@0:
Chris@0: $settings['settings'][$settings_key] = (object) [
Chris@0: 'value' => $values,
Chris@0: 'required' => TRUE,
Chris@0: ];
Chris@0: }
Chris@0: // Only rewrite settings if there are any translation changes to write.
Chris@0: if (!empty($settings)) {
Chris@0: $this->writeSettings($settings);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Cleans up after testing.
Chris@0: *
Chris@0: * Deletes created files and temporary files directory, deletes the tables
Chris@0: * created by setUp(), and resets the database prefix.
Chris@0: */
Chris@0: protected function tearDown() {
Chris@0: // Destroy the testing kernel.
Chris@0: if (isset($this->kernel)) {
Chris@0: $this->kernel->shutdown();
Chris@0: }
Chris@0: parent::tearDown();
Chris@0:
Chris@0: // Ensure that the maximum meta refresh count is reset.
Chris@0: $this->maximumMetaRefreshCount = NULL;
Chris@0:
Chris@0: // Ensure that internal logged in variable and cURL options are reset.
Chris@0: $this->loggedInUser = FALSE;
Chris@0: $this->additionalCurlOptions = [];
Chris@0:
Chris@0: // Close the CURL handler and reset the cookies array used for upgrade
Chris@0: // testing so test classes containing multiple tests are not polluted.
Chris@0: $this->curlClose();
Chris@0: $this->curlCookies = [];
Chris@0: $this->cookies = [];
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Initializes the cURL connection.
Chris@0: *
Chris@0: * If the simpletest_httpauth_credentials variable is set, this function will
Chris@0: * add HTTP authentication headers. This is necessary for testing sites that
Chris@0: * are protected by login credentials from public access.
Chris@0: * See the description of $curl_options for other options.
Chris@0: */
Chris@0: protected function curlInitialize() {
Chris@0: global $base_url;
Chris@0:
Chris@0: if (!isset($this->curlHandle)) {
Chris@0: $this->curlHandle = curl_init();
Chris@0:
Chris@0: // Some versions/configurations of cURL break on a NULL cookie jar, so
Chris@0: // supply a real file.
Chris@0: if (empty($this->cookieFile)) {
Chris@0: $this->cookieFile = $this->publicFilesDirectory . '/cookie.jar';
Chris@0: }
Chris@0:
Chris@0: $curl_options = [
Chris@0: CURLOPT_COOKIEJAR => $this->cookieFile,
Chris@0: CURLOPT_URL => $base_url,
Chris@0: CURLOPT_FOLLOWLOCATION => FALSE,
Chris@0: CURLOPT_RETURNTRANSFER => TRUE,
Chris@0: // Required to make the tests run on HTTPS.
Chris@0: CURLOPT_SSL_VERIFYPEER => FALSE,
Chris@0: // Required to make the tests run on HTTPS.
Chris@0: CURLOPT_SSL_VERIFYHOST => FALSE,
Chris@0: CURLOPT_HEADERFUNCTION => [&$this, 'curlHeaderCallback'],
Chris@0: CURLOPT_USERAGENT => $this->databasePrefix,
Chris@0: // Disable support for the @ prefix for uploading files.
Chris@0: CURLOPT_SAFE_UPLOAD => TRUE,
Chris@0: ];
Chris@0: if (isset($this->httpAuthCredentials)) {
Chris@0: $curl_options[CURLOPT_HTTPAUTH] = $this->httpAuthMethod;
Chris@0: $curl_options[CURLOPT_USERPWD] = $this->httpAuthCredentials;
Chris@0: }
Chris@0: // curl_setopt_array() returns FALSE if any of the specified options
Chris@0: // cannot be set, and stops processing any further options.
Chris@0: $result = curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
Chris@0: if (!$result) {
Chris@0: throw new \UnexpectedValueException('One or more cURL options could not be set.');
Chris@0: }
Chris@0: }
Chris@0: // We set the user agent header on each request so as to use the current
Chris@0: // time and a new uniqid.
Chris@0: curl_setopt($this->curlHandle, CURLOPT_USERAGENT, drupal_generate_test_ua($this->databasePrefix));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Initializes and executes a cURL request.
Chris@0: *
Chris@0: * @param $curl_options
Chris@0: * An associative array of cURL options to set, where the keys are constants
Chris@0: * defined by the cURL library. For a list of valid options, see
Chris@0: * http://php.net/manual/function.curl-setopt.php
Chris@0: * @param $redirect
Chris@0: * FALSE if this is an initial request, TRUE if this request is the result
Chris@0: * of a redirect.
Chris@0: *
Chris@0: * @return
Chris@0: * The content returned from the call to curl_exec().
Chris@0: *
Chris@0: * @see curlInitialize()
Chris@0: */
Chris@0: protected function curlExec($curl_options, $redirect = FALSE) {
Chris@0: $this->curlInitialize();
Chris@0:
Chris@0: if (!empty($curl_options[CURLOPT_URL])) {
Chris@0: // cURL incorrectly handles URLs with a fragment by including the
Chris@0: // fragment in the request to the server, causing some web servers
Chris@0: // to reject the request citing "400 - Bad Request". To prevent
Chris@0: // this, we strip the fragment from the request.
Chris@0: // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
Chris@0: if (strpos($curl_options[CURLOPT_URL], '#')) {
Chris@0: $original_url = $curl_options[CURLOPT_URL];
Chris@0: $curl_options[CURLOPT_URL] = strtok($curl_options[CURLOPT_URL], '#');
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: $url = empty($curl_options[CURLOPT_URL]) ? curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL) : $curl_options[CURLOPT_URL];
Chris@0:
Chris@0: if (!empty($curl_options[CURLOPT_POST])) {
Chris@0: // This is a fix for the Curl library to prevent Expect: 100-continue
Chris@0: // headers in POST requests, that may cause unexpected HTTP response
Chris@0: // codes from some webservers (like lighttpd that returns a 417 error
Chris@0: // code). It is done by setting an empty "Expect" header field that is
Chris@0: // not overwritten by Curl.
Chris@0: $curl_options[CURLOPT_HTTPHEADER][] = 'Expect:';
Chris@0: }
Chris@0:
Chris@0: $cookies = [];
Chris@0: if (!empty($this->curlCookies)) {
Chris@0: $cookies = $this->curlCookies;
Chris@0: }
Chris@0:
Chris@0: foreach ($this->extractCookiesFromRequest(\Drupal::request()) as $cookie_name => $values) {
Chris@0: foreach ($values as $value) {
Chris@0: $cookies[] = $cookie_name . '=' . $value;
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: // Merge additional cookies in.
Chris@0: if (!empty($cookies)) {
Chris@0: $curl_options += [
Chris@0: CURLOPT_COOKIE => '',
Chris@0: ];
Chris@0: // Ensure any existing cookie data string ends with the correct separator.
Chris@0: if (!empty($curl_options[CURLOPT_COOKIE])) {
Chris@0: $curl_options[CURLOPT_COOKIE] = rtrim($curl_options[CURLOPT_COOKIE], '; ') . '; ';
Chris@0: }
Chris@0: $curl_options[CURLOPT_COOKIE] .= implode('; ', $cookies) . ';';
Chris@0: }
Chris@0:
Chris@0: curl_setopt_array($this->curlHandle, $this->additionalCurlOptions + $curl_options);
Chris@0:
Chris@0: if (!$redirect) {
Chris@0: // Reset headers, the session ID and the redirect counter.
Chris@0: $this->sessionId = NULL;
Chris@0: $this->headers = [];
Chris@0: $this->redirectCount = 0;
Chris@0: }
Chris@0:
Chris@0: $content = curl_exec($this->curlHandle);
Chris@0: $status = curl_getinfo($this->curlHandle, CURLINFO_HTTP_CODE);
Chris@0:
Chris@0: // cURL incorrectly handles URLs with fragments, so instead of
Chris@0: // letting cURL handle redirects we take of them ourselves to
Chris@0: // to prevent fragments being sent to the web server as part
Chris@0: // of the request.
Chris@0: // TODO: Remove this for Drupal 8, since fixed in curl 7.20.0.
Chris@0: if (in_array($status, [300, 301, 302, 303, 305, 307]) && $this->redirectCount < $this->maximumRedirects) {
Chris@0: if ($this->drupalGetHeader('location')) {
Chris@0: $this->redirectCount++;
Chris@0: $curl_options = [];
Chris@0: $curl_options[CURLOPT_URL] = $this->drupalGetHeader('location');
Chris@0: $curl_options[CURLOPT_HTTPGET] = TRUE;
Chris@0: return $this->curlExec($curl_options, TRUE);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: $this->setRawContent($content);
Chris@0: $this->url = isset($original_url) ? $original_url : curl_getinfo($this->curlHandle, CURLINFO_EFFECTIVE_URL);
Chris@0:
Chris@0: $message_vars = [
Chris@0: '@method' => !empty($curl_options[CURLOPT_NOBODY]) ? 'HEAD' : (empty($curl_options[CURLOPT_POSTFIELDS]) ? 'GET' : 'POST'),
Chris@0: '@url' => isset($original_url) ? $original_url : $url,
Chris@0: '@status' => $status,
Chris@17: '@length' => format_size(strlen($this->getRawContent())),
Chris@0: ];
Chris@17: $message = new FormattableMarkup('@method @url returned @status (@length).', $message_vars);
Chris@0: $this->assertTrue($this->getRawContent() !== FALSE, $message, 'Browser');
Chris@0: return $this->getRawContent();
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Reads headers and registers errors received from the tested site.
Chris@0: *
Chris@0: * @param $curlHandler
Chris@0: * The cURL handler.
Chris@0: * @param $header
Chris@0: * An header.
Chris@0: *
Chris@0: * @see _drupal_log_error()
Chris@0: */
Chris@0: protected function curlHeaderCallback($curlHandler, $header) {
Chris@0: // Header fields can be extended over multiple lines by preceding each
Chris@0: // extra line with at least one SP or HT. They should be joined on receive.
Chris@0: // Details are in RFC2616 section 4.
Chris@0: if ($header[0] == ' ' || $header[0] == "\t") {
Chris@0: // Normalize whitespace between chucks.
Chris@0: $this->headers[] = array_pop($this->headers) . ' ' . trim($header);
Chris@0: }
Chris@0: else {
Chris@0: $this->headers[] = $header;
Chris@0: }
Chris@0:
Chris@0: // Errors are being sent via X-Drupal-Assertion-* headers,
Chris@0: // generated by _drupal_log_error() in the exact form required
Chris@0: // by \Drupal\simpletest\WebTestBase::error().
Chris@0: if (preg_match('/^X-Drupal-Assertion-[0-9]+: (.*)$/', $header, $matches)) {
Chris@14: $parameters = unserialize(urldecode($matches[1]));
Chris@14: // Handle deprecation notices triggered by system under test.
Chris@14: if ($parameters[1] === 'User deprecated function') {
Chris@14: if (getenv('SYMFONY_DEPRECATIONS_HELPER') !== 'disabled') {
Chris@14: $message = (string) $parameters[0];
Chris@17: $test_info = TestDiscovery::getTestInfo(get_called_class());
Chris@17: if ($test_info['group'] !== 'legacy' && !in_array($message, DeprecationListenerTrait::getSkippedDeprecations())) {
Chris@14: call_user_func_array([&$this, 'error'], $parameters);
Chris@14: }
Chris@14: }
Chris@14: }
Chris@14: else {
Chris@14: // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
Chris@14: // the header.
Chris@14: call_user_func_array([&$this, 'error'], $parameters);
Chris@14: }
Chris@0: }
Chris@0:
Chris@0: // Save cookies.
Chris@0: if (preg_match('/^Set-Cookie: ([^=]+)=(.+)/', $header, $matches)) {
Chris@0: $name = $matches[1];
Chris@0: $parts = array_map('trim', explode(';', $matches[2]));
Chris@0: $value = array_shift($parts);
Chris@0: $this->cookies[$name] = ['value' => $value, 'secure' => in_array('secure', $parts)];
Chris@0: if ($name === $this->getSessionName()) {
Chris@0: if ($value != 'deleted') {
Chris@0: $this->sessionId = $value;
Chris@0: }
Chris@0: else {
Chris@0: $this->sessionId = NULL;
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: // This is required by cURL.
Chris@0: return strlen($header);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Close the cURL handler and unset the handler.
Chris@0: */
Chris@0: protected function curlClose() {
Chris@0: if (isset($this->curlHandle)) {
Chris@0: curl_close($this->curlHandle);
Chris@0: unset($this->curlHandle);
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Returns whether the test is being executed from within a test site.
Chris@0: *
Chris@0: * Mainly used by recursive tests (i.e. to test the testing framework).
Chris@0: *
Chris@0: * @return bool
Chris@0: * TRUE if this test was instantiated in a request within the test site,
Chris@0: * FALSE otherwise.
Chris@0: *
Chris@0: * @see \Drupal\Core\DrupalKernel::bootConfiguration()
Chris@0: */
Chris@0: protected function isInChildSite() {
Chris@0: return DRUPAL_TEST_IN_CHILD_SITE;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves a Drupal path or an absolute path.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Drupal path or URL to load into internal browser
Chris@0: * @param $options
Chris@0: * Options to be forwarded to the url generator.
Chris@0: * @param $headers
Chris@0: * An array containing additional HTTP request headers, each formatted as
Chris@0: * "name: value".
Chris@0: *
Chris@0: * @return string
Chris@0: * The retrieved HTML string, also available as $this->getRawContent()
Chris@0: */
Chris@0: protected function drupalGet($path, array $options = [], array $headers = []) {
Chris@0: // We re-using a CURL connection here. If that connection still has certain
Chris@0: // options set, it might change the GET into a POST. Make sure we clear out
Chris@0: // previous options.
Chris@0: $out = $this->curlExec([CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $this->buildUrl($path, $options), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPHEADER => $headers]);
Chris@0: // Ensure that any changes to variables in the other thread are picked up.
Chris@0: $this->refreshVariables();
Chris@0:
Chris@0: // Replace original page output with new output from redirected page(s).
Chris@0: if ($new = $this->checkForMetaRefresh()) {
Chris@0: $out = $new;
Chris@0: // We are finished with all meta refresh redirects, so reset the counter.
Chris@0: $this->metaRefreshCount = 0;
Chris@0: }
Chris@0:
Chris@0: if ($path instanceof Url) {
Chris@0: $path = $path->setAbsolute()->toString(TRUE)->getGeneratedUrl();
Chris@0: }
Chris@0:
Chris@0: $verbose = 'GET request to: ' . $path .
Chris@0: '
';
Chris@0: }
Chris@0: $verbose .= '' . $out;
Chris@0:
Chris@0: $this->verbose($verbose);
Chris@0: return $out;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves a Drupal path or an absolute path and JSON decodes the result.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Drupal path or URL to request AJAX from.
Chris@0: * @param array $options
Chris@0: * Array of URL options.
Chris@0: * @param array $headers
Chris@0: * Array of headers. Eg array('Accept: application/vnd.drupal-ajax').
Chris@0: *
Chris@0: * @return array
Chris@0: * Decoded json.
Chris@0: */
Chris@0: protected function drupalGetJSON($path, array $options = [], array $headers = []) {
Chris@0: return Json::decode($this->drupalGetWithFormat($path, 'json', $options, $headers));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves a Drupal path or an absolute path for a given format.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Drupal path or URL to request given format from.
Chris@0: * @param string $format
Chris@0: * The wanted request format.
Chris@0: * @param array $options
Chris@0: * Array of URL options.
Chris@0: * @param array $headers
Chris@0: * Array of headers.
Chris@0: *
Chris@0: * @return mixed
Chris@0: * The result of the request.
Chris@0: */
Chris@0: protected function drupalGetWithFormat($path, $format, array $options = [], array $headers = []) {
Chris@14: $options = array_merge_recursive(['query' => ['_format' => $format]], $options);
Chris@0: return $this->drupalGet($path, $options, $headers);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Requests a path or URL in drupal_ajax format and JSON-decodes the response.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Drupal path or URL to request from.
Chris@0: * @param array $options
Chris@0: * Array of URL options.
Chris@0: * @param array $headers
Chris@0: * Array of headers.
Chris@0: *
Chris@0: * @return array
Chris@0: * Decoded JSON.
Chris@0: */
Chris@0: protected function drupalGetAjax($path, array $options = [], array $headers = []) {
Chris@0: if (!isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT])) {
Chris@0: $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] = 'drupal_ajax';
Chris@0: }
Chris@0: return Json::decode($this->drupalGetXHR($path, $options, $headers));
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Requests a Drupal path or an absolute path as if it is a XMLHttpRequest.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Drupal path or URL to request from.
Chris@0: * @param array $options
Chris@0: * Array of URL options.
Chris@0: * @param array $headers
Chris@0: * Array of headers.
Chris@0: *
Chris@0: * @return string
Chris@0: * The retrieved content.
Chris@0: */
Chris@0: protected function drupalGetXHR($path, array $options = [], array $headers = []) {
Chris@0: $headers[] = 'X-Requested-With: XMLHttpRequest';
Chris@0: return $this->drupalGet($path, $options, $headers);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Executes a form submission.
Chris@0: *
Chris@0: * It will be done as usual POST request with SimpleBrowser.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Location of the post form. Either a Drupal path or an absolute path or
Chris@0: * NULL to post to the current page. For multi-stage forms you can set the
Chris@0: * path to NULL and have it post to the last received page. Example:
Chris@0: *
Chris@0: * @code
Chris@0: * // First step in form.
Chris@0: * $edit = array(...);
Chris@0: * $this->drupalPostForm('some_url', $edit, t('Save'));
Chris@0: *
Chris@0: * // Second step in form.
Chris@0: * $edit = array(...);
Chris@0: * $this->drupalPostForm(NULL, $edit, t('Save'));
Chris@0: * @endcode
Chris@0: * @param $edit
Chris@0: * Field data in an associative array. Changes the current input fields
Chris@0: * (where possible) to the values indicated.
Chris@0: *
Chris@0: * When working with form tests, the keys for an $edit element should match
Chris@0: * the 'name' parameter of the HTML of the form. For example, the 'body'
Chris@0: * field for a node has the following HTML:
Chris@0: * @code
Chris@0: *
Chris@0: * @endcode
Chris@0: * When testing this field using an $edit parameter, the code becomes:
Chris@0: * @code
Chris@0: * $edit["body[0][value]"] = 'My test value';
Chris@0: * @endcode
Chris@0: *
Chris@0: * A checkbox can be set to TRUE to be checked and should be set to FALSE to
Chris@0: * be unchecked. Multiple select fields can be tested using 'name[]' and
Chris@0: * setting each of the desired values in an array:
Chris@0: * @code
Chris@0: * $edit = array();
Chris@0: * $edit['name[]'] = array('value1', 'value2');
Chris@0: * @endcode
Chris@0: * @param $submit
Chris@0: * Value of the submit button whose click is to be emulated. For example,
Chris@0: * t('Save'). The processing of the request depends on this value. For
Chris@0: * example, a form may have one button with the value t('Save') and another
Chris@0: * button with the value t('Delete'), and execute different code depending
Chris@0: * on which one is clicked.
Chris@0: *
Chris@0: * This function can also be called to emulate an Ajax submission. In this
Chris@0: * case, this value needs to be an array with the following keys:
Chris@0: * - path: A path to submit the form values to for Ajax-specific processing.
Chris@0: * - triggering_element: If the value for the 'path' key is a generic Ajax
Chris@0: * processing path, this needs to be set to the name of the element. If
Chris@0: * the name doesn't identify the element uniquely, then this should
Chris@0: * instead be an array with a single key/value pair, corresponding to the
Chris@0: * element name and value. The \Drupal\Core\Form\FormAjaxResponseBuilder
Chris@0: * uses this to find the #ajax information for the element, including
Chris@0: * which specific callback to use for processing the request.
Chris@0: *
Chris@0: * This can also be set to NULL in order to emulate an Internet Explorer
Chris@0: * submission of a form with a single text field, and pressing ENTER in that
Chris@0: * textfield: under these conditions, no button information is added to the
Chris@0: * POST data.
Chris@0: * @param $options
Chris@0: * Options to be forwarded to the url generator.
Chris@0: * @param $headers
Chris@0: * An array containing additional HTTP request headers, each formatted as
Chris@0: * "name: value".
Chris@0: * @param $form_html_id
Chris@0: * (optional) HTML ID of the form to be submitted. On some pages
Chris@0: * there are many identical forms, so just using the value of the submit
Chris@0: * button is not enough. For example: 'trigger-node-presave-assign-form'.
Chris@0: * Note that this is not the Drupal $form_id, but rather the HTML ID of the
Chris@0: * form, which is typically the same thing but with hyphens replacing the
Chris@0: * underscores.
Chris@0: * @param $extra_post
Chris@0: * (optional) A string of additional data to append to the POST submission.
Chris@0: * This can be used to add POST data for which there are no HTML fields, as
Chris@0: * is done by drupalPostAjaxForm(). This string is literally appended to the
Chris@0: * POST data, so it must already be urlencoded and contain a leading "&"
Chris@0: * (e.g., "&extra_var1=hello+world&extra_var2=you%26me").
Chris@0: */
Chris@0: protected function drupalPostForm($path, $edit, $submit, array $options = [], array $headers = [], $form_html_id = NULL, $extra_post = NULL) {
Chris@0: if (is_object($submit)) {
Chris@0: // Cast MarkupInterface objects to string.
Chris@0: $submit = (string) $submit;
Chris@0: }
Chris@0: if (is_array($edit)) {
Chris@0: $edit = $this->castSafeStrings($edit);
Chris@0: }
Chris@0:
Chris@0: $submit_matches = FALSE;
Chris@0: $ajax = is_array($submit);
Chris@0: if (isset($path)) {
Chris@0: $this->drupalGet($path, $options);
Chris@0: }
Chris@0:
Chris@0: if ($this->parse()) {
Chris@0: $edit_save = $edit;
Chris@0: // Let's iterate over all the forms.
Chris@0: $xpath = "//form";
Chris@0: if (!empty($form_html_id)) {
Chris@0: $xpath .= "[@id='" . $form_html_id . "']";
Chris@0: }
Chris@0: $forms = $this->xpath($xpath);
Chris@0: foreach ($forms as $form) {
Chris@0: // We try to set the fields of this form as specified in $edit.
Chris@0: $edit = $edit_save;
Chris@0: $post = [];
Chris@0: $upload = [];
Chris@0: $submit_matches = $this->handleForm($post, $edit, $upload, $ajax ? NULL : $submit, $form);
Chris@0: $action = isset($form['action']) ? $this->getAbsoluteUrl((string) $form['action']) : $this->getUrl();
Chris@0: if ($ajax) {
Chris@0: if (empty($submit['path'])) {
Chris@0: throw new \Exception('No #ajax path specified.');
Chris@0: }
Chris@0: $action = $this->getAbsoluteUrl($submit['path']);
Chris@0: // Ajax callbacks verify the triggering element if necessary, so while
Chris@0: // we may eventually want extra code that verifies it in the
Chris@0: // handleForm() function, it's not currently a requirement.
Chris@0: $submit_matches = TRUE;
Chris@0: }
Chris@0: // We post only if we managed to handle every field in edit and the
Chris@0: // submit button matches.
Chris@0: if (!$edit && ($submit_matches || !isset($submit))) {
Chris@0: $post_array = $post;
Chris@0: if ($upload) {
Chris@0: foreach ($upload as $key => $file) {
Chris@0: if (is_array($file) && count($file)) {
Chris@0: // There seems to be no way via php's API to cURL to upload
Chris@0: // several files with the same post field name. However, Drupal
Chris@0: // still sees array-index syntax in a similar way.
Chris@0: for ($i = 0; $i < count($file); $i++) {
Chris@0: $postfield = str_replace('[]', '', $key) . '[' . $i . ']';
Chris@0: $file_path = $this->container->get('file_system')->realpath($file[$i]);
Chris@0: $post[$postfield] = curl_file_create($file_path);
Chris@0: }
Chris@0: }
Chris@0: else {
Chris@0: $file = $this->container->get('file_system')->realpath($file);
Chris@0: if ($file && is_file($file)) {
Chris@0: $post[$key] = curl_file_create($file);
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: else {
Chris@0: $post = $this->serializePostValues($post) . $extra_post;
Chris@0: }
Chris@0: $out = $this->curlExec([CURLOPT_URL => $action, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $post, CURLOPT_HTTPHEADER => $headers]);
Chris@0: // Ensure that any changes to variables in the other thread are picked
Chris@0: // up.
Chris@0: $this->refreshVariables();
Chris@0:
Chris@0: // Replace original page output with new output from redirected
Chris@0: // page(s).
Chris@0: if ($new = $this->checkForMetaRefresh()) {
Chris@0: $out = $new;
Chris@0: }
Chris@0:
Chris@0: if ($path instanceof Url) {
Chris@0: $path = $path->toString();
Chris@0: }
Chris@0: $verbose = 'POST request to: ' . $path;
Chris@0: $verbose .= 'Ending URL: ' . $this->getUrl();
Chris@0: if ($this->dumpHeaders) {
Chris@0: $verbose .= 'Headers:
';
Chris@0: }
Chris@0: $verbose .= 'Fields: ' . highlight_string('' . $out;
Chris@0:
Chris@0: $this->verbose($verbose);
Chris@0: return $out;
Chris@0: }
Chris@0: }
Chris@0: // We have not found a form which contained all fields of $edit.
Chris@0: foreach ($edit as $name => $value) {
Chris@17: $this->fail(new FormattableMarkup('Failed to set field @name to @value', ['@name' => $name, '@value' => $value]));
Chris@0: }
Chris@0: if (!$ajax && isset($submit)) {
Chris@0: $this->assertTrue($submit_matches, format_string('Found the @submit button', ['@submit' => $submit]));
Chris@0: }
Chris@0: $this->fail(format_string('Found the requested form fields at @path', ['@path' => ($path instanceof Url) ? $path->toString() : $path]));
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Executes an Ajax form submission.
Chris@0: *
Chris@0: * This executes a POST as ajax.js does. The returned JSON data is used to
Chris@0: * update $this->content via drupalProcessAjaxResponse(). It also returns
Chris@0: * the array of AJAX commands received.
Chris@0: *
Chris@0: * @param \Drupal\Core\Url|string $path
Chris@0: * Location of the form containing the Ajax enabled element to test. Can be
Chris@0: * either a Drupal path or an absolute path or NULL to use the current page.
Chris@0: * @param $edit
Chris@0: * Field data in an associative array. Changes the current input fields
Chris@0: * (where possible) to the values indicated.
Chris@0: * @param $triggering_element
Chris@0: * The name of the form element that is responsible for triggering the Ajax
Chris@0: * functionality to test. May be a string or, if the triggering element is
Chris@0: * a button, an associative array where the key is the name of the button
Chris@0: * and the value is the button label. i.e.) array('op' => t('Refresh')).
Chris@0: * @param $ajax_path
Chris@0: * (optional) Override the path set by the Ajax settings of the triggering
Chris@0: * element.
Chris@0: * @param $options
Chris@0: * (optional) Options to be forwarded to the url generator.
Chris@0: * @param $headers
Chris@0: * (optional) An array containing additional HTTP request headers, each
Chris@0: * formatted as "name: value". Forwarded to drupalPostForm().
Chris@0: * @param $form_html_id
Chris@0: * (optional) HTML ID of the form to be submitted, use when there is more
Chris@0: * than one identical form on the same page and the value of the triggering
Chris@0: * element is not enough to identify the form. Note this is not the Drupal
Chris@0: * ID of the form but rather the HTML ID of the form.
Chris@0: * @param $ajax_settings
Chris@0: * (optional) An array of Ajax settings which if specified will be used in
Chris@0: * place of the Ajax settings of the triggering element.
Chris@0: *
Chris@0: * @return
Chris@0: * An array of Ajax commands.
Chris@0: *
Chris@0: * @see drupalPostForm()
Chris@0: * @see drupalProcessAjaxResponse()
Chris@0: * @see ajax.js
Chris@0: */
Chris@0: protected function drupalPostAjaxForm($path, $edit, $triggering_element, $ajax_path = NULL, array $options = [], array $headers = [], $form_html_id = NULL, $ajax_settings = NULL) {
Chris@0:
Chris@0: // Get the content of the initial page prior to calling drupalPostForm(),
Chris@0: // since drupalPostForm() replaces $this->content.
Chris@0: if (isset($path)) {
Chris@0: // Avoid sending the wrapper query argument to drupalGet so we can fetch
Chris@0: // the form and populate the internal WebTest values.
Chris@0: $get_options = $options;
Chris@0: unset($get_options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
Chris@0: $this->drupalGet($path, $get_options);
Chris@0: }
Chris@0: $content = $this->content;
Chris@0: $drupal_settings = $this->drupalSettings;
Chris@0:
Chris@0: // Provide a default value for the wrapper envelope.
Chris@0: $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] =
Chris@0: isset($options['query'][MainContentViewSubscriber::WRAPPER_FORMAT]) ?
Chris@0: $options['query'][MainContentViewSubscriber::WRAPPER_FORMAT] :
Chris@0: 'drupal_ajax';
Chris@0:
Chris@0: // Get the Ajax settings bound to the triggering element.
Chris@0: if (!isset($ajax_settings)) {
Chris@0: if (is_array($triggering_element)) {
Chris@0: $xpath = '//*[@name="' . key($triggering_element) . '" and @value="' . current($triggering_element) . '"]';
Chris@0: }
Chris@0: else {
Chris@0: $xpath = '//*[@name="' . $triggering_element . '"]';
Chris@0: }
Chris@0: if (isset($form_html_id)) {
Chris@0: $xpath = '//form[@id="' . $form_html_id . '"]' . $xpath;
Chris@0: }
Chris@0: $element = $this->xpath($xpath);
Chris@0: $element_id = (string) $element[0]['id'];
Chris@0: $ajax_settings = $drupal_settings['ajax'][$element_id];
Chris@0: }
Chris@0:
Chris@0: // Add extra information to the POST data as ajax.js does.
Chris@0: $extra_post = [];
Chris@0: if (isset($ajax_settings['submit'])) {
Chris@0: foreach ($ajax_settings['submit'] as $key => $value) {
Chris@0: $extra_post[$key] = $value;
Chris@0: }
Chris@0: }
Chris@0: $extra_post[AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER] = 1;
Chris@0: $extra_post += $this->getAjaxPageStatePostData();
Chris@0: // Now serialize all the $extra_post values, and prepend it with an '&'.
Chris@0: $extra_post = '&' . $this->serializePostValues($extra_post);
Chris@0:
Chris@0: // Unless a particular path is specified, use the one specified by the
Chris@0: // Ajax settings.
Chris@0: if (!isset($ajax_path)) {
Chris@0: if (isset($ajax_settings['url'])) {
Chris@0: // In order to allow to set for example the wrapper envelope query
Chris@0: // parameter we need to get the system path again.
Chris@0: $parsed_url = UrlHelper::parse($ajax_settings['url']);
Chris@0: $options['query'] = $parsed_url['query'] + $options['query'];
Chris@0: $options += ['fragment' => $parsed_url['fragment']];
Chris@0:
Chris@0: // We know that $parsed_url['path'] is already with the base path
Chris@0: // attached.
Chris@0: $ajax_path = preg_replace(
Chris@0: '/^' . preg_quote(base_path(), '/') . '/',
Chris@0: '',
Chris@0: $parsed_url['path']
Chris@0: );
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: if (empty($ajax_path)) {
Chris@0: throw new \Exception('No #ajax path specified.');
Chris@0: }
Chris@0:
Chris@0: $ajax_path = $this->container->get('unrouted_url_assembler')->assemble('base://' . $ajax_path, $options);
Chris@0:
Chris@0: // Submit the POST request.
Chris@0: $return = Json::decode($this->drupalPostForm(NULL, $edit, ['path' => $ajax_path, 'triggering_element' => $triggering_element], $options, $headers, $form_html_id, $extra_post));
Chris@0: if ($this->assertAjaxHeader) {
Chris@0: $this->assertIdentical($this->drupalGetHeader('X-Drupal-Ajax-Token'), '1', 'Ajax response header found.');
Chris@0: }
Chris@0:
Chris@0: // Change the page content by applying the returned commands.
Chris@0: if (!empty($ajax_settings) && !empty($return)) {
Chris@0: $this->drupalProcessAjaxResponse($content, $return, $ajax_settings, $drupal_settings);
Chris@0: }
Chris@0:
Chris@0: $verbose = 'AJAX POST request to: ' . $path;
Chris@0: $verbose .= ' AJAX controller path: ' . $ajax_path;
Chris@0: $verbose .= 'Ending URL: ' . $this->getUrl();
Chris@0: $verbose .= '' . $this->content;
Chris@0:
Chris@0: $this->verbose($verbose);
Chris@0:
Chris@0: return $return;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Processes an AJAX response into current content.
Chris@0: *
Chris@0: * This processes the AJAX response as ajax.js does. It uses the response's
Chris@0: * JSON data, an array of commands, to update $this->content using equivalent
Chris@0: * DOM manipulation as is used by ajax.js.
Chris@0: * It does not apply custom AJAX commands though, because emulation is only
Chris@0: * implemented for the AJAX commands that ship with Drupal core.
Chris@0: *
Chris@0: * @param string $content
Chris@0: * The current HTML content.
Chris@0: * @param array $ajax_response
Chris@0: * An array of AJAX commands.
Chris@0: * @param array $ajax_settings
Chris@0: * An array of AJAX settings which will be used to process the response.
Chris@0: * @param array $drupal_settings
Chris@0: * An array of settings to update the value of drupalSettings for the
Chris@0: * currently-loaded page.
Chris@0: *
Chris@0: * @see drupalPostAjaxForm()
Chris@0: * @see ajax.js
Chris@0: */
Chris@0: protected function drupalProcessAjaxResponse($content, array $ajax_response, array $ajax_settings, array $drupal_settings) {
Chris@0:
Chris@0: // ajax.js applies some defaults to the settings object, so do the same
Chris@0: // for what's used by this function.
Chris@0: $ajax_settings += [
Chris@0: 'method' => 'replaceWith',
Chris@0: ];
Chris@0: // DOM can load HTML soup. But, HTML soup can throw warnings, suppress
Chris@0: // them.
Chris@0: $dom = new \DOMDocument();
Chris@0: @$dom->loadHTML($content);
Chris@0: // XPath allows for finding wrapper nodes better than DOM does.
Chris@0: $xpath = new \DOMXPath($dom);
Chris@0: foreach ($ajax_response as $command) {
Chris@0: // Error messages might be not commands.
Chris@0: if (!is_array($command)) {
Chris@0: continue;
Chris@0: }
Chris@0: switch ($command['command']) {
Chris@0: case 'settings':
Chris@0: $drupal_settings = NestedArray::mergeDeepArray([$drupal_settings, $command['settings']], TRUE);
Chris@0: break;
Chris@0:
Chris@0: case 'insert':
Chris@0: $wrapperNode = NULL;
Chris@0: // When a command doesn't specify a selector, use the
Chris@0: // #ajax['wrapper'] which is always an HTML ID.
Chris@0: if (!isset($command['selector'])) {
Chris@0: $wrapperNode = $xpath->query('//*[@id="' . $ajax_settings['wrapper'] . '"]')->item(0);
Chris@0: }
Chris@0: // @todo Ajax commands can target any jQuery selector, but these are
Chris@0: // hard to fully emulate with XPath. For now, just handle 'head'
Chris@0: // and 'body', since these are used by the Ajax renderer.
Chris@0: elseif (in_array($command['selector'], ['head', 'body'])) {
Chris@0: $wrapperNode = $xpath->query('//' . $command['selector'])->item(0);
Chris@0: }
Chris@0: if ($wrapperNode) {
Chris@0: // ajax.js adds an enclosing DIV to work around a Safari bug.
Chris@0: $newDom = new \DOMDocument();
Chris@0: // DOM can load HTML soup. But, HTML soup can throw warnings,
Chris@0: // suppress them.
Chris@0: @$newDom->loadHTML('
' . $command['data'] . '
');
Chris@0: // Suppress warnings thrown when duplicate HTML IDs are encountered.
Chris@0: // This probably means we are replacing an element with the same ID.
Chris@0: $newNode = @$dom->importNode($newDom->documentElement->firstChild->firstChild, TRUE);
Chris@0: $method = isset($command['method']) ? $command['method'] : $ajax_settings['method'];
Chris@0: // The "method" is a jQuery DOM manipulation function. Emulate
Chris@0: // each one using PHP's DOMNode API.
Chris@0: switch ($method) {
Chris@0: case 'replaceWith':
Chris@0: $wrapperNode->parentNode->replaceChild($newNode, $wrapperNode);
Chris@0: break;
Chris@0: case 'append':
Chris@0: $wrapperNode->appendChild($newNode);
Chris@0: break;
Chris@0: case 'prepend':
Chris@0: // If no firstChild, insertBefore() falls back to
Chris@0: // appendChild().
Chris@0: $wrapperNode->insertBefore($newNode, $wrapperNode->firstChild);
Chris@0: break;
Chris@0: case 'before':
Chris@0: $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode);
Chris@0: break;
Chris@0: case 'after':
Chris@0: // If no nextSibling, insertBefore() falls back to
Chris@0: // appendChild().
Chris@0: $wrapperNode->parentNode->insertBefore($newNode, $wrapperNode->nextSibling);
Chris@0: break;
Chris@0: case 'html':
Chris@0: foreach ($wrapperNode->childNodes as $childNode) {
Chris@0: $wrapperNode->removeChild($childNode);
Chris@0: }
Chris@0: $wrapperNode->appendChild($newNode);
Chris@0: break;
Chris@0: }
Chris@0: }
Chris@0: break;
Chris@0:
Chris@0: // @todo Add suitable implementations for these commands in order to
Chris@0: // have full test coverage of what ajax.js can do.
Chris@0: case 'remove':
Chris@0: break;
Chris@0: case 'changed':
Chris@0: break;
Chris@0: case 'css':
Chris@0: break;
Chris@0: case 'data':
Chris@0: break;
Chris@0: case 'restripe':
Chris@0: break;
Chris@0: case 'add_css':
Chris@0: break;
Chris@0: case 'update_build_id':
Chris@0: $buildId = $xpath->query('//input[@name="form_build_id" and @value="' . $command['old'] . '"]')->item(0);
Chris@0: if ($buildId) {
Chris@0: $buildId->setAttribute('value', $command['new']);
Chris@0: }
Chris@0: break;
Chris@0: }
Chris@0: }
Chris@0: $content = $dom->saveHTML();
Chris@0: $this->setRawContent($content);
Chris@0: $this->setDrupalSettings($drupal_settings);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Perform a POST HTTP request.
Chris@0: *
Chris@0: * @param string|\Drupal\Core\Url $path
Chris@0: * Drupal path or absolute path where the request should be POSTed.
Chris@0: * @param string $accept
Chris@0: * The value for the "Accept" header. Usually either 'application/json' or
Chris@0: * 'application/vnd.drupal-ajax'.
Chris@0: * @param array $post
Chris@0: * The POST data. When making a 'application/vnd.drupal-ajax' request, the
Chris@0: * Ajax page state data should be included. Use getAjaxPageStatePostData()
Chris@0: * for that.
Chris@0: * @param array $options
Chris@0: * (optional) Options to be forwarded to the url generator. The 'absolute'
Chris@0: * option will automatically be enabled.
Chris@0: *
Chris@0: * @return
Chris@0: * The content returned from the call to curl_exec().
Chris@0: *
Chris@0: * @see WebTestBase::getAjaxPageStatePostData()
Chris@0: * @see WebTestBase::curlExec()
Chris@0: */
Chris@0: protected function drupalPost($path, $accept, array $post, $options = []) {
Chris@0: return $this->curlExec([
Chris@0: CURLOPT_URL => $this->buildUrl($path, $options),
Chris@0: CURLOPT_POST => TRUE,
Chris@0: CURLOPT_POSTFIELDS => $this->serializePostValues($post),
Chris@0: CURLOPT_HTTPHEADER => [
Chris@0: 'Accept: ' . $accept,
Chris@0: 'Content-Type: application/x-www-form-urlencoded',
Chris@0: ],
Chris@0: ]);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Performs a POST HTTP request with a specific format.
Chris@0: *
Chris@0: * @param string|\Drupal\Core\Url $path
Chris@0: * Drupal path or absolute path where the request should be POSTed.
Chris@0: * @param string $format
Chris@0: * The request format.
Chris@0: * @param array $post
Chris@0: * The POST data. When making a 'application/vnd.drupal-ajax' request, the
Chris@0: * Ajax page state data should be included. Use getAjaxPageStatePostData()
Chris@0: * for that.
Chris@0: * @param array $options
Chris@0: * (optional) Options to be forwarded to the url generator. The 'absolute'
Chris@0: * option will automatically be enabled.
Chris@0: *
Chris@0: * @return string
Chris@0: * The content returned from the call to curl_exec().
Chris@0: *
Chris@0: * @see WebTestBase::drupalPost
Chris@0: * @see WebTestBase::getAjaxPageStatePostData()
Chris@0: * @see WebTestBase::curlExec()
Chris@0: */
Chris@0: protected function drupalPostWithFormat($path, $format, array $post, $options = []) {
Chris@0: $options['query']['_format'] = $format;
Chris@0: return $this->drupalPost($path, '', $post, $options);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Get the Ajax page state from drupalSettings and prepare it for POSTing.
Chris@0: *
Chris@0: * @return array
Chris@0: * The Ajax page state POST data.
Chris@0: */
Chris@0: protected function getAjaxPageStatePostData() {
Chris@0: $post = [];
Chris@0: $drupal_settings = $this->drupalSettings;
Chris@0: if (isset($drupal_settings['ajaxPageState']['theme'])) {
Chris@0: $post['ajax_page_state[theme]'] = $drupal_settings['ajaxPageState']['theme'];
Chris@0: }
Chris@0: if (isset($drupal_settings['ajaxPageState']['theme_token'])) {
Chris@0: $post['ajax_page_state[theme_token]'] = $drupal_settings['ajaxPageState']['theme_token'];
Chris@0: }
Chris@0: if (isset($drupal_settings['ajaxPageState']['libraries'])) {
Chris@0: $post['ajax_page_state[libraries]'] = $drupal_settings['ajaxPageState']['libraries'];
Chris@0: }
Chris@0: return $post;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Serialize POST HTTP request values.
Chris@0: *
Chris@0: * Encode according to application/x-www-form-urlencoded. Both names and
Chris@0: * values needs to be urlencoded, according to
Chris@0: * http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
Chris@0: *
Chris@0: * @param array $post
Chris@0: * The array of values to be POSTed.
Chris@0: *
Chris@0: * @return string
Chris@0: * The serialized result.
Chris@0: */
Chris@0: protected function serializePostValues($post = []) {
Chris@0: foreach ($post as $key => $value) {
Chris@0: $post[$key] = urlencode($key) . '=' . urlencode($value);
Chris@0: }
Chris@0: return implode('&', $post);
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Transforms a nested array into a flat array suitable for WebTestBase::drupalPostForm().
Chris@0: *
Chris@0: * @param array $values
Chris@0: * A multi-dimensional form values array to convert.
Chris@0: *
Chris@0: * @return array
Chris@0: * The flattened $edit array suitable for WebTestBase::drupalPostForm().
Chris@0: */
Chris@0: protected function translatePostValues(array $values) {
Chris@0: $edit = [];
Chris@0: // The easiest and most straightforward way to translate values suitable for
Chris@0: // WebTestBase::drupalPostForm() is to actually build the POST data string
Chris@0: // and convert the resulting key/value pairs back into a flat array.
Chris@0: $query = http_build_query($values);
Chris@0: foreach (explode('&', $query) as $item) {
Chris@0: list($key, $value) = explode('=', $item);
Chris@0: $edit[urldecode($key)] = urldecode($value);
Chris@0: }
Chris@0: return $edit;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Checks for meta refresh tag and if found call drupalGet() recursively.
Chris@0: *
Chris@0: * This function looks for the http-equiv attribute to be set to "Refresh" and
Chris@0: * is case-sensitive.
Chris@0: *
Chris@0: * @return
Chris@0: * Either the new page content or FALSE.
Chris@0: */
Chris@0: protected function checkForMetaRefresh() {
Chris@0: if (strpos($this->getRawContent(), 'parse() && (!isset($this->maximumMetaRefreshCount) || $this->metaRefreshCount < $this->maximumMetaRefreshCount)) {
Chris@0: $refresh = $this->xpath('//meta[@http-equiv="Refresh"]');
Chris@0: if (!empty($refresh)) {
Chris@0: // Parse the content attribute of the meta tag for the format:
Chris@0: // "[delay]: URL=[page_to_redirect_to]".
Chris@0: if (preg_match('/\d+;\s*URL=(?.*)/i', $refresh[0]['content'], $match)) {
Chris@0: $this->metaRefreshCount++;
Chris@0: return $this->drupalGet($this->getAbsoluteUrl(Html::decodeEntities($match['url'])));
Chris@0: }
Chris@0: }
Chris@0: }
Chris@0: return FALSE;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Retrieves only the headers for a Drupal path or an absolute path.
Chris@0: *
Chris@0: * @param $path
Chris@0: * Drupal path or URL to load into internal browser
Chris@0: * @param $options
Chris@0: * Options to be forwarded to the url generator.
Chris@0: * @param $headers
Chris@0: * An array containing additional HTTP request headers, each formatted as
Chris@0: * "name: value".
Chris@0: *
Chris@0: * @return
Chris@0: * The retrieved headers, also available as $this->getRawContent()
Chris@0: */
Chris@0: protected function drupalHead($path, array $options = [], array $headers = []) {
Chris@0: $options['absolute'] = TRUE;
Chris@0: $url = $this->buildUrl($path, $options);
Chris@0: $out = $this->curlExec([CURLOPT_NOBODY => TRUE, CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers]);
Chris@0: // Ensure that any changes to variables in the other thread are picked up.
Chris@0: $this->refreshVariables();
Chris@0:
Chris@0: if ($this->dumpHeaders) {
Chris@0: $this->verbose('GET request to: ' . $path .
Chris@0: 'Ending URL: ' . $this->getUrl() .
Chris@0: 'Headers:
');
Chris@0: }
Chris@0:
Chris@0: return $out;
Chris@0: }
Chris@0:
Chris@0: /**
Chris@0: * Handles form input related to drupalPostForm().
Chris@0: *
Chris@0: * Ensure that the specified fields exist and attempt to create POST data in
Chris@0: * the correct manner for the particular field type.
Chris@0: *
Chris@0: * @param $post
Chris@0: * Reference to array of post values.
Chris@0: * @param $edit
Chris@0: * Reference to array of edit values to be checked against the form.
Chris@0: * @param $submit
Chris@0: * Form submit button value.
Chris@0: * @param $form
Chris@0: * Array of form elements.
Chris@0: *
Chris@0: * @return
Chris@0: * Submit value matches a valid submit input in the form.
Chris@0: */
Chris@0: protected function handleForm(&$post, &$edit, &$upload, $submit, $form) {
Chris@0: // Retrieve the form elements.
Chris@0: $elements = $form->xpath('.//input[not(@disabled)]|.//textarea[not(@disabled)]|.//select[not(@disabled)]');
Chris@0: $submit_matches = FALSE;
Chris@0: foreach ($elements as $element) {
Chris@0: // SimpleXML objects need string casting all the time.
Chris@0: $name = (string) $element['name'];
Chris@0: // This can either be the type of or the name of the tag itself
Chris@0: // for