UpdatePathTestBase.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. namespace Drupal\FunctionalTests\Update;
  3. use Drupal\Component\Utility\Crypt;
  4. use Drupal\Core\Test\TestRunnerKernel;
  5. use Drupal\Tests\BrowserTestBase;
  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\user\Entity\User;
  12. use Symfony\Component\DependencyInjection\Reference;
  13. use Symfony\Component\HttpFoundation\Request;
  14. /**
  15. * Provides a base class for writing an update test.
  16. *
  17. * To write an update test:
  18. * - Write the hook_update_N() implementations that you are testing.
  19. * - Create one or more database dump files, which will set the database to the
  20. * "before updates" state. Normally, these will add some configuration data to
  21. * the database, set up some tables/fields, etc.
  22. * - Create a class that extends this class.
  23. * - Ensure that the test is in the legacy group. Tests can have multiple
  24. * groups.
  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 BrowserTestBase {
  40. use SchemaCheckTestTrait;
  41. /**
  42. * Modules to enable after the database is loaded.
  43. */
  44. protected static $modules = [];
  45. /**
  46. * The file path(s) to the dumped database(s) to load into the child site.
  47. *
  48. * The file system/tests/fixtures/update/drupal-8.bare.standard.php.gz is
  49. * normally included first -- this sets up the base database from a bare
  50. * standard Drupal installation.
  51. *
  52. * The file system/tests/fixtures/update/drupal-8.filled.standard.php.gz
  53. * can also be used in case we want to test with a database filled with
  54. * content, and with all core modules enabled.
  55. *
  56. * @var array
  57. */
  58. protected $databaseDumpFiles = [];
  59. /**
  60. * The install profile used in the database dump file.
  61. *
  62. * @var string
  63. */
  64. protected $installProfile = 'standard';
  65. /**
  66. * Flag that indicates whether the child site has been updated.
  67. *
  68. * @var bool
  69. */
  70. protected $upgradedSite = FALSE;
  71. /**
  72. * Array of errors triggered during the update process.
  73. *
  74. * @var array
  75. */
  76. protected $upgradeErrors = [];
  77. /**
  78. * Array of modules loaded when the test starts.
  79. *
  80. * @var array
  81. */
  82. protected $loadedModules = [];
  83. /**
  84. * Flag to indicate whether zlib is installed or not.
  85. *
  86. * @var bool
  87. */
  88. protected $zlibInstalled = TRUE;
  89. /**
  90. * Flag to indicate whether there are pending updates or not.
  91. *
  92. * @var bool
  93. */
  94. protected $pendingUpdates = TRUE;
  95. /**
  96. * The update URL.
  97. *
  98. * @var string
  99. */
  100. protected $updateUrl;
  101. /**
  102. * Disable strict config schema checking.
  103. *
  104. * The schema is verified at the end of running the update.
  105. *
  106. * @var bool
  107. */
  108. protected $strictConfigSchema = FALSE;
  109. /**
  110. * Fail the test if there are failed updates.
  111. *
  112. * @var bool
  113. */
  114. protected $checkFailedUpdates = TRUE;
  115. /**
  116. * Constructs an UpdatePathTestCase object.
  117. *
  118. * @param $test_id
  119. * (optional) The ID of the test. Tests with the same id are reported
  120. * together.
  121. */
  122. public function __construct($test_id = NULL) {
  123. parent::__construct($test_id);
  124. $this->zlibInstalled = function_exists('gzopen');
  125. }
  126. /**
  127. * Overrides WebTestBase::setUp() for update testing.
  128. *
  129. * The main difference in this method is that rather than performing the
  130. * installation via the installer, a database is loaded. Additional work is
  131. * then needed to set various things such as the config directories and the
  132. * container that would normally be done via the installer.
  133. */
  134. protected function setUp() {
  135. $request = Request::createFromGlobals();
  136. // Boot up Drupal into a state where calling the database API is possible.
  137. // This is used to initialize the database system, so we can load the dump
  138. // files.
  139. $autoloader = require $this->root . '/autoload.php';
  140. $kernel = TestRunnerKernel::createFromRequest($request, $autoloader);
  141. $kernel->loadLegacyIncludes();
  142. // Set the update url. This must be set here rather than in
  143. // self::__construct() or the old URL generator will leak additional test
  144. // sites.
  145. $this->updateUrl = Url::fromRoute('system.db_update');
  146. $this->setupBaseUrl();
  147. // Install Drupal test site.
  148. $this->prepareEnvironment();
  149. $this->runDbTasks();
  150. // Allow classes to set database dump files.
  151. $this->setDatabaseDumpFiles();
  152. // We are going to set a missing zlib requirement property for usage
  153. // during the performUpgrade() and tearDown() methods. Also set that the
  154. // tests failed.
  155. if (!$this->zlibInstalled) {
  156. parent::setUp();
  157. return;
  158. }
  159. $this->installDrupal();
  160. // Add the config directories to settings.php.
  161. drupal_install_config_directories();
  162. // Set the container. parent::rebuildAll() would normally do this, but this
  163. // not safe to do here, because the database has not been updated yet.
  164. $this->container = \Drupal::getContainer();
  165. $this->replaceUser1();
  166. require_once $this->root . '/core/includes/update.inc';
  167. // Setup Mink.
  168. $this->initMink();
  169. // Set up the browser test output file.
  170. $this->initBrowserOutputFile();
  171. }
  172. /**
  173. * {@inheritdoc}
  174. */
  175. public function installDrupal() {
  176. $this->initUserSession();
  177. $this->prepareSettings();
  178. $this->doInstall();
  179. $this->initSettings();
  180. $request = Request::createFromGlobals();
  181. $container = $this->initKernel($request);
  182. $this->initConfig($container);
  183. }
  184. /**
  185. * {@inheritdoc}
  186. */
  187. protected function doInstall() {
  188. $this->runDbTasks();
  189. // Allow classes to set database dump files.
  190. $this->setDatabaseDumpFiles();
  191. // Load the database(s).
  192. foreach ($this->databaseDumpFiles as $file) {
  193. if (substr($file, -3) == '.gz') {
  194. $file = "compress.zlib://$file";
  195. }
  196. require $file;
  197. }
  198. }
  199. /**
  200. * {@inheritdoc}
  201. */
  202. protected function initFrontPage() {
  203. // Do nothing as Drupal is not installed yet.
  204. }
  205. /**
  206. * Set database dump files to be used.
  207. */
  208. abstract protected function setDatabaseDumpFiles();
  209. /**
  210. * Add settings that are missed since the installer isn't run.
  211. */
  212. protected function prepareSettings() {
  213. parent::prepareSettings();
  214. // Remember the profile which was used.
  215. $settings['settings']['install_profile'] = (object) [
  216. 'value' => $this->installProfile,
  217. 'required' => TRUE,
  218. ];
  219. // Generate a hash salt.
  220. $settings['settings']['hash_salt'] = (object) [
  221. 'value' => Crypt::randomBytesBase64(55),
  222. 'required' => TRUE,
  223. ];
  224. // Since the installer isn't run, add the database settings here too.
  225. $settings['databases']['default'] = (object) [
  226. 'value' => Database::getConnectionInfo(),
  227. 'required' => TRUE,
  228. ];
  229. $this->writeSettings($settings);
  230. }
  231. /**
  232. * Helper function to run pending database updates.
  233. */
  234. protected function runUpdates() {
  235. if (!$this->zlibInstalled) {
  236. $this->fail('Missing zlib requirement for update tests.');
  237. return FALSE;
  238. }
  239. // The site might be broken at the time so logging in using the UI might
  240. // not work, so we use the API itself.
  241. drupal_rewrite_settings([
  242. 'settings' => [
  243. 'update_free_access' => (object) [
  244. 'value' => TRUE,
  245. 'required' => TRUE,
  246. ],
  247. ],
  248. ]);
  249. $this->drupalGet($this->updateUrl);
  250. $this->clickLink(t('Continue'));
  251. $this->doSelectionTest();
  252. // Run the update hooks.
  253. $this->clickLink(t('Apply pending updates'));
  254. $this->checkForMetaRefresh();
  255. // Ensure there are no failed updates.
  256. if ($this->checkFailedUpdates) {
  257. $failure = $this->cssSelect('.failure');
  258. if ($failure) {
  259. $this->fail('The update failed with the following message: "' . reset($failure)->getText() . '"');
  260. }
  261. // Ensure that there are no pending updates.
  262. foreach (['update', 'post_update'] as $update_type) {
  263. switch ($update_type) {
  264. case 'update':
  265. $all_updates = update_get_update_list();
  266. break;
  267. case 'post_update':
  268. $all_updates = \Drupal::service('update.post_update_registry')->getPendingUpdateInformation();
  269. break;
  270. }
  271. foreach ($all_updates as $module => $updates) {
  272. if (!empty($updates['pending'])) {
  273. foreach (array_keys($updates['pending']) as $update_name) {
  274. $this->fail("The $update_name() update function from the $module module did not run.");
  275. }
  276. }
  277. }
  278. }
  279. // Reset the static cache of drupal_get_installed_schema_version() so that
  280. // more complex update path testing works.
  281. drupal_static_reset('drupal_get_installed_schema_version');
  282. // The config schema can be incorrect while the update functions are being
  283. // executed. But once the update has been completed, it needs to be valid
  284. // again. Assert the schema of all configuration objects now.
  285. $names = $this->container->get('config.storage')->listAll();
  286. /** @var \Drupal\Core\Config\TypedConfigManagerInterface $typed_config */
  287. $typed_config = $this->container->get('config.typed');
  288. $typed_config->clearCachedDefinitions();
  289. foreach ($names as $name) {
  290. $config = $this->config($name);
  291. $this->assertConfigSchema($typed_config, $name, $config->get());
  292. }
  293. // Ensure that the update hooks updated all entity schema.
  294. $needs_updates = \Drupal::entityDefinitionUpdateManager()->needsUpdates();
  295. if ($needs_updates) {
  296. foreach (\Drupal::entityDefinitionUpdateManager()->getChangeSummary() as $entity_type_id => $summary) {
  297. $entity_type_label = \Drupal::entityTypeManager()->getDefinition($entity_type_id)->getLabel();
  298. foreach ($summary as $message) {
  299. $this->fail("$entity_type_label: $message");
  300. }
  301. }
  302. // The above calls to `fail()` should prevent this from ever being
  303. // called, but it is here in case something goes really wrong.
  304. $this->assertFalse($needs_updates, 'After all updates ran, entity schema is up to date.');
  305. }
  306. }
  307. }
  308. /**
  309. * Runs the install database tasks for the driver used by the test runner.
  310. */
  311. protected function runDbTasks() {
  312. // Create a minimal container so that t() works.
  313. // @see install_begin_request()
  314. $container = new ContainerBuilder();
  315. $container->setParameter('language.default_values', Language::$defaultValues);
  316. $container
  317. ->register('language.default', 'Drupal\Core\Language\LanguageDefault')
  318. ->addArgument('%language.default_values%');
  319. $container
  320. ->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
  321. ->addArgument(new Reference('language.default'));
  322. \Drupal::setContainer($container);
  323. require_once __DIR__ . '/../../../../includes/install.inc';
  324. $connection = Database::getConnection();
  325. $errors = db_installer_object($connection->driver())->runTasks();
  326. if (!empty($errors)) {
  327. $this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
  328. }
  329. }
  330. /**
  331. * Replace User 1 with the user created here.
  332. */
  333. protected function replaceUser1() {
  334. /** @var \Drupal\user\UserInterface $account */
  335. // @todo: Saving the account before the update is problematic.
  336. // https://www.drupal.org/node/2560237
  337. $account = User::load(1);
  338. $account->setPassword($this->rootUser->pass_raw);
  339. $account->setEmail($this->rootUser->getEmail());
  340. $account->setUsername($this->rootUser->getUsername());
  341. $account->save();
  342. }
  343. /**
  344. * Tests the selection page.
  345. */
  346. protected function doSelectionTest() {
  347. // No-op. Tests wishing to do test the selection page or the general
  348. // update.php environment before running update.php can override this method
  349. // and implement their required tests.
  350. }
  351. }