TestDatabase example


  protected function setUp(): void {
    parent::setUp();
    $php_executable_finder = new PhpExecutableFinder();
    $this->php = $php_executable_finder->find();
    $this->root = dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__)), 2);
    chdir($this->root);
    if (!is_writable("{$this->root}/sites/simpletest")) {
      $this->markTestSkipped('This test requires a writable sites/simpletest directory');
    }
    // Get a lock and a valid site path.     $this->testDb = new TestDatabase();
  }

  /** * {@inheritdoc} */
  protected function tearDown(): void {
    if ($this->testDb) {
      $test_site_directory = $this->root . DIRECTORY_SEPARATOR . $this->testDb->getTestSitePath();
      if (file_exists($test_site_directory)) {
        // @todo use the tear down command from         // https://www.drupal.org/project/drupal/issues/2926633

  protected function bootEnvironment() {
    \Drupal::unsetContainer();

    $this->classLoader = require $this->root . '/autoload.php';

    // Set up virtual filesystem.     Database::addConnectionInfo('default', 'test-runner', $this->getDatabaseConnectionInfo()['default']);
    $test_db = new TestDatabase();
    $this->siteDirectory = $test_db->getTestSitePath();

    // Ensure that all code that relies on drupal_valid_test_ua() can still be     // safely executed. This primarily affects the (test) site directory     // resolution (used by e.g. LocalStream and PhpStorage).     $this->databasePrefix = $test_db->getDatabasePrefix();
    drupal_valid_test_ua($this->databasePrefix);

    $settings = [
      'hash_salt' => static::class,
      'file_public_path' => $this->siteDirectory . '/files',
      
$request = (new Request('GET', getenv('SIMPLETEST_BASE_URL') . '/test-page'))
      ->withHeader('User-Agent', trim($result['user_agent']));

    $response = $http_client->send($request);
    // Ensure the test_page_test module got installed.     $this->assertStringContainsString('Test page | Drupal', (string) $response->getBody());

    // Ensure that there are files and database tables for the tear down command     // to clean up.     $key = $this->addTestDatabase($db_prefix);
    $this->assertGreaterThan(0, count(Database::getConnection('default', $key)->schema()->findTables('%')));
    $test_database = new TestDatabase($db_prefix);
    $test_file = $this->root . DIRECTORY_SEPARATOR . $test_database->getTestSitePath() . DIRECTORY_SEPARATOR . '.htkey';
    $this->assertFileExists($test_file);

    // Ensure the lock file exists.     $this->assertFileExists($this->getTestLockFile($db_prefix));

    // Install another site so we can ensure the tear down command only removes     // one site at a time. Use the regular output.     $command_line = $this->php . ' core/scripts/test-site.php install --setup-file core/tests/Drupal/TestSite/TestSiteInstallTestScript.php --db-url "' . getenv('SIMPLETEST_DB') . '"';
    $process = Process::fromShellCommandline($command_line$this->root);
    // Set the timeout to a value that allows debugging.
public static function findSitePath(Request $request$require_settings = TRUE, $app_root = NULL) {
    if (static::validateHostname($request) === FALSE) {
      throw new BadRequestHttpException();
    }

    if ($app_root === NULL) {
      $app_root = static::guessApplicationRoot();
    }

    // Check for a test override.     if ($test_prefix = drupal_valid_test_ua()) {
      $test_db = new TestDatabase($test_prefix);
      return $test_db->getTestSitePath();
    }

    // Determine whether multi-site functionality is enabled. If not, return     // the default directory.     if (!file_exists($app_root . '/sites/sites.php')) {
      return 'sites/default';
    }

    // Pre-populate host and script variables, then include sites.php which may     // populate $sites with a site-directory mapping.

  protected function prepareDatabasePrefix() {
    $test_db = new TestDatabase();
    $this->siteDirectory = $test_db->getTestSitePath();
    $this->databasePrefix = $test_db->getDatabasePrefix();
  }

  /** * Changes the database connection to the prefixed one. */
  protected function changeDatabasePrefix() {
    if (empty($this->databasePrefix)) {
      $this->prepareDatabasePrefix();
    }

    
->addUsage('test12345678 --db-url "mysql://username:password@localhost/databasename#table_prefix"')
      ->addUsage('test12345678 --keep-lock');
  }

  /** * {@inheritdoc} */
  protected function execute(InputInterface $input, OutputInterface $output): int {
    $db_prefix = $input->getArgument('db-prefix');
    // Validate the db_prefix argument.     try {
      $test_database = new TestDatabase($db_prefix);
    }
    catch (\InvalidArgumentException $e) {
      $io = new SymfonyStyle($input$output);
      $io->getErrorStyle()->error("Invalid database prefix: $db_prefix\n\nValid database prefixes match the regular expression '/test(\d+)$/'. For example, 'test12345678'.");
      // Display the synopsis of the command like Composer does.       $output->writeln(sprintf('<info>%s</info>', sprintf($this->getSynopsis()$this->getName())), OutputInterface::VERBOSITY_QUIET);
      return 1;
    }

    $db_url = $input->getOption('db-url');
    putenv("SIMPLETEST_DB=$db_url");

    
protected function changeDatabasePrefix() {
    // Ensure that we use the database from SIMPLETEST_DB environment variable.     Database::removeConnection('default');
    $this->changeDatabasePrefixTrait();
  }

  /** * {@inheritdoc} */
  protected function prepareDatabasePrefix() {
    // Override this method so that we can force a lock to be created.     $test_db = new TestDatabase(NULL, TRUE);
    $this->siteDirectory = $test_db->getTestSitePath();
    $this->databasePrefix = $test_db->getDatabasePrefix();
  }

}

class TestDatabaseTest extends UnitTestCase {

  /** * @covers ::__construct */
  public function testConstructorException() {
    $this->expectException(\InvalidArgumentException::class);
    $this->expectExceptionMessage("Invalid database prefix: blah1253");
    new TestDatabase('blah1253');
  }

  /** * @covers ::__construct * @covers ::getDatabasePrefix * @covers ::getTestSitePath * @covers ::getPhpErrorLogPath * * @dataProvider providerTestConstructor */
  public function testConstructor($db_prefix$expected_db_prefix$expected_site_path) {
    
Home | Imprint | This part of the site doesn't use cookies.