3 namespace Drupal\FunctionalTests\Update;
5 use Behat\Mink\Driver\GoutteDriver;
7 use Behat\Mink\Selector\SelectorsHandler;
8 use Behat\Mink\Session;
9 use Drupal\Component\Utility\Crypt;
10 use Drupal\Core\Test\TestRunnerKernel;
11 use Drupal\Tests\BrowserTestBase;
12 use Drupal\Tests\HiddenFieldSelector;
13 use Drupal\Tests\SchemaCheckTestTrait;
14 use Drupal\Core\Database\Database;
15 use Drupal\Core\DependencyInjection\ContainerBuilder;
16 use Drupal\Core\Language\Language;
18 use Drupal\user\Entity\User;
19 use Symfony\Component\DependencyInjection\Reference;
20 use Symfony\Component\HttpFoundation\Request;
23 * Provides a base class for writing an update test.
25 * To write an update test:
26 * - Write the hook_update_N() implementations that you are testing.
27 * - Create one or more database dump files, which will set the database to the
28 * "before updates" state. Normally, these will add some configuration data to
29 * the database, set up some tables/fields, etc.
30 * - Create a class that extends this class.
31 * - In your setUp() method, point the $this->databaseDumpFiles variable to the
32 * database dump files, and then call parent::setUp() to run the base setUp()
33 * method in this class.
34 * - In your test method, call $this->runUpdates() to run the necessary updates,
35 * and then use test assertions to verify that the result is what you expect.
36 * - In order to test both with a "bare" database dump as well as with a
37 * database dump filled with content, extend your update path test class with
38 * a new test class that overrides the bare database dump. Refer to
39 * UpdatePathTestBaseFilledTest for an example.
43 * @see hook_update_N()
45 abstract class UpdatePathTestBase extends BrowserTestBase {
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() {
155 $request = Request::createFromGlobals();
157 // Boot up Drupal into a state where calling the database API is possible.
158 // This is used to initialize the database system, so we can load the dump
160 $autoloader = require $this->root . '/autoload.php';
161 $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
162 $kernel->loadLegacyIncludes();
164 $this->changeDatabasePrefix();
166 // Allow classes to set database dump files.
167 $this->setDatabaseDumpFiles();
169 // We are going to set a missing zlib requirement property for usage
170 // during the performUpgrade() and tearDown() methods. Also set that the
172 if (!$this->zlibInstalled) {
176 // Set the update url. This must be set here rather than in
177 // self::__construct() or the old URL generator will leak additional test
179 $this->updateUrl = Url::fromRoute('system.db_update');
181 $this->setupBaseUrl();
183 // Install Drupal test site.
184 $this->prepareEnvironment();
185 $this->installDrupal();
187 // Add the config directories to settings.php.
188 drupal_install_config_directories();
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';
199 $session = $this->initMink();
201 $cookies = $this->extractCookiesFromRequest(\Drupal::request());
202 foreach ($cookies as $cookie_name => $values) {
203 foreach ($values as $value) {
204 $session->setCookie($cookie_name, $value);
208 // Set up the browser test output file.
209 $this->initBrowserOutputFile();
215 public function installDrupal() {
216 $this->initUserSession();
217 $this->prepareSettings();
219 $this->initSettings();
221 $request = Request::createFromGlobals();
222 $container = $this->initKernel($request);
223 $this->initConfig($container);
229 protected function doInstall() {
231 // Allow classes to set database dump files.
232 $this->setDatabaseDumpFiles();
234 // Load the database(s).
235 foreach ($this->databaseDumpFiles as $file) {
236 if (substr($file, -3) == '.gz') {
237 $file = "compress.zlib://$file";
246 protected function initMink() {
247 $driver = $this->getDefaultDriverInstance();
249 if ($driver instanceof GoutteDriver) {
250 // Turn off curl timeout. Having a timeout is not a problem in a normal
251 // test running, but it is a problem when debugging. Also, disable SSL
252 // peer verification so that testing under HTTPS always works.
253 /** @var \GuzzleHttp\Client $client */
254 $client = $this->container->get('http_client_factory')->fromOptions([
259 // Inject a Guzzle middleware to generate debug output for every request
260 // performed in the test.
261 $handler_stack = $client->getConfig('handler');
262 $handler_stack->push($this->getResponseLogHandler());
264 $driver->getClient()->setClient($client);
267 $selectors_handler = new SelectorsHandler([
268 'hidden_field_selector' => new HiddenFieldSelector()
270 $session = new Session($driver, $selectors_handler);
271 $this->mink = new Mink();
272 $this->mink->registerSession('default', $session);
273 $this->mink->setDefaultSessionName('default');
274 $this->registerSessions();
280 * Set database dump files to be used.
282 abstract protected function setDatabaseDumpFiles();
285 * Add settings that are missed since the installer isn't run.
287 protected function prepareSettings() {
288 parent::prepareSettings();
290 // Remember the profile which was used.
291 $settings['settings']['install_profile'] = (object) [
292 'value' => $this->installProfile,
295 // Generate a hash salt.
296 $settings['settings']['hash_salt'] = (object) [
297 'value' => Crypt::randomBytesBase64(55),
301 // Since the installer isn't run, add the database settings here too.
302 $settings['databases']['default'] = (object) [
303 'value' => Database::getConnectionInfo(),
307 $this->writeSettings($settings);
311 * Helper function to run pending database updates.
313 protected function runUpdates() {
314 if (!$this->zlibInstalled) {
315 $this->fail('Missing zlib requirement for update tests.');
318 // The site might be broken at the time so logging in using the UI might
319 // not work, so we use the API itself.
320 drupal_rewrite_settings([
322 'update_free_access' => (object) [
329 $this->drupalGet($this->updateUrl);
330 $this->clickLink(t('Continue'));
332 $this->doSelectionTest();
333 // Run the update hooks.
334 $this->clickLink(t('Apply pending updates'));
335 $this->checkForMetaRefresh();
337 // Ensure there are no failed updates.
338 if ($this->checkFailedUpdates) {
339 $this->assertNoRaw('<strong>' . t('Failed:') . '</strong>');
341 // Ensure that there are no pending updates.
342 foreach (['update', 'post_update'] as $update_type) {
343 switch ($update_type) {
345 $all_updates = update_get_update_list();
348 $all_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
351 foreach ($all_updates as $module => $updates) {
352 if (!empty($updates['pending'])) {
353 foreach (array_keys($updates['pending']) as $update_name) {
354 $this->fail("The $update_name() update function from the $module module did not run.");
359 // Reset the static cache of drupal_get_installed_schema_version() so that
360 // more complex update path testing works.
361 drupal_static_reset('drupal_get_installed_schema_version');
363 // The config schema can be incorrect while the update functions are being
364 // executed. But once the update has been completed, it needs to be valid
365 // again. Assert the schema of all configuration objects now.
366 $names = $this->container->get('config.storage')->listAll();
367 /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
368 $typed_config = $this->container->get('config.typed');
369 $typed_config->clearCachedDefinitions();
370 foreach ($names as $name) {
371 $config = $this->config($name);
372 $this->assertConfigSchema($typed_config, $name, $config->get());
375 // Ensure that the update hooks updated all entity schema.
376 $needs_updates = \Drupal::entityDefinitionUpdateManager()->needsUpdates();
377 if ($needs_updates) {
378 foreach (\Drupal::entityDefinitionUpdateManager()
379 ->getChangeSummary() as $entity_type_id => $summary) {
380 foreach ($summary as $message) {
381 $this->fail($message);
384 // The above calls to `fail()` should prevent this from ever being
385 // called, but it is here in case something goes really wrong.
386 $this->assertFalse($needs_updates, 'After all updates ran, entity schema is up to date.');
392 * Runs the install database tasks for the driver used by the test runner.
394 protected function runDbTasks() {
395 // Create a minimal container so that t() works.
396 // @see install_begin_request()
397 $container = new ContainerBuilder();
398 $container->setParameter('language.default_values', Language::$defaultValues);
400 ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
401 ->addArgument('%language.default_values%');
403 ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
404 ->addArgument(new Reference('language.default'));
405 \Drupal::setContainer($container);
407 require_once __DIR__ . '/../../../../includes/install.inc';
408 $connection = Database::getConnection();
409 $errors = db_installer_object($connection->driver())->runTasks();
410 if (!empty($errors)) {
411 $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
416 * Replace User 1 with the user created here.
418 protected function replaceUser1() {
419 /** @var \Drupal\user\UserInterface $account */
420 // @todo: Saving the account before the update is problematic.
421 // https://www.drupal.org/node/2560237
422 $account = User::load(1);
423 $account->setPassword($this->rootUser->pass_raw);
424 $account->setEmail($this->rootUser->getEmail());
425 $account->setUsername($this->rootUser->getUsername());
430 * Tests the selection page.
432 protected function doSelectionTest() {
433 // No-op. Tests wishing to do test the selection page or the general
434 // update.php environment before running update.php can override this method
435 // and implement their required tests.