WebTestBase.php 98 KB
Newer Older
1 2 3
<?php

/**
4
 * @file
5
 * Definition of \Drupal\simpletest\WebTestBase.
6
 */
7

8
namespace Drupal\simpletest;
9

10
use Drupal\Component\Serialization\Json;
11
use Drupal\Component\Serialization\Yaml;
12
use Drupal\Component\Utility\Crypt;
13
use Drupal\Component\Utility\NestedArray;
14
use Drupal\Component\Utility\String;
15
use Drupal\Core\Cache\Cache;
16
use Drupal\Core\DependencyInjection\YamlFileLoader;
17
use Drupal\Core\DrupalKernel;
18 19
use Drupal\Core\Database\Database;
use Drupal\Core\Database\ConnectionNotDefinedException;
20
use Drupal\Core\Entity\EntityInterface;
21
use Drupal\Core\Language\LanguageInterface;
22
use Drupal\Core\Render\Element;
23
use Drupal\Core\Session\AccountInterface;
24
use Drupal\Core\Session\AnonymousUserSession;
25
use Drupal\Core\Session\UserSession;
26
use Drupal\Core\Site\Settings;
27
use Drupal\Core\StreamWrapper\PublicStream;
28
use Drupal\Core\Datetime\DrupalDateTime;
29
use Drupal\block\Entity\Block;
30
use Symfony\Component\HttpFoundation\Request;
31
use Drupal\user\Entity\Role;
32 33 34

/**
 * Test case for typical Drupal tests.
35 36
 *
 * @ingroup testing
37
 */
38 39
abstract class WebTestBase extends TestBase {

40 41
  use AssertContentTrait;

42 43 44 45 46
  /**
   * The profile to install as a basis for testing.
   *
   * @var string
   */
47
  protected $profile = 'testing';
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
  /**
   * The URL currently loaded in the internal browser.
   *
   * @var string
   */
  protected $url;

  /**
   * The handle of the current cURL connection.
   *
   * @var resource
   */
  protected $curlHandle;

  /**
   * The headers of the page currently loaded in the internal browser.
   *
   * @var Array
   */
  protected $headers;

70 71 72 73 74 75 76
  /**
   * The cookies of the page currently loaded in the internal browser.
   *
   * @var array
   */
  protected $cookies;

77 78 79 80
  /**
   * Indicates that headers should be dumped if verbose output is enabled.
   *
   * Headers are dumped to verbose by drupalGet(), drupalHead(), and
81
   * drupalPostForm().
82 83 84 85 86
   *
   * @var bool
   */
  protected $dumpHeaders = FALSE;

87 88 89
  /**
   * The current user logged in using the internal browser.
   *
90
   * @var \Drupal\Core\Session\AccountInterface|bool
91 92 93
   */
  protected $loggedInUser = FALSE;

94 95 96 97 98 99 100 101
  /**
   * The "#1" admin user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $rootUser;


102 103 104 105 106 107 108 109 110 111 112
  /**
   * The current cookie file used by cURL.
   *
   * We do not reuse the cookies in further runs, so we do not need a file
   * but we still need cookie handling, so we set the jar to NULL.
   */
  protected $cookieFile = NULL;

  /**
   * Additional cURL options.
   *
113 114
   * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
   * is set.
115 116 117
   */
  protected $additionalCurlOptions = array();

118 119 120 121 122 123 124
  /**
   * The original batch, before it was changed for testing purposes.
   *
   * @var array
   */
  protected $originalBatch;

125
  /**
126
   * The original user, before it was changed to a clean uid = 1 for testing.
127 128 129 130 131
   *
   * @var object
   */
  protected $originalUser = NULL;

132
  /**
133
   * The original shutdown handlers array, before it was cleaned for testing.
134 135 136 137 138
   *
   * @var array
   */
  protected $originalShutdownCallbacks = array();

139 140 141
  /**
   * The current session name, if available.
   */
142
  protected $sessionName = NULL;
143 144 145 146

  /**
   * The current session ID, if available.
   */
147
  protected $sessionId = NULL;
148

149 150 151 152 153
  /**
   * Whether the files were copied to the test files directory.
   */
  protected $generatedTestFiles = FALSE;

154 155 156 157 158
  /**
   * The maximum number of redirects to follow when handling responses.
   */
  protected $maximumRedirects = 5;

159 160 161
  /**
   * The number of redirects followed during the handling of a request.
   */
162
  protected $redirectCount;
163

164 165
  /**
   * The kernel used in this test.
166 167
   *
   * @var \Drupal\Core\DrupalKernel
168 169 170
   */
  protected $kernel;

171 172 173 174 175
  /**
   * The config directories used in this test.
   */
  protected $configDirectories = array();

176 177 178 179 180 181 182
  /**
   * Cookies to set on curl requests.
   *
   * @var array
   */
  protected $curlCookies = array();

183 184 185 186 187 188 189
  /**
   * An array of custom translations suitable for drupal_rewrite_settings().
   *
   * @var array
   */
  protected $customTranslations;

190
  /**
191
   * Constructor for \Drupal\simpletest\WebTestBase.
192 193 194 195 196 197
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->skipClasses[__CLASS__] = TRUE;
  }

198 199 200
  /**
   * Get a node from the database based on its title.
   *
201
   * @param $title
202
   *   A node title, usually generated by $this->randomMachineName().
203
   * @param $reset
204
   *   (optional) Whether to reset the entity cache.
205
   *
206
   * @return \Drupal\node\NodeInterface
207
   *   A node entity matching $title.
208
   */
209
  function drupalGetNodeByTitle($title, $reset = FALSE) {
210
    if ($reset) {
211
      \Drupal::entityManager()->getStorage('node')->resetCache();
212 213
    }
    $nodes = entity_load_multiple_by_properties('node', array('title' => $title));
214 215 216 217 218
    // Load the first node returned from the database.
    $returned_node = reset($nodes);
    return $returned_node;
  }

219 220 221
  /**
   * Creates a node based on default settings.
   *
222 223 224 225 226 227 228 229 230 231 232 233 234
   * @param array $settings
   *   (optional) An associative array of settings for the node, as used in
   *   entity_create(). Override the defaults by specifying the key and value
   *   in the array, for example:
   *   @code
   *     $this->drupalCreateNode(array(
   *       'title' => t('Hello, world!'),
   *       'type' => 'article',
   *     ));
   *   @endcode
   *   The following defaults are provided:
   *   - body: Random string using the default filter format:
   *     @code
235
   *       $settings['body'][0] = array(
236
   *         'value' => $this->randomMachineName(32),
237 238 239 240 241
   *         'format' => filter_default_format(),
   *       );
   *     @endcode
   *   - title: Random string.
   *   - type: 'page'.
242
   *   - uid: The currently logged in user, or anonymous.
243
   *
244
   * @return \Drupal\node\NodeInterface
245 246 247
   *   The created node entity.
   */
  protected function drupalCreateNode(array $settings = array()) {
248
    // Populate defaults array.
249
    $settings += array(
250 251 252 253
      'body'      => array(array(
        'value' => $this->randomMachineName(32),
        'format' => filter_default_format(),
      )),
254
      'title'     => $this->randomMachineName(8),
255
      'type'      => 'page',
256
      'uid'       => \Drupal::currentUser()->id(),
257
    );
258 259
    $node = entity_create('node', $settings);
    $node->save();
260 261 262 263 264 265 266

    return $node;
  }

  /**
   * Creates a custom content type based on default settings.
   *
267
   * @param array $values
268 269
   *   An array of settings to change from the defaults.
   *   Example: 'type' => 'foo'.
270
   *
271
   * @return \Drupal\node\Entity\NodeType
272
   *   Created content type.
273
   */
274
  protected function drupalCreateContentType(array $values = array()) {
275
    // Find a non-existent random type name.
276 277
    if (!isset($values['type'])) {
      do {
278
        $id = strtolower($this->randomMachineName(8));
279 280 281 282 283 284 285 286
      } while (node_type_load($id));
    }
    else {
      $id = $values['type'];
    }
    $values += array(
      'type' => $id,
      'name' => $id,
287
    );
288 289
    $type = entity_create('node_type', $values);
    $status = $type->save();
290
    node_add_body_field($type);
291
    \Drupal::service('router.builder')->rebuild();
292

293
    $this->assertEqual($status, SAVED_NEW, String::format('Created content type %type.', array('%type' => $type->id())));
294

295 296 297
    return $type;
  }

298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
  /**
   * Builds the renderable view of an entity.
   *
   * Entities postpone the composition of their renderable arrays to #pre_render
   * functions in order to maximize cache efficacy. This means that the full
   * rendable array for an entity is constructed in drupal_render(). Some tests
   * require the complete renderable array for an entity outside of the
   * drupal_render process in order to verify the presence of specific values.
   * This method isolates the steps in the render process that produce an
   * entity's renderable array.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to prepare a renderable array for.
   * @param string $view_mode
   *   (optional) The view mode that should be used to build the entity.
   * @param null $langcode
   *   (optional) For which language the entity should be prepared, defaults to
   *   the current content language.
   * @param bool $reset
   *   (optional) Whether to clear the cache for this entity.
   * @return array
   *
   * @see drupal_render()
   */
  protected function drupalBuildEntityView(EntityInterface $entity, $view_mode = 'full', $langcode = NULL, $reset = FALSE) {
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345
    $ensure_fully_built = function(&$elements) use (&$ensure_fully_built) {
      // If the default values for this element have not been loaded yet, populate
      // them.
      if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
        $elements += element_info($elements['#type']);
      }

      // Make any final changes to the element before it is rendered. This means
      // that the $element or the children can be altered or corrected before the
      // element is rendered into the final text.
      if (isset($elements['#pre_render'])) {
        foreach ($elements['#pre_render'] as $callable) {
          $elements = call_user_func($callable, $elements);
        }
      }

      // And recurse.
      $children = Element::children($elements, TRUE);
      foreach ($children as $key) {
        $ensure_fully_built($elements[$key]);
      }
    };

346 347 348 349
    $render_controller = $this->container->get('entity.manager')->getViewBuilder($entity->getEntityTypeId());
    if ($reset) {
      $render_controller->resetCache(array($entity->id()));
    }
350 351
    $build = $render_controller->view($entity, $view_mode, $langcode);
    $ensure_fully_built($build);
352

353
    return $build;
354 355
  }

356 357 358 359 360
  /**
   * Creates a block instance based on default settings.
   *
   * @param string $plugin_id
   *   The plugin ID of the block type for this block instance.
361 362
   * @param array $settings
   *   (optional) An associative array of settings for the block entity.
363
   *   Override the defaults by specifying the key and value in the array, for
364 365 366
   *   example:
   *   @code
   *     $this->drupalPlaceBlock('system_powered_by_block', array(
367
   *       'label' => t('Hello, world!'),
368 369 370
   *     ));
   *   @endcode
   *   The following defaults are provided:
371
   *   - label: Random string.
372
   *   - ID: Random string.
373
   *   - region: 'sidebar_first'.
374
   *   - theme: The default theme.
375
   *   - visibility: Empty array.
376
   *   - cache: array('max_age' => 0).
377
   *
378
   * @return \Drupal\block\Entity\Block
379
   *   The block entity.
380 381 382 383
   *
   * @todo
   *   Add support for creating custom block instances.
   */
384 385
  protected function drupalPlaceBlock($plugin_id, array $settings = array()) {
    $settings += array(
386
      'plugin' => $plugin_id,
387
      'region' => 'sidebar_first',
388
      'id' => strtolower($this->randomMachineName(8)),
389
      'theme' => $this->config('system.theme')->get('default'),
390
      'label' => $this->randomMachineName(8),
391
      'visibility' => array(),
392
      'weight' => 0,
393 394 395
      'cache' => array(
        'max_age' => 0,
      ),
396
    );
397 398
    $values = [];
    foreach (array('region', 'id', 'theme', 'plugin', 'weight', 'visibility') as $key) {
399
      $values[$key] = $settings[$key];
400
      // Remove extra values that do not belong in the settings array.
401 402
      unset($settings[$key]);
    }
403 404
    foreach ($values['visibility'] as $id => $visibility) {
      $values['visibility'][$id]['id'] = $id;
405
    }
406
    $values['settings'] = $settings;
407 408 409
    $block = entity_create('block', $values);
    $block->save();
    return $block;
410 411
  }

412 413 414 415 416 417 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 444 445 446
  /**
   * Checks to see whether a block appears on the page.
   *
   * @param \Drupal\block\Entity\Block $block
   *   The block entity to find on the page.
   */
  protected function assertBlockAppears(Block $block) {
    $result = $this->findBlockInstance($block);
    $this->assertTrue(!empty($result), format_string('Ensure the block @id appears on the page', array('@id' => $block->id())));
  }

  /**
   * Checks to see whether a block does not appears on the page.
   *
   * @param \Drupal\block\Entity\Block $block
   *   The block entity to find on the page.
   */
  protected function assertNoBlockAppears(Block $block) {
    $result = $this->findBlockInstance($block);
    $this->assertFalse(!empty($result), format_string('Ensure the block @id does not appear on the page', array('@id' => $block->id())));
  }

  /**
   * Find a block instance on the page.
   *
   * @param \Drupal\block\Entity\Block $block
   *   The block entity to find on the page.
   *
   * @return array
   *   The result from the xpath query.
   */
  protected function findBlockInstance(Block $block) {
    return $this->xpath('//div[@id = :id]', array(':id' => 'block-' . $block->id()));
  }

447
  /**
448
   * Gets a list files that can be used in tests.
449
   *
450
   * @param $type
451 452
   *   File type, possible values: 'binary', 'html', 'image', 'javascript',
   *   'php', 'sql', 'text'.
453 454
   * @param $size
   *   File size in bytes to match. Please check the tests/files folder.
455
   *
456 457
   * @return
   *   List of files that match filter.
458
   */
459
  protected function drupalGetTestFiles($type, $size = NULL) {
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478
    if (empty($this->generatedTestFiles)) {
      // Generate binary test files.
      $lines = array(64, 1024);
      $count = 0;
      foreach ($lines as $line) {
        simpletest_generate_file('binary-' . $count++, 64, $line, 'binary');
      }

      // Generate text test files.
      $lines = array(16, 256, 1024, 2048, 20480);
      $count = 0;
      foreach ($lines as $line) {
        simpletest_generate_file('text-' . $count++, 64, $line);
      }

      // Copy other test files from simpletest.
      $original = drupal_get_path('module', 'simpletest') . '/files';
      $files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
      foreach ($files as $file) {
479
        file_unmanaged_copy($file->uri, PublicStream::basePath());
480
      }
481

482 483 484 485
      $this->generatedTestFiles = TRUE;
    }

    $files = array();
486 487
    // Make sure type is valid.
    if (in_array($type, array('binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'))) {
488
      $files = file_scan_directory('public://', '/' . $type . '\-.*/');
489 490 491 492

      // If size is set then remove any files that are not of that size.
      if ($size !== NULL) {
        foreach ($files as $file) {
493
          $stats = stat($file->uri);
494
          if ($stats['size'] != $size) {
495
            unset($files[$file->uri]);
496 497 498 499 500 501 502 503 504
          }
        }
      }
    }
    usort($files, array($this, 'drupalCompareFiles'));
    return $files;
  }

  /**
505
   * Compare two files based on size and file name.
506
   */
507
  protected function drupalCompareFiles($file1, $file2) {
508
    $compare_size = filesize($file1->uri) - filesize($file2->uri);
509 510 511
    if ($compare_size) {
      // Sort by file size.
      return $compare_size;
512 513
    }
    else {
514 515
      // The files were the same size, so sort alphabetically.
      return strnatcmp($file1->name, $file2->name);
516 517 518 519
    }
  }

  /**
520
   * Create a user with a given set of permissions.
521
   *
522 523 524
   * @param array $permissions
   *   Array of permission names to assign to user. Note that the user always
   *   has the default permissions derived from the "authenticated users" role.
525
   * @param string $name
526
   *   The user name.
527
   *
528
   * @return \Drupal\user\Entity\User|false
529
   *   A fully loaded user object with pass_raw property, or FALSE if account
530 531
   *   creation fails.
   */
532
  protected function drupalCreateUser(array $permissions = array(), $name = NULL) {
533 534 535 536 537 538 539
    // Create a role with the given permission set, if any.
    $rid = FALSE;
    if ($permissions) {
      $rid = $this->drupalCreateRole($permissions);
      if (!$rid) {
        return FALSE;
      }
540 541 542 543
    }

    // Create a user assigned to that role.
    $edit = array();
544
    $edit['name']   = !empty($name) ? $name : $this->randomMachineName();
545
    $edit['mail']   = $edit['name'] . '@example.com';
546 547
    $edit['pass']   = user_password();
    $edit['status'] = 1;
548
    if ($rid) {
549
      $edit['roles'] = array($rid);
550
    }
551

552 553
    $account = entity_create('user', $edit);
    $account->save();
554

555 556
    $this->assertTrue($account->id(), String::format('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), 'User login');
    if (!$account->id()) {
557 558 559 560 561 562 563 564 565
      return FALSE;
    }

    // Add the raw password so that we can log in as this user.
    $account->pass_raw = $edit['pass'];
    return $account;
  }

  /**
566
   * Creates a role with specified permissions.
567
   *
568
   * @param array $permissions
569
   *   Array of permission names to assign to role.
570 571 572 573
   * @param string $rid
   *   (optional) The role ID (machine name). Defaults to a random name.
   * @param string $name
   *   (optional) The label for the role. Defaults to a random string.
574 575 576
   * @param integer $weight
   *   (optional) The weight for the role. Defaults NULL so that entity_create()
   *   sets the weight to maximum + 1.
577 578
   *
   * @return string
579
   *   Role ID of newly created role, or FALSE if role creation failed.
580
   */
581
  protected function drupalCreateRole(array $permissions, $rid = NULL, $name = NULL, $weight = NULL) {
582 583
    // Generate a random, lowercase machine name if none was passed.
    if (!isset($rid)) {
584
      $rid = strtolower($this->randomMachineName(8));
585 586 587
    }
    // Generate a random label.
    if (!isset($name)) {
588 589 590
      // In the role UI role names are trimmed and random string can start or
      // end with a space.
      $name = trim($this->randomString(8));
591 592
    }

593
    // Check the all the permissions strings are valid.
594 595 596 597
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

598
    // Create new role.
599 600 601 602 603 604 605 606
    $role = entity_create('user_role', array(
      'id' => $rid,
      'label' => $name,
    ));
    if (!is_null($weight)) {
      $role->set('weight', $weight);
    }
    $result = $role->save();
607

608
    $this->assertIdentical($result, SAVED_NEW, String::format('Created role ID @rid with name @name.', array(
609 610
      '@name' => var_export($role->label(), TRUE),
      '@rid' => var_export($role->id(), TRUE),
611
    )), 'Role');
612 613 614 615

    if ($result === SAVED_NEW) {
      // Grant the specified permissions to the role, if any.
      if (!empty($permissions)) {
616
        user_role_grant_permissions($role->id(), $permissions);
617
        $assigned_permissions = Role::load($role->id())->getPermissions();
618 619
        $missing_permissions = array_diff($permissions, $assigned_permissions);
        if (!$missing_permissions) {
620
          $this->pass(String::format('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), 'Role');
621 622
        }
        else {
623
          $this->fail(String::format('Failed to create permissions: @perms', array('@perms' => implode(', ', $missing_permissions))), 'Role');
624 625
        }
      }
626
      return $role->id();
627 628 629 630 631 632
    }
    else {
      return FALSE;
    }
  }

633
  /**
634
   * Checks whether a given list of permission names is valid.
635
   *
636 637
   * @param array $permissions
   *   The permission names to check.
638
   *
639 640
   * @return bool
   *   TRUE if the permissions are valid, FALSE otherwise.
641
   */
642
  protected function checkPermissions(array $permissions) {
643
    $available = array_keys(\Drupal::service('user.permissions')->getPermissions());
644 645 646
    $valid = TRUE;
    foreach ($permissions as $permission) {
      if (!in_array($permission, $available)) {
647
        $this->fail(String::format('Invalid permission %permission.', array('%permission' => $permission)), 'Role');
648 649 650 651 652 653
        $valid = FALSE;
      }
    }
    return $valid;
  }

654
  /**
655 656 657 658 659
   * Log in a user with the internal browser.
   *
   * If a user is already logged in, then the current user is logged out before
   * logging in the specified user.
   *
660
   * Please note that neither the current user nor the passed-in user object is
661 662 663
   * populated with data of the logged in user. If you need full access to the
   * user object after logging in, it must be updated manually. If you also need
   * access to the plain-text password of the user (set by drupalCreateUser()),
664
   * e.g. to log in the same user again, then it must be re-assigned manually.
665 666 667 668 669 670 671
   * For example:
   * @code
   *   // Create a user.
   *   $account = $this->drupalCreateUser(array());
   *   $this->drupalLogin($account);
   *   // Load real user object.
   *   $pass_raw = $account->pass_raw;
672
   *   $account = user_load($account->id());
673 674
   *   $account->pass_raw = $pass_raw;
   * @endcode
675
   *
676
   * @param \Drupal\Core\Session\AccountInterface $account
677
   *   User object representing the user to log in.
678 679
   *
   * @see drupalCreateUser()
680
   */
681
  protected function drupalLogin(AccountInterface $account) {
682
    if ($this->loggedInUser) {
683 684 685 686
      $this->drupalLogout();
    }

    $edit = array(
687
      'name' => $account->getUsername(),
688
      'pass' => $account->pass_raw
689
    );
690
    $this->drupalPostForm('user/login', $edit, t('Log in'));
691

692
    // @see WebTestBase::drupalUserIsLoggedIn()
693 694
    if (isset($this->sessionId)) {
      $account->session_id = $this->sessionId;
695
    }
696
    $pass = $this->assert($this->drupalUserIsLoggedIn($account), format_string('User %name successfully logged in.', array('%name' => $account->getUsername())), 'User login');
697
    if ($pass) {
698
      $this->loggedInUser = $account;
699
      $this->container->get('current_user')->setAccount($account);
700
    }
701 702
  }

703 704 705
  /**
   * Returns whether a given user account is logged in.
   *
706
   * @param \Drupal\user\UserInterface $account
707 708 709 710 711 712
   *   The user account object to check.
   */
  protected function drupalUserIsLoggedIn($account) {
    if (!isset($account->session_id)) {
      return FALSE;
    }
713 714
    // The session ID is hashed before being stored in the database.
    // @see \Drupal\Core\Session\SessionHandler::read()
715
    return (bool) db_query("SELECT sid FROM {users_field_data} u INNER JOIN {sessions} s ON u.uid = s.uid AND u.default_langcode = 1 WHERE s.sid = :sid", array(':sid' => Crypt::hashBase64($account->session_id)))->fetchField();
716 717
  }

718 719 720 721
  /**
   * Logs a user out of the internal browser and confirms.
   *
   * Confirms logout by checking the login page.
722
   */
723
  protected function drupalLogout() {
724 725 726
    // Make a request to the logout page, and redirect to the user page, the
    // idea being if you were properly logged out you should be seeing a login
    // screen.
727
    $this->drupalGet('user/logout', array('query' => array('destination' => 'user/login')));
728 729 730
    $this->assertResponse(200, 'User was logged out.');
    $pass = $this->assertField('name', 'Username field found.', 'Logout');
    $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
731

732
    if ($pass) {
733 734
      // @see WebTestBase::drupalUserIsLoggedIn()
      unset($this->loggedInUser->session_id);
735
      $this->loggedInUser = FALSE;
736
      $this->container->get('current_user')->setAccount(new AnonymousUserSession());
737
    }
738 739
  }

740 741 742 743 744 745 746
  /**
   * Returns the session name in use on the child site.
   *
   * @return string
   *   The name of the session cookie.
   */
  public function getSessionName() {
747
    return $this->sessionName;
748 749
  }

750 751 752
  /**
   * Sets up a Drupal site for running functional and integration tests.
   *
753 754
   * Installs Drupal with the installation profile specified in
   * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
755
   *
756 757 758
   * Afterwards, installs any additional modules specified in the static
   * \Drupal\simpletest\WebTestBase::$modules property of each class in the
   * class hierarchy.
759 760 761 762 763 764 765
   *
   * After installation all caches are flushed and several configuration values
   * are reset to the values of the parent site executing the test, since the
   * default values may be incompatible with the environment in which tests are
   * being executed.
   */
  protected function setUp() {
766 767 768 769 770 771 772
    // When running tests through the Simpletest UI (vs. on the command line),
    // Simpletest's batch conflicts with the installer's batch. Batch API does
    // not support the concept of nested batches (in which the nested is not
    // progressive), so we need to temporarily pretend there was no batch.
    // Backup the currently running Simpletest batch.
    $this->originalBatch = batch_get();

773
    // Define information about the user 1 account.
774
    $this->rootUser = new UserSession(array(
775
      'uid' => 1,
776 777
      'name' => 'admin',
      'mail' => 'admin@example.com',
778
      'pass_raw' => $this->randomMachineName(),
779
    ));
780

781 782 783 784
    // The child site derives its session name from the database prefix when
    // running web tests.
    $prefix = (Request::createFromGlobals()->isSecure() ? 'SSESS' : 'SESS');
    $this->sessionName = $prefix . substr(hash('sha256', $this->databasePrefix), 0, 32);
785

786 787 788
    // Reset the static batch to remove Simpletest's batch operations.
    $batch = &batch_get();
    $batch = array();
789

790 791 792 793 794 795 796
    // Get parameters for install_drupal() before removing global variables.
    $parameters = $this->installParameters();

    // Prepare installer settings that are not install_drupal() parameters.
    // Copy and prepare an actual settings.php, so as to resemble a regular
    // installation.
    // Not using File API; a potential error must trigger a PHP warning.
797 798
    $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
    copy(DRUPAL_ROOT . '/sites/default/default.settings.php', $directory . '/settings.php');
799
    copy(DRUPAL_ROOT . '/sites/default/default.services.yml', $directory . '/services.yml');
800 801 802 803 804

    // All file system paths are created by System module during installation.
    // @see system_requirements()
    // @see TestBase::prepareEnvironment()
    $settings['settings']['file_public_path'] = (object) array(
805
      'value' => $this->publicFilesDirectory,
806 807
      'required' => TRUE,
    );
808
    $settings['settings']['file_private_path'] = (object) array(
809
      'value' => $this->privateFilesDirectory,
810 811
      'required' => TRUE,
    );
812 813 814
    // Save the original site directory path, so that extensions in the
    // site-specific directory can still be discovered in the test site
    // environment.
815
    // @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
816 817 818 819
    $settings['settings']['test_parent_site'] = (object) array(
      'value' => $this->originalSite,
      'required' => TRUE,
    );
820
    // Add the parent profile's search path to the child site's search paths.
821
    // @see \Drupal\Core\Extension\ExtensionDiscovery::getProfileDirectories()
822 823 824 825 826
    $settings['conf']['simpletest.settings']['parent_profile'] = (object) array(
      'value' => $this->originalProfile,
      'required' => TRUE,
    );
    $this->writeSettings($settings);
827 828 829 830 831 832 833
    // Allow for test-specific overrides.
    $settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSite . '/settings.testing.php';
    if (file_exists($settings_testing_file)) {
      // Copy the testing-specific settings.php overrides in place.
      copy($settings_testing_file, $directory . '/settings.testing.php');
      // Add the name of the testing class to settings.php and include the
      // testing specific overrides
834
      file_put_contents($directory . '/settings.php', "\n\$test_class = '" . get_class($this) ."';\n" . 'include DRUPAL_ROOT . \'/\' . $site_path . \'/settings.testing.php\';' ."\n", FILE_APPEND);
835 836 837 838 839 840
    }
    $settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
    if (file_exists($settings_services_file)) {
      // Copy the testing-specific service overrides in place.
      copy($settings_services_file, $directory . '/services.yml');
    }
841 842 843 844 845 846 847 848 849 850 851
    if ($this->strictConfigSchema) {
      // Add a listener to validate configuration schema on save.
      $yaml = new \Symfony\Component\Yaml\Yaml();
      $services = $yaml->parse($directory . '/services.yml');
      $services['services']['simpletest.config_schema_checker'] = [
        'class' => 'Drupal\Core\Config\Testing\ConfigSchemaChecker',
        'arguments' => ['@config.typed'],
        'tags' => [['name' => 'event_subscriber']]
      ];
      file_put_contents($directory . '/services.yml', $yaml->dump($services));
    }
852 853 854
    // Since Drupal is bootstrapped already, install_begin_request() will not
    // bootstrap into DRUPAL_BOOTSTRAP_CONFIGURATION (again). Hence, we have to
    // reload the newly written custom settings.php manually.
855
    $class_loader = require DRUPAL_ROOT . '/core/vendor/autoload.php';
856
    Settings::initialize(DRUPAL_ROOT, $directory, $class_loader);
857

858 859
    // Execute the non-interactive installer.
    require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
860
    install_drupal($class_loader, $parameters);
861

862
    // Import new settings.php written by the installer.
863
    Settings::initialize(DRUPAL_ROOT, $directory, $class_loader);
864 865 866 867 868 869 870 871 872 873
    foreach ($GLOBALS['config_directories'] as $type => $path) {
      $this->configDirectories[$type] = $path;
    }

    // After writing settings.php, the installer removes write permissions
    // from the site directory. To allow drupal_generate_test_ua() to write
    // a file containing the private key for drupal_valid_test_ua(), the site
    // directory has to be writable.
    // TestBase::restoreEnvironment() will delete the entire site directory.
    // Not using File API; a potential error must trigger a PHP warning.
874
    chmod($directory, 0777);
875

876
    $request = \Drupal::request();
877
    $this->kernel = DrupalKernel::createFromRequest($request, $class_loader, 'prod', TRUE);
878
    $this->kernel->prepareLegacyRequest($request);
879 880 881
    // Force the container to be built from scratch instead of loaded from the
    // disk. This forces us to not accidently load the parent site.
    $container = $this->kernel->rebuildContainer();
882

883
    $config = $container->get('config.factory');
884

885 886 887 888
    // Manually create and configure private and temporary files directories.
    // While these could be preset/enforced in settings.php like the public
    // files directory above, some tests expect them to be configurable in the
    // UI. If declared in settings.php, they would no longer be configurable.
889 890
    file_prepare_directory($this->privateFilesDirectory, FILE_CREATE_DIRECTORY);
    file_prepare_directory($this->tempFilesDirectory, FILE_CREATE_DIRECTORY);
891
    $config->get('system.file')
892
      ->set('path.temporary', $this->tempFilesDirectory)
893 894 895
      ->save();

    // Manually configure the test mail collector implementation to prevent
896
    // tests from sending out emails and collect them in state instead.
897 898
    // While this should be enforced via settings.php prior to installation,
    // some tests expect to be able to test mail system implementations.
899
    $config->get('system.mail')
900
      ->set('interface.default', 'test_mail_collector')
901 902
      ->save();

903 904 905 906
    // By default, verbosely display all errors and disable all production
    // environment optimizations for all tests to avoid needless overhead and
    // ensure a sane default experience for test authors.
    // @see https://drupal.org/node/2259167
907
    $config->get('system.logging')
908 909
      ->set('error_level', 'verbose')
      ->save();
910
    $config->get('system.performance')
911 912
      ->set('css.preprocess', FALSE)
      ->set('js.preprocess', FALSE)
913 914
      ->save();

915 916 917
    // Restore the original Simpletest batch.
    $batch = &batch_get();
    $batch = $this->originalBatch;
918

919 920
    // Collect modules to install.
    $class = get_class($this);
921
    $modules = array();
922 923 924 925 926 927
    while ($class) {
      if (property_exists($class, 'modules')) {
        $modules = array_merge($modules, $class::$modules);
      }
      $class = get_parent_class($class);
    }
928
    if ($modules) {
929
      $modules = array_unique($modules);
930 931 932 933 934 935 936 937 938
      try {
        $success = $container->get('module_installer')->install($modules, TRUE);
        $this->assertTrue($success, String::format('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
      }
      catch (\Drupal\Core\Extension\MissingDependencyException $e) {
        // The exception message has all the details.
        $this->fail($e->getMessage());
      }

939
      $this->rebuildContainer();
940
    }
941

942 943 944
    // Reset/rebuild all data structures after enabling the modules, primarily
    // to synchronize all data structures and caches between the test runner and
    // the child site.
945
    // @see \Drupal\Core\DrupalKernel::bootCode()
946 947
    // @todo Test-specific setUp() methods may set up further fixtures; find a
    //   way to execute this after setUp() is done, or to eliminate it entirely.
948
    $this->resetAll();
949
    $this->kernel->prepareLegacyRequest($request);
950

951 952 953 954 955
    // Explicitly call register() again on the container registered in \Drupal.
    // @todo This should already be called through
    //   DrupalKernel::prepareLegacyRequest() -> DrupalKernel::boot() but that
    //   appears to be calling a different container.
    $this->container->get('stream_wrapper_manager')->register();
956 957
  }