update drupal

This commit is contained in:
Tessier
2020-10-15 11:59:37 +02:00
parent ebb5db14b5
commit d8b9162932
558 changed files with 5954 additions and 4475 deletions
@@ -240,8 +240,7 @@ class UncaughtExceptionTest extends BrowserTestBase {
default:
// We can not carry out this test.
$this->pass('Unable to run \Drupal\system\Tests\System\UncaughtExceptionTest::testLostDatabaseConnection for this database type.');
return;
$this->markTestSkipped('Unable to run \Drupal\system\Tests\System\UncaughtExceptionTest::testLostDatabaseConnection for this database type.');
}
// We simulate a broken database connection by rewrite settings.php to no
@@ -283,7 +283,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "notexisting" field was found.');
}
catch (ExpectationFailedException $e) {
$this->pass('assertFieldByXPath correctly failed. The "notexisting" field was not found.');
// Expected exception; just continue testing.
}
try {
@@ -291,7 +291,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-name" field was not found.');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldByXPath correctly failed. The "edit-name" field was found.');
// Expected exception; just continue testing.
}
try {
@@ -299,7 +299,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-name" field is found with the value "not the value".');
}
catch (ExpectationFailedException $e) {
$this->pass('The "edit-name" field is not found with the value "not the value".');
// Expected exception; just continue testing.
}
}
@@ -318,7 +318,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field was not found based on name.');
}
catch (ExpectationException $e) {
$this->pass('assertNoField correctly failed. The "name" field was found by name.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly when searching by id.
@@ -327,7 +327,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field was not found based on id.');
}
catch (ExpectationException $e) {
$this->pass('assertNoField correctly failed. The "name" field was found by id.');
// Expected exception; just continue testing.
}
// *** 2. assertField().
@@ -340,7 +340,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "invalid_name_and_id" field was found.');
}
catch (ExpectationFailedException $e) {
$this->pass('assertField correctly failed. The "invalid_name_and_id" field was not found.');
// Expected exception; just continue testing.
}
// *** 3. assertNoFieldById().
@@ -355,7 +355,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "description" field, with no value was not found.');
}
catch (ExpectationException $e) {
$this->pass('The "description" field, with no value was found.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly if a NULL value is passed in.
@@ -364,7 +364,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field was not found.');
}
catch (ExpectationException $e) {
$this->pass('The "name" field was found.');
// Expected exception; just continue testing.
}
// *** 4. assertFieldById().
@@ -379,7 +379,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-name" field with no value was found.');
}
catch (ExpectationFailedException $e) {
$this->pass('The "edit-name" field with no value was not found.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly if the wrong value is passed in.
@@ -388,7 +388,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field was found, using the wrong value.');
}
catch (ExpectationFailedException $e) {
$this->pass('The "name" field was not found, using the wrong value.');
// Expected exception; just continue testing
}
// *** 5. assertNoFieldByName().
@@ -403,7 +403,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "description" field, with no value was not found.');
}
catch (ExpectationException $e) {
$this->pass('The "description" field, with no value was found.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly if a NULL value is passed in.
@@ -412,7 +412,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field was not found.');
}
catch (ExpectationException $e) {
$this->pass('The "name" field was found.');
// Expected exception; just continue testing.
}
// *** 6. assertFieldByName().
@@ -429,7 +429,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "non-existing-name" field was found.');
}
catch (ExpectationFailedException $e) {
$this->pass('The "non-existing-name" field was not found');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly if given the wrong value.
@@ -438,7 +438,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "name" field with incorrect value was found.');
}
catch (ExpectationFailedException $e) {
$this->pass('assertFieldByName correctly failed. The "name" field with incorrect value was not found.');
// Expected exception; just continue testing.
}
// Test that text areas can contain new lines.
@@ -458,7 +458,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The select option "four" was found.');
}
catch (ExpectationException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
$this->assertOption('options', 1);
@@ -467,7 +467,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The select option "4" was found.');
}
catch (ExpectationException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
$this->assertNoOption('options', 'non-existing');
@@ -476,7 +476,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The select option "one" was not found.');
}
catch (ExpectationException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
$this->assertOptionSelected('options', 2);
@@ -485,7 +485,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The select option "4" was selected.');
}
catch (ExpectationException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
try {
@@ -493,7 +493,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The select option "1" was selected.');
}
catch (ExpectationFailedException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
}
@@ -512,7 +512,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The field with id of "Save" was found.');
}
catch (ExpectationFailedException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
$this->assertNoFieldById('Save', NULL);
@@ -523,7 +523,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The field with id of "edit-save" was not found.');
}
catch (ExpectationException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
// Test that multiple fields with the same name are validated correctly.
@@ -536,7 +536,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "duplicate_button" field with the value Duplicate button 2 was not found.');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldByName correctly failed. The "duplicate_button" field with the value Duplicate button 2 was found.');
// Expected exception; just continue testing.
}
}
@@ -573,7 +573,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "checkbox_enabled" field was not found by name, using NULL value.');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldByName failed correctly. The "checkbox_enabled" field was found using NULL value.');
// Expected exception; just continue testing.
}
// Part 2 - Test by ID.
@@ -603,7 +603,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-checkbox-disabled" field was not found by ID, using NULL value.');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldById failed correctly. The "edit-checkbox-disabled" field was found by ID using NULL value.');
// Expected exception; just continue testing.
}
// Part 3 - Test the specific 'checked' assertions.
@@ -616,7 +616,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "incorrect_checkbox_id" field was found');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldChecked correctly failed. The "incorrect_checkbox_id" field was not found.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly for a checkbox that is checked.
@@ -625,7 +625,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-checkbox-enabled" field was not found in a checked state.');
}
catch (ExpectationException $e) {
$this->pass('assertNoFieldChecked correctly failed. The "edit-checkbox-enabled" field was found in a checked state.');
// Expected exception; just continue testing.
}
// Test that the assertion fails correctly for a checkbox that is not
@@ -635,7 +635,7 @@ class BrowserTestBaseTest extends BrowserTestBase {
$this->fail('The "edit-checkbox-disabled" field was found and checked.');
}
catch (ExpectationException $e) {
$this->pass('assertFieldChecked correctly failed. The "edit-checkbox-disabled" field was not found in a checked state.');
// Expected exception; just continue testing.
}
}
@@ -126,7 +126,6 @@ class DistributionProfileExistingSettingsTest extends InstallerTestBase {
$this->assertEqual($this->config('core.extension')->get('profile'), 'mydistro', 'The install profile has been written to core.extension configuration.');
$this->rebuildContainer();
$this->pass('Container can be rebuilt even though distribution is not written to settings.php.');
$this->assertEqual(\Drupal::installProfile(), 'mydistro');
}
@@ -85,7 +85,6 @@ class MultipleDistributionsProfileTest extends InstallerTestBase {
$this->assertEqual($this->config('core.extension')->get('profile'), 'distribution_one', 'The install profile has been written to core.extension configuration.');
$this->rebuildContainer();
$this->pass('Container can be rebuilt as distribution is written to configuration.');
$this->assertEqual(\Drupal::installProfile(), 'distribution_one');
}
@@ -118,10 +118,9 @@ class DefaultConfigTest extends KernelTestBase {
$entity_storage->load($id)->calculateDependencies()->save();
}
$result = $config_manager->diff($default_config_storage, $active_config_storage, $config_name);
$this->assertConfigDiff($result, $config_name, static::$skippedConfig);
// The method call above will throw an exception if the configuration is
// ::assertConfigDiff will throw an exception if the configuration is
// different.
$this->pass("$config_name has no differences");
$this->assertNull($this->assertConfigDiff($result, $config_name, static::$skippedConfig));
}
else {
$info = $this->container->get('extension.list.module')->getExtensionInfo($module);
@@ -229,8 +229,7 @@ class LibraryDiscoveryIntegrationTest extends KernelTestBase {
$this->libraryDiscovery->clearCachedDefinitions();
// Assert message.
$this->pass(sprintf('Activated theme "%s"', $theme_name));
$this->assertSame($theme_name, $theme_manager->getActiveTheme()->getName());
}
/**
@@ -257,7 +256,7 @@ class LibraryDiscoveryIntegrationTest extends KernelTestBase {
$library = $this->libraryDiscovery->getLibraryByName($extension, $library_name);
foreach ($library[$sub_key] as $definition) {
if ($asset == $definition['data']) {
return $this->pass($message);
return TRUE;
}
}
return $this->fail($message);
@@ -290,7 +289,7 @@ class LibraryDiscoveryIntegrationTest extends KernelTestBase {
return $this->fail($message);
}
}
return $this->pass($message);
return TRUE;
}
}
@@ -44,15 +44,6 @@ class DbDumpTest extends KernelTestBase {
*/
protected $data;
/**
* Flag to skip these tests, which are database-backend dependent (MySQL).
*
* @see \Drupal\Core\Command\DbDumpCommand
*
* @var bool
*/
protected $skipTests = FALSE;
/**
* An array of original table schemas.
*
@@ -93,8 +84,9 @@ class DbDumpTest extends KernelTestBase {
protected function setUp() {
parent::setUp();
// Determine what database backend is running, and set the skip flag.
$this->skipTests = Database::getConnection()->databaseType() !== 'mysql';
if (Database::getConnection()->databaseType() !== 'mysql') {
$this->markTestSkipped("Skipping test since the DbDumpCommand is currently only compatible with MySql");
}
// Create some schemas so our export contains tables.
$this->installSchema('system', [
@@ -161,10 +153,6 @@ class DbDumpTest extends KernelTestBase {
* Test the command directly.
*/
public function testDbDumpCommand() {
if ($this->skipTests) {
$this->pass("Skipping test since the DbDumpCommand is currently only compatible with MySql");
return;
}
$application = new DbDumpApplication();
$command = $application->find('dump-database-d8-mysql');
@@ -194,10 +182,6 @@ class DbDumpTest extends KernelTestBase {
* Test loading the script back into the database.
*/
public function testScriptLoad() {
if ($this->skipTests) {
$this->pass("Skipping test since the DbDumpCommand is currently only compatible with MySql");
return;
}
// Generate the script.
$application = new DbDumpApplication();
@@ -193,24 +193,22 @@ class ConfigCRUDTest extends KernelTestBase {
public function testNameValidation() {
// Verify that an object name without namespace causes an exception.
$name = 'nonamespace';
$message = 'Expected ConfigNameException was thrown for a name without a namespace.';
try {
$this->config($name)->save();
$this->fail($message);
$this->fail('Expected ConfigNameException was thrown for a name without a namespace.');
}
catch (ConfigNameException $e) {
$this->pass($message);
catch (\Exception $e) {
$this->assertInstanceOf(ConfigNameException::class, $e);
}
// Verify that a name longer than the maximum length causes an exception.
$name = 'config_test.herman_melville.moby_dick_or_the_whale.harper_1851.now_small_fowls_flew_screaming_over_the_yet_yawning_gulf_a_sullen_white_surf_beat_against_its_steep_sides_then_all_collapsed_and_the_great_shroud_of_the_sea_rolled_on_as_it_rolled_five_thousand_years_ago';
$message = 'Expected ConfigNameException was thrown for a name longer than Config::MAX_NAME_LENGTH.';
try {
$this->config($name)->save();
$this->fail($message);
$this->fail('Expected ConfigNameException was thrown for a name longer than Config::MAX_NAME_LENGTH.');
}
catch (ConfigNameException $e) {
$this->pass($message);
catch (\Exception $e) {
$this->assertInstanceOf(ConfigNameException::class, $e);
}
// Verify that disallowed characters in the name cause an exception.
@@ -231,14 +229,12 @@ class ConfigCRUDTest extends KernelTestBase {
// Verify that a valid config object name can be saved.
$name = 'namespace.object';
$message = 'ConfigNameException was not thrown for a valid object name.';
try {
$config = $this->config($name);
$config->save();
$this->pass($message);
}
catch (ConfigNameException $e) {
$this->fail($message);
$this->fail('ConfigNameException was not thrown for a valid object name.');
}
}
@@ -248,23 +244,21 @@ class ConfigCRUDTest extends KernelTestBase {
*/
public function testValueValidation() {
// Verify that setData() will catch dotted keys.
$message = 'Expected ConfigValueException was thrown from setData() for value with dotted keys.';
try {
$this->config('namespace.object')->setData(['key.value' => 12])->save();
$this->fail($message);
$this->fail('Expected ConfigValueException was thrown from setData() for value with dotted keys.');
}
catch (ConfigValueException $e) {
$this->pass($message);
catch (\Exception $e) {
$this->assertInstanceOf(ConfigValueException::class, $e);
}
// Verify that set() will catch dotted keys.
$message = 'Expected ConfigValueException was thrown from set() for value with dotted keys.';
try {
$this->config('namespace.object')->set('foo', ['key.value' => 12])->save();
$this->fail($message);
$this->fail('Expected ConfigValueException was thrown from set() for value with dotted keys.');
}
catch (ConfigValueException $e) {
$this->pass($message);
catch (\Exception $e) {
$this->assertInstanceOf(ConfigValueException::class, $e);
}
}
@@ -325,9 +319,7 @@ class ConfigCRUDTest extends KernelTestBase {
$this->fail('No Exception thrown upon saving invalid data type.');
}
catch (UnsupportedDataTypeConfigException $e) {
$this->pass(new FormattableMarkup('%class thrown upon saving invalid data type.', [
'%class' => get_class($e),
]));
// Expected exception; just continue testing.
}
// Test that setting an unsupported type for a config object with no schema
@@ -342,9 +334,7 @@ class ConfigCRUDTest extends KernelTestBase {
$this->fail('No Exception thrown upon saving invalid data type.');
}
catch (UnsupportedDataTypeConfigException $e) {
$this->pass(new FormattableMarkup('%class thrown upon saving invalid data type.', [
'%class' => get_class($e),
]));
// Expected exception; just continue testing.
}
}
@@ -2,7 +2,6 @@
namespace Drupal\KernelTests\Core\Config;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Config\ConfigDuplicateUUIDException;
use Drupal\KernelTests\KernelTestBase;
@@ -44,7 +43,7 @@ class ConfigEntityStorageTest extends KernelTestBase {
$this->fail('Exception thrown when attempting to save a configuration entity with a UUID that does not match the existing UUID.');
}
catch (ConfigDuplicateUUIDException $e) {
$this->pass(new FormattableMarkup('Exception thrown when attempting to save a configuration entity with a UUID that does not match existing data: %e.', ['%e' => $e]));
// Expected exception; just continue testing.
}
// Ensure that the config entity was not corrupted.
@@ -40,13 +40,8 @@ class ConfigExportStorageTest extends KernelTestBase {
}
// Test that the export storage is read-only.
try {
$export->deleteAll();
$this->fail("export storage must not allow editing");
}
catch (\BadMethodCallException $exception) {
$this->pass("Exception is thrown.");
}
$this->expectException(\BadMethodCallException::class);
$export->deleteAll();
}
}
@@ -111,10 +111,10 @@ class ConfigFileContentTest extends KernelTestBase {
$this->assertEqual($config->get($nested_array_key), $array_value, 'Nested array configuration value found.');
// Read a top level value that doesn't exist.
$this->assertNull($config->get('i_dont_exist'), 'Non-existent top level value returned NULL.');
$this->assertNull($config->get('i_do_not_exist'), 'Non-existent top level value returned NULL.');
// Read a nested value that doesn't exist.
$this->assertNull($config->get('i.dont.exist'), 'Non-existent nested value returned NULL.');
$this->assertNull($config->get('i.do.not.exist'), 'Non-existent nested value returned NULL.');
// Read false value.
$this->assertFalse($config->get($false_key), "Boolean FALSE value returned the FALSE.");
@@ -110,7 +110,6 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
$this->fail('Expected ConfigImporterException thrown when a renamed configuration entity does not match the existing entity type.');
}
catch (ConfigImporterException $e) {
$this->pass('Expected ConfigImporterException thrown when a renamed configuration entity does not match the existing entity type.');
$expected = [
new FormattableMarkup('Entity type mismatch on rename. @old_type not equal to @new_type for existing configuration @old_name and staged configuration @new_name.', ['@old_type' => 'node_type', '@new_type' => 'config_test', '@old_name' => 'node.type.' . $content_type->id(), '@new_name' => 'config_test.dynamic.' . $test_entity_id]),
];
@@ -153,7 +152,6 @@ class ConfigImportRenameValidationTest extends KernelTestBase {
$this->fail('Expected ConfigImporterException thrown when simple configuration is renamed.');
}
catch (ConfigImporterException $e) {
$this->pass('Expected ConfigImporterException thrown when simple configuration is renamed.');
$expected = [
new FormattableMarkup('Rename operation for simple configuration. Existing configuration @old_name and staged configuration @new_name.', ['@old_name' => 'config_test.old', '@new_name' => 'config_test.new']),
];
@@ -84,14 +84,9 @@ class ConfigImporterTest extends KernelTestBase {
* fails.
*/
public function testEmptyImportFails() {
try {
$this->container->get('config.storage.sync')->deleteAll();
$this->configImporter->reset()->import();
$this->fail('ConfigImporterException thrown, successfully stopping an empty import.');
}
catch (ConfigImporterException $e) {
$this->pass('ConfigImporterException thrown, successfully stopping an empty import.');
}
$this->expectException(ConfigImporterException::class);
$this->container->get('config.storage.sync')->deleteAll();
$this->configImporter->reset()->import();
}
/**
@@ -834,7 +829,7 @@ class ConfigImporterTest extends KernelTestBase {
$this->fail('Expected \InvalidArgumentException thrown');
}
catch (\InvalidArgumentException $e) {
$this->pass('Expected \InvalidArgumentException thrown');
// Expected exception; just continue testing.
}
$this->assertFalse(\Drupal::isConfigSyncing(), 'After an invalid step \Drupal::isConfigSyncing() returns FALSE');
}
@@ -228,7 +228,6 @@ class ConfigSchemaTest extends KernelTestBase {
$this->assertEqual($definition, $expected, 'Retrieved the right metadata for the first effect of image.style.medium');
$a = \Drupal::config('config_test.dynamic.third_party');
$test = \Drupal::service('config.typed')->get('config_test.dynamic.third_party')->get('third_party_settings.config_schema_test');
$definition = $test->getDataDefinition()->toArray();
$expected = [];
@@ -560,36 +559,30 @@ class ConfigSchemaTest extends KernelTestBase {
// Ensure that keys can not be added or removed by
// hook_config_schema_info_alter().
\Drupal::state()->set('config_schema_test_exception_remove', TRUE);
$message = 'Expected ConfigSchemaAlterException thrown.';
try {
$typed_config->getDefinitions();
$this->fail($message);
$this->fail('Expected ConfigSchemaAlterException thrown.');
}
catch (ConfigSchemaAlterException $e) {
$this->pass($message);
$this->assertEqual($e->getMessage(), 'Invoking hook_config_schema_info_alter() has removed (config_schema_test.hook) schema definitions');
}
\Drupal::state()->set('config_schema_test_exception_add', TRUE);
$message = 'Expected ConfigSchemaAlterException thrown.';
try {
$typed_config->getDefinitions();
$this->fail($message);
$this->fail('Expected ConfigSchemaAlterException thrown.');
}
catch (ConfigSchemaAlterException $e) {
$this->pass($message);
$this->assertEqual($e->getMessage(), 'Invoking hook_config_schema_info_alter() has added (config_schema_test.hook_added_defintion) and removed (config_schema_test.hook) schema definitions');
$this->assertEqual($e->getMessage(), 'Invoking hook_config_schema_info_alter() has added (config_schema_test.hook_added_definition) and removed (config_schema_test.hook) schema definitions');
}
\Drupal::state()->set('config_schema_test_exception_remove', FALSE);
$message = 'Expected ConfigSchemaAlterException thrown.';
try {
$typed_config->getDefinitions();
$this->fail($message);
$this->fail('Expected ConfigSchemaAlterException thrown.');
}
catch (ConfigSchemaAlterException $e) {
$this->pass($message);
$this->assertEqual($e->getMessage(), 'Invoking hook_config_schema_info_alter() has added (config_schema_test.hook_added_defintion) schema definitions');
$this->assertEqual($e->getMessage(), 'Invoking hook_config_schema_info_alter() has added (config_schema_test.hook_added_definition) schema definitions');
}
// Tests that hook_config_schema_info_alter() can add additional metadata to
@@ -82,7 +82,6 @@ class FileStorageTest extends ConfigStorageTestBase {
$config_parsed = $this->storage->read('core.extension');
}
catch (UnsupportedDataTypeConfigException $e) {
$this->pass('Exception thrown when trying to read a field containing invalid data type.');
$this->assertStringContainsString($this->storage->getFilePath('core.extension'), $e->getMessage(), 'Erroneous file path is displayed.');
}
}
@@ -128,33 +128,17 @@ class ConnectionTest extends DatabaseTestBase {
$this->markTestSkipped("This test only runs for MySQL");
}
$db = Database::getConnection('default', 'default');
// Disable the protection at the PHP level.
try {
$db->query('SELECT * FROM {test}; SELECT * FROM {test_people}',
[],
['allow_delimiter_in_query' => TRUE]
);
$this->fail('No PDO exception thrown for multiple statements.');
}
catch (DatabaseExceptionWrapper $e) {
$this->pass('PDO exception thrown for multiple statements.');
}
$this->expectException(DatabaseExceptionWrapper::class);
Database::getConnection('default', 'default')->query('SELECT * FROM {test}; SELECT * FROM {test_people}', [], ['allow_delimiter_in_query' => TRUE]);
}
/**
* Ensure that you cannot execute multiple statements.
*/
public function testMultipleStatements() {
$db = Database::getConnection('default', 'default');
try {
$db->query('SELECT * FROM {test}; SELECT * FROM {test_people}');
$this->fail('No exception thrown for multiple statements.');
}
catch (\InvalidArgumentException $e) {
$this->pass('Exception thrown for multiple statements.');
}
$this->expectException(\InvalidArgumentException::class);
Database::getConnection('default', 'default')->query('SELECT * FROM {test}; SELECT * FROM {test_people}');
}
/**
@@ -29,14 +29,8 @@ class DatabaseExceptionWrapperTest extends KernelTestBase {
$this->fail('Expected PDOException or DatabaseExceptionWrapper, none was thrown.');
}
catch (\PDOException $e) {
$this->pass('Expected PDOException was thrown.');
}
catch (DatabaseExceptionWrapper $e) {
$this->pass('Expected DatabaseExceptionWrapper was thrown.');
}
catch (\Exception $e) {
$this->fail("Thrown exception is not a PDOException:\n" . (string) $e);
$this->assertTrue($e instanceof \PDOException || $e instanceof DatabaseExceptionWrapper, 'Exception should be an instance of \PDOException or DatabaseExceptionWrapper, thrown ' . get_class($e));
}
}
@@ -44,17 +38,8 @@ class DatabaseExceptionWrapperTest extends KernelTestBase {
* Tests the expected database exception thrown for inexistent tables.
*/
public function testQueryThrowsDatabaseExceptionWrapperException() {
$connection = Database::getConnection();
try {
$connection->query('SELECT * FROM {does_not_exist}');
$this->fail('Expected PDOException, none was thrown.');
}
catch (DatabaseExceptionWrapper $e) {
$this->pass('Expected DatabaseExceptionWrapper was thrown.');
}
catch (\Exception $e) {
$this->fail("Thrown exception is not a DatabaseExceptionWrapper:\n" . (string) $e);
}
$this->expectException(DatabaseExceptionWrapper::class);
Database::getConnection()->query('SELECT * FROM {does_not_exist}');
}
}
@@ -37,6 +37,7 @@ abstract class DatabaseTestBase extends KernelTestBase {
'test_serialized',
'test_special_columns',
'TEST_UPPERCASE',
'virtual',
]);
self::addSampleData();
}
@@ -164,6 +165,13 @@ abstract class DatabaseTestBase extends KernelTestBase {
'function' => 'Function value 1',
])
->execute();
$connection->insert('virtual')
->fields([
'id' => 1,
'function' => 'Function value 1',
])
->execute();
}
}
@@ -36,7 +36,7 @@ class InsertDefaultsTest extends DatabaseTestBase {
$this->fail('Expected exception NoFieldsException has not been thrown.');
}
catch (NoFieldsException $e) {
$this->pass('Expected exception NoFieldsException has been thrown.');
// Expected exception; just continue testing.
}
$num_records_after = (int) $this->connection->query('SELECT COUNT(*) FROM {test}')->fetchField();
@@ -207,11 +207,9 @@ class MergeTest extends DatabaseTestBase {
'name' => 'Tiffany',
])
->execute();
$this->pass('$options[\'throw_exception\'] is FALSE, no InvalidMergeQueryException thrown.');
}
catch (InvalidMergeQueryException $e) {
$this->fail('$options[\'throw_exception\'] is FALSE, but InvalidMergeQueryException thrown for invalid query.');
return;
}
try {
@@ -222,12 +220,11 @@ class MergeTest extends DatabaseTestBase {
'name' => 'Tiffany',
])
->execute();
$this->fail('InvalidMergeQueryException should be thrown.');
}
catch (InvalidMergeQueryException $e) {
$this->pass('InvalidMergeQueryException thrown for invalid query.');
return;
catch (\Exception $e) {
$this->assertInstanceOf(InvalidMergeQueryException::class, $e);
}
$this->fail('No InvalidMergeQueryException thrown');
}
}
@@ -28,8 +28,8 @@ class QueryTest extends DatabaseTestBase {
$names = $this->connection->query('SELECT name FROM {test} WHERE age IN ( :ages[] ) ORDER BY age', [':ages[]' => 25])->fetchAll();
$this->fail('Array placeholder with scalar argument should result in an exception.');
}
catch (\InvalidArgumentException $e) {
$this->pass('Array placeholder with scalar argument should result in an exception.');
catch (\Exception $e) {
$this->assertInstanceOf(\InvalidArgumentException::class, $e);
}
}
@@ -48,7 +48,7 @@ class QueryTest extends DatabaseTestBase {
$this->fail('SQL injection attempt via array arguments should result in a database exception.');
}
catch (\InvalidArgumentException $e) {
$this->pass('SQL injection attempt via array arguments should result in a database exception.');
// Expected exception; just continue testing.
}
// Test that the insert query that was used in the SQL injection attempt did
@@ -85,7 +85,7 @@ class QueryTest extends DatabaseTestBase {
$this->fail('Should not be able to attempt SQL injection via condition operator.');
}
catch (\ErrorException $e) {
$this->pass('SQL injection attempt via condition arguments should result in a database exception.');
// Expected exception; just continue testing.
}
// Test that the insert query that was used in the SQL injection attempt did
@@ -113,7 +113,7 @@ class QueryTest extends DatabaseTestBase {
$this->fail('Should not be able to attempt SQL injection via operator.');
}
catch (\ErrorException $e) {
$this->pass('SQL injection attempt via condition arguments should result in a database exception.');
// Expected exception; just continue testing.
}
// Attempt SQLi via union query - uppercase tablename.
@@ -130,7 +130,7 @@ class QueryTest extends DatabaseTestBase {
$this->fail('Should not be able to attempt SQL injection via operator.');
}
catch (\ErrorException $e) {
$this->pass('SQL injection attempt via condition arguments should result in a database exception.');
// Expected exception; just continue testing.
}
restore_error_handler();
}
@@ -0,0 +1,83 @@
<?php
namespace Drupal\KernelTests\Core\Database;
/**
* Tests queries that include reserved words.
*
* @group Database
*/
class ReservedWordTest extends DatabaseTestBase {
/**
* Tests SELECT count query from a table with a reserved name.
*/
public function testSelectReservedWordTableCount() {
$query = $this->connection->select('virtual');
$num_records = $query->countQuery()->execute()->fetchField();
$this->assertSame('1', $num_records);
}
/**
* Tests SELECT query with a specific field from a table with a reserved name.
*/
public function testSelectReservedWordTableSpecificField() {
$query = $this->connection->select('virtual');
$query->addField('virtual', 'function');
$rows = $query->execute()->fetchCol();
$this->assertSame('Function value 1', $rows[0]);
}
/**
* Tests SELECT query with all fields from a table with a reserved name.
*/
public function testSelectReservedWordTableAllFields() {
$query = $this->connection->select('virtual');
$query->fields('virtual');
$result = $query->execute()->fetchObject();
$this->assertSame('Function value 1', $result->function);
}
/**
* Tests SELECT count query from a table with a reserved alias.
*/
public function testSelectReservedWordAliasCount() {
$query = $this->connection->select('test', 'character');
$num_records = $query->countQuery()->execute()->fetchField();
$this->assertSame('4', $num_records);
}
/**
* Tests SELECT query with specific fields from a table with a reserved alias.
*/
public function testSelectReservedWordAliasSpecificFields() {
$query = $this->connection->select('test', 'high_priority');
$query->addField('high_priority', 'name');
$query->addField('high_priority', 'age', 'age');
$query->condition('age', 27);
$record = $query->execute()->fetchObject();
// Ensure that we got the right record.
$this->assertSame('George', $record->name);
$this->assertSame('27', $record->age);
}
/**
* Tests SELECT query with all fields from a table with a reserved alias.
*/
public function testSelectReservedWordAliasAllFields() {
$record = $this->connection->select('test', 'signal')
->fields('signal')
->condition('age', 27)
->execute()->fetchObject();
// Ensure that we got the right record.
$this->assertSame('George', $record->name);
$this->assertSame('27', $record->age);
}
}
@@ -433,7 +433,7 @@ class SchemaTest extends KernelTestBase {
$this->fail('\Drupal\Core\Database\SchemaObjectExistsException exception missed.');
}
catch (SchemaObjectExistsException $e) {
$this->pass('\Drupal\Core\Database\SchemaObjectExistsException thrown when index already exists.');
// Expected exception; just continue testing.
}
try {
@@ -441,7 +441,7 @@ class SchemaTest extends KernelTestBase {
$this->fail('\Drupal\Core\Database\SchemaObjectDoesNotExistException exception missed.');
}
catch (SchemaObjectDoesNotExistException $e) {
$this->pass('\Drupal\Core\Database\SchemaObjectDoesNotExistException thrown when index already exists.');
// Expected exception; just continue testing.
}
// Get index information.
@@ -687,7 +687,6 @@ class SchemaTest extends KernelTestBase {
'primary key' => ['serial_column'],
];
$this->schema->createTable($table_name, $table_spec);
$this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
// Check the characteristics of the field.
$this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
@@ -705,7 +704,6 @@ class SchemaTest extends KernelTestBase {
'primary key' => ['serial_column'],
];
$this->schema->createTable($table_name, $table_spec);
$this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
// Insert some rows to the table to test the handling of initial values.
for ($i = 0; $i < 3; $i++) {
@@ -723,7 +721,6 @@ class SchemaTest extends KernelTestBase {
->execute();
$this->schema->addField($table_name, 'test_field', $field_spec);
$this->pass(new FormattableMarkup('Column %column created.', ['%column' => 'test_field']));
// Check the characteristics of the field.
$this->assertFieldCharacteristics($table_name, 'test_field', $field_spec);
@@ -1025,7 +1022,6 @@ class SchemaTest extends KernelTestBase {
'primary key' => ['serial_column'],
];
$this->schema->createTable($table_name, $table_spec);
$this->pass(new FormattableMarkup('Table %table created.', ['%table' => $table_name]));
// Check the characteristics of the field.
$this->assertFieldCharacteristics($table_name, 'test_field', $old_spec);
@@ -161,8 +161,8 @@ class SelectComplexTest extends DatabaseTestBase {
*/
public function testRangeUndo() {
$query = $this->connection->select('test');
$name_field = $query->addField('test', 'name');
$age_field = $query->addField('test', 'age', 'age');
$query->addField('test', 'name');
$query->addField('test', 'age', 'age');
$query->range(0, 2);
$query->range(NULL, NULL);
$query_result = $query->countQuery()->execute()->fetchField();
@@ -4,6 +4,7 @@ namespace Drupal\KernelTests\Core\Database;
use Drupal\Core\Database\InvalidQueryException;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\DatabaseExceptionWrapper;
/**
* Tests the Select query builder.
@@ -551,7 +552,7 @@ class SelectTest extends DatabaseTestBase {
}
/**
* Tests that an invalid merge query throws an exception.
* Tests that an invalid count query throws an exception.
*/
public function testInvalidSelectCount() {
try {
@@ -563,12 +564,9 @@ class SelectTest extends DatabaseTestBase {
->fields('t')
->countQuery()
->execute();
$this->pass('$options[\'throw_exception\'] is FALSE, no Exception thrown.');
}
catch (\Exception $e) {
$this->fail('$options[\'throw_exception\'] is FALSE, but Exception thrown for invalid query.');
return;
}
try {
@@ -577,12 +575,11 @@ class SelectTest extends DatabaseTestBase {
->fields('t')
->countQuery()
->execute();
$this->fail('No Exception thrown.');
}
catch (\Exception $e) {
$this->pass('Exception thrown for invalid query.');
return;
$this->assertInstanceOf(DatabaseExceptionWrapper::class, $e);
}
$this->fail('No Exception thrown.');
}
/**
@@ -300,7 +300,7 @@ class TransactionTest extends DatabaseTestBase {
// $this->fail('Rolling back a transaction containing DDL should fail.');
}
catch (TransactionNoActiveException $e) {
$this->pass('Rolling back a transaction containing DDL should fail.');
// Expected exception; just continue testing.
}
$this->assertRowPresent('row');
}
@@ -466,12 +466,12 @@ class TransactionTest extends DatabaseTestBase {
$this->fail('Rolling back the outer transaction while the inner transaction is active resulted in an exception.');
}
catch (TransactionOutOfOrderException $e) {
$this->pass('Rolling back the outer transaction while the inner transaction is active resulted in an exception.');
// Expected exception; just continue testing.
}
$this->assertFalse($this->connection->inTransaction(), 'No more in a transaction after rolling back the outer transaction');
// Try to commit one inner transaction.
unset($transaction3);
$this->pass('Trying to commit an inner transaction resulted in an exception.');
// Try to rollback one inner transaction.
try {
$transaction->rollBack();
@@ -479,7 +479,7 @@ class TransactionTest extends DatabaseTestBase {
$this->fail('Trying to commit an inner transaction resulted in an exception.');
}
catch (TransactionNoActiveException $e) {
$this->pass('Trying to commit an inner transaction resulted in an exception.');
// Expected exception; just continue testing.
}
$this->assertRowAbsent('outer');
$this->assertRowAbsent('inner');
@@ -496,10 +496,10 @@ class TransactionTest extends DatabaseTestBase {
// Test a failed query using the query() method.
try {
$this->connection->query('SELECT age FROM {test} WHERE name = :name', [':name' => 'David'])->fetchField();
$this->fail('Using the query method failed.');
$this->fail('Using the query method should have failed.');
}
catch (\Exception $e) {
$this->pass('Using the query method failed.');
// Just continue testing.
}
// Test a failed select query.
@@ -508,10 +508,10 @@ class TransactionTest extends DatabaseTestBase {
->fields('test', ['name'])
->execute();
$this->fail('Select query failed.');
$this->fail('Select query should have failed.');
}
catch (\Exception $e) {
$this->pass('Select query failed.');
// Just continue testing.
}
// Test a failed insert query.
@@ -523,10 +523,10 @@ class TransactionTest extends DatabaseTestBase {
])
->execute();
$this->fail('Insert query failed.');
$this->fail('Insert query should have failed.');
}
catch (\Exception $e) {
$this->pass('Insert query failed.');
// Just continue testing.
}
// Test a failed update query.
@@ -536,10 +536,10 @@ class TransactionTest extends DatabaseTestBase {
->condition('id', 1)
->execute();
$this->fail('Update query failed.');
$this->fail('Update query sould have failed.');
}
catch (\Exception $e) {
$this->pass('Update query failed.');
// Just continue testing.
}
// Test a failed delete query.
@@ -548,10 +548,10 @@ class TransactionTest extends DatabaseTestBase {
->condition('id', 1)
->execute();
$this->fail('Delete query failed.');
$this->fail('Delete query should have failed.');
}
catch (\Exception $e) {
$this->pass('Delete query failed.');
// Just continue testing.
}
// Test a failed merge query.
@@ -564,10 +564,10 @@ class TransactionTest extends DatabaseTestBase {
])
->execute();
$this->fail('Merge query failed.');
$this->fail('Merge query should have failed.');
}
catch (\Exception $e) {
$this->pass('Merge query failed.');
// Just continue testing.
}
// Test a failed upsert query.
@@ -582,10 +582,10 @@ class TransactionTest extends DatabaseTestBase {
])
->execute();
$this->fail('Upset query failed.');
$this->fail('Upsert query should have failed.');
}
catch (\Exception $e) {
$this->pass('Upset query failed.');
// Just continue testing.
}
// Create the missing schema and insert a row.
@@ -3,6 +3,7 @@
namespace Drupal\KernelTests\Core\DrupalKernel;
use Drupal\Core\DrupalKernel;
use Drupal\Core\DrupalKernelInterface;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
@@ -158,10 +159,8 @@ class DrupalKernelTest extends KernelTestBase {
$kernel = DrupalKernel::createFromRequest($request, $class_loader, $environment);
$this->setSetting('container_yamls', []);
$this->setSetting('hash_salt', $this->databasePrefix);
$kernel->boot();
$this->assertInstanceOf(DrupalKernelInterface::class, $kernel->boot(), "Environment $environment should boot.");
}
$this->pass('Repeatedly loaded compiled DIC with different environment');
}
/**
@@ -114,6 +114,27 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->entities[] = $entity;
$entity->enforceIsNew();
$entity->save();
$array['level1'] = [];
$entity = ConfigQueryTest::create([
'label' => $this->randomMachineName(),
'id' => '6',
'array' => $array,
]);
$this->entities[] = $entity;
$entity->enforceIsNew();
$entity->save();
$array['level1']['level2'] = 4;
$entity = ConfigQueryTest::create([
'label' => $this->randomMachineName(),
'id' => '7',
'number' => 70,
'array' => $array,
]);
$this->entities[] = $entity;
$entity->enforceIsNew();
$entity->save();
}
/**
@@ -123,11 +144,11 @@ class ConfigEntityQueryTest extends KernelTestBase {
// Run a test without any condition.
$this->queryResults = $this->entityStorage->getQuery()
->execute();
$this->assertResults(['1', '2', '3', '4', '5']);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
// No conditions, OR.
$this->queryResults = $this->entityStorage->getQuery('OR')
->execute();
$this->assertResults(['1', '2', '3', '4', '5']);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
// Filter by ID with equality.
$this->queryResults = $this->entityStorage->getQuery()
@@ -169,19 +190,19 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', '3', '>')
->execute();
$this->assertResults(['4', '5']);
$this->assertResults(['4', '5', '6', '7']);
// Filter by ID with the >= operator.
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', '3', '>=')
->execute();
$this->assertResults(['3', '4', '5']);
$this->assertResults(['3', '4', '5', '6', '7']);
// Filter by ID with the <> operator.
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', '3', '<>')
->execute();
$this->assertResults(['1', '2', '4', '5']);
$this->assertResults(['1', '2', '4', '5', '6', '7']);
// Filter by ID with the < operator.
$this->queryResults = $this->entityStorage->getQuery()
@@ -226,7 +247,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
->condition('number', 10, '>=')
->condition('number', 50, '>=')
->execute();
$this->assertResults(['3', '5']);
$this->assertResults(['3', '5', '7']);
// Filter with an OR condition group.
$this->queryResults = $this->entityStorage->getQuery('OR')
@@ -249,7 +270,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', ['1', '2'], 'NOT IN')
->execute();
$this->assertResults(['3', '4', '5']);
$this->assertResults(['3', '4', '5', '6', '7']);
// Filter with an OR condition group on different fields.
$this->queryResults = $this->entityStorage->getQuery('OR')
@@ -328,7 +349,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->queryResults = $this->entityStorage->getQuery()
->exists('id')
->execute();
$this->assertResults(['1', '2', '3', '4', '5']);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
$this->queryResults = $this->entityStorage->getQuery()
->exists('non-existent')
@@ -343,7 +364,7 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->queryResults = $this->entityStorage->getQuery()
->notExists('non-existent')
->execute();
$this->assertResults(['1', '2', '3', '4', '5']);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
}
/**
@@ -436,38 +457,38 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->queryResults = $this->entityStorage->getQuery()
->sort('number', 'DESC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
$this->assertIdentical(array_values($this->queryResults), ['7', '3', '5', '2', '1', '4', '6']);
$this->queryResults = $this->entityStorage->getQuery()
->sort('number', 'ASC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
$this->assertIdentical(array_values($this->queryResults), ['6', '4', '1', '2', '5', '3', '7']);
// Apply some filters and sort.
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', '3', '>')
->sort('number', 'DESC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['5', '4']);
$this->assertIdentical(array_values($this->queryResults), ['7', '5', '4', '6']);
$this->queryResults = $this->entityStorage->getQuery()
->condition('id', '3', '>')
->sort('number', 'ASC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['4', '5']);
$this->assertIdentical(array_values($this->queryResults), ['6', '4', '5', '7']);
// Apply a pager and sort.
$this->queryResults = $this->entityStorage->getQuery()
->sort('number', 'DESC')
->range('2', '2')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['2', '1']);
$this->assertIdentical(array_values($this->queryResults), ['5', '2']);
$this->queryResults = $this->entityStorage->getQuery()
->sort('number', 'ASC')
->range('2', '2')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['2', '5']);
$this->assertIdentical(array_values($this->queryResults), ['1', '2']);
// Add a range to a query without a start parameter.
$this->queryResults = $this->entityStorage->getQuery()
@@ -499,28 +520,28 @@ class ConfigEntityQueryTest extends KernelTestBase {
->tableSort($header)
->sort('id', 'DESC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['5', '4', '3', '2', '1']);
$this->assertIdentical(array_values($this->queryResults), ['7', '6', '5', '4', '3', '2', '1']);
// Sorting with 'ASC' upper case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('id', 'ASC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5']);
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5', '6', '7']);
// Sorting with 'desc' lower case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('id', 'desc')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['5', '4', '3', '2', '1']);
$this->assertIdentical(array_values($this->queryResults), ['7', '6', '5', '4', '3', '2', '1']);
// Sorting with 'asc' lower case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('id', 'asc')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5']);
$this->assertIdentical(array_values($this->queryResults), ['1', '2', '3', '4', '5', '6', '7']);
// Sort key: number
// Sorting with 'DeSc' mixed upper and lower case
@@ -528,28 +549,28 @@ class ConfigEntityQueryTest extends KernelTestBase {
->tableSort($header)
->sort('number', 'DeSc')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
$this->assertIdentical(array_values($this->queryResults), ['7', '3', '5', '2', '1', '4', '6']);
// Sorting with 'AsC' mixed upper and lower case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('number', 'AsC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
$this->assertIdentical(array_values($this->queryResults), ['6', '4', '1', '2', '5', '3', '7']);
// Sorting with 'dEsC' mixed upper and lower case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('number', 'dEsC')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['3', '5', '2', '1', '4']);
$this->assertIdentical(array_values($this->queryResults), ['7', '3', '5', '2', '1', '4', '6']);
// Sorting with 'aSc' mixed upper and lower case
$this->queryResults = $this->entityStorage->getQuery()
->tableSort($header)
->sort('number', 'aSc')
->execute();
$this->assertIdentical(array_values($this->queryResults), ['4', '1', '2', '5', '3']);
$this->assertIdentical(array_values($this->queryResults), ['6', '4', '1', '2', '5', '3', '7']);
}
/**
@@ -572,6 +593,15 @@ class ConfigEntityQueryTest extends KernelTestBase {
->condition('array.level1.level2', 3)
->execute();
$this->assertResults(['5']);
// Test dotted sorting.
$this->queryResults = $this->entityStorage->getQuery()
->sort('array.level1.level2')
->execute();
$this->assertResults(['6', '1', '3', '2', '4', '5', '7']);
$this->queryResults = $this->entityStorage->getQuery()
->sort('array.level1.level2', 'DESC')
->execute();
$this->assertResults(['7', '5', '2', '4', '1', '3', '6']);
// Make sure that values on the wildcard level do not match if there are
// sub-keys defined. This must not find anything even if entity 2 has a
// top-level key number with value 41.
@@ -581,23 +611,22 @@ class ConfigEntityQueryTest extends KernelTestBase {
$this->assertResults([]);
// Make sure that "IS NULL" and "IS NOT NULL" work correctly with
// array-valued fields/keys.
$all = ['1', '2', '3', '4', '5'];
$this->queryResults = $this->entityStorage->getQuery()
->exists('array.level1.level2')
->execute();
$this->assertResults($all);
$this->assertResults(['1', '2', '3', '4', '5', '7']);
$this->queryResults = $this->entityStorage->getQuery()
->exists('array.level1')
->execute();
$this->assertResults($all);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
$this->queryResults = $this->entityStorage->getQuery()
->exists('array')
->execute();
$this->assertResults($all);
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
$this->queryResults = $this->entityStorage->getQuery()
->notExists('array.level1.level2')
->execute();
$this->assertResults([]);
$this->assertResults(['6']);
$this->queryResults = $this->entityStorage->getQuery()
->notExists('array.level1')
->execute();
@@ -606,6 +635,16 @@ class ConfigEntityQueryTest extends KernelTestBase {
->notExists('array')
->execute();
$this->assertResults([]);
// Make sure that "IS NULL" and "IS NOT NULL" work correctly when the dotted
// path cannot be fully followed.
$this->queryResults = $this->entityStorage->getQuery()
->exists('does.not.exist')
->execute();
$this->assertResults([]);
$this->queryResults = $this->entityStorage->getQuery()
->notExists('does.not.exist')
->execute();
$this->assertResults(['1', '2', '3', '4', '5', '6', '7']);
}
/**
@@ -214,7 +214,6 @@ class EntityApiTest extends EntityKernelTestBase {
try {
unset($GLOBALS['entity_test_throw_exception']);
$entity->save();
$this->pass('Exception presave not thrown and not caught.');
}
catch (EntityStorageException $e) {
$this->assertNotEqual($e->getCode(), 1, 'Entity presave EntityStorageException caught.');
@@ -236,7 +235,6 @@ class EntityApiTest extends EntityKernelTestBase {
$entity->save();
try {
$entity->delete();
$this->pass('Entity predelete EntityStorageException not thrown and not caught.');
}
catch (EntityStorageException $e) {
$this->assertNotEqual($e->getCode(), 2, 'Entity predelete EntityStorageException thrown.');
@@ -115,7 +115,7 @@ class EntityAutocompleteTest extends EntityKernelTestBase {
$this->fail('Non-existent selection settings key throws an exception.');
}
catch (AccessDeniedHttpException $e) {
$this->pass('Non-existent selection settings key throws an exception.');
// Expected exception; just continue testing.
}
try {
@@ -129,12 +129,7 @@ class EntityAutocompleteTest extends EntityKernelTestBase {
$entity_reference_controller->handleAutocomplete($request, $this->entityType, 'default', $selection_settings_key);
}
catch (AccessDeniedHttpException $e) {
if ($e->getMessage() == 'Invalid selection settings key.') {
$this->pass('Invalid selection settings key throws an exception.');
}
else {
$this->fail('Invalid selection settings key throws an exception.');
}
$this->assertSame('Invalid selection settings key.', $e->getMessage());
}
}
@@ -551,7 +551,7 @@ class EntityCrudHookTest extends EntityKernelTestBase {
$this->fail('Expected exception has not been thrown.');
}
catch (\Exception $e) {
$this->pass('Expected exception has been thrown.');
// Expected exception; just continue testing.
}
if (Database::getConnection()->supportsTransactions()) {
@@ -17,6 +17,7 @@ use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\entity_test\FieldStorageDefinition;
use Drupal\entity_test_update\Entity\EntityTestUpdate;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Tests\system\Functional\Entity\Traits\EntityDefinitionTestTrait;
/**
@@ -56,7 +57,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
*
* @var array
*/
public static $modules = ['entity_test_update'];
public static $modules = ['entity_test_update', 'language'];
/**
* {@inheritdoc}
@@ -144,7 +145,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail('EntityStorageException thrown when trying to apply an update that requires shared table schema changes.');
}
catch (EntityStorageException $e) {
$this->pass('EntityStorageException thrown when trying to apply an update that requires shared table schema changes.');
// Expected exception; just continue testing.
}
}
@@ -426,7 +427,6 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->assertTrue($assert, 'Columns created again in shared table for new_base_field.');
$entity = $storage->create(['name' => $name]);
$entity->save();
$this->pass('The new_base_field columns are still nullable');
}
/**
@@ -490,7 +490,6 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->database->insert('entity_test_update__new_bundle_field')
->fields($values)
->execute();
$this->pass($message);
}
else {
// Keep throwing it.
@@ -504,18 +503,22 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
*
* @dataProvider baseFieldDeleteWithExistingDataTestCases
*/
public function testBaseFieldDeleteWithExistingData($entity_type_id, $create_entity_revision, $base_field_revisionable) {
public function testBaseFieldDeleteWithExistingData($entity_type_id, $create_entity_revision, $base_field_revisionable, $create_entity_translation) {
// Enable an additional language.
ConfigurableLanguage::createFromLangcode('ro')->save();
/** @var \Drupal\Core\Entity\Sql\SqlEntityStorageInterface $storage */
$storage = $this->entityTypeManager->getStorage($entity_type_id);
$schema_handler = $this->database->schema();
// Create an entity without the base field, to ensure NULL values are not
// added to the dedicated table storage to be purged.
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $storage->create();
$entity->save();
// Add the base field and run the update.
$this->addBaseField('string', $entity_type_id, $base_field_revisionable);
$this->addBaseField('string', $entity_type_id, $base_field_revisionable, TRUE, $create_entity_translation);
$this->applyEntityUpdates();
/** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
@@ -526,10 +529,22 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$entity = $storage->create(['new_base_field' => 'foo']);
$entity->save();
if ($create_entity_translation) {
$translation = $entity->addTranslation('ro', ['new_base_field' => 'foo-ro']);
$translation->save();
}
if ($create_entity_revision) {
$entity->setNewRevision(TRUE);
$entity->isDefaultRevision(FALSE);
$entity->new_base_field = 'bar';
$entity->save();
if ($create_entity_translation) {
$translation = $entity->getTranslation('ro');
$translation->new_base_field = 'bar-ro';
$translation->save();
}
}
// Remove the base field and apply updates.
@@ -544,65 +559,81 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$dedicated_deleted_table_name = $table_mapping->getDedicatedDataTableName($storage_definition, TRUE);
$this->assertTrue($schema_handler->tableExists($dedicated_deleted_table_name), 'A dedicated table was created for the deleted new_base_field.');
$expected[] = [
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => '2',
'revision_id' => '2',
'langcode' => 'en',
'delta' => '0',
'new_base_field_value' => 'foo',
];
if ($create_entity_translation) {
$expected[] = [
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => '2',
'revision_id' => '2',
'langcode' => 'ro',
'delta' => '0',
'new_base_field_value' => 'foo-ro',
];
}
// Check that the deleted field's data is preserved in the dedicated
// 'deleted' table.
$result = $this->database->select($dedicated_deleted_table_name, 't')
->fields('t')
->orderBy('revision_id', 'ASC')
->orderBy('langcode', 'ASC')
->execute()
->fetchAll();
$this->assertCount(1, $result);
->fetchAll(\PDO::FETCH_ASSOC);
$this->assertCount(count($expected), $result);
$expected = [
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => $entity->id(),
'revision_id' => $create_entity_revision ? $entity->getRevisionId() : $entity->id(),
'langcode' => $entity->language()->getId(),
'delta' => '0',
'new_base_field_value' => $entity->new_base_field->value,
];
// Use assertEquals and not assertSame here to prevent that a different
// sequence of the columns in the table will affect the check.
$this->assertEquals($expected, (array) $result[0]);
$this->assertEquals($expected, $result);
if ($create_entity_revision) {
$dedicated_deleted_revision_table_name = $table_mapping->getDedicatedRevisionTableName($storage_definition, TRUE);
$this->assertTrue($schema_handler->tableExists($dedicated_deleted_revision_table_name), 'A dedicated revision table was created for the deleted new_base_field.');
if ($base_field_revisionable) {
$expected[] = [
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => '2',
'revision_id' => '3',
'langcode' => 'en',
'delta' => '0',
'new_base_field_value' => 'bar',
];
if ($create_entity_translation) {
$expected[] = [
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => '2',
'revision_id' => '3',
'langcode' => 'ro',
'delta' => '0',
'new_base_field_value' => 'bar-ro',
];
}
}
$result = $this->database->select($dedicated_deleted_revision_table_name, 't')
->fields('t')
->orderBy('revision_id', 'DESC')
->orderBy('revision_id', 'ASC')
->orderBy('langcode', 'ASC')
->execute()
->fetchAll();
// Only one row will be created for non-revisionable base fields.
$this->assertCount($base_field_revisionable ? 2 : 1, $result);
->fetchAll(\PDO::FETCH_ASSOC);
$this->assertCount(count($expected), $result);
// Use assertEquals and not assertSame here to prevent that a different
// sequence of the columns in the table will affect the check.
$this->assertEquals([
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => $entity->id(),
'revision_id' => '3',
'langcode' => $entity->language()->getId(),
'delta' => '0',
'new_base_field_value' => 'bar',
], (array) $result[0]);
// Two rows only exist if the base field is revisionable.
if ($base_field_revisionable) {
// Use assertEquals and not assertSame here to prevent that a different
// sequence of the columns in the table will affect the check.
$this->assertEquals([
'bundle' => $entity->bundle(),
'deleted' => '1',
'entity_id' => $entity->id(),
'revision_id' => '2',
'langcode' => $entity->language()->getId(),
'delta' => '0',
'new_base_field_value' => 'foo',
], (array) $result[1]);
}
$this->assertEquals($expected, $result);
}
// Check that the field storage definition is marked for purging.
@@ -626,45 +657,65 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
*/
public function baseFieldDeleteWithExistingDataTestCases() {
return [
'Non-revisionable entity type' => [
'Non-revisionable, non-translatable entity type' => [
'entity_test_update',
FALSE,
FALSE,
FALSE,
],
'Non-revisionable custom data table' => [
'Non-revisionable, non-translatable custom data table' => [
'entity_test_mul',
FALSE,
FALSE,
FALSE,
],
'Non-revisionable entity type, revisionable base field' => [
'Non-revisionable, non-translatable entity type, revisionable base field' => [
'entity_test_update',
FALSE,
TRUE,
FALSE,
],
'Non-revisionable custom data table, revisionable base field' => [
'Non-revisionable, non-translatable custom data table, revisionable base field' => [
'entity_test_mul',
FALSE,
TRUE,
FALSE,
],
'Revisionable entity type, non revisionable base field' => [
'Revisionable, translatable entity type, non revisionable and non-translatable base field' => [
'entity_test_mulrev',
TRUE,
FALSE,
FALSE,
],
'Revisionable entity type, revisionable base field' => [
'Revisionable, translatable entity type, revisionable and non-translatable base field' => [
'entity_test_mulrev',
TRUE,
TRUE,
FALSE,
],
'Non-translatable revisionable entity type, revisionable base field' => [
'Revisionable and non-translatable entity type, revisionable and non-translatable base field' => [
'entity_test_rev',
TRUE,
TRUE,
FALSE,
],
'Non-translatable revisionable entity type, non-revisionable base field' => [
'Revisionable and non-translatable entity type, non-revisionable and non-translatable base field' => [
'entity_test_rev',
TRUE,
FALSE,
FALSE,
],
'Revisionable and translatable entity type, non-revisionable and translatable base field' => [
'entity_test_mulrev',
TRUE,
FALSE,
TRUE,
],
'Revisionable and translatable entity type, revisionable and translatable base field' => [
'entity_test_mulrev',
TRUE,
TRUE,
TRUE,
],
];
}
@@ -763,7 +814,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail('FieldStorageDefinitionUpdateForbiddenException thrown when trying to update a field schema that has data.');
}
catch (FieldStorageDefinitionUpdateForbiddenException $e) {
$this->pass('FieldStorageDefinitionUpdateForbiddenException thrown when trying to update a field schema that has data.');
// Expected exception; just continue testing.
}
}
@@ -787,7 +838,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail('FieldStorageDefinitionUpdateForbiddenException thrown when trying to update a field schema that has data.');
}
catch (FieldStorageDefinitionUpdateForbiddenException $e) {
$this->pass('FieldStorageDefinitionUpdateForbiddenException thrown when trying to update a field schema that has data.');
// Expected exception; just continue testing.
}
}
@@ -972,7 +1023,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (PluginNotFoundException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Ensure that a field cannot be installed on non-existing entity type.
@@ -985,7 +1036,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (PluginNotFoundException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Ensure that installing an existing entity type is a no-op.
@@ -1114,14 +1165,13 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (EntityStorageException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Check that the update is correctly applied when no NULL data is left.
$entity->set('new_base_field', $this->randomString());
$entity->save();
$this->applyEntityUpdates();
$this->pass('The update is correctly performed when no NULL data exists.');
// Check that the update actually applied a NOT NULL constraint.
$entity->set('new_base_field', NULL);
@@ -1131,7 +1181,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (EntityStorageException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
@@ -1269,7 +1319,6 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
}
catch (FieldException $e) {
$this->assertEquals('Illegal initial value definition on new_base_field: The field field_that_does_not_exist does not exist.', $e->getMessage());
$this->pass('Using a non-existent field as initial value does not work.');
}
try {
@@ -1282,7 +1331,6 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
}
catch (FieldException $e) {
$this->assertEquals('Illegal initial value definition on new_base_field: The field types do not match.', $e->getMessage());
$this->pass('Using a field of a different type as initial value does not work.');
}
try {
@@ -1306,7 +1354,6 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
}
catch (FieldException $e) {
$this->assertEquals('Illegal initial value definition on new_base_field: Both fields have to be stored in the shared entity tables.', $e->getMessage());
$this->pass('Using a field that is not stored in the shared tables as initial value does not work.');
}
}
@@ -1106,17 +1106,12 @@ class EntityQueryTest extends EntityKernelTestBase {
* database driver's EntityQuery\Condition class.
*/
public function testInjectionInCondition() {
try {
$this->queryResults = $this->storage
->getQuery()
->condition('1 ; -- ', [0, 1], 'IN')
->sort('id')
->execute();
$this->fail('SQL Injection attempt in Entity Query condition in operator should result in an exception.');
}
catch (\Exception $e) {
$this->pass('SQL Injection attempt in Entity Query condition in operator should result in an exception.');
}
$this->expectException(\Exception::class);
$this->queryResults = $this->storage
->getQuery()
->condition('1 ; -- ', [0, 1], 'IN')
->sort('id')
->execute();
}
/**
@@ -273,7 +273,7 @@ class EntityReferenceFieldTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
$this->assertUserAutocreate($entity, function (EntityInterface $entity, UserInterface $user) {
$entity->user_id = $user;
@@ -307,7 +307,7 @@ class EntityReferenceFieldTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
$this->assertUserRoleAutocreate($entity, function (EntityInterface $entity, RoleInterface $role) {
$entity->user_role = $role;
@@ -404,7 +404,6 @@ class EntityReferenceFieldTest extends EntityKernelTestBase {
->getStorage($entity_type->id())
->create(['name' => $this->randomString()]);
$entity->target_reference = $target_id;
$this->pass($message);
}
catch (EntityStorageException $e) {
$this->fail($message);
@@ -418,7 +417,7 @@ class EntityReferenceFieldTest extends EntityKernelTestBase {
$this->fail($message);
}
catch (EntityStorageException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
@@ -62,13 +62,12 @@ class EntityTranslationTest extends EntityLanguageTestBase {
$this->assertEqual($field->getLangcode(), LanguageInterface::LANGCODE_NOT_SPECIFIED, new FormattableMarkup('%entity_type: Field object has the expected langcode.', ['%entity_type' => $entity_type]));
// Try to get add a translation to language neutral entity.
$message = 'Adding a translation to a language-neutral entity results in an error.';
try {
$entity->addTranslation($this->langcodes[1]);
$this->fail($message);
$this->fail('Adding a translation to a language-neutral entity results in an error.');
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Now, make the entity language-specific by assigning a language and test
@@ -101,26 +100,24 @@ class EntityTranslationTest extends EntityLanguageTestBase {
$this->assertEqual($entity->getTranslationLanguages(FALSE), $translations, 'Translations retrieved.');
// Try to get a value using a language code for a non-existing translation.
$message = 'Getting a non existing translation results in an error.';
try {
$entity->getTranslation($this->langcodes[2])->get($this->fieldName)->value;
$this->fail($message);
$this->fail('Getting a non existing translation results in an error.');
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Try to get a not available translation.
$this->assertNull($entity->addTranslation($this->langcodes[2])->get($this->fieldName)->value, new FormattableMarkup('%entity_type: A translation that is not available is NULL.', ['%entity_type' => $entity_type]));
// Try to get a value using an invalid language code.
$message = 'Getting an invalid translation results in an error.';
try {
$entity->getTranslation('invalid')->get($this->fieldName)->value;
$this->fail($message);
$this->fail('Getting an invalid translation results in an error.');
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Try to set a value using an invalid language code.
@@ -129,7 +126,7 @@ class EntityTranslationTest extends EntityLanguageTestBase {
$this->fail(new FormattableMarkup('%entity_type: Setting a translation for an invalid language throws an exception.', ['%entity_type' => $entity_type]));
}
catch (\InvalidArgumentException $e) {
$this->pass(new FormattableMarkup('%entity_type: Setting a translation for an invalid language throws an exception.', ['%entity_type' => $entity_type]));
// Expected exception; just continue testing.
}
// Set the value in default language.
@@ -352,13 +349,12 @@ class EntityTranslationTest extends EntityLanguageTestBase {
// Verify that trying to retrieve a translation for a locked language when
// the entity is language-aware causes an exception to be thrown.
$message = 'A language-neutral translation cannot be retrieved.';
try {
$entity->getTranslation(LanguageInterface::LANGCODE_NOT_SPECIFIED);
$this->fail($message);
$this->fail('A language-neutral translation cannot be retrieved.');
}
catch (\LogicException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Create a translation and verify that the translation object and the
@@ -391,23 +387,20 @@ class EntityTranslationTest extends EntityLanguageTestBase {
// Verify that changing translation language causes an exception to be
// thrown.
$message = 'The translation language cannot be changed.';
try {
$translation->{$langcode_key}->value = $this->langcodes[2];
$this->fail($message);
$this->fail('The translation language cannot be changed.');
}
catch (\LogicException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
// Verify that reassigning the same translation language is allowed.
$message = 'The translation language can be reassigned the same value.';
try {
$translation->{$langcode_key}->value = $langcode;
$this->pass($message);
}
catch (\LogicException $e) {
$this->fail($message);
$this->fail('The translation language can be reassigned the same value.');
}
// Verify that changing the default translation flag causes an exception to
@@ -416,22 +409,19 @@ class EntityTranslationTest extends EntityLanguageTestBase {
$translation = $entity->getTranslation($t_langcode);
$default = $translation->isDefaultTranslation();
$message = 'The default translation flag can be reassigned the same value.';
try {
$translation->{$default_langcode_key}->value = $default;
$this->pass($message);
}
catch (\LogicException $e) {
$this->fail($message);
$this->fail('The default translation flag can be reassigned the same value.');
}
$message = 'The default translation flag cannot be changed.';
try {
$translation->{$default_langcode_key}->value = !$default;
$this->fail($message);
$this->fail('The default translation flag cannot be changed.');
}
catch (\LogicException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
$this->assertEqual($translation->{$default_langcode_key}->value, $default);
@@ -464,13 +454,12 @@ class EntityTranslationTest extends EntityLanguageTestBase {
$translation = $entity->getTranslation($langcode2);
$entity->removeTranslation($langcode2);
foreach (['get', 'set', '__get', '__set', 'createDuplicate'] as $method) {
$message = new FormattableMarkup('The @method method raises an exception when trying to manipulate a removed translation.', ['@method' => $method]);
try {
$translation->{$method}('name', $this->randomMachineName());
$this->fail($message);
$this->fail("The $method method raises an exception when trying to manipulate a removed translation.");
}
catch (\Exception $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
@@ -486,13 +475,12 @@ class EntityTranslationTest extends EntityLanguageTestBase {
// Check that removing an invalid translation causes an exception to be
// thrown.
foreach ([$default_langcode, LanguageInterface::LANGCODE_DEFAULT, $this->randomMachineName()] as $invalid_langcode) {
$message = new FormattableMarkup('Removing an invalid translation (@langcode) causes an exception to be thrown.', ['@langcode' => $invalid_langcode]);
try {
$entity->removeTranslation($invalid_langcode);
$this->fail($message);
$this->fail("Removing an invalid translation ($invalid_langcode) causes an exception to be thrown.");
}
catch (\Exception $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
@@ -714,14 +702,13 @@ class EntityTranslationTest extends EntityLanguageTestBase {
foreach ($translatable_fields as $name => $translatable) {
$this->state->set('entity_test.field_definitions.translatable', [$name => $translatable]);
$entity_field_manager->clearCachedFieldDefinitions();
$message = new FormattableMarkup('Field %field cannot be translatable.', ['%field' => $name]);
try {
$entity_field_manager->getBaseFieldDefinitions($entity_type);
$this->fail($message);
$this->fail("Field $name cannot be translatable.");
}
catch (\LogicException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
}
@@ -778,13 +765,12 @@ class EntityTranslationTest extends EntityLanguageTestBase {
// Check that setting the default language to an existing translation
// language causes an exception to be thrown.
$message = 'An exception is thrown when setting the default language to an existing translation language';
try {
$entity->{$langcode_key}->value = $this->langcodes[2];
$this->fail($message);
$this->fail('An exception is thrown when setting the default language to an existing translation language');
}
catch (\InvalidArgumentException $e) {
$this->pass($message);
// Expected exception; just continue testing.
}
}
@@ -339,13 +339,8 @@ class FieldSqlStorageTest extends EntityKernelTestBase {
// Attempt to update the field in a way that would work without data.
$field_storage->setSetting('scale', 3);
try {
$field_storage->save();
$this->fail('Cannot update field schema with data.');
}
catch (FieldStorageDefinitionUpdateForbiddenException $e) {
$this->pass('Cannot update field schema with data.');
}
$this->expectException(FieldStorageDefinitionUpdateForbiddenException::class);
$field_storage->save();
}
/**
@@ -373,7 +368,7 @@ class FieldSqlStorageTest extends EntityKernelTestBase {
$this->fail('Update succeeded.');
}
catch (\Exception $e) {
$this->pass('Update properly failed.');
// Expected exception; just continue testing.
}
// Ensure that the field tables are still there.
@@ -77,15 +77,10 @@ class ModuleImplementsAlterTest extends KernelTestBase {
// Install the module_test module.
\Drupal::service('module_installer')->install(['module_test']);
try {
// Trigger hook discovery.
\Drupal::moduleHandler()->getImplementations('unimplemented_test_hook');
$this->fail('An exception should be thrown for the non-existing implementation.');
}
catch (\RuntimeException $e) {
$this->pass('An exception should be thrown for the non-existing implementation.');
$this->assertEqual($e->getMessage(), 'An invalid implementation module_test_unimplemented_test_hook was added by hook_module_implements_alter()');
}
// Trigger hook discovery.
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('An invalid implementation module_test_unimplemented_test_hook was added by hook_module_implements_alter()');
\Drupal::moduleHandler()->getImplementations('unimplemented_test_hook');
}
}
@@ -62,7 +62,7 @@ class KeyValueContentEntityStorageTest extends KernelTestBase {
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
$this->pass('EntityMalformedException was thrown.');
// Expected exception; just continue testing.
}
// Verify that an empty entity cannot be saved.
@@ -71,7 +71,7 @@ class KeyValueContentEntityStorageTest extends KernelTestBase {
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
$this->pass('EntityMalformedException was thrown.');
// Expected exception; just continue testing.
}
// Verify that an entity with an empty ID string is considered empty, too.
@@ -84,7 +84,7 @@ class KeyValueContentEntityStorageTest extends KernelTestBase {
$this->fail('EntityMalformedException was thrown.');
}
catch (EntityMalformedException $e) {
$this->pass('EntityMalformedException was thrown.');
// Expected exception; just continue testing.
}
// Verify properties on a newly created entity.
@@ -108,7 +108,6 @@ class KeyValueContentEntityStorageTest extends KernelTestBase {
// Verify that the entity can be saved.
try {
$status = $entity_test->save();
$this->pass('EntityMalformedException was not thrown.');
}
catch (EntityMalformedException $e) {
$this->fail('EntityMalformedException was not thrown.');
@@ -143,7 +142,7 @@ class KeyValueContentEntityStorageTest extends KernelTestBase {
$this->fail('Not possible to overwrite an entity entity.');
}
catch (EntityStorageException $e) {
$this->pass('Not possible to overwrite an entity entity.');
// Expected exception; just continue testing.
}
// Verify that renaming the ID returns correct status and properties.
@@ -214,7 +214,7 @@ class MenuTreeStorageTest extends KernelTestBase {
$this->fail('Exception was not thrown');
}
catch (PluginException $e) {
$this->pass($e->getMessage());
// Expected exception; just continue testing.
}
// The opposite move should work, and change the has_children flag.
$this->moveMenuLink('footerA', 'test1');
@@ -354,7 +354,6 @@ class MenuTreeStorageTest extends KernelTestBase {
}
catch (\InvalidArgumentException $e) {
$this->assertRegExp('/^An invalid property name, .+ was specified. Allowed property names are:/', $e->getMessage(), 'Found expected exception message.');
$this->pass($message);
}
}
$this->addMenuLink('test_link.1', '', 'test', [], 'menu1');
@@ -31,11 +31,8 @@ class FactoryTest extends PluginTestBase {
$this->testPluginManager->createInstance('non_existing');
$this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected');
}
catch (ExceptionInterface $e) {
$this->pass('Drupal\Component\Plugin\Exception\ExceptionInterface expected and caught.');
}
catch (\Exception $e) {
$this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected, but ' . get_class($e) . ' was thrown.');
$this->assertInstanceOf(ExceptionInterface::class, $e);
}
}
@@ -68,11 +65,8 @@ class FactoryTest extends PluginTestBase {
$this->mockBlockManager->createInstance($invalid_id);
$this->fail('Drupal\Component\Plugin\Exception\ExceptionInterface expected');
}
catch (ExceptionInterface $e) {
$this->pass('Drupal\Component\Plugin\Exception\ExceptionInterface expected and caught.');
}
catch (\Exception $e) {
$this->fail('An unexpected Exception of type "' . get_class($e) . '" was thrown with message ' . $e->getMessage());
$this->assertInstanceOf(ExceptionInterface::class, $e);
}
}
}
@@ -68,13 +68,8 @@ class RenderTest extends KernelTestBase {
$build['#attached']['library'][] = 'core/drupal.states';
$build['#attached']['drupal_process_states'][] = [];
$renderer = $this->container->get('bare_html_page_renderer');
try {
$renderer->renderBarePage($build, '', 'maintenance_page');
$this->fail("Invalid #attachment 'drupal_process_states' allowed");
}
catch (\LogicException $e) {
$this->pass("Invalid #attachment 'drupal_process_states' not allowed");
}
$this->expectException(\LogicException::class);
$renderer->renderBarePage($build, '', 'maintenance_page');
}
/**
@@ -136,17 +136,13 @@ class ContentNegotiationRoutingTest extends KernelTestBase {
$path = $test[0];
$accept_header = $test[1];
$content_type = $test[2];
$message = "Testing path:$path Accept:$accept_header Content-type:$content_type";
$request = Request::create('/' . $path);
$request->headers->set('Accept', $accept_header);
/** @var \Symfony\Component\HttpKernel\HttpKernelInterface $kernel */
$kernel = \Drupal::getContainer()->get('http_kernel');
$response = $kernel->handle($request);
// Verbose message since simpletest doesn't let us provide a message and
// see the error.
$this->pass($message);
$this->assertEqual($response->getStatusCode(), Response::HTTP_OK);
$this->assertEqual($response->getStatusCode(), Response::HTTP_OK, "Testing path:$path Accept:$accept_header Content-type:$content_type");
}
}
@@ -95,16 +95,8 @@ class MatcherDumperTest extends KernelTestBase {
$dumper_routes = $dumper->getRoutes()->all();
$collection_routes = $collection->all();
$success = TRUE;
foreach ($collection_routes as $name => $route) {
if (empty($dumper_routes[$name])) {
$success = FALSE;
$this->fail('Not all routes found in the dumper.');
}
}
if ($success) {
$this->pass('All routes found in the dumper.');
$this->assertNotEmpty($dumper_routes[$name], "Route $name should be present in the dumper.");
}
}
@@ -50,18 +50,9 @@ class AccountSwitcherTest extends KernelTestBase {
// Verify that AccountSwitcherInterface::switchBack() will throw
// an exception if there are no accounts left in the stack.
try {
$switcher->switchBack();
$this->fail('::switchBack() throws exception if called without previous switch.');
}
catch (\RuntimeException $e) {
if ($e->getMessage() == 'No more accounts to revert to.') {
$this->pass('::switchBack() throws exception if called without previous switch.');
}
else {
$this->fail($e->getMessage());
}
}
$this->expectException(\RuntimeException::class);
$this->expectExceptionMessage('No more accounts to revert to.');
$switcher->switchBack();
}
}
@@ -115,8 +115,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->install([$name]);
$this->fail($message);
}
catch (UnknownExtensionException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(UnknownExtensionException::class, $e);
}
$themes = $this->themeHandler()->listInfo();
@@ -134,8 +134,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->install([$name]);
$this->fail($message);
}
catch (ExtensionNameLengthException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(ExtensionNameLengthException::class, $e);
}
}
@@ -230,8 +230,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->uninstall([$name]);
$this->fail($message);
}
catch (\InvalidArgumentException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(\InvalidArgumentException::class, $e);
}
$themes = $this->themeHandler()->listInfo();
@@ -257,8 +257,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->uninstall([$name]);
$this->fail($message);
}
catch (\InvalidArgumentException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(\InvalidArgumentException::class, $e);
}
$themes = $this->themeHandler()->listInfo();
@@ -295,8 +295,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->uninstall([$name]);
$this->fail($message);
}
catch (\InvalidArgumentException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(\InvalidArgumentException::class, $e);
}
$themes = $this->themeHandler()->listInfo();
@@ -325,8 +325,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->uninstall([$name]);
$this->fail($message);
}
catch (UnknownExtensionException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(UnknownExtensionException::class, $e);
}
$themes = $this->themeHandler()->listInfo();
@@ -367,8 +367,8 @@ class ThemeInstallerTest extends KernelTestBase {
$this->themeInstaller()->uninstall([$name]);
$this->fail($message);
}
catch (UnknownExtensionException $e) {
$this->pass(get_class($e) . ': ' . $e->getMessage());
catch (\Exception $e) {
$this->assertInstanceOf(UnknownExtensionException::class, $e);
}
}
@@ -428,7 +428,7 @@ class TypedDataTest extends KernelTestBase {
$this->fail('No exception has been thrown when setting an invalid value.');
}
catch (\Exception $e) {
$this->pass('Exception thrown:' . $e->getMessage());
// Expected exception; just continue testing.
}
}
@@ -550,7 +550,7 @@ class TypedDataTest extends KernelTestBase {
$this->fail('No exception has been thrown when getting an invalid value.');
}
catch (\Exception $e) {
$this->pass('Exception thrown:' . $e->getMessage());
// Expected exception; just continue testing.
}
// Test setting invalid values.
@@ -559,7 +559,7 @@ class TypedDataTest extends KernelTestBase {
$this->fail('No exception has been thrown when setting an invalid value.');
}
catch (\Exception $e) {
$this->pass('Exception thrown:' . $e->getMessage());
// Expected exception; just continue testing.
}
// Test adding a new property to the map.
@@ -2,7 +2,8 @@ module.exports = {
'@tags': ['core'],
before(browser) {
browser.drupalInstall({
setupFile: 'core/tests/Drupal/TestSite/TestSiteInstallTestScript.php',
setupFile:
'core/tests/Drupal/TestSite/TestSiteMultilingualInstallTestScript.php',
langcode: 'fr',
});
},
@@ -1216,7 +1216,7 @@ DOCBLOCK;
$this->assertInstanceOf(Null::class, $result[0]);
}
public function testSetValuesExeption()
public function testSetValuesException()
{
$this->expectException('\Doctrine\Common\Annotations\AnnotationException');
$this->expectExceptionMessage('[Creation Error] The annotation @SomeAnnotationClassNameWithoutConstructor declared on some class does not have a property named "invalidaProperty". Available properties: data, name');
@@ -112,6 +112,23 @@ class DateTimePlusTest extends TestCase {
);
}
/**
* Tests DateTimePlus::checkArray().
*
* @param mixed $array
* Input argument for DateTimePlus::checkArray().
* @param bool $expected
* The expected result of DateTimePlus::checkArray().
*
* @dataProvider providerTestCheckArray
*/
public function testCheckArray(array $array, $expected) {
$this->assertSame(
$expected,
DateTimePlus::checkArray($array)
);
}
/**
* Test creating dates from timestamps, and manipulating timezones.
*
@@ -442,6 +459,30 @@ class DateTimePlusTest extends TestCase {
];
}
/**
* Data provider for testCheckArray.
*
* @return array
* An array of arrays, each containing:
* - 'array' - Input for DateTimePlus::checkArray().
* - 'expected' - Expected output for DateTimePlus::checkArray().
*
* @see testCheckArray
*/
public function providerTestCheckArray() {
return [
'Date array, date only' => [['year' => 2010, 'month' => 2, 'day' => 28], TRUE],
'Date array with hour' => [['year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10], TRUE],
'One year larger than the documented upper limit of checkdate()' => [['year' => 32768, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], FALSE],
'One year smaller than the documented lower limit of checkdate()' => [['year' => 0, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], FALSE],
'Invalid month from date array' => [['year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], FALSE],
'Invalid hour from date array' => [['year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0], FALSE],
'Invalid minute from date array.' => [['year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0], FALSE],
'Missing day' => [['year' => 2059, 'month' => 1, 'second' => 1], FALSE],
'Zero day' => [['year' => 2059, 'month' => 1, 'day' => 0], FALSE],
];
}
/**
* Provides data for testDateTimezone.
*
@@ -254,7 +254,7 @@ class ContainerTest extends TestCase {
* @covers ::getAlternatives
* @covers ::getServiceAlternatives
*/
public function testGetForNonExistantService() {
public function testGetForNonExistentService() {
$this->expectException(ServiceNotFoundException::class);
$this->container->get('service_not_exists');
}
@@ -286,7 +286,7 @@ class ContainerTest extends TestCase {
* @covers ::createService
* @covers ::resolveServicesAndParameters
*/
public function testGetForNonExistantParameterDependency() {
public function testGetForNonExistentParameterDependency() {
$service = $this->container->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$this->assertNull($service, 'Service is NULL.');
}
@@ -315,7 +315,7 @@ class ContainerTest extends TestCase {
* @covers ::createService
* @covers ::resolveServicesAndParameters
*/
public function testGetForNonExistantParameterDependencyWithException() {
public function testGetForNonExistentParameterDependencyWithException() {
$this->expectException(InvalidArgumentException::class);
$this->container->get('service_parameter_not_exists');
}
@@ -327,7 +327,7 @@ class ContainerTest extends TestCase {
* @covers ::createService
* @covers ::resolveServicesAndParameters
*/
public function testGetForNonExistantServiceDependency() {
public function testGetForNonExistentServiceDependency() {
$service = $this->container->get('service_dependency_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$this->assertNull($service, 'Service is NULL.');
}
@@ -340,7 +340,7 @@ class ContainerTest extends TestCase {
* @covers ::resolveServicesAndParameters
* @covers ::getAlternatives
*/
public function testGetForNonExistantServiceDependencyWithException() {
public function testGetForNonExistentServiceDependencyWithException() {
$this->expectException(ServiceNotFoundException::class);
$this->container->get('service_dependency_not_exists');
}
@@ -351,7 +351,7 @@ class ContainerTest extends TestCase {
* @covers ::get
* @covers ::createService
*/
public function testGetForNonExistantServiceWhenUsingNull() {
public function testGetForNonExistentServiceWhenUsingNull() {
$this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception.');
}
@@ -360,7 +360,7 @@ class ContainerTest extends TestCase {
* @covers ::get
* @covers ::createService
*/
public function testGetForNonExistantNULLService() {
public function testGetForNonExistentNULLService() {
$this->expectException(ServiceNotFoundException::class);
$this->container->get(NULL);
}
@@ -371,7 +371,7 @@ class ContainerTest extends TestCase {
* @covers ::get
* @covers ::createService
*/
public function testGetForNonExistantServiceMultipleTimes() {
public function testGetForNonExistentServiceMultipleTimes() {
$container = new $this->containerClass();
$this->assertNull($container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does not throw exception.');
@@ -385,7 +385,7 @@ class ContainerTest extends TestCase {
* @covers ::createService
* @covers ::getAlternatives
*/
public function testGetForNonExistantServiceWithExceptionOnSecondCall() {
public function testGetForNonExistentServiceWithExceptionOnSecondCall() {
$this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.');
$this->expectException(ServiceNotFoundException::class);
$this->container->get('service_not_exists');
@@ -62,7 +62,7 @@ class StaticDiscoveryDecoratorTest extends TestCase {
// Mock our StaticDiscoveryDecorator.
$mock_decorator = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator')
->disableOriginalConstructor()
->setMethods(['registeredDefintionCallback'])
->setMethods(['registeredDefinitionCallback'])
->getMock();
// Set up the ::$registerDefinitions property.
@@ -132,7 +132,7 @@ class StaticDiscoveryDecoratorTest extends TestCase {
// Mock our StaticDiscoveryDecorator.
$mock_decorator = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator')
->disableOriginalConstructor()
->setMethods(['registeredDefintionCallback'])
->setMethods(['registeredDefinitionCallback'])
->getMock();
// Set up the ::$registerDefinitions property.
@@ -21,9 +21,9 @@ class HtmlEscapedTextTest extends TestCase {
* @dataProvider providerToString
*/
public function testToString($text, $expected, $message) {
$escapeable_string = new HtmlEscapedText($text);
$this->assertEquals($expected, (string) $escapeable_string, $message);
$this->assertEquals($expected, $escapeable_string->jsonSerialize());
$escapable_string = new HtmlEscapedText($text);
$this->assertEquals($expected, (string) $escapable_string, $message);
$this->assertEquals($expected, $escapable_string->jsonSerialize());
}
/**
@@ -57,8 +57,8 @@ class HtmlEscapedTextTest extends TestCase {
*/
public function testCount() {
$string = 'Can I please have a <em>kitten</em>';
$escapeable_string = new HtmlEscapedText($string);
$this->assertEquals(strlen($string), $escapeable_string->count());
$escapable_string = new HtmlEscapedText($string);
$this->assertEquals(strlen($string), $escapable_string->count());
}
}
@@ -58,8 +58,8 @@ class PhpTransliterationTest extends TestCase {
// Test all characters in the Unicode range 0x01CD to 0x024F.
['ǍǎǏ', 'AaI'],
['ǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟ', 'iOoUuUuUuUuUuǝAa'],
['ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ', 'AaǢǣGgGgKkOoOoǮǯ'],
['ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ', 'jDZDzdzGgǶǷNnAaǼǽOo'],
['ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ', 'AaÆæGgGgKkOoOoƷʒ'],
['ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ', 'jDZDzdzGgǶǷNnAaÆæOo'],
['ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏ', 'AaAaEeEeIiIiOoOo'],
['ȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟ', 'RrRrUuUuSsTtȜȝHh'],
['ȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯ', 'ȠȡȢȣZzAaEeOoOoOo'],
@@ -56,6 +56,9 @@ class BytesTest extends TestCase {
['76MRandomStringThatShouldBeIgnoredByParseSize.', 79691776],
// 76.24 GB (with typo).
['76.24 Giggabyte', 81862076662],
['1.5', 2],
['2.4', 2],
['', 0],
];
}
@@ -23,15 +23,13 @@ class UnicodeTest extends TestCase {
}
/**
* Tests multibyte encoding and decoding.
* Tests multibyte encoding.
*
* @dataProvider providerTestMimeHeader
* @covers ::mimeHeaderEncode
* @covers ::mimeHeaderDecode
*/
public function testMimeHeader($value, $encoded) {
public function testMimeHeaderEncode($value, $encoded) {
$this->assertEquals($encoded, Unicode::mimeHeaderEncode($value));
$this->assertEquals($value, Unicode::mimeHeaderDecode($encoded));
}
/**
@@ -44,9 +42,49 @@ class UnicodeTest extends TestCase {
*/
public function providerTestMimeHeader() {
return [
['tést.txt', '=?UTF-8?B?dMOpc3QudHh0?='],
// Simple ASCII characters.
['ASCII', 'ASCII'],
"Base64 encoding" => ['tést.txt', '=?UTF-8?B?dMOpc3QudHh0?='],
"ASCII characters only" => ['test.txt', 'test.txt'],
];
}
/**
* Tests multibyte decoding.
*
* @dataProvider providerTestMimeHeaderDecode
* @covers ::mimeHeaderDecode
*/
public function testMimeHeaderDecode($value, $encoded) {
$this->assertEquals($value, Unicode::mimeHeaderDecode($encoded));
}
/**
* Data provider for testMimeHeaderDecode().
*
* @return array
* An array containing a string and its encoded value.
*/
public function providerTestMimeHeaderDecode() {
return [
'Uppercase base64 encoding' => [
'tést.txt',
'=?utf-8?B?dMOpc3QudHh0?=',
],
'Uppercase quoted-printable encoding' => [
'tést.txt',
'=?UTF-8?Q?t=C3=A9st.txt?=',
],
'Lowercase base64 encoding' => [
'tést.txt',
'=?utf-8?b?dMOpc3QudHh0?=',
],
'Lowercase quoted-printable encoding' => [
'tést.txt',
'=?UTF-8?q?t=C3=A9st.txt?=',
],
'ASCII characters only' => [
'test.txt',
'test.txt',
],
];
}
@@ -192,7 +192,6 @@ class ScaffoldTest extends TestCase {
*/
public function testProjectThatScaffoldsEmptyProject() {
$fixture_name = 'project-allowing-empty-fixture';
$is_link = FALSE;
$result = $this->scaffoldSut($fixture_name, FALSE, FALSE);
$this->assertStringContainsString('The allowed package fixtures/empty-fixture does not provide a file mapping for Composer Scaffold', $result->scaffoldOutput());
$this->assertCommonDrupalAssetsWereScaffolded($result->docroot(), FALSE);
@@ -6,13 +6,13 @@ use Composer\Composer;
use Composer\IO\IOInterface;
use Composer\Package\PackageInterface;
use Composer\Package\RootPackageInterface;
use Drupal\Composer\VendorHardening\Config;
use Drupal\Composer\Plugin\VendorHardening\Config;
use Drupal\Composer\Plugin\VendorHardening\VendorHardeningPlugin;
use org\bovigo\vfs\vfsStream;
use PHPUnit\Framework\TestCase;
/**
* @coversDefaultClass Drupal\Composer\Plugin\VendorHardening\VendorHardeningPlugin
* @coversDefaultClass \Drupal\Composer\Plugin\VendorHardening\VendorHardeningPlugin
* @group VendorHardening
*/
class VendorHardeningPluginTest extends TestCase {
@@ -36,7 +36,6 @@ class VendorHardeningPluginTest extends TestCase {
public function testCleanPackage() {
$config = $this->getMockBuilder(Config::class)
->setMethods(['getPathsForPackage'])
->disableOriginalConstructor()
->getMock();
$config->expects($this->once())
@@ -85,7 +84,6 @@ class VendorHardeningPluginTest extends TestCase {
*/
public function testCleanAllPackages() {
$config = $this->getMockBuilder(Config::class)
->setMethods(['getAllCleanupPaths'])
->disableOriginalConstructor()
->getMock();
$config->expects($this->once())
@@ -93,7 +91,6 @@ class VendorHardeningPluginTest extends TestCase {
->willReturn(['drupal/package' => ['tests']]);
$package = $this->getMockBuilder(PackageInterface::class)
->setMethods(['getName'])
->getMockForAbstractClass();
$package->expects($this->any())
->method('getName')
@@ -374,7 +374,6 @@ class AccessManagerTest extends UnitTestCase {
->with('test_route_1')
->will($this->returnValue($route));
$map = [];
$map[] = ['test_route_1', ['value' => 'example'], '/test-route-1/example'];
$this->paramConverter = $this->createMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
@@ -423,7 +422,6 @@ class AccessManagerTest extends UnitTestCase {
->with('test_route_1')
->will($this->returnValue($route));
$map = [];
$map[] = ['test_route_1', ['value' => 'example'], '/test-route-1/example'];
$this->paramConverter = $this->createMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
@@ -644,6 +644,24 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$this->assertEquals('libraries/third_party_library/css/example.css', $library['css'][0]['data']);
}
/**
* @covers ::parseLibraryInfo
*/
public function testEmptyLibraryFile() {
$this->moduleHandler->expects($this->atLeastOnce())
->method('moduleExists')
->with('empty')
->will($this->returnValue(TRUE));
$path = __DIR__ . '/library_test_files';
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'empty', $path);
$libraries = $this->libraryDiscoveryParser->buildByExtension('empty');
$this->assertEquals([], $libraries);
}
}
/**
@@ -0,0 +1 @@
# This file intentionally left empty
@@ -36,8 +36,8 @@ class EntityTypeTest extends UnitTestCase {
*
* @dataProvider providerTestGet
*/
public function testGet(array $defintion, $key, $expected) {
$entity_type = $this->setUpEntityType($defintion);
public function testGet(array $definition, $key, $expected) {
$entity_type = $this->setUpEntityType($definition);
$this->assertSame($expected, $entity_type->get($key));
}
@@ -54,7 +54,6 @@ class FormAjaxResponseBuilderTest extends UnitTestCase {
$form_state = new FormState();
$commands = [];
$expected = [];
$this->expectException(HttpException::class);
$this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
}
@@ -73,7 +72,6 @@ class FormAjaxResponseBuilderTest extends UnitTestCase {
$form_state->setTriggeringElement($triggering_element);
$commands = [];
$expected = [];
$this->expectException(HttpException::class);
$this->formAjaxResponseBuilder->buildResponse($request, $form, $form_state, $commands);
}
@@ -53,17 +53,6 @@ class PathProcessorTest extends UnitTestCase {
],
];
// Create a URL-based language negotiation method definition.
$method_definitions = [
LanguageNegotiationUrl::METHOD_ID => [
'class' => '\Drupal\language\Plugin\LanguageNegotiation\LanguageNegotiationUrl',
'weight' => 9,
],
];
// Create a URL-based language negotiation method.
$method_instance = new LanguageNegotiationUrl($config);
// Create a language manager stub.
$language_manager = $this->getMockBuilder('Drupal\language\ConfigurableLanguageManagerInterface')
->getMock();
@@ -77,7 +66,6 @@ class PathProcessorTest extends UnitTestCase {
->method('getLanguageTypes')
->will($this->returnValue([LanguageInterface::TYPE_INTERFACE]));
$method_instance->setLanguageManager($language_manager);
$this->languageManager = $language_manager;
}
@@ -100,7 +100,7 @@ class HookDiscoveryTest extends UnitTestCase {
]
));
$this->assertNull($this->hookDiscovery->getDefinition('test_non_existant', FALSE));
$this->assertNull($this->hookDiscovery->getDefinition('test_non_existent', FALSE));
$plugin_definition = $this->hookDiscovery->getDefinition('test_id_1');
$this->assertEquals($plugin_definition['class'], 'Drupal\plugin_test\Plugin\plugin_test\fruit\Apple');
@@ -126,7 +126,7 @@ class HookDiscoveryTest extends UnitTestCase {
->will($this->returnValue([]));
$this->expectException(PluginNotFoundException::class);
$this->hookDiscovery->getDefinition('test_non_existant', TRUE);
$this->hookDiscovery->getDefinition('test_non_existent', TRUE);
}
protected function hookDiscoveryTestTestPlugin() {
@@ -42,7 +42,7 @@ class PluginWithFormsTraitTest extends UnitTestCase {
return [
'block plugin without forms, "configure" operation' => [$block_plugin_without_forms, 'configure', TestClass::class],
'block plugin without forms, "tickle" operation' => [$block_plugin_without_forms, 'tickle', NULL],
'block plugin withut forms, "poke" operation' => [$block_plugin_without_forms, 'poke', NULL],
'block plugin without forms, "poke" operation' => [$block_plugin_without_forms, 'poke', NULL],
'block plugin with forms, "configure" operation' => [$block_plugin_with_forms, 'configure', TestClass::class],
'block plugin with forms, "tickle" operation' => [$block_plugin_with_forms, 'tickle', NULL],
'block plugin with forms, "poke" operation' => [$block_plugin_with_forms, 'poke', static::class],
@@ -35,9 +35,9 @@ class RequestFormatRouteFilterTest extends UnitTestCase {
public function filterProvider() {
$route_without_format = new Route('/test');
$route_with_format = $route = new Route('/test');
$route_with_format = new Route('/test');
$route_with_format->setRequirement('_format', 'json');
$route_with_multiple_formats = $route = new Route('/test');
$route_with_multiple_formats = new Route('/test');
$route_with_multiple_formats->setRequirement('_format', 'json|xml');
$collection = new RouteCollection();
@@ -71,7 +71,7 @@ class RequestFormatRouteFilterTest extends UnitTestCase {
\Drupal::setContainer($container);
$collection = new RouteCollection();
$route_with_format = $route = new Route('/test');
$route_with_format = new Route('/test');
$route_with_format->setRequirement('_format', 'json');
$collection->add('test_0', $route_with_format);
$collection->add('test_1', clone $route_with_format);
@@ -102,7 +102,7 @@ class RequestFormatRouteFilterTest extends UnitTestCase {
\Drupal::setContainer($container);
$collection = new RouteCollection();
$route_with_format = $route = new Route('/test');
$route_with_format = new Route('/test');
$route_with_format->setRequirement('_format', 'json|xml');
$collection->add('sole_route_multiple_formats', $route_with_format);
@@ -57,7 +57,7 @@ class PhpUnitTestRunnerTest extends UnitTestCase {
'test_id' => $test_id,
'test_class' => 'SomeTest',
'status' => TestStatus::label(TestStatus::EXCEPTION),
'message' => 'PHPunit Test failed to complete; Error: ',
'message' => 'PHPUnit Test failed to complete; Error: ',
'message_group' => 'Other',
'function' => 'SomeTest',
'line' => '0',