3 namespace Drupal\system\Tests\Update;
5 use Drupal\Component\Utility\Crypt;
6 use Drupal\Tests\SchemaCheckTestTrait;
7 use Drupal\Core\Database\Database;
8 use Drupal\Core\DependencyInjection\ContainerBuilder;
9 use Drupal\Core\Language\Language;
11 use Drupal\simpletest\WebTestBase;
12 use Drupal\user\Entity\User;
13 use Symfony\Component\DependencyInjection\Reference;
14 use Symfony\Component\HttpFoundation\Request;
17 * Provides a base class for writing an update test.
19 * To write an update test:
20 * - Write the hook_update_N() implementations that you are testing.
21 * - Create one or more database dump files, which will set the database to the
22 * "before updates" state. Normally, these will add some configuration data to
23 * the database, set up some tables/fields, etc.
24 * - Create a class that extends this class.
25 * - In your setUp() method, point the $this->databaseDumpFiles variable to the
26 * database dump files, and then call parent::setUp() to run the base setUp()
27 * method in this class.
28 * - In your test method, call $this->runUpdates() to run the necessary updates,
29 * and then use test assertions to verify that the result is what you expect.
30 * - In order to test both with a "bare" database dump as well as with a
31 * database dump filled with content, extend your update path test class with
32 * a new test class that overrides the bare database dump. Refer to
33 * UpdatePathTestBaseFilledTest for an example.
37 * @see hook_update_N()
39 abstract class UpdatePathTestBase extends WebTestBase {
41 use SchemaCheckTestTrait;
44 * Modules to enable after the database is loaded.
46 protected static $modules = [];
49 * The file path(s) to the dumped database(s) to load into the child site.
51 * The file system/tests/fixtures/update/drupal-8.bare.standard.php.gz is
52 * normally included first -- this sets up the base database from a bare
53 * standard Drupal installation.
55 * The file system/tests/fixtures/update/drupal-8.filled.standard.php.gz
56 * can also be used in case we want to test with a database filled with
57 * content, and with all core modules enabled.
61 protected $databaseDumpFiles = [];
64 * The install profile used in the database dump file.
68 protected $installProfile = 'standard';
71 * Flag that indicates whether the child site has been updated.
75 protected $upgradedSite = FALSE;
78 * Array of errors triggered during the update process.
82 protected $upgradeErrors = [];
85 * Array of modules loaded when the test starts.
89 protected $loadedModules = [];
92 * Flag to indicate whether zlib is installed or not.
96 protected $zlibInstalled = TRUE;
99 * Flag to indicate whether there are pending updates or not.
103 protected $pendingUpdates = TRUE;
110 protected $updateUrl;
113 * Disable strict config schema checking.
115 * The schema is verified at the end of running the update.
119 protected $strictConfigSchema = FALSE;
122 * Fail the test if there are failed updates.
126 protected $checkFailedUpdates = TRUE;
129 * Constructs an UpdatePathTestCase object.
132 * (optional) The ID of the test. Tests with the same id are reported
135 public function __construct($test_id = NULL) {
136 parent::__construct($test_id);
137 $this->zlibInstalled = function_exists('gzopen');
141 * Overrides WebTestBase::setUp() for update testing.
143 * The main difference in this method is that rather than performing the
144 * installation via the installer, a database is loaded. Additional work is
145 * then needed to set various things such as the config directories and the
146 * container that would normally be done via the installer.
148 protected function setUp() {
150 // Allow classes to set database dump files.
151 $this->setDatabaseDumpFiles();
153 // We are going to set a missing zlib requirement property for usage
154 // during the performUpgrade() and tearDown() methods. Also set that the
156 if (!$this->zlibInstalled) {
161 // Set the update url. This must be set here rather than in
162 // self::__construct() or the old URL generator will leak additional test
164 $this->updateUrl = Url::fromRoute('system.db_update');
166 // These methods are called from parent::setUp().
168 $this->initUserSession();
169 $this->prepareSettings();
171 // Load the database(s).
172 foreach ($this->databaseDumpFiles as $file) {
173 if (substr($file, -3) == '.gz') {
174 $file = "compress.zlib://$file";
179 $this->initSettings();
180 $request = Request::createFromGlobals();
181 $container = $this->initKernel($request);
182 $this->initConfig($container);
184 // Add the config directories to settings.php.
185 drupal_install_config_directories();
187 // Restore the original Simpletest batch.
188 $this->restoreBatch();
190 // Set the container. parent::rebuildAll() would normally do this, but this
191 // not safe to do here, because the database has not been updated yet.
192 $this->container = \Drupal::getContainer();
194 $this->replaceUser1();
196 require_once \Drupal::root() . '/core/includes/update.inc';
200 * Set database dump files to be used.
202 abstract protected function setDatabaseDumpFiles();
205 * Add settings that are missed since the installer isn't run.
207 protected function prepareSettings() {
208 parent::prepareSettings();
210 // Remember the profile which was used.
211 $settings['settings']['install_profile'] = (object) [
212 'value' => $this->installProfile,
215 // Generate a hash salt.
216 $settings['settings']['hash_salt'] = (object) [
217 'value' => Crypt::randomBytesBase64(55),
221 // Since the installer isn't run, add the database settings here too.
222 $settings['databases']['default'] = (object) [
223 'value' => Database::getConnectionInfo(),
227 $this->writeSettings($settings);
231 * Helper function to run pending database updates.
233 protected function runUpdates() {
234 if (!$this->zlibInstalled) {
235 $this->fail('Missing zlib requirement for update tests.');
238 // The site might be broken at the time so logging in using the UI might
239 // not work, so we use the API itself.
240 drupal_rewrite_settings(['settings' => ['update_free_access' => (object) [
245 $this->drupalGet($this->updateUrl);
246 $this->clickLink(t('Continue'));
248 $this->doSelectionTest();
249 // Run the update hooks.
250 $this->clickLink(t('Apply pending updates'));
252 // Ensure there are no failed updates.
253 if ($this->checkFailedUpdates) {
254 $this->assertNoRaw('<strong>' . t('Failed:') . '</strong>');
256 // Ensure that there are no pending updates.
257 foreach (['update', 'post_update'] as $update_type) {
258 switch ($update_type) {
260 $all_updates = update_get_update_list();
263 $all_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
266 foreach ($all_updates as $module => $updates) {
267 if (!empty($updates['pending'])) {
268 foreach (array_keys($updates['pending']) as $update_name) {
269 $this->fail("The $update_name() update function from the $module module did not run.");
274 // Reset the static cache of drupal_get_installed_schema_version() so that
275 // more complex update path testing works.
276 drupal_static_reset('drupal_get_installed_schema_version');
278 // The config schema can be incorrect while the update functions are being
279 // executed. But once the update has been completed, it needs to be valid
280 // again. Assert the schema of all configuration objects now.
281 $names = $this->container->get('config.storage')->listAll();
282 /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
283 $typed_config = $this->container->get('config.typed');
284 $typed_config->clearCachedDefinitions();
285 foreach ($names as $name) {
286 $config = $this->config($name);
287 $this->assertConfigSchema($typed_config, $name, $config->get());
290 // Ensure that the update hooks updated all entity schema.
291 $needs_updates = \Drupal::entityDefinitionUpdateManager()->needsUpdates();
292 $this->assertFalse($needs_updates, 'After all updates ran, entity schema is up to date.');
293 if ($needs_updates) {
294 foreach (\Drupal::entityDefinitionUpdateManager()
295 ->getChangeSummary() as $entity_type_id => $summary) {
296 foreach ($summary as $message) {
297 $this->fail($message);
305 * Runs the install database tasks for the driver used by the test runner.
307 protected function runDbTasks() {
308 // Create a minimal container so that t() works.
309 // @see install_begin_request()
310 $container = new ContainerBuilder();
311 $container->setParameter('language.default_values', Language::$defaultValues);
313 ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
314 ->addArgument('%language.default_values%');
316 ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
317 ->addArgument(new Reference('language.default'));
318 \Drupal::setContainer($container);
320 require_once __DIR__ . '/../../../../../includes/install.inc';
321 $connection = Database::getConnection();
322 $errors = db_installer_object($connection->driver())->runTasks();
323 if (!empty($errors)) {
324 $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
329 * Replace User 1 with the user created here.
331 protected function replaceUser1() {
332 /** @var \Drupal\user\UserInterface $account */
333 // @todo: Saving the account before the update is problematic.
334 // https://www.drupal.org/node/2560237
335 $account = User::load(1);
336 $account->setPassword($this->rootUser->pass_raw);
337 $account->setEmail($this->rootUser->getEmail());
338 $account->setUsername($this->rootUser->getUsername());
343 * Tests the selection page.
345 protected function doSelectionTest() {
346 // No-op. Tests wishing to do test the selection page or the general
347 // update.php environment before running update.php can override this method
348 // and implement their required tests.