WebTestBase.php 101 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\FileCache\FileCacheFactory;
11
use Drupal\Component\Serialization\Json;
12
use Drupal\Component\Serialization\Yaml;
13
use Drupal\Component\Utility\Crypt;
14
use Drupal\Component\Utility\Html;
15
use Drupal\Component\Utility\NestedArray;
16
use Drupal\Core\Cache\Cache;
17
use Drupal\Component\Utility\SafeMarkup;
18
use Drupal\Core\DependencyInjection\YamlFileLoader;
19
use Drupal\Core\DrupalKernel;
20 21
use Drupal\Core\Database\Database;
use Drupal\Core\Database\ConnectionNotDefinedException;
22
use Drupal\Core\Entity\EntityInterface;
23
use Drupal\Core\Language\LanguageInterface;
24
use Drupal\Core\Render\Element;
25
use Drupal\Core\Session\AccountInterface;
26
use Drupal\Core\Session\AnonymousUserSession;
27
use Drupal\Core\Session\UserSession;
28
use Drupal\Core\Site\Settings;
29
use Drupal\Core\StreamWrapper\PublicStream;
30
use Drupal\Core\Datetime\DrupalDateTime;
31
use Drupal\block\Entity\Block;
32
use Drupal\node\Entity\NodeType;
33
use Drupal\Core\Url;
34
use Symfony\Component\HttpFoundation\Request;
35
use Drupal\user\Entity\Role;
36 37 38

/**
 * Test case for typical Drupal tests.
39 40
 *
 * @ingroup testing
41
 */
42 43
abstract class WebTestBase extends TestBase {

44 45
  use AssertContentTrait;

46 47 48 49 50
  /**
   * The profile to install as a basis for testing.
   *
   * @var string
   */
51
  protected $profile = 'testing';
52

53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
  /**
   * 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;

74 75 76 77 78 79 80
  /**
   * The cookies of the page currently loaded in the internal browser.
   *
   * @var array
   */
  protected $cookies;

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

91 92 93
  /**
   * The current user logged in using the internal browser.
   *
94
   * @var \Drupal\Core\Session\AccountInterface|bool
95 96 97
   */
  protected $loggedInUser = FALSE;

98 99 100 101 102 103 104 105
  /**
   * The "#1" admin user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $rootUser;


106 107 108 109 110 111 112 113 114 115 116
  /**
   * 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.
   *
117 118
   * \Drupal\simpletest\WebTestBase itself never sets this but always obeys what
   * is set.
119 120 121
   */
  protected $additionalCurlOptions = array();

122 123 124 125 126 127 128
  /**
   * The original batch, before it was changed for testing purposes.
   *
   * @var array
   */
  protected $originalBatch;

129
  /**
130
   * The original user, before it was changed to a clean uid = 1 for testing.
131 132 133 134 135
   *
   * @var object
   */
  protected $originalUser = NULL;

136
  /**
137
   * The original shutdown handlers array, before it was cleaned for testing.
138 139 140 141 142
   *
   * @var array
   */
  protected $originalShutdownCallbacks = array();

143 144 145
  /**
   * The current session name, if available.
   */
146
  protected $sessionName = NULL;
147 148 149 150

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

153 154 155 156 157
  /**
   * Whether the files were copied to the test files directory.
   */
  protected $generatedTestFiles = FALSE;

158 159 160 161 162
  /**
   * The maximum number of redirects to follow when handling responses.
   */
  protected $maximumRedirects = 5;

163 164 165
  /**
   * The number of redirects followed during the handling of a request.
   */
166
  protected $redirectCount;
167

168 169
  /**
   * The kernel used in this test.
170 171
   *
   * @var \Drupal\Core\DrupalKernel
172 173 174
   */
  protected $kernel;

175 176 177 178 179
  /**
   * The config directories used in this test.
   */
  protected $configDirectories = array();

180 181 182 183 184 185 186
  /**
   * Cookies to set on curl requests.
   *
   * @var array
   */
  protected $curlCookies = array();

187 188 189 190 191 192 193
  /**
   * An array of custom translations suitable for drupal_rewrite_settings().
   *
   * @var array
   */
  protected $customTranslations;

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

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

223 224 225
  /**
   * Creates a node based on default settings.
   *
226 227 228 229 230 231 232 233 234 235 236 237 238
   * @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
239
   *       $settings['body'][0] = array(
240
   *         'value' => $this->randomMachineName(32),
241 242 243 244 245
   *         'format' => filter_default_format(),
   *       );
   *     @endcode
   *   - title: Random string.
   *   - type: 'page'.
246
   *   - uid: The currently logged in user, or anonymous.
247
   *
248
   * @return \Drupal\node\NodeInterface
249 250 251
   *   The created node entity.
   */
  protected function drupalCreateNode(array $settings = array()) {
252
    // Populate defaults array.
253
    $settings += array(
254 255 256 257
      'body'      => array(array(
        'value' => $this->randomMachineName(32),
        'format' => filter_default_format(),
      )),
258
      'title'     => $this->randomMachineName(8),
259
      'type'      => 'page',
260
      'uid'       => \Drupal::currentUser()->id(),
261
    );
262 263
    $node = entity_create('node', $settings);
    $node->save();
264 265 266 267 268 269 270

    return $node;
  }

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

297
    $this->assertEqual($status, SAVED_NEW, SafeMarkup::format('Created content type %type.', array('%type' => $type->id())));
298

299 300 301
    return $type;
  }

302 303 304 305 306
  /**
   * 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
307 308
   * renderable array for an entity is constructed in drupal_render(). Some
   * tests require the complete renderable array for an entity outside of the
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
   * 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) {
327 328 329 330
    $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'])) {
331
        $elements += \Drupal::service('element_info')->getInfo($elements['#type']);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
      }

      // 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]);
      }
    };

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

357
    return $build;
358 359
  }

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

451
  /**
452
   * Gets a list files that can be used in tests.
453
   *
454
   * @param $type
455 456
   *   File type, possible values: 'binary', 'html', 'image', 'javascript',
   *   'php', 'sql', 'text'.
457 458
   * @param $size
   *   File size in bytes to match. Please check the tests/files folder.
459
   *
460 461
   * @return
   *   List of files that match filter.
462
   */
463
  protected function drupalGetTestFiles($type, $size = NULL) {
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
    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) {
483
        file_unmanaged_copy($file->uri, PublicStream::basePath());
484
      }
485

486 487 488 489
      $this->generatedTestFiles = TRUE;
    }

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

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

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

  /**
524
   * Create a user with a given set of permissions.
525
   *
526 527 528
   * @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.
529
   * @param string $name
530
   *   The user name.
531
   *
532
   * @return \Drupal\user\Entity\User|false
533
   *   A fully loaded user object with pass_raw property, or FALSE if account
534 535
   *   creation fails.
   */
536
  protected function drupalCreateUser(array $permissions = array(), $name = NULL) {
537 538 539 540 541 542 543
    // Create a role with the given permission set, if any.
    $rid = FALSE;
    if ($permissions) {
      $rid = $this->drupalCreateRole($permissions);
      if (!$rid) {
        return FALSE;
      }
544 545 546 547
    }

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

556 557
    $account = entity_create('user', $edit);
    $account->save();
558

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

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

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

597
    // Check the all the permissions strings are valid.
598 599 600 601
    if (!$this->checkPermissions($permissions)) {
      return FALSE;
    }

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

612
    $this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array(
613 614
      '@name' => var_export($role->label(), TRUE),
      '@rid' => var_export($role->id(), TRUE),
615
    )), 'Role');
616 617 618 619

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

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

658
  /**
659 660 661 662 663
   * 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.
   *
664
   * Please note that neither the current user nor the passed-in user object is
665 666 667
   * 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()),
668
   * e.g. to log in the same user again, then it must be re-assigned manually.
669 670 671 672 673 674 675
   * For example:
   * @code
   *   // Create a user.
   *   $account = $this->drupalCreateUser(array());
   *   $this->drupalLogin($account);
   *   // Load real user object.
   *   $pass_raw = $account->pass_raw;
676
   *   $account = User::load($account->id());
677 678
   *   $account->pass_raw = $pass_raw;
   * @endcode
679
   *
680
   * @param \Drupal\Core\Session\AccountInterface $account
681
   *   User object representing the user to log in.
682 683
   *
   * @see drupalCreateUser()
684
   */
685
  protected function drupalLogin(AccountInterface $account) {
686
    if ($this->loggedInUser) {
687 688 689 690
      $this->drupalLogout();
    }

    $edit = array(
691
      'name' => $account->getUsername(),
692
      'pass' => $account->pass_raw
693
    );
694
    $this->drupalPostForm('user/login', $edit, t('Log in'));
695

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

707 708 709
  /**
   * Returns whether a given user account is logged in.
   *
710
   * @param \Drupal\user\UserInterface $account
711 712 713 714 715 716
   *   The user account object to check.
   */
  protected function drupalUserIsLoggedIn($account) {
    if (!isset($account->session_id)) {
      return FALSE;
    }
717 718 719 720 721 722 723 724 725 726 727
    $session_id = $account->session_id;
    $request_stack = $this->container->get('request_stack');
    $request = $request_stack->getCurrentRequest();
    $cookies = $request->cookies->all();
    foreach ($this->cookies as $name => $value) {
      $cookies[$name] = $value['value'];
    }
    $request_stack->push($request->duplicate(NULL, NULL, NULL, $cookies));
    $logged_in = (bool) $this->container->get('session_manager')->getSaveHandler()->read($session_id);
    $request_stack->pop();
    return $logged_in;
728 729
  }

730 731 732 733
  /**
   * Logs a user out of the internal browser and confirms.
   *
   * Confirms logout by checking the login page.
734
   */
735
  protected function drupalLogout() {
736 737 738
    // 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.
739
    $this->drupalGet('user/logout', array('query' => array('destination' => 'user/login')));
740 741 742
    $this->assertResponse(200, 'User was logged out.');
    $pass = $this->assertField('name', 'Username field found.', 'Logout');
    $pass = $pass && $this->assertField('pass', 'Password field found.', 'Logout');
743

744
    if ($pass) {
745 746
      // @see WebTestBase::drupalUserIsLoggedIn()
      unset($this->loggedInUser->session_id);
747
      $this->loggedInUser = FALSE;
748
      $this->container->get('current_user')->setAccount(new AnonymousUserSession());
749
    }
750 751
  }

752 753 754 755 756 757 758
  /**
   * Returns the session name in use on the child site.
   *
   * @return string
   *   The name of the session cookie.
   */
  public function getSessionName() {
759
    return $this->sessionName;
760 761
  }

762 763 764
  /**
   * Sets up a Drupal site for running functional and integration tests.
   *
765 766
   * Installs Drupal with the installation profile specified in
   * \Drupal\simpletest\WebTestBase::$profile into the prefixed database.
767
   *
768 769 770
   * Afterwards, installs any additional modules specified in the static
   * \Drupal\simpletest\WebTestBase::$modules property of each class in the
   * class hierarchy.
771 772 773 774 775 776 777
   *
   * 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() {
778 779 780 781 782 783 784
    // 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();

785
    // Define information about the user 1 account.
786
    $this->rootUser = new UserSession(array(
787
      'uid' => 1,
788 789
      'name' => 'admin',
      'mail' => 'admin@example.com',
790
      'pass_raw' => $this->randomMachineName(),
791
    ));
792

793 794 795 796
    // 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);
797

798 799 800
    // Reset the static batch to remove Simpletest's batch operations.
    $batch = &batch_get();
    $batch = array();
801

802 803 804 805 806 807 808
    // 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.
809 810
    $directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
    copy(DRUPAL_ROOT . '/sites/default/default.settings.php', $directory . '/settings.php');
811
    copy(DRUPAL_ROOT . '/sites/default/default.services.yml', $directory . '/services.yml');
812 813 814 815 816

    // All file system paths are created by System module during installation.
    // @see system_requirements()
    // @see TestBase::prepareEnvironment()
    $settings['settings']['file_public_path'] = (object) array(
817
      'value' => $this->publicFilesDirectory,
818 819
      'required' => TRUE,
    );
820
    $settings['settings']['file_private_path'] = (object) array(
821
      'value' => $this->privateFilesDirectory,
822 823
      'required' => TRUE,
    );
824 825 826
    // Save the original site directory path, so that extensions in the
    // site-specific directory can still be discovered in the test site
    // environment.
827
    // @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
828 829 830 831
    $settings['settings']['test_parent_site'] = (object) array(
      'value' => $this->originalSite,
      'required' => TRUE,
    );
832
    // Add the parent profile's search path to the child site's search paths.
833
    // @see \Drupal\Core\Extension\ExtensionDiscovery::getProfileDirectories()
834 835 836 837
    $settings['conf']['simpletest.settings']['parent_profile'] = (object) array(
      'value' => $this->originalProfile,
      'required' => TRUE,
    );
838 839 840 841
    $settings['settings']['apcu_ensure_unique_prefix'] = (object) array(
      'value' => FALSE,
      'required' => TRUE,
    );
842
    $this->writeSettings($settings);
843 844 845 846 847 848 849
    // 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
850
      file_put_contents($directory . '/settings.php', "\n\$test_class = '" . get_class($this) ."';\n" . 'include DRUPAL_ROOT . \'/\' . $site_path . \'/settings.testing.php\';' ."\n", FILE_APPEND);
851 852 853 854 855 856
    }
    $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');
    }
857 858 859 860 861 862 863 864 865 866 867
    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));
    }
868
    // Since Drupal is bootstrapped already, install_begin_request() will not
869 870
    // bootstrap again. Hence, we have to reload the newly written custom
    // settings.php manually.
871
    $class_loader = require DRUPAL_ROOT . '/autoload.php';
872
    Settings::initialize(DRUPAL_ROOT, $this->siteDirectory, $class_loader);
873

874 875
    // Execute the non-interactive installer.
    require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
876
    install_drupal($class_loader, $parameters);
877

878
    // Import new settings.php written by the installer.
879
    Settings::initialize(DRUPAL_ROOT, $this->siteDirectory, $class_loader);
880 881 882 883 884 885 886 887 888 889
    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.
890
    chmod($directory, 0777);
891

catch's avatar