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