UpdatePathTestBase.php 7.33 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
32
33
34
35
 * 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.
 *
 * @ingroup update_api
 *
 * @see hook_update_N()
36
37
38
 */
abstract class UpdatePathTestBase extends WebTestBase {

39
40
  use SchemaCheckTestTrait;

41
42
43
44
45
46
47
48
  /**
   * 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.
   *
49
50
51
52
   * 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.
   *
53
54
55
56
57
58
59
60
61
62
63
64
   * @var array
   */
  protected $databaseDumpFiles = [];

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

  /**
65
   * Flag that indicates whether the child site has been updated.
66
67
68
69
70
71
   *
   * @var bool
   */
  protected $upgradedSite = FALSE;

  /**
72
   * Array of errors triggered during the update process.
73
74
75
76
77
78
79
80
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
   *
   * @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;

106
107
108
109
110
111
112
113
114
  /**
   * Disable strict config schema checking.
   *
   * The schema is verified at the end of running the update.
   *
   * @var bool
   */
  protected $strictConfigSchema = FALSE;

115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  /**
   * 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');

    // Set the update url.
    $this->updateUrl = Url::fromRoute('system.db_update');
  }

  /**
131
   * Overrides WebTestBase::setUp() for update testing.
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
   *
   * 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() {
    // 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;
    }

    // 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();

    // Install any additional modules.
    $this->installModulesFromClassProperty($container);

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

    // Rebuild and reset.
    $this->rebuildAll();

    // Replace User 1 with the user created here.
    /** @var \Drupal\user\UserInterface $account */
    $account = User::load(1);
    $account->setPassword($this->rootUser->pass_raw);
    $account->setEmail($this->rootUser->getEmail());
    $account->setUsername($this->rootUser->getUsername());
    $account->save();
  }

  /**
   * 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) {
217
      $this->fail('Missing zlib requirement for update tests.');
218
219
      return FALSE;
    }
220
221
222
223
224
225
226
    // 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,
    ]]]);

227
228
229
230
231
    $this->drupalGet($this->updateUrl);
    $this->clickLink(t('Continue'));

    // Run the update hooks.
    $this->clickLink(t('Apply pending updates'));
232
233
234
235
236
237
238
239
240
241
242

    // 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());
    }
243
244
  }

245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  /**
   * {@inheritdoc}
   */
  protected function rebuildAll() {
    parent::rebuildAll();

    // Remove the notices we get due to the menu link rebuild prior to running
    // the system updates for the schema change.
    foreach ($this->assertions as $key => $assertion) {
      if ($assertion['message_group'] == 'Notice' && basename($assertion['file']) == 'MenuTreeStorage.php' && strpos($assertion['message'], 'unserialize(): Error at offset 0') !== FALSE) {
        unset($this->assertions[$key]);
        $this->deleteAssert($assertion['message_id']);
        $this->results['#exception']--;
      }
    }
  }

262
}