DbCommandBaseTest.php in Drupal 8
File
core/modules/system/tests/src/Kernel/Scripts/DbCommandBaseTest.php
View source
<?php
namespace Drupal\Tests\system\Kernel\Scripts;
use Drupal\Core\Command\DbCommandBase;
use Drupal\Core\Database\ConnectionNotDefinedException;
use Drupal\Core\Database\Database;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Tester\CommandTester;
class DbCommandBaseTest extends KernelTestBase {
public function testSpecifyDatabaseKey() {
$command = new DbCommandBaseTester();
$command_tester = new CommandTester($command);
Database::addConnectionInfo('magic_db', 'default', Database::getConnectionInfo('default')['default']);
$command_tester
->execute([
'--database' => 'magic_db',
]);
$this
->assertEquals('magic_db', $command
->getDatabaseConnection($command_tester
->getInput())
->getKey(), 'Special db key is returned');
}
public function testSpecifyDatabaseDoesNotExist() {
$command = new DbCommandBaseTester();
$command_tester = new CommandTester($command);
$command_tester
->execute([
'--database' => 'dne',
]);
$this
->expectException(ConnectionNotDefinedException::class);
$command
->getDatabaseConnection($command_tester
->getInput());
}
public function testSpecifyDbUrl() {
$command = new DbCommandBaseTester();
$command_tester = new CommandTester($command);
$command_tester
->execute([
'-db-url' => Database::getConnectionInfoAsUrl(),
]);
$this
->assertEquals('db-tools', $command
->getDatabaseConnection($command_tester
->getInput())
->getKey());
Database::removeConnection('db-tools');
$command_tester
->execute([
'--database-url' => Database::getConnectionInfoAsUrl(),
]);
$this
->assertEquals('db-tools', $command
->getDatabaseConnection($command_tester
->getInput())
->getKey());
}
public function testPrefix() {
if (Database::getConnection()
->driver() == 'sqlite') {
$this
->markTestSkipped('SQLITE modifies the prefixes so we cannot effectively test it');
}
Database::addConnectionInfo('magic_db', 'default', Database::getConnectionInfo('default')['default']);
$command = new DbCommandBaseTester();
$command_tester = new CommandTester($command);
$command_tester
->execute([
'--database' => 'magic_db',
'--prefix' => 'extra',
]);
$this
->assertEquals('extra', $command
->getDatabaseConnection($command_tester
->getInput())
->tablePrefix());
$command_tester
->execute([
'-db-url' => Database::getConnectionInfoAsUrl(),
'--prefix' => 'extra2',
]);
$this
->assertEquals('extra2', $command
->getDatabaseConnection($command_tester
->getInput())
->tablePrefix());
}
}
class DbCommandBaseTester extends DbCommandBase {
public function configure() {
parent::configure();
$this
->setName('test');
}
public function getDatabaseConnection(InputInterface $input) {
return parent::getDatabaseConnection($input);
}
protected function execute(InputInterface $input, OutputInterface $output) {
return 0;
}
}