UpdatePathTestBase.php 13 KB

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