Verified Commit e5a59ea9 authored by Andrei Mateescu's avatar Andrei Mateescu
Browse files

task: #3612249 Split update script missing extension test to its own class

By: catch
By: smustgrave
By: godotislate
By: dcam
parent 56283a66
Loading
Loading
Loading
Loading
Loading
+225 −0
Changes for core/modules/system/tests/src/Functional/UpdateSystem/UpdateScriptMissingExtensionTest.php: 225 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Tests\system\Functional\UpdateSystem;

use Drupal\Component\Serialization\Yaml;
use Drupal\system\Install\Requirements\SystemRequirements;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;

/**
 * Tests the update script access and functionality.
 */
#[Group('Update')]
#[Group('#slow')]
#[RunTestsInSeparateProcesses]
class UpdateScriptMissingExtensionTest extends UpdateScriptTestBase {

  /**
   * Tests that a missing extension prevents updates.
   *
   * @param array $core
   *   An array keyed by 'module' and 'theme' where each sub array contains
   *   a list of extension machine names.
   * @param array $contrib
   *   An array keyed by 'module' and 'theme' where each sub array contains
   *   a list of extension machine names.
   */
  #[DataProvider('providerMissingExtension')]
  public function testMissingExtension(array $core, array $contrib): void {
    $this->drupalLogin(
      $this->drupalCreateUser(
        [
          'administer software updates',
          'administer site configuration',
          'administer modules',
          'administer themes',
        ]
      )
    );

    $all_extensions_info = [];
    $file_paths = [];
    $test_error_texts = [];
    $test_error_urls = [];
    $extension_base_info = [
      'version' => 'VERSION',
      'core_version_requirement' => \Drupal::VERSION,
    ];

    // For each core extension create an error from info.yml information and
    // the expected error message.
    foreach ($core as $type => $extensions) {
      $removed_list = [];
      $error_url = 'https://www.drupal.org/node/3223395#s-recommendations-for-deprecated-modules';
      $extension_base_info += ['package' => 'Core'];
      if ($type === 'module') {
        $removed_core_list = SystemRequirements::DRUPAL_CORE_REMOVED_MODULE_LIST;
      }
      else {
        $removed_core_list = SystemRequirements::DRUPAL_CORE_REMOVED_THEME_LIST;
      }

      foreach ($extensions as $extension) {
        $extension_info = $extension_base_info +
          [
            'name' => "The magically disappearing core $type $extension",
            'type' => $type,
          ];
        if ($type === 'theme') {
          $extension_info['base theme'] = FALSE;
        }
        $all_extensions_info[$extension] = $extension_info;
        $removed_list[] = $removed_core_list[$extension];
      }

      // Create the requirements test message.
      if (!empty($extensions)) {
        $handbook_message = "For more information read the documentation on deprecated {$type}s.";
        if (count($removed_list) === 1) {
          $test_error_texts[$type][] = "Removed core {$type} "
            . "You must add the following contributed $type and reload this page."
            . implode($removed_list)
            . "This $type is installed on your site but is no longer provided by Core."
            . $handbook_message;
        }
        else {
          $test_error_texts[$type][] = "Removed core {$type}s "
            . "You must add the following contributed {$type}s and reload this page."
            . implode($removed_list)
            . "These {$type}s are installed on your site but are no longer provided by Core."
            . $handbook_message;
        }
        $test_error_urls[$type][] = $error_url;
      }
    }

    // For each contrib extension create an error from info.yml information and
    // the expected error message.
    foreach ($contrib as $type => $extensions) {
      unset($extension_base_info['package']);
      $handbook_message = 'Review the suggestions for resolving this incompatibility to repair your installation, and then re-run update.php.';
      $error_url = 'https://www.drupal.org/docs/updating-drupal/troubleshooting-database-updates';
      foreach ($extensions as $extension) {
        $extension_info = $extension_base_info +
          [
            'name' => "The magically disappearing contrib $type $extension",
            'type' => $type,
          ];
        if ($type === 'theme') {
          $extension_info['base theme'] = FALSE;
        }
        $all_extensions_info[$extension] = $extension_info;
      }

      // Create the requirements test message.
      if (!empty($extensions)) {
        if (count($extensions) === 1) {
          $test_error_texts[$type][] = "Missing or invalid {$type} "
            . "The following {$type} is marked as installed in the core.extension configuration, but it is missing:"
            . implode($extensions)
            . $handbook_message;
        }
        else {
          $test_error_texts[$type][] = "Missing or invalid {$type}s "
            . "The following {$type}s are marked as installed in the core.extension configuration, but they are missing:"
            . implode($extensions)
            . $handbook_message;
        }
        $test_error_urls[$type][] = $error_url;
      }
    }

    // Create the info.yml files for each extension.
    foreach ($all_extensions_info as $machine_name => $extension_info) {
      $type = $extension_info['type'];
      $folder_path = \Drupal::getContainer()->getParameter('site.path') . "/{$type}s/contrib/$machine_name";
      $file_path = "$folder_path/$machine_name.info.yml";
      mkdir($folder_path, 0777, TRUE);
      file_put_contents($file_path, Yaml::encode($extension_info));
      $file_paths[$machine_name] = $file_path;
    }

    // Enable all the extensions.
    foreach ($all_extensions_info as $machine_name => $extension_info) {
      $extension_machine_names = [$machine_name];
      $extension_names = [$extension_info['name']];
      $this->enableExtensions($extension_info['type'], $extension_machine_names, $extension_names);
    }

    // If there are no requirements warnings or errors, we expect to be able to
    // go through the update process uninterrupted.
    $this->drupalGet($this->statusReportUrl);
    $types = ['module', 'theme'];
    foreach ($types as $type) {
      $all = array_merge($core[$type], $contrib[$type]);
      $this->assertUpdateWithNoErrors($test_error_texts[$type], $type, $all);
    }

    // Delete the info.yml(s) and confirm updates are prevented.
    foreach ($file_paths as $file_path) {
      unlink($file_path);
    }
    $this->drupalGet($this->statusReportUrl);
    foreach ($types as $type) {
      $all = array_merge($core[$type], $contrib[$type]);
      $this->assertErrorOnUpdates($test_error_texts[$type], $type, $all, $test_error_urls[$type]);
    }

    // Add the info.yml file(s) back and confirm we are able to go through the
    // update process uninterrupted.
    foreach ($all_extensions_info as $machine_name => $extension_info) {
      file_put_contents($file_paths[$machine_name], Yaml::encode($extension_info));
    }
    $this->drupalGet($this->statusReportUrl);
    foreach ($types as $type) {
      $all = array_merge($core[$type], $contrib[$type]);
      $this->assertUpdateWithNoErrors($test_error_texts[$type], $type, $all);
    }
  }

  /**
   * Data provider for ::testMissingExtension().
   *
   * @return array[]
   *   Set of test cases to pass to the test method.
   */
  public static function providerMissingExtension(): array {
    return [
      'core only' => [
        'core' => [
          'module' => ['aggregator'],
          'theme' => ['seven'],
        ],
        'contrib' => [
          'module' => [],
          'theme' => [],
        ],
      ],
      'contrib only' => [
        'core' => [
          'module' => [],
          'theme' => [],
        ],
        'contrib' => [
          'module' => ['module'],
          'theme' => ['theme'],
        ],
      ],
      'core and contrib' => [
        'core' => [
          'module' => ['aggregator', 'rdf'],
          'theme' => ['seven'],
        ],
        'contrib' => [
          'module' => ['module_a', 'module_b'],
          'theme' => ['theme_a', 'theme_b'],
        ],
      ],
    ];
  }

}
+1 −520

File changed.

Preview size limit exceeded, changes collapsed.

+250 −0
Changes for core/modules/system/tests/src/Functional/UpdateSystem/UpdateScriptTestBase.php: 250 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

declare(strict_types=1);

namespace Drupal\Tests\system\Functional\UpdateSystem;

use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
use Drupal\Tests\RequirementsPageTrait;
use Drupal\TestTools\Extension\InfoWriterTrait;
use Drupal\user\UserInterface;

/**
 * Tests the update script access and functionality.
 */
abstract class UpdateScriptTestBase extends BrowserTestBase {
  use InfoWriterTrait;
  use RequirementsPageTrait;

  protected const HANDBOOK_MESSAGE = 'Review the suggestions for resolving this incompatibility to repair your installation, and then re-run update.php.';

  /**
   * {@inheritdoc}
   */
  protected static $modules = [
    'update_script_test',
    'dblog',
    'language',
    'test_module_required_by_theme',
    'test_another_module_required_by_theme',
  ];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  /**
   * The URL to the status report page.
   */
  protected Url $statusReportUrl;

  /**
   * URL to the update.php script.
   */
  protected Url $updateUrl;

  /**
   * A user with the necessary permissions to administer software updates.
   */
  protected UserInterface $updateUser;

  /**
   * {@inheritdoc}
   */
  protected function setUp(): void {
    parent::setUp();
    $this->updateUrl = Url::fromRoute('system.db_update');
    $this->statusReportUrl = Url::fromRoute('system.status');
    $this->updateUser = $this->drupalCreateUser([
      'administer software updates',
      'access site in maintenance mode',
      'administer themes',
    ]);
  }

  /**
   * Enables an extension using the UI.
   *
   * @param string $extension_type
   *   The extension type.
   * @param array $extension_machine_names
   *   An array of the extension machine names.
   * @param array $extension_names
   *   An array of extension names.
   */
  protected function enableExtensions(string $extension_type, array $extension_machine_names, array $extension_names): void {
    if ($extension_type === 'module') {
      $edit = [];
      foreach ($extension_machine_names as $extension_machine_name) {
        $edit["modules[$extension_machine_name][enable]"] = $extension_machine_name;
      }
      $this->drupalGet('admin/modules');
      $this->submitForm($edit, 'Install');
    }
    elseif ($extension_type === 'theme') {
      $this->drupalGet('admin/appearance');
      foreach ($extension_names as $extension_name) {
        $this->click("a[title~=\"$extension_name\"]");
      }
    }
  }

  /**
   * Enables extensions via the UI.
   *
   * @param array $extension_info
   *   An array of extension information arrays. The array is keyed by 'module'
   *   and 'theme'.
   */
  protected function enableMissingExtensions(array $extension_info): void {
    $edit = [];
    foreach ($extension_info as $info) {
      if ($info['type'] === 'module') {
        $machine_name = $info['machine_name'];
        $edit["modules[$machine_name][enable]"] = $machine_name;
      }
      if (!empty($edit)) {
        $this->drupalGet('admin/modules');
        $this->submitForm($edit, 'Install');
      }
    }

    if (isset($extension_info['theme'])) {
      $this->drupalGet('admin/appearance');
      foreach ($extension_info as $info) {
        if ($info['type' === 'theme']) {
          $this->click('a[title~="' . $info['name'] . '"]');
        }
      }
    }
  }

  /**
   * Helper function to run updates via the browser.
   */
  protected function runUpdates($maintenance_mode): void {
    /** @var \Drupal\Core\Update\UpdateHookRegistry $update_registry */
    $update_registry = \Drupal::service('update.update_hook_registry');
    $schema_version = $update_registry->getInstalledVersion('update_script_test');
    $this->assertEquals(8001, $schema_version, 'update_script_test is initially installed with schema version 8001.');

    // Set the installed schema version to one less than the current update.
    $update_registry->setInstalledVersion('update_script_test', $schema_version - 1);
    $schema_version = $update_registry->getInstalledVersion('update_script_test');
    $this->assertEquals(8000, $schema_version, 'update_script_test schema version overridden to 8000.');

    // Click through update.php with 'administer software updates' permission.
    $this->drupalLogin($this->updateUser);
    if ($maintenance_mode) {
      $this->assertSession()->pageTextContains('Operating in maintenance mode.');
    }
    else {
      $this->assertSession()->pageTextNotContains('Operating in maintenance mode.');
    }
    $this->drupalGet($this->updateUrl, ['external' => TRUE]);
    $this->updateRequirementsProblem();
    $this->clickLink('Continue');
    $this->clickLink('Apply pending updates');
    $this->checkForMetaRefresh();

    // Verify that updates were completed successfully.
    $this->assertSession()->pageTextContains('Updates were attempted.');
    $this->assertSession()->linkExists('site');
    $this->assertSession()->pageTextContains('The update_script_test_update_8001() update was executed successfully.');

    // Verify that no 7.x updates were run.
    $this->assertSession()->pageTextNotContains('The update_script_test_update_7200() update was executed successfully.');
    $this->assertSession()->pageTextNotContains('The update_script_test_update_7201() update was executed successfully.');

    // Verify that there are no links to different parts of the workflow.
    $this->assertSession()->linkNotExists('Administration pages');
    $this->assertSession()->elementNotExists('xpath', '//main//a[contains(@href, "update.php")]');
    $this->assertSession()->linkNotExists('logged');

    // Verify the front page can be visited following the upgrade.
    $this->clickLink('Front page');
    $this->assertSession()->statusCodeEquals(200);
  }

  /**
   * Asserts that an installed extension's config setting is correct.
   *
   * @param string $extension_type
   *   The extension type, either 'module' or 'theme'.
   * @param array $extension_machine_names
   *   An array of the extension machine names.
   *
   * @internal
   */
  protected function assertInstalledExtensionsConfig(string $extension_type, array $extension_machine_names): void {
    $extension_config = $this->container->get('config.factory')->get('core.extension');
    foreach ($extension_machine_names as $extension_machine_name) {
      $this->assertSame(0, $extension_config->get("$extension_type.$extension_machine_name"));
    }
  }

  /**
   * Asserts particular errors are not shown on update and status report pages.
   *
   * @param array $unexpected_error_texts
   *   An array of the error texts that should not be shown.
   * @param string $extension_type
   *   The extension type, either 'module' or 'theme'.
   * @param array $extension_machine_names
   *   An array of  the extension machine names.
   *
   * @internal
   */
  protected function assertUpdateWithNoErrors(array $unexpected_error_texts, string $extension_type, array $extension_machine_names): void {
    $assert_session = $this->assertSession();
    foreach ($unexpected_error_texts as $unexpected_error_text) {
      $assert_session->pageTextNotContains($unexpected_error_text);
    }
    $this->drupalGet($this->updateUrl, ['external' => TRUE]);
    foreach ($unexpected_error_texts as $unexpected_error_text) {
      $assert_session->pageTextNotContains($unexpected_error_text);
    }
    $this->updateRequirementsProblem();
    $this->clickLink('Continue');
    $assert_session->pageTextContains('No pending updates.');
    $this->assertInstalledExtensionsConfig($extension_type, $extension_machine_names);
  }

  /**
   * Asserts errors are shown on the update and status report pages.
   *
   * @param array $expected_error_texts
   *   The expected error texts.
   * @param string $extension_type
   *   The extension type, either 'module' or 'theme'.
   * @param array $extension_machine_names
   *   The extension machine names.
   * @param array $test_error_urls
   *   The URLs in the error texts.
   *
   * @internal
   */
  protected function assertErrorOnUpdates(array $expected_error_texts, string $extension_type, array $extension_machine_names, array $test_error_urls): void {
    $assert_session = $this->assertSession();
    foreach ($expected_error_texts as $expected_error_text) {
      $assert_session->pageTextContains($expected_error_text);
    }
    foreach ($test_error_urls as $test_error_url) {
      $assert_session->linkByHrefExists($test_error_url);
    }

    // Reload the update page to ensure the extension with the breaking values
    // has not been uninstalled or otherwise affected.
    for ($i = 0; $i < 2; $i++) {
      $this->drupalGet($this->updateUrl, ['external' => TRUE]);
      foreach ($expected_error_texts as $expected_error_text) {
        $assert_session->pageTextContains($expected_error_text);
      }
      $assert_session->linkNotExists('Continue');
    }
    $this->assertInstalledExtensionsConfig($extension_type, $extension_machine_names);
  }

}
+1 −1
Changes for core/tests/Drupal/TestTools/Extension/InfoWriterTrait.php: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -25,7 +25,7 @@ trait InfoWriterTrait {
   * @return void
   *   No return value.
   */
  private function writeInfoFile(string $file_path, array $info): void {
  protected function writeInfoFile(string $file_path, array $info): void {
    $mtime = file_exists($file_path) ? filemtime($file_path) : FALSE;

    file_put_contents($file_path, Yaml::encode($info));