UpdatePathTestBase.php 8.37 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
<?php

/**
 * @file
 * Contains \Drupal\system\Tests\Update\UpdatePathTestBase.
 */

namespace Drupal\system\Tests\Update;

use Drupal\Component\Utility\Crypt;
11
use Drupal\config\Tests\SchemaCheckTestTrait;
12 13 14 15 16 17 18
use Drupal\Core\Database\Database;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
use Drupal\user\Entity\User;
use Symfony\Component\HttpFoundation\Request;

/**
19 20 21 22 23 24 25 26 27 28 29 30 31
 * Provides a base class for writing an update test.
 *
 * To write an update test:
 * - Write the hook_update_N() implementations that you are testing.
 * - Create one or more database dump files, which will set the database to the
 *   "before updates" state. Normally, these will add some configuration data to
 *   the database, set up some tables/fields, etc.
 * - Create a class that extends this class.
 * - In your setUp() method, point the $this->databaseDumpFiles variable to the
 *   database dump files, and then call parent::setUp() to run the base setUp()
 *   method in this class.
 * - In your test method, call $this->runUpdates() to run the necessary updates,
 *   and then use test assertions to verify that the result is what you expect.
32 33 34 35
 * - In order to test both with a "bare" database dump as well as with a
 *   database dump filled with content, extend your update path test class with
 *   a new test class that overrides the bare database dump. Refer to
 *   UpdatePathTestBaseFilledTest for an example.
36 37 38 39
 *
 * @ingroup update_api
 *
 * @see hook_update_N()
40 41 42
 */
abstract class UpdatePathTestBase extends WebTestBase {

43 44
  use SchemaCheckTestTrait;

45 46 47 48 49 50 51 52
  /**
   * Modules to enable after the database is loaded.
   */
  protected static $modules = [];

 /**
   * The file path(s) to the dumped database(s) to load into the child site.
   *
53 54 55 56
   * The file system/tests/fixtures/update/drupal-8.bare.standard.php.gz is
   * normally included first -- this sets up the base database from a bare
   * standard Drupal installation.
   *
57 58 59 60
   * The file system/tests/fixtures/update/drupal-8.filled.standard.php.gz
   * can also be used in case we want to test with a database filled with
   * content, and with all core modules enabled.
   *
61 62 63 64 65 66 67 68 69 70 71 72
   * @var array
   */
  protected $databaseDumpFiles = [];

  /**
   * The install profile used in the database dump file.
   *
   * @var string
   */
  protected $installProfile = 'standard';

  /**
73
   * Flag that indicates whether the child site has been updated.
74 75 76 77 78 79
   *
   * @var bool
   */
  protected $upgradedSite = FALSE;

  /**
80
   * Array of errors triggered during the update process.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
   *
   * @var array
   */
  protected $upgradeErrors = [];

  /**
   * Array of modules loaded when the test starts.
   *
   * @var array
   */
  protected $loadedModules = [];

  /**
   * Flag to indicate whether zlib is installed or not.
   *
   * @var bool
   */
  protected $zlibInstalled = TRUE;

  /**
   * Flag to indicate whether there are pending updates or not.
   *
   * @var bool
   */
  protected $pendingUpdates = TRUE;

  /**
   * The update URL.
   *
   * @var string
   */
  protected $updateUrl;

114 115 116 117 118 119 120 121 122
  /**
   * Disable strict config schema checking.
   *
   * The schema is verified at the end of running the update.
   *
   * @var bool
   */
  protected $strictConfigSchema = FALSE;

123 124 125 126 127 128 129 130 131 132 133 134 135
  /**
   * Constructs an UpdatePathTestCase object.
   *
   * @param $test_id
   *   (optional) The ID of the test. Tests with the same id are reported
   *   together.
   */
  function __construct($test_id = NULL) {
    parent::__construct($test_id);
    $this->zlibInstalled = function_exists('gzopen');
  }

  /**
136
   * Overrides WebTestBase::setUp() for update testing.
137 138 139 140 141 142 143
   *
   * The main difference in this method is that rather than performing the
   * installation via the installer, a database is loaded. Additional work is
   * then needed to set various things such as the config directories and the
   * container that would normally be done via the installer.
   */
  protected function setUp() {
144 145 146 147

    // Allow classes to set database dump files.
    $this->setDatabaseDumpFiles();

148 149 150 151 152 153 154 155
    // We are going to set a missing zlib requirement property for usage
    // during the performUpgrade() and tearDown() methods. Also set that the
    // tests failed.
    if (!$this->zlibInstalled) {
      parent::setUp();
      return;
    }

156 157 158 159 160
    // Set the update url. This must be set here rather than in
    // self::__construct() or the old URL generator will leak additional test
    // sites.
    $this->updateUrl = Url::fromRoute('system.db_update');

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
    // These methods are called from parent::setUp().
    $this->setBatch();
    $this->initUserSession();
    $this->prepareSettings();

    // Load the database(s).
    foreach ($this->databaseDumpFiles as $file) {
      if (substr($file, -3) == '.gz') {
        $file = "compress.zlib://$file";
      }
      require $file;
    }

    $this->initSettings();
    $request = Request::createFromGlobals();
    $container = $this->initKernel($request);
    $this->initConfig($container);

    // Add the config directories to settings.php.
    drupal_install_config_directories();

    // Restore the original Simpletest batch.
    $this->restoreBatch();

185 186 187
    // Set the container. parent::rebuildAll() would normally do this, but this
    // not safe to do here, because the database has not been updated yet.
    $this->container = \Drupal::getContainer();
188

189
    $this->replaceUser1();
190 191
  }

192 193 194 195 196
  /**
   * Set database dump files to be used.
   */
  abstract protected function setDatabaseDumpFiles();

197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
  /**
   * Add settings that are missed since the installer isn't run.
   */
  protected function prepareSettings() {
    parent::prepareSettings();

    // Remember the profile which was used.
    $settings['settings']['install_profile'] = (object) [
      'value' => $this->installProfile,
      'required' => TRUE,
    ];
    // Generate a hash salt.
    $settings['settings']['hash_salt'] = (object) [
      'value'    => Crypt::randomBytesBase64(55),
      'required' => TRUE,
    ];

    // Since the installer isn't run, add the database settings here too.
    $settings['databases']['default'] = (object) [
      'value' => Database::getConnectionInfo(),
      'required' => TRUE,
    ];

    $this->writeSettings($settings);
  }

  /**
   * Helper function to run pending database updates.
   */
  protected function runUpdates() {
    if (!$this->zlibInstalled) {
228
      $this->fail('Missing zlib requirement for update tests.');
229 230
      return FALSE;
    }
231 232 233 234 235 236 237
    // The site might be broken at the time so logging in using the UI might
    // not work, so we use the API itself.
    drupal_rewrite_settings(['settings' => ['update_free_access' => (object) [
      'value' => TRUE,
      'required' => TRUE,
    ]]]);

238 239 240
    $this->drupalGet($this->updateUrl);
    $this->clickLink(t('Continue'));

241
    $this->doSelectionTest();
242 243
    // Run the update hooks.
    $this->clickLink(t('Apply pending updates'));
244

245 246 247
    // Ensure there are no failed updates.
    $this->assertNoRaw('<strong>' . t('Failed:') . '</strong>');

248 249 250 251 252 253 254 255 256 257
    // The config schema can be incorrect while the update functions are being
    // executed. But once the update has been completed, it needs to be valid
    // again. Assert the schema of all configuration objects now.
    $names = $this->container->get('config.storage')->listAll();
    /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
    $typed_config = $this->container->get('config.typed');
    foreach ($names as $name) {
      $config = $this->config($name);
      $this->assertConfigSchema($typed_config, $name, $config->get());
    }
258 259 260

    // Ensure that the update hooks updated all entity schema.
    $this->assertFalse(\Drupal::service('entity.definition_update_manager')->needsUpdates(), 'After all updates ran, entity schema is up to date.');
261 262
  }

263 264 265 266 267 268 269 270 271 272 273 274 275 276
  /**
   * Replace User 1 with the user created here.
   */
  protected function replaceUser1() {
    /** @var \Drupal\user\UserInterface $account */
    // @todo: Saving the account before the update is problematic.
    //   https://www.drupal.org/node/2560237
    $account = User::load(1);
    $account->setPassword($this->rootUser->pass_raw);
    $account->setEmail($this->rootUser->getEmail());
    $account->setUsername($this->rootUser->getUsername());
    $account->save();
  }

277 278 279 280 281 282 283 284 285
  /**
   * Tests the selection page.
   */
  protected function doSelectionTest() {
    // No-op. Tests wishing to do test the selection page or the general
    // update.php environment before running update.php can override this method
    // and implement their required tests.
  }

286
}