function KernelTestBase::releaseSharedDatabase

Same name and namespace in other branches
  1. 11.x core/tests/Drupal/KernelTests/KernelTestBase.php \Drupal\KernelTests\KernelTestBase::releaseSharedDatabase()

Drops the tables of the test class once all its test methods have run.

Attributes

#[AfterClass]

File

core/tests/Drupal/KernelTests/KernelTestBase.php, line 323

Class

KernelTestBase
Base class for functional integration tests.

Namespace

Drupal\KernelTests

Code

public static function releaseSharedDatabase() : void {
  if (!static::sharesEnvironment()) {
    return;
  }
  $shared_database = getenv(self::SHARED_DATABASE_PREFIX_ENV);
  if ($shared_database === FALSE) {
    return;
  }
  [$prefix, $pid] = explode(':', $shared_database);
  if ((int) $pid !== getmypid()) {
    // A forked test method process: more test methods may still follow.
    return;
  }
  putenv(self::SHARED_DATABASE_PREFIX_ENV);
  // This runs in the test runner process, which has no bootstrapped Drupal,
  // so the connection has to be set up from scratch.
  $db_url = getenv('SIMPLETEST_DB');
  if ($db_url === FALSE) {
    return;
  }
  // Resolving the database driver reads its .info.yml and its class through
  // paths that the extension discovery returns relative to the Drupal root.
  // The working directory of the test runner process is not guaranteed to be
  // that root, while the forked test method processes chdir() into it.
  // @see _drupal_shutdown_function()
  $working_directory = getcwd();
  chdir(DRUPAL_ROOT);
  try {
    $connection_info = Database::convertDbUrlToConnectionInfo($db_url, TRUE);
    $connection_info['prefix'] = $prefix;
    Database::addConnectionInfo(__METHOD__, 'default', $connection_info);
    $schema = Database::getConnection('default', __METHOD__)->schema();
    foreach ($schema->findTables('%') as $table) {
      $schema->dropTable($table);
    }
  } finally {
    Database::removeConnection(__METHOD__);
    (new TestDatabase($prefix))->releaseLock();
    if ($working_directory !== FALSE) {
      chdir($working_directory);
    }
  }
}

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