Commit 580d3951 authored by webchick's avatar webchick

Issue #1598568 by aspilicious, Rob Loach: Convert database.test to PSR-0.

parent 7f6f4678
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\AlterTest.
*/
namespace Drupal\system\Tests\Database;
/**
* Select alter tests.
*
* @see database_test_query_alter()
*/
class AlterTest extends DatabaseTestBase {
public static function getInfo() {
return array(
'name' => 'Query altering tests',
'description' => 'Test the hook_query_alter capabilities of the Select builder.',
'group' => 'Database',
);
}
/**
* Test that we can do basic alters.
*/
function testSimpleAlter() {
$query = db_select('test');
$query->addField('test', 'name');
$query->addField('test', 'age', 'age');
$query->addTag('database_test_alter_add_range');
$result = $query->execute();
$num_records = 0;
foreach ($result as $record) {
$num_records++;
}
$this->assertEqual($num_records, 2, t('Returned the correct number of rows.'));
}
/**
* Test that we can alter the joins on a query.
*/
function testAlterWithJoin() {
$query = db_select('test_task');
$tid_field = $query->addField('test_task', 'tid');
$task_field = $query->addField('test_task', 'task');
$query->orderBy($task_field);
$query->addTag('database_test_alter_add_join');
$result = $query->execute();
$records = $result->fetchAll();
$this->assertEqual(count($records), 2, t('Returned the correct number of rows.'));
$this->assertEqual($records[0]->name, 'George', t('Correct data retrieved.'));
$this->assertEqual($records[0]->$tid_field, 4, t('Correct data retrieved.'));
$this->assertEqual($records[0]->$task_field, 'sing', t('Correct data retrieved.'));
$this->assertEqual($records[1]->name, 'George', t('Correct data retrieved.'));
$this->assertEqual($records[1]->$tid_field, 5, t('Correct data retrieved.'));
$this->assertEqual($records[1]->$task_field, 'sleep', t('Correct data retrieved.'));
}
/**
* Test that we can alter a query's conditionals.
*/
function testAlterChangeConditional() {
$query = db_select('test_task');
$tid_field = $query->addField('test_task', 'tid');
$pid_field = $query->addField('test_task', 'pid');
$task_field = $query->addField('test_task', 'task');
$people_alias = $query->join('test', 'people', "test_task.pid = people.id");
$name_field = $query->addField($people_alias, 'name', 'name');
$query->condition('test_task.tid', '1');
$query->orderBy($tid_field);
$query->addTag('database_test_alter_change_conditional');
$result = $query->execute();
$records = $result->fetchAll();
$this->assertEqual(count($records), 1, t('Returned the correct number of rows.'));
$this->assertEqual($records[0]->$name_field, 'John', t('Correct data retrieved.'));
$this->assertEqual($records[0]->$tid_field, 2, t('Correct data retrieved.'));
$this->assertEqual($records[0]->$pid_field, 1, t('Correct data retrieved.'));
$this->assertEqual($records[0]->$task_field, 'sleep', t('Correct data retrieved.'));
}
/**
* Test that we can alter the fields of a query.
*/
function testAlterChangeFields() {
$query = db_select('test');
$name_field = $query->addField('test', 'name');
$age_field = $query->addField('test', 'age', 'age');
$query->orderBy('name');
$query->addTag('database_test_alter_change_fields');
$record = $query->execute()->fetch();
$this->assertEqual($record->$name_field, 'George', t('Correct data retrieved.'));
$this->assertFalse(isset($record->$age_field), t('Age field not found, as intended.'));
}
/**
* Test that we can alter expressions in the query.
*/
function testAlterExpression() {
$query = db_select('test');
$name_field = $query->addField('test', 'name');
$age_field = $query->addExpression("age*2", 'double_age');
$query->condition('age', 27);
$query->addTag('database_test_alter_change_expressions');
$result = $query->execute();
// Ensure that we got the right record.
$record = $result->fetch();
$this->assertEqual($record->$name_field, 'George', t('Fetched name is correct.'));
$this->assertEqual($record->$age_field, 27*3, t('Fetched age expression is correct.'));
}
/**
* Test that we can remove a range() value from a query. This also tests hook_query_TAG_alter().
*/
function testAlterRemoveRange() {
$query = db_select('test');
$query->addField('test', 'name');
$query->addField('test', 'age', 'age');
$query->range(0, 2);
$query->addTag('database_test_alter_remove_range');
$num_records = count($query->execute()->fetchAll());
$this->assertEqual($num_records, 4, t('Returned the correct number of rows.'));
}
/**
* Test that we can do basic alters on subqueries.
*/
function testSimpleAlterSubquery() {
// Create a sub-query with an alter tag.
$subquery = db_select('test', 'p');
$subquery->addField('p', 'name');
$subquery->addField('p', 'id');
// Pick out George.
$subquery->condition('age', 27);
$subquery->addExpression("age*2", 'double_age');
// This query alter should change it to age * 3.
$subquery->addTag('database_test_alter_change_expressions');
// Create a main query and join to sub-query.
$query = db_select('test_task', 'tt');
$query->join($subquery, 'pq', 'pq.id = tt.pid');
$age_field = $query->addField('pq', 'double_age');
$name_field = $query->addField('pq', 'name');
$record = $query->execute()->fetch();
$this->assertEqual($record->$name_field, 'George', t('Fetched name is correct.'));
$this->assertEqual($record->$age_field, 27*3, t('Fetched age expression is correct.'));
}
}
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\BasicSyntaxTest.
*/
namespace Drupal\system\Tests\Database;
/**
* Test how the current database driver interprets the SQL syntax.
*
* In order to ensure consistent SQL handling throughout Drupal
* across multiple kinds of database systems, we test that the
* database system interprets SQL syntax in an expected fashion.
*/
class BasicSyntaxTest extends DatabaseTestBase {
public static function getInfo() {
return array(
'name' => 'Basic SQL syntax tests',
'description' => 'Test SQL syntax interpretation.',
'group' => 'Database',
);
}
/**
* Test for string concatenation.
*/
function testBasicConcat() {
$result = db_query('SELECT CONCAT(:a1, CONCAT(:a2, CONCAT(:a3, CONCAT(:a4, :a5))))', array(
':a1' => 'This',
':a2' => ' ',
':a3' => 'is',
':a4' => ' a ',
':a5' => 'test.',
));
$this->assertIdentical($result->fetchField(), 'This is a test.', t('Basic CONCAT works.'));
}
/**
* Test for string concatenation with field values.
*/
function testFieldConcat() {
$result = db_query('SELECT CONCAT(:a1, CONCAT(name, CONCAT(:a2, CONCAT(age, :a3)))) FROM {test} WHERE age = :age', array(
':a1' => 'The age of ',
':a2' => ' is ',
':a3' => '.',
':age' => 25,
));
$this->assertIdentical($result->fetchField(), 'The age of John is 25.', t('Field CONCAT works.'));
}
/**
* Test escaping of LIKE wildcards.
*/
function testLikeEscape() {
db_insert('test')
->fields(array(
'name' => 'Ring_',
))
->execute();
// Match both "Ringo" and "Ring_".
$num_matches = db_select('test', 't')
->condition('name', 'Ring_', 'LIKE')
->countQuery()
->execute()
->fetchField();
$this->assertIdentical($num_matches, '2', t('Found 2 records.'));
// Match only "Ring_" using a LIKE expression with no wildcards.
$num_matches = db_select('test', 't')
->condition('name', db_like('Ring_'), 'LIKE')
->countQuery()
->execute()
->fetchField();
$this->assertIdentical($num_matches, '1', t('Found 1 record.'));
}
/**
* Test LIKE query containing a backslash.
*/
function testLikeBackslash() {
db_insert('test')
->fields(array('name'))
->values(array(
'name' => 'abcde\f',
))
->values(array(
'name' => 'abc%\_',
))
->execute();
// Match both rows using a LIKE expression with two wildcards and a verbatim
// backslash.
$num_matches = db_select('test', 't')
->condition('name', 'abc%\\\\_', 'LIKE')
->countQuery()
->execute()
->fetchField();
$this->assertIdentical($num_matches, '2', t('Found 2 records.'));
// Match only the former using a LIKE expression with no wildcards.
$num_matches = db_select('test', 't')
->condition('name', db_like('abc%\_'), 'LIKE')
->countQuery()
->execute()
->fetchField();
$this->assertIdentical($num_matches, '1', t('Found 1 record.'));
}
}
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\CaseSensitivityTest.
*/
namespace Drupal\system\Tests\Database;
/**
* Test case sensitivity handling.
*/
class CaseSensitivityTest extends DatabaseTestBase {
public static function getInfo() {
return array(
'name' => 'Case sensitivity',
'description' => 'Test handling case sensitive collation.',
'group' => 'Database',
);
}
/**
* Test BINARY collation in MySQL.
*/
function testCaseSensitiveInsert() {
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
$john = db_insert('test')
->fields(array(
'name' => 'john', // <- A record already exists with name 'John'.
'age' => 2,
'job' => 'Baby',
))
->execute();
$num_records_after = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
$this->assertIdentical($num_records_before + 1, (int) $num_records_after, t('Record inserts correctly.'));
$saved_age = db_query('SELECT age FROM {test} WHERE name = :name', array(':name' => 'john'))->fetchField();
$this->assertIdentical($saved_age, '2', t('Can retrieve after inserting.'));
}
}
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\ConnectionTest.
*/
namespace Drupal\system\Tests\Database;
use Drupal\Core\Database\Database;
/**
* Test connection management.
*/
class ConnectionTest extends DatabaseTestBase {
public static function getInfo() {
return array(
'name' => 'Connection tests',
'description' => 'Tests of the core database system.',
'group' => 'Database',
);
}
/**
* Test that connections return appropriate connection objects.
*/
function testConnectionRouting() {
// Clone the master credentials to a slave connection.
// Note this will result in two independent connection objects that happen
// to point to the same place.
$connection_info = Database::getConnectionInfo('default');
Database::addConnectionInfo('default', 'slave', $connection_info['default']);
$db1 = Database::getConnection('default', 'default');
$db2 = Database::getConnection('slave', 'default');
$this->assertNotNull($db1, t('default connection is a real connection object.'));
$this->assertNotNull($db2, t('slave connection is a real connection object.'));
$this->assertNotIdentical($db1, $db2, t('Each target refers to a different connection.'));
// Try to open those targets another time, that should return the same objects.
$db1b = Database::getConnection('default', 'default');
$db2b = Database::getConnection('slave', 'default');
$this->assertIdentical($db1, $db1b, t('A second call to getConnection() returns the same object.'));
$this->assertIdentical($db2, $db2b, t('A second call to getConnection() returns the same object.'));
// Try to open an unknown target.
$unknown_target = $this->randomName();
$db3 = Database::getConnection($unknown_target, 'default');
$this->assertNotNull($db3, t('Opening an unknown target returns a real connection object.'));
$this->assertIdentical($db1, $db3, t('An unknown target opens the default connection.'));
// Try to open that unknown target another time, that should return the same object.
$db3b = Database::getConnection($unknown_target, 'default');
$this->assertIdentical($db3, $db3b, t('A second call to getConnection() returns the same object.'));
}
/**
* Test that connections return appropriate connection objects.
*/
function testConnectionRoutingOverride() {
// Clone the master credentials to a slave connection.
// Note this will result in two independent connection objects that happen
// to point to the same place.
$connection_info = Database::getConnectionInfo('default');
Database::addConnectionInfo('default', 'slave', $connection_info['default']);
Database::ignoreTarget('default', 'slave');
$db1 = Database::getConnection('default', 'default');
$db2 = Database::getConnection('slave', 'default');
$this->assertIdentical($db1, $db2, t('Both targets refer to the same connection.'));
}
/**
* Tests the closing of a database connection.
*/
function testConnectionClosing() {
// Open the default target so we have an object to compare.
$db1 = Database::getConnection('default', 'default');
// Try to close the the default connection, then open a new one.
Database::closeConnection('default', 'default');
$db2 = Database::getConnection('default', 'default');
// Opening a connection after closing it should yield an object different than the original.
$this->assertNotIdentical($db1, $db2, t('Opening the default connection after it is closed returns a new object.'));
}
/**
* Tests the connection options of the active database.
*/
function testConnectionOptions() {
$connection_info = Database::getConnectionInfo('default');
// Be sure we're connected to the default database.
$db = Database::getConnection('default', 'default');
$connectionOptions = $db->getConnectionOptions();
// In the MySQL driver, the port can be different, so check individual
// options.
$this->assertEqual($connection_info['default']['driver'], $connectionOptions['driver'], t('The default connection info driver matches the current connection options driver.'));
$this->assertEqual($connection_info['default']['database'], $connectionOptions['database'], t('The default connection info database matches the current connection options database.'));
// Set up identical slave and confirm connection options are identical.
Database::addConnectionInfo('default', 'slave', $connection_info['default']);
$db2 = Database::getConnection('slave', 'default');
$connectionOptions2 = $db2->getConnectionOptions();
// Get a fresh copy of the default connection options.
$connectionOptions = $db->getConnectionOptions();
$this->assertIdentical($connectionOptions, $connectionOptions2, t('The default and slave connection options are identical.'));
// Set up a new connection with different connection info.
$test = $connection_info['default'];
$test['database'] .= 'test';
Database::addConnectionInfo('test', 'default', $test);
$connection_info = Database::getConnectionInfo('test');
// Get a fresh copy of the default connection options.
$connectionOptions = $db->getConnectionOptions();
$this->assertNotEqual($connection_info['default']['database'], $connectionOptions['database'], t('The test connection info database does not match the current connection options database.'));
}
}
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\DatabaseTestBase.
*/
namespace Drupal\system\Tests\Database;
use Drupal\simpletest\WebTestBase;
/**
* Base test class for databases.
*
* Because all database tests share the same test data, we can centralize that
* here.
*/
class DatabaseTestBase extends WebTestBase {
function setUp() {
$modules = func_get_args();
if (isset($modules[0]) && is_array($modules[0])) {
$modules = $modules[0];
}
$modules[] = 'database_test';
parent::setUp($modules);
$schema['test'] = drupal_get_schema('test');
$schema['test_people'] = drupal_get_schema('test_people');
$schema['test_one_blob'] = drupal_get_schema('test_one_blob');
$schema['test_two_blobs'] = drupal_get_schema('test_two_blobs');
$schema['test_task'] = drupal_get_schema('test_task');
$this->installTables($schema);
$this->addSampleData();
}
/**
* Set up several tables needed by a certain test.
*
* @param $schema
* An array of table definitions to install.
*/
function installTables($schema) {
// This ends up being a test for table drop and create, too, which is nice.
foreach ($schema as $name => $data) {
if (db_table_exists($name)) {
db_drop_table($name);
}
db_create_table($name, $data);
}
foreach ($schema as $name => $data) {
$this->assertTrue(db_table_exists($name), t('Table @name created successfully.', array('@name' => $name)));
}
}
/**
* Set up tables for NULL handling.
*/
function ensureSampleDataNull() {
$schema['test_null'] = drupal_get_schema('test_null');
$this->installTables($schema);
db_insert('test_null')
->fields(array('name', 'age'))
->values(array(
'name' => 'Kermit',
'age' => 25,
))
->values(array(
'name' => 'Fozzie',
'age' => NULL,
))
->values(array(
'name' => 'Gonzo',
'age' => 27,
))
->execute();
}
/**
* Setup our sample data.
*
* These are added using db_query(), since we're not trying to test the
* INSERT operations here, just populate.
*/
function addSampleData() {
// We need the IDs, so we can't use a multi-insert here.
$john = db_insert('test')
->fields(array(
'name' => 'John',
'age' => 25,
'job' => 'Singer',
))
->execute();
$george = db_insert('test')
->fields(array(
'name' => 'George',
'age' => 27,
'job' => 'Singer',
))
->execute();
$ringo = db_insert('test')
->fields(array(
'name' => 'Ringo',
'age' => 28,
'job' => 'Drummer',
))
->execute();
$paul = db_insert('test')
->fields(array(
'name' => 'Paul',
'age' => 26,
'job' => 'Songwriter',
))
->execute();
db_insert('test_people')
->fields(array(
'name' => 'Meredith',
'age' => 30,
'job' => 'Speaker',
))
->execute();
db_insert('test_task')
->fields(array('pid', 'task', 'priority'))
->values(array(
'pid' => $john,
'task' => 'eat',
'priority' => 3,
))
->values(array(
'pid' => $john,
'task' => 'sleep',
'priority' => 4,
))
->values(array(
'pid' => $john,
'task' => 'code',
'priority' => 1,
))
->values(array(
'pid' => $george,
'task' => 'sing',
'priority' => 2,
))
->values(array(
'pid' => $george,
'task' => 'sleep',
'priority' => 2,
))
->values(array(
'pid' => $paul,
'task' => 'found new band',
'priority' => 1,
))
->values(array(
'pid' => $paul,
'task' => 'perform at superbowl',
'priority' => 3,
))
->execute();
}
}
<?php
/**
* @file
* Definition of Drupal\system\Tests\Database\DeleteTruncateTest.
*/
namespace Drupal\system\Tests\Database;
/**
* Delete/Truncate tests.
*
* The DELETE tests are not as extensive, as all of the interesting code for
* DELETE queries is in the conditional which is identical to the UPDATE and
* SELECT conditional handling.
*
* The TRUNCATE tests are not extensive either, because the behavior of
* TRUNCATE queries is not consistent across database engines. We only test
* that a TRUNCATE query actually deletes all rows from the target table.
*/
class DeleteTruncateTest extends DatabaseTestBase {
public static function getInfo() {
return array(
'name' => 'Delete/Truncate tests',
'description' => 'Test the Delete and Truncate query builders.',
'group' => 'Database',
);
}
/**
* Confirm that we can use a subselect in a delete successfully.
*/
function testSubselectDelete() {
$num_records_before = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
$pid_to_delete = db_query("SELECT * FROM {test_task} WHERE task = 'sleep'")->fetchField();
$subquery = db_select('test', 't')
->fields('t', array('id'))
->condition('t.id', array($pid_to_delete), 'IN');
$delete = db_delete('test_task')
->condition('task', 'sleep')
->condition('pid', $subquery, 'IN');
$num_deleted = $delete->execute();
$this->assertEqual($num_deleted, 1, t("Deleted 1 record."));
$num_records_after = db_query('SELECT COUNT(*) FROM {test_task}')->fetchField();
$this->assertEqual($num_records_before, $num_records_after + $num_deleted, t('Deletion adds up.'));
}
/**
* Confirm that we can delete a single record successfully.
*/
function testSimpleDelete() {
$num_records_before = db_query('SELECT COUNT(*) FROM {test}')->fetchField();
$num_deleted = db_delete('test')
->condition('id', 1)
->execute();
$this->assertIdentical($num_deleted, 1, t('Deleted 1 record.'));