05719fb6d4bafc49567a344d28030e8255399945
[yaffs-website] / web / core / modules / system / src / Tests / Update / UpdatePathTestBase.php
1 <?php
2
3 namespace Drupal\system\Tests\Update;
4
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);
6
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;
12 use Drupal\Core\Url;
13 use Drupal\simpletest\WebTestBase;
14 use Drupal\user\Entity\User;
15 use Symfony\Component\DependencyInjection\Reference;
16 use Symfony\Component\HttpFoundation\Request;
17
18 /**
19  * Provides a base class for writing an update test.
20  *
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.
36  *
37  * @ingroup update_api
38  *
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
42  *
43  * @see hook_update_N()
44  */
45 abstract class UpdatePathTestBase extends WebTestBase {
46
47   use SchemaCheckTestTrait;
48
49   /**
50    * Modules to enable after the database is loaded.
51    */
52   protected static $modules = [];
53
54   /**
55    * The file path(s) to the dumped database(s) to load into the child site.
56    *
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.
60    *
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.
64    *
65    * @var array
66    */
67   protected $databaseDumpFiles = [];
68
69   /**
70    * The install profile used in the database dump file.
71    *
72    * @var string
73    */
74   protected $installProfile = 'standard';
75
76   /**
77    * Flag that indicates whether the child site has been updated.
78    *
79    * @var bool
80    */
81   protected $upgradedSite = FALSE;
82
83   /**
84    * Array of errors triggered during the update process.
85    *
86    * @var array
87    */
88   protected $upgradeErrors = [];
89
90   /**
91    * Array of modules loaded when the test starts.
92    *
93    * @var array
94    */
95   protected $loadedModules = [];
96
97   /**
98    * Flag to indicate whether zlib is installed or not.
99    *
100    * @var bool
101    */
102   protected $zlibInstalled = TRUE;
103
104   /**
105    * Flag to indicate whether there are pending updates or not.
106    *
107    * @var bool
108    */
109   protected $pendingUpdates = TRUE;
110
111   /**
112    * The update URL.
113    *
114    * @var string
115    */
116   protected $updateUrl;
117
118   /**
119    * Disable strict config schema checking.
120    *
121    * The schema is verified at the end of running the update.
122    *
123    * @var bool
124    */
125   protected $strictConfigSchema = FALSE;
126
127   /**
128    * Fail the test if there are failed updates.
129    *
130    * @var bool
131    */
132   protected $checkFailedUpdates = TRUE;
133
134   /**
135    * Constructs an UpdatePathTestCase object.
136    *
137    * @param $test_id
138    *   (optional) The ID of the test. Tests with the same id are reported
139    *   together.
140    */
141   public function __construct($test_id = NULL) {
142     parent::__construct($test_id);
143     $this->zlibInstalled = function_exists('gzopen');
144   }
145
146   /**
147    * Overrides WebTestBase::setUp() for update testing.
148    *
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.
153    */
154   protected function setUp() {
155     $this->runDbTasks();
156     // Allow classes to set database dump files.
157     $this->setDatabaseDumpFiles();
158
159     // We are going to set a missing zlib requirement property for usage
160     // during the performUpgrade() and tearDown() methods. Also set that the
161     // tests failed.
162     if (!$this->zlibInstalled) {
163       parent::setUp();
164       return;
165     }
166
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
169     // sites.
170     $this->updateUrl = Url::fromRoute('system.db_update');
171
172     // These methods are called from parent::setUp().
173     $this->setBatch();
174     $this->initUserSession();
175     $this->prepareSettings();
176
177     // Load the database(s).
178     foreach ($this->databaseDumpFiles as $file) {
179       if (substr($file, -3) == '.gz') {
180         $file = "compress.zlib://$file";
181       }
182       require $file;
183     }
184
185     $this->initSettings();
186     $request = Request::createFromGlobals();
187     $container = $this->initKernel($request);
188     $this->initConfig($container);
189
190     // Add the config directories to settings.php.
191     drupal_install_config_directories();
192
193     // Restore the original Simpletest batch.
194     $this->restoreBatch();
195
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();
199
200     $this->replaceUser1();
201
202     require_once \Drupal::root() . '/core/includes/update.inc';
203   }
204
205   /**
206    * Set database dump files to be used.
207    */
208   abstract protected function setDatabaseDumpFiles();
209
210   /**
211    * Add settings that are missed since the installer isn't run.
212    */
213   protected function prepareSettings() {
214     parent::prepareSettings();
215
216     // Remember the profile which was used.
217     $settings['settings']['install_profile'] = (object) [
218       'value' => $this->installProfile,
219       'required' => TRUE,
220     ];
221     // Generate a hash salt.
222     $settings['settings']['hash_salt'] = (object) [
223       'value'    => Crypt::randomBytesBase64(55),
224       'required' => TRUE,
225     ];
226
227     // Since the installer isn't run, add the database settings here too.
228     $settings['databases']['default'] = (object) [
229       'value' => Database::getConnectionInfo(),
230       'required' => TRUE,
231     ];
232
233     $this->writeSettings($settings);
234   }
235
236   /**
237    * Helper function to run pending database updates.
238    */
239   protected function runUpdates() {
240     if (!$this->zlibInstalled) {
241       $this->fail('Missing zlib requirement for update tests.');
242       return FALSE;
243     }
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([
247       'settings' => [
248         'update_free_access' => (object) [
249           'value' => TRUE,
250           'required' => TRUE,
251         ],
252       ],
253     ]);
254
255     $this->drupalGet($this->updateUrl);
256     $this->clickLink(t('Continue'));
257
258     $this->doSelectionTest();
259     // Run the update hooks.
260     $this->clickLink(t('Apply pending updates'));
261
262     // Ensure there are no failed updates.
263     if ($this->checkFailedUpdates) {
264       $this->assertNoRaw('<strong>' . t('Failed:') . '</strong>');
265
266       // Ensure that there are no pending updates.
267       foreach (['update', 'post_update'] as $update_type) {
268         switch ($update_type) {
269           case 'update':
270             $all_updates = update_get_update_list();
271             break;
272           case 'post_update':
273             $all_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
274             break;
275         }
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.");
280             }
281           }
282         }
283       }
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');
287
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());
298       }
299
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);
308           }
309         }
310       }
311     }
312   }
313
314   /**
315    * Runs the install database tasks for the driver used by the test runner.
316    */
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);
322     $container
323       ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
324       ->addArgument('%language.default_values%');
325     $container
326       ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
327       ->addArgument(new Reference('language.default'));
328     \Drupal::setContainer($container);
329
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));
335     }
336   }
337
338   /**
339    * Replace User 1 with the user created here.
340    */
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());
349     $account->save();
350   }
351
352   /**
353    * Tests the selection page.
354    */
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.
359   }
360
361 }