function TestSetupTrait::changeDatabasePrefix

Same name in other branches
  1. 9 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()
  3. 11.x core/lib/Drupal/Core/Test/TestSetupTrait.php \Drupal\Core\Test\TestSetupTrait::changeDatabasePrefix()

Changes the database connection to the prefixed one.

2 calls to TestSetupTrait::changeDatabasePrefix()
TestBase::prepareEnvironment in core/modules/simpletest/src/TestBase.php
Prepares the current environment for running the test.
TestSiteInstallCommand::changeDatabasePrefix in core/tests/Drupal/TestSite/Commands/TestSiteInstallCommand.php

File

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

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'] = [
                'default' => $value['prefix']['default'] . $this->databasePrefix,
            ];
        }
        Database::addConnectionInfo('default', 'default', $connection_info['default']);
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.