3 namespace Drupal\system\Tests\Update;
5 @trigger_error(__NAMESPACE__ . '\UpdatePathTestBase is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. Use \Drupal\FunctionalTests\Update\UpdatePathTestBase instead. See https://www.drupal.org/node/2896640.', E_USER_DEPRECATED);
7 use Drupal\Component\Utility\Crypt;
8 use Drupal\Tests\SchemaCheckTestTrait;
9 use Drupal\Core\Database\Database;
10 use Drupal\Core\DependencyInjection\ContainerBuilder;
11 use Drupal\Core\Language\Language;
13 use Drupal\simpletest\WebTestBase;
14 use Drupal\user\Entity\User;
15 use Symfony\Component\DependencyInjection\Reference;
16 use Symfony\Component\HttpFoundation\Request;
19 * Provides a base class for writing an update test.
21 * To write an update test:
22 * - Write the hook_update_N() implementations that you are testing.
23 * - Create one or more database dump files, which will set the database to the
24 * "before updates" state. Normally, these will add some configuration data to
25 * the database, set up some tables/fields, etc.
26 * - Create a class that extends this class.
27 * - In your setUp() method, point the $this->databaseDumpFiles variable to the
28 * database dump files, and then call parent::setUp() to run the base setUp()
29 * method in this class.
30 * - In your test method, call $this->runUpdates() to run the necessary updates,
31 * and then use test assertions to verify that the result is what you expect.
32 * - In order to test both with a "bare" database dump as well as with a
33 * database dump filled with content, extend your update path test class with
34 * a new test class that overrides the bare database dump. Refer to
35 * UpdatePathTestBaseFilledTest for an example.
39 * @deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0.
40 * Use \Drupal\FunctionalTests\Update\UpdatePathTestBase.
41 * @see https://www.drupal.org/node/2896640
43 * @see hook_update_N()
45 abstract class UpdatePathTestBase extends WebTestBase {
47 use SchemaCheckTestTrait;
50 * Modules to enable after the database is loaded.
52 protected static $modules = [];
55 * The file path(s) to the dumped database(s) to load into the child site.
57 * The file system/tests/fixtures/update/drupal-8.bare.standard.php.gz is
58 * normally included first -- this sets up the base database from a bare
59 * standard Drupal installation.
61 * The file system/tests/fixtures/update/drupal-8.filled.standard.php.gz
62 * can also be used in case we want to test with a database filled with
63 * content, and with all core modules enabled.
67 protected $databaseDumpFiles = [];
70 * The install profile used in the database dump file.
74 protected $installProfile = 'standard';
77 * Flag that indicates whether the child site has been updated.
81 protected $upgradedSite = FALSE;
84 * Array of errors triggered during the update process.
88 protected $upgradeErrors = [];
91 * Array of modules loaded when the test starts.
95 protected $loadedModules = [];
98 * Flag to indicate whether zlib is installed or not.
102 protected $zlibInstalled = TRUE;
105 * Flag to indicate whether there are pending updates or not.
109 protected $pendingUpdates = TRUE;
116 protected $updateUrl;
119 * Disable strict config schema checking.
121 * The schema is verified at the end of running the update.
125 protected $strictConfigSchema = FALSE;
128 * Fail the test if there are failed updates.
132 protected $checkFailedUpdates = TRUE;
135 * Constructs an UpdatePathTestCase object.
138 * (optional) The ID of the test. Tests with the same id are reported
141 public function __construct($test_id = NULL) {
142 parent::__construct($test_id);
143 $this->zlibInstalled = function_exists('gzopen');
147 * Overrides WebTestBase::setUp() for update testing.
149 * The main difference in this method is that rather than performing the
150 * installation via the installer, a database is loaded. Additional work is
151 * then needed to set various things such as the config directories and the
152 * container that would normally be done via the installer.
154 protected function setUp() {
156 // Allow classes to set database dump files.
157 $this->setDatabaseDumpFiles();
159 // We are going to set a missing zlib requirement property for usage
160 // during the performUpgrade() and tearDown() methods. Also set that the
162 if (!$this->zlibInstalled) {
167 // Set the update url. This must be set here rather than in
168 // self::__construct() or the old URL generator will leak additional test
170 $this->updateUrl = Url::fromRoute('system.db_update');
172 // These methods are called from parent::setUp().
174 $this->initUserSession();
175 $this->prepareSettings();
177 // Load the database(s).
178 foreach ($this->databaseDumpFiles as $file) {
179 if (substr($file, -3) == '.gz') {
180 $file = "compress.zlib://$file";
185 $this->initSettings();
186 $request = Request::createFromGlobals();
187 $container = $this->initKernel($request);
188 $this->initConfig($container);
190 // Add the config directories to settings.php.
191 drupal_install_config_directories();
193 // Restore the original Simpletest batch.
194 $this->restoreBatch();
196 // Set the container. parent::rebuildAll() would normally do this, but this
197 // not safe to do here, because the database has not been updated yet.
198 $this->container = \Drupal::getContainer();
200 $this->replaceUser1();
202 require_once \Drupal::root() . '/core/includes/update.inc';
206 * Set database dump files to be used.
208 abstract protected function setDatabaseDumpFiles();
211 * Add settings that are missed since the installer isn't run.
213 protected function prepareSettings() {
214 parent::prepareSettings();
216 // Remember the profile which was used.
217 $settings['settings']['install_profile'] = (object) [
218 'value' => $this->installProfile,
221 // Generate a hash salt.
222 $settings['settings']['hash_salt'] = (object) [
223 'value' => Crypt::randomBytesBase64(55),
227 // Since the installer isn't run, add the database settings here too.
228 $settings['databases']['default'] = (object) [
229 'value' => Database::getConnectionInfo(),
233 $this->writeSettings($settings);
237 * Helper function to run pending database updates.
239 protected function runUpdates() {
240 if (!$this->zlibInstalled) {
241 $this->fail('Missing zlib requirement for update tests.');
244 // The site might be broken at the time so logging in using the UI might
245 // not work, so we use the API itself.
246 drupal_rewrite_settings([
248 'update_free_access' => (object) [
255 $this->drupalGet($this->updateUrl);
256 $this->clickLink(t('Continue'));
258 $this->doSelectionTest();
259 // Run the update hooks.
260 $this->clickLink(t('Apply pending updates'));
262 // Ensure there are no failed updates.
263 if ($this->checkFailedUpdates) {
264 $this->assertNoRaw('<strong>' . t('Failed:') . '</strong>');
266 // Ensure that there are no pending updates.
267 foreach (['update', 'post_update'] as $update_type) {
268 switch ($update_type) {
270 $all_updates = update_get_update_list();
273 $all_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
276 foreach ($all_updates as $module => $updates) {
277 if (!empty($updates['pending'])) {
278 foreach (array_keys($updates['pending']) as $update_name) {
279 $this->fail("The $update_name() update function from the $module module did not run.");
284 // Reset the static cache of drupal_get_installed_schema_version() so that
285 // more complex update path testing works.
286 drupal_static_reset('drupal_get_installed_schema_version');
288 // The config schema can be incorrect while the update functions are being
289 // executed. But once the update has been completed, it needs to be valid
290 // again. Assert the schema of all configuration objects now.
291 $names = $this->container->get('config.storage')->listAll();
292 /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
293 $typed_config = $this->container->get('config.typed');
294 $typed_config->clearCachedDefinitions();
295 foreach ($names as $name) {
296 $config = $this->config($name);
297 $this->assertConfigSchema($typed_config, $name, $config->get());
300 // Ensure that the update hooks updated all entity schema.
301 $needs_updates = \Drupal::entityDefinitionUpdateManager()->needsUpdates();
302 $this->assertFalse($needs_updates, 'After all updates ran, entity schema is up to date.');
303 if ($needs_updates) {
304 foreach (\Drupal::entityDefinitionUpdateManager()
305 ->getChangeSummary() as $entity_type_id => $summary) {
306 foreach ($summary as $message) {
307 $this->fail($message);
315 * Runs the install database tasks for the driver used by the test runner.
317 protected function runDbTasks() {
318 // Create a minimal container so that t() works.
319 // @see install_begin_request()
320 $container = new ContainerBuilder();
321 $container->setParameter('language.default_values', Language::$defaultValues);
323 ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
324 ->addArgument('%language.default_values%');
326 ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
327 ->addArgument(new Reference('language.default'));
328 \Drupal::setContainer($container);
330 require_once __DIR__ . '/../../../../../includes/install.inc';
331 $connection = Database::getConnection();
332 $errors = db_installer_object($connection->driver())->runTasks();
333 if (!empty($errors)) {
334 $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
339 * Replace User 1 with the user created here.
341 protected function replaceUser1() {
342 /** @var \Drupal\user\UserInterface $account */
343 // @todo: Saving the account before the update is problematic.
344 // https://www.drupal.org/node/2560237
345 $account = User::load(1);
346 $account->setPassword($this->rootUser->pass_raw);
347 $account->setEmail($this->rootUser->getEmail());
348 $account->setUsername($this->rootUser->getUsername());
353 * Tests the selection page.
355 protected function doSelectionTest() {
356 // No-op. Tests wishing to do test the selection page or the general
357 // update.php environment before running update.php can override this method
358 // and implement their required tests.