You are here

protected function TestSetupTrait::changeDatabasePrefix in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Test/TestSetupTrait.php \Drupal\Core\Test\TestSetupTrait::changeDatabasePrefix()
  2. 10 core/lib/Drupal/Core/Test/TestSetupTrait.php \Drupal\Core\Test\TestSetupTrait::changeDatabasePrefix()

Changes the database connection to the prefixed one.

1 call to TestSetupTrait::changeDatabasePrefix()
TestSiteInstallCommand::changeDatabasePrefix in core/tests/Drupal/TestSite/Commands/TestSiteInstallCommand.php

File

core/lib/Drupal/Core/Test/TestSetupTrait.php, line 145

Class

TestSetupTrait
Provides a trait for shared test setup functionality.

Namespace

Drupal\Core\Test

Code

protected function changeDatabasePrefix() {
  if (empty($this->databasePrefix)) {
    $this
      ->prepareDatabasePrefix();
  }

  // If the test is run with argument dburl then use it.
  $db_url = getenv('SIMPLETEST_DB');
  if (!empty($db_url)) {

    // Ensure no existing database gets in the way. If a default database
    // exists already it must be removed.
    Database::removeConnection('default');
    $database = Database::convertDbUrlToConnectionInfo($db_url, isset($this->root) ? $this->root : DRUPAL_ROOT);
    Database::addConnectionInfo('default', 'default', $database);
  }

  // Clone the current connection and replace the current prefix.
  $connection_info = Database::getConnectionInfo('default');
  if (is_null($connection_info)) {
    throw new \InvalidArgumentException('There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh.');
  }
  else {
    Database::renameConnection('default', 'simpletest_original_default');
    foreach ($connection_info as $target => $value) {

      // Replace the full table prefix definition to ensure that no table
      // prefixes of the test runner leak into the test.
      $connection_info[$target]['prefix'] = $value['prefix'] . $this->databasePrefix;
    }
    Database::addConnectionInfo('default', 'default', $connection_info['default']);
  }
}