Update to Drupal 8.1.1. For more information, see https://www.drupal.org/node/2718713

This commit is contained in:
Pantheon Automation 2016-05-04 14:35:41 -07:00 committed by Greg Anderson
parent c0a0d5a94c
commit 9eae24d844
669 changed files with 3873 additions and 1553 deletions

View file

@ -41,6 +41,9 @@ abstract class JavascriptTestBase extends BrowserTestBase {
* The CSS selector identifying the element to check.
* @param string $message
* Optional message to show alongside the assertion.
*
* @deprecated in Drupal 8.1.x, will be removed before Drupal 8.3.x. Use
* \Behat\Mink\Element\NodeElement::isVisible() instead.
*/
protected function assertElementVisible($css_selector, $message = '') {
$this->assertTrue($this->getSession()->getDriver()->isVisible(CssSelector::toXPath($css_selector)), $message);
@ -53,6 +56,9 @@ abstract class JavascriptTestBase extends BrowserTestBase {
* The CSS selector identifying the element to check.
* @param string $message
* Optional message to show alongside the assertion.
*
* @deprecated in Drupal 8.1.x, will be removed before Drupal 8.3.x. Use
* \Behat\Mink\Element\NodeElement::isVisible() instead.
*/
protected function assertElementNotVisible($css_selector, $message = '') {
$this->assertFalse($this->getSession()->getDriver()->isVisible(CssSelector::toXPath($css_selector)), $message);

View file

@ -0,0 +1,57 @@
<?php
namespace Drupal\FunctionalTests\Breadcrumb;
use Drupal\simpletest\BlockCreationTrait;
use Drupal\Tests\BrowserTestBase;
/**
* Tests the breadcrumb of 404 pages.
*
* @group breadcrumb
*/
class Breadcrumb404Test extends BrowserTestBase {
use BlockCreationTrait;
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'block'];
/**
* Tests that different 404s don't create unnecessary cache entries.
*/
public function testBreadcrumbOn404Pages() {
$this->placeBlock('system_breadcrumb_block', ['id' => 'breadcrumb']);
// Prime the cache first.
$this->drupalGet('/not-found-1');
$base_count = count($this->getBreadcrumbCacheEntries());
$this->drupalGet('/not-found-2');
$next_count = count($this->getBreadcrumbCacheEntries());
$this->assertEquals($base_count, $next_count);
$this->drupalGet('/not-found-3');
$next_count = count($this->getBreadcrumbCacheEntries());
$this->assertEquals($base_count, $next_count);
}
/**
* Gets the breadcrumb cache entries.
*
* @return array
* The breadcrumb cache entries.
*/
protected function getBreadcrumbCacheEntries() {
$database = \Drupal::database();
$cache_entries = $database->select('cache_render')
->fields('cache_render')
->condition('cid', $database->escapeLike('entity_view:block:breadcrumb') . '%', 'LIKE')
->execute()
->fetchAllAssoc('cid');
return $cache_entries;
}
}

View file

@ -112,4 +112,3 @@ class DefaultConfigTest extends KernelTestBase {
}
}

View file

@ -686,4 +686,98 @@ class ConfigImporterTest extends KernelTestBase {
}
}
/**
* Tests the isSyncing flags.
*/
public function testIsSyncingInHooks() {
$dynamic_name = 'config_test.dynamic.dotted.default';
$storage = $this->container->get('config.storage');
// Verify the default configuration values exist.
$config = $this->config($dynamic_name);
$this->assertSame('dotted.default', $config->get('id'));
// Delete the config so that create hooks will fire.
$storage->delete($dynamic_name);
\Drupal::state()->set('config_test.store_isSyncing', []);
$this->configImporter->reset()->import();
// The values of the syncing values should be stored in state by
// config_test_config_test_create().
$state = \Drupal::state()->get('config_test.store_isSyncing');
$this->assertTrue($state['global_state::create'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::create'], 'ConfigEntity::isSyncing() returns TRUE');
$this->assertTrue($state['global_state::presave'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::presave'], 'ConfigEntity::isSyncing() returns TRUE');
$this->assertTrue($state['global_state::insert'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::insert'], 'ConfigEntity::isSyncing() returns TRUE');
// Cause a config update so update hooks will fire.
$config = $this->config($dynamic_name);
$config->set('label', 'A new name')->save();
\Drupal::state()->set('config_test.store_isSyncing', []);
$this->configImporter->reset()->import();
// The values of the syncing values should be stored in state by
// config_test_config_test_create().
$state = \Drupal::state()->get('config_test.store_isSyncing');
$this->assertTrue($state['global_state::presave'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::presave'], 'ConfigEntity::isSyncing() returns TRUE');
$this->assertTrue($state['global_state::update'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::update'], 'ConfigEntity::isSyncing() returns TRUE');
// Cause a config delete so delete hooks will fire.
$sync = $this->container->get('config.storage.sync');
$sync->delete($dynamic_name);
\Drupal::state()->set('config_test.store_isSyncing', []);
$this->configImporter->reset()->import();
// The values of the syncing values should be stored in state by
// config_test_config_test_create().
$state = \Drupal::state()->get('config_test.store_isSyncing');
$this->assertTrue($state['global_state::predelete'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::predelete'], 'ConfigEntity::isSyncing() returns TRUE');
$this->assertTrue($state['global_state::delete'], '\Drupal::isConfigSyncing() returns TRUE');
$this->assertTrue($state['entity_state::delete'], 'ConfigEntity::isSyncing() returns TRUE');
}
/**
* Tests that the isConfigSyncing flag is cleanup after an invalid step.
*/
public function testInvalidStep() {
$this->assertFalse(\Drupal::isConfigSyncing(), 'Before an import \Drupal::isConfigSyncing() returns FALSE');
$context = [];
try {
$this->configImporter->doSyncStep('a_non_existent_step', $context);
$this->fail('Expected \InvalidArgumentException thrown');
}
catch (\InvalidArgumentException $e) {
$this->pass('Expected \InvalidArgumentException thrown');
}
$this->assertFalse(\Drupal::isConfigSyncing(), 'After an invalid step \Drupal::isConfigSyncing() returns FALSE');
}
/**
* Tests that the isConfigSyncing flag is set correctly during a custom step.
*/
public function testCustomStep() {
$this->assertFalse(\Drupal::isConfigSyncing(), 'Before an import \Drupal::isConfigSyncing() returns FALSE');
$context = [];
$this->configImporter->doSyncStep([self::class, 'customStep'], $context);
$this->assertTrue($context['is_syncing'], 'Inside a custom step \Drupal::isConfigSyncing() returns TRUE');
$this->assertFalse(\Drupal::isConfigSyncing(), 'After an valid custom step \Drupal::isConfigSyncing() returns FALSE');
}
/**
* Helper meothd to test custom config installer steps.
*
* @param array $context
* Batch context.
* @param \Drupal\Core\Config\ConfigImporter $importer
* The config importer.
*/
public static function customStep(array &$context, ConfigImporter $importer) {
$context['is_syncing'] = \Drupal::isConfigSyncing();
}
}

View file

@ -117,4 +117,3 @@ class ConfigLanguageOverrideTest extends KernelTestBase {
$this->assertEqual($override->get('value'), NULL);
}
}

View file

@ -23,7 +23,7 @@ class ConfigOverridesPriorityTest extends KernelTestBase {
public function testOverridePriorities() {
$GLOBALS['config_test_run_module_overrides'] = FALSE;
$non_overridden_mail = 'site@example.com';
$non_overridden_mail = 'site@example.com';
$language_overridden_mail = 'french@example.com';
$language_overridden_name = 'French site name';

View file

@ -95,7 +95,7 @@ class ConfigSchemaTest extends KernelTestBase {
$expected['label'] = 'Maintenance mode';
$expected['class'] = '\Drupal\Core\Config\Schema\Mapping';
$expected['mapping']['message'] = array(
'label' => 'Message to display when in maintenance mode',
'label' => 'Message to display when in maintenance mode',
'type' => 'text',
);
$expected['mapping']['langcode'] = array(
@ -119,7 +119,7 @@ class ConfigSchemaTest extends KernelTestBase {
);
$expected['mapping']['_core']['type'] = '_core_config_info';
$expected['mapping']['label'] = array(
'label' => 'Label',
'label' => 'Label',
'type' => 'label',
);
$expected['mapping']['irrelevant'] = array(
@ -204,7 +204,7 @@ class ConfigSchemaTest extends KernelTestBase {
$effects = \Drupal::service('config.typed')->get('image.style.medium')->get('effects');
$definition = $effects->get('bddf0d06-42f9-4c75-a700-a33cafa25ea0')->get('data')->getDataDefinition()->toArray();
// This should be the schema for image.effect.image_scale, reuse previous one.
$expected['type'] = 'image.effect.image_scale';
$expected['type'] = 'image.effect.image_scale';
$this->assertEqual($definition, $expected, 'Retrieved the right metadata for the first effect of image.style.medium');

View file

@ -103,7 +103,7 @@ class AlterTest extends DatabaseTestBase {
$record = $result->fetch();
$this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
$this->assertEqual($record->$age_field, 27*3, 'Fetched age expression is correct.');
$this->assertEqual($record->$age_field, 27 * 3, 'Fetched age expression is correct.');
}
/**
@ -145,6 +145,6 @@ class AlterTest extends DatabaseTestBase {
$record = $query->execute()->fetch();
$this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
$this->assertEqual($record->$age_field, 27*3, 'Fetched age expression is correct.');
$this->assertEqual($record->$age_field, 27 * 3, 'Fetched age expression is correct.');
}
}

View file

@ -427,7 +427,7 @@ class SchemaTest extends KernelTestBase {
// Now set up columns for the other types.
$types = array('int', 'float', 'numeric');
foreach ($types as $type) {
$column_spec = array('type' => $type, 'unsigned'=> TRUE);
$column_spec = array('type' => $type, 'unsigned' => TRUE);
if ($type == 'numeric') {
$column_spec += array('precision' => 10, 'scale' => 0);
}

View file

@ -133,7 +133,7 @@ class SelectTest extends DatabaseTestBase {
// Ensure that we got the right record.
$record = $result->fetch();
$this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
$this->assertEqual($record->$age_field, 27*2, 'Fetched age expression is correct.');
$this->assertEqual($record->$age_field, 27 * 2, 'Fetched age expression is correct.');
}
/**
@ -154,8 +154,8 @@ class SelectTest extends DatabaseTestBase {
// Ensure that we got the right record.
$record = $result->fetch();
$this->assertEqual($record->$name_field, 'George', 'Fetched name is correct.');
$this->assertEqual($record->$age_double_field, 27*2, 'Fetched double age expression is correct.');
$this->assertEqual($record->$age_triple_field, 27*3, 'Fetched triple age expression is correct.');
$this->assertEqual($record->$age_double_field, 27 * 2, 'Fetched double age expression is correct.');
$this->assertEqual($record->$age_triple_field, 27 * 3, 'Fetched triple age expression is correct.');
}
/**

View file

@ -137,7 +137,7 @@ class UpdateTest extends DatabaseTestBase {
->execute();
$this->assertIdentical($num_updated, 1, 'Updated 1 record.');
$saved_name= db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 42))->fetchField();
$saved_name = db_query('SELECT name FROM {test} WHERE id = :id', array(':id' => 42))->fetchField();
$this->assertIdentical($saved_name, 'John', 'Updated primary key successfully.');
}

View file

@ -0,0 +1,177 @@
<?php
namespace Drupal\KernelTests\Core\Entity;
use Drupal\entity_test\Entity\EntityTestMulRev;
use Drupal\entity_test\Entity\EntityTestRev;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Tests non-revisionable fields on revisionable (and translatable) entities.
*
* @group Entity
*/
class ContentEntityNonRevisionableFieldTest extends EntityKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['language'];
/**
* The EntityTestMulRev entity type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $mulRev;
/**
* The EntityTestRev entity type storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $rev;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Enable an additional language.
ConfigurableLanguage::createFromLangcode('de')->save();
$this->installEntitySchema('entity_test_mulrev');
$this->installEntitySchema('entity_test_rev');
$this->mulRev = $this->entityManager->getStorage('entity_test_mulrev');
$this->rev = $this->entityManager->getStorage('entity_test_rev');
}
/**
* Tests non-revisionable fields on revisionable and translatable entities.
*/
public function testMulNonRevisionableField() {
$user1 = $this->createUser();
$user2 = $this->createUser();
// Create a test entity.
$entity = EntityTestMulRev::create(array(
'name' => $this->randomString(),
'user_id' => $user1->id(),
'language' => 'en',
'non_rev_field' => 'Huron',
));
$entity->save();
// Create a test entity.
$entity2 = EntityTestMulRev::create(array(
'name' => $this->randomString(),
'user_id' => $user1->id(),
'language' => 'en',
'non_rev_field' => 'Michigan',
));
$entity2->save();
$this->assertEquals('Huron', $entity->get('non_rev_field')->value, 'Huron found on entity 1');
$this->assertEquals('Michigan', $entity2->get('non_rev_field')->value, 'Michigan found on entity 2');
$entity->setNewRevision();
$entity->setOwner($user2);
$entity->save();
$entity2->setNewRevision();
$entity2->setOwner($user2);
$entity2->save();
$this->assertEquals($user2->id(), $entity->getOwner()->id(), 'User 2 found on entity 1');
$this->assertEquals($user2->id(), $entity2->getOwner()->id(), 'User 2 found on entity 2');
$entity->addTranslation('de');
$entity->save();
$entity2->addTranslation('de');
$entity2->save();
$expected_revision_ids = [
4 => 2,
3 => 1,
2 => 2,
1 => 1,
];
$revision_ids = $this->mulRev->getQuery()
->allRevisions()
->sort('revision_id', 'DESC')
->execute();
$this->assertEquals($expected_revision_ids, $revision_ids, 'Revision ids found');
$expected_non_rev_field_revision_ids = [
3 => 1,
1 => 1,
];
$non_rev_field_revision_ids = $this->mulRev->getQuery()
->allRevisions()
->condition('non_rev_field', 'Huron')
->sort('revision_id', 'DESC')
->execute();
$this->assertEquals($expected_non_rev_field_revision_ids, $non_rev_field_revision_ids, 'Revision ids found');
}
/**
* Tests non-revisionable fields on revisionable entities.
*/
public function testNonRevisionableField() {
$user1 = $this->createUser();
$user2 = $this->createUser();
// Create a test entity.
$entity = EntityTestRev::create(array(
'name' => $this->randomString(),
'user_id' => $user1->id(),
'non_rev_field' => 'Superior',
));
$entity->save();
// Create a test entity.
$entity2 = EntityTestRev::create(array(
'name' => $this->randomString(),
'user_id' => $user1->id(),
'non_rev_field' => 'Ontario',
));
$entity2->save();
$this->assertEquals('Superior', $entity->get('non_rev_field')->value, 'Superior found on entity 1');
$this->assertEquals('Ontario', $entity2->get('non_rev_field')->value, 'Ontario found on entity 2');
$entity->setNewRevision();
$entity->setOwner($user2);
$entity->save();
$entity2->setNewRevision();
$entity2->setOwner($user2);
$entity2->save();
$this->assertEquals($user2->id(), $entity->getOwner()->id(), 'User 2 found on entity 1');
$this->assertEquals($user2->id(), $entity2->getOwner()->id(), 'User 2 found on entity 2');
$expected_revision_ids = [
4 => 2,
3 => 1,
2 => 2,
1 => 1,
];
$revision_ids = $this->rev->getQuery()
->allRevisions()
->sort('revision_id', 'DESC')
->execute();
$this->assertEquals($expected_revision_ids, $revision_ids, 'Revision ids found');
$expected_non_rev_field_revision_ids = [
3 => 1,
1 => 1,
];
$non_rev_field_revision_ids = $this->rev->getQuery()
->allRevisions()
->condition('non_rev_field', 'Superior')
->sort('revision_id', 'DESC')
->execute();
$this->assertEquals($expected_non_rev_field_revision_ids, $non_rev_field_revision_ids, 'Revision ids found');
}
}

View file

@ -344,7 +344,7 @@ class EntityDefinitionUpdateTest extends EntityKernelTestBase {
$message = 'The new_bundle_field_shape column is not nullable.';
$values = array(
'bundle' => $entity->bundle(),
'deleted'=> 0,
'deleted' => 0,
'entity_id' => $entity->id(),
'revision_id' => $entity->id(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,

View file

@ -3,12 +3,16 @@
namespace Drupal\KernelTests\Core\Entity;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\TypedData\EntityDataDefinition;
use Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\TypedData\ComplexDataDefinitionInterface;
use Drupal\Core\TypedData\ComplexDataInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\ListInterface;
use Drupal\Core\TypedData\Type\StringInterface;
use Drupal\Core\TypedData\TypedDataInterface;
use Drupal\node\Entity\Node;
@ -420,7 +424,7 @@ class EntityFieldTest extends EntityKernelTestBase {
$this->assertEqual($value_definition->getDataType(), 'string');
// Test deriving metadata from references.
$entity_definition = \Drupal\Core\Entity\TypedData\EntityDataDefinition::create($entity_type);
$entity_definition = EntityDataDefinition::create($entity_type);
$langcode_key = $this->entityManager->getDefinition($entity_type)->getKey('langcode');
$reference_definition = $entity_definition->getPropertyDefinition($langcode_key)
->getPropertyDefinition('language')
@ -431,7 +435,7 @@ class EntityFieldTest extends EntityKernelTestBase {
->getPropertyDefinition('entity')
->getTargetDefinition();
$this->assertTrue($reference_definition instanceof \Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface, 'Definition of the referenced user retrieved.');
$this->assertTrue($reference_definition instanceof EntityDataDefinitionInterface, 'Definition of the referenced user retrieved.');
$this->assertEqual($reference_definition->getEntityTypeId(), 'user', 'Referenced entity is of type "user".');
// Test propagating down.
@ -583,12 +587,12 @@ class EntityFieldTest extends EntityKernelTestBase {
// Recurse until a certain depth is reached if possible.
if ($depth < 7) {
if ($wrapper instanceof \Drupal\Core\TypedData\ListInterface) {
if ($wrapper instanceof ListInterface) {
foreach ($wrapper as $item) {
$this->getContainedStrings($item, $depth + 1, $strings);
}
}
elseif ($wrapper instanceof \Drupal\Core\TypedData\ComplexDataInterface) {
elseif ($wrapper instanceof ComplexDataInterface) {
foreach ($wrapper as $property) {
$this->getContainedStrings($property, $depth + 1, $strings);
}

View file

@ -135,7 +135,7 @@ class EntityQueryAggregateTest extends EntityKernelTestBase {
$function_expected['min'] = array(array('id_min' => 1));
$function_expected['max'] = array(array('id_max' => 6));
$function_expected['sum'] = array(array('id_sum' => 21));
$function_expected['avg'] = array(array('id_avg' => (21.0/6.0)));
$function_expected['avg'] = array(array('id_avg' => (21.0 / 6.0)));
// Apply a simple aggregation for different aggregation functions.
foreach ($function_expected as $aggregation_function => $expected) {

View file

@ -535,7 +535,7 @@ class EntityQueryTest extends EntityKernelTestBase {
protected function assertBundleOrder($order) {
// This loop is for bundle1 entities.
for ($i = 1; $i <= 15; $i +=2) {
for ($i = 1; $i <= 15; $i += 2) {
$ok = TRUE;
$index1 = array_search($i, $this->queryResults);
$this->assertNotIdentical($index1, FALSE, "$i found at $index1.");

View file

@ -4,9 +4,9 @@ namespace Drupal\KernelTests\Core\Entity\EntityReferenceSelection;
use Drupal\Component\Utility\Html;
use Drupal\field\Entity\FieldConfig;
use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
use Drupal\system\Tests\Entity\EntityUnitTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
@ -14,7 +14,7 @@ use Drupal\field\Entity\FieldStorageConfig;
*
* @group entity_reference
*/
class EntityReferenceSelectionSortTest extends EntityUnitTestBase {
class EntityReferenceSelectionSortTest extends EntityKernelTestBase {
/**
* Modules to enable.

View file

@ -158,7 +158,7 @@ class EntityViewBuilderTest extends EntityKernelTestBase {
// Test a view mode in default conditions: render caching is enabled for
// the entity type and the view mode.
$build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
$this->assertTrue(isset($build['#cache']) && array_keys($build['#cache']) == ['tags', 'contexts', 'max-age', 'keys', 'bin'] , 'A view mode with render cache enabled has the correct output (cache tags, keys, contexts, max-age and bin).');
$this->assertTrue(isset($build['#cache']) && array_keys($build['#cache']) == ['tags', 'contexts', 'max-age', 'keys', 'bin'], 'A view mode with render cache enabled has the correct output (cache tags, keys, contexts, max-age and bin).');
// Test that a view mode can opt out of render caching.
$build = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'test');
@ -185,7 +185,7 @@ class EntityViewBuilderTest extends EntityKernelTestBase {
// Create and build a test entity.
$entity_test = $this->createTestEntity('entity_test');
$view = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
$view = $this->container->get('entity.manager')->getViewBuilder('entity_test')->view($entity_test, 'full');
$renderer->renderRoot($view);
// Check that the weight is respected.

View file

@ -16,7 +16,9 @@ class AliasStorageTest extends KernelTestBase {
*/
public static $modules = ['system'];
/** @var \Drupal\Core\Path\AliasStorage */
/**
* @var \Drupal\Core\Path\AliasStorage
*/
protected $storage;
/**

View file

@ -16,10 +16,11 @@ use Drupal\Core\DependencyInjection\ServiceProviderInterface;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
use Drupal\Core\Extension\ExtensionDiscovery;
use Drupal\Core\Language\Language;
use Drupal\Core\Site\Settings;
use Drupal\simpletest\AssertContentTrait;
use Drupal\simpletest\AssertHelperTrait;
use Drupal\simpletest\RandomGeneratorTrait;
use Drupal\Tests\RandomGeneratorTrait;
use Drupal\simpletest\TestServiceProvider;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpFoundation\Request;
@ -136,10 +137,9 @@ abstract class KernelTestBase extends \PHPUnit_Framework_TestCase implements Ser
/**
* Modules to enable.
*
* Test classes extending this class, and any classes in the hierarchy up to
* this class, may specify individual lists of modules to enable by setting
* this property. The values of all properties in all classes in the class
* hierarchy are merged.
* The test runner will merge the $modules lists from this class, the class
* it extends, and so on up the class hierarchy. It is not necessary to
* include modules in your list that a parent class has already declared.
*
* @see \Drupal\Tests\KernelTestBase::enableModules()
* @see \Drupal\Tests\KernelTestBase::bootKernel()
@ -604,6 +604,9 @@ abstract class KernelTestBase extends \PHPUnit_Framework_TestCase implements Ser
$container
->setAlias('keyvalue', 'keyvalue.memory');
// Set the default language on the minimal container.
$container->setParameter('language.default_values', Language::$defaultValues);
if ($this->strictConfigSchema) {
$container
->register('simpletest.config_schema_checker', 'Drupal\Core\Config\Testing\ConfigSchemaChecker')
@ -1205,7 +1208,7 @@ abstract class KernelTestBase extends \PHPUnit_Framework_TestCase implements Ser
/**
* {@inheritdoc}
*/
public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = false, $ignoreCase = false) {
public static function assertEquals($expected, $actual, $message = '', $delta = 0.0, $maxDepth = 10, $canonicalize = FALSE, $ignoreCase = FALSE) {
$expected = static::castSafeStrings($expected);
$actual = static::castSafeStrings($actual);
parent::assertEquals($expected, $actual, $message, $delta, $maxDepth, $canonicalize, $ignoreCase);

View file

@ -0,0 +1,21 @@
<?php
namespace Drupal\simpletest\Tests;
use Drupal\KernelTests\KernelTestBase;
/**
* This test should not load since it requires a module that is not found.
*
* @group simpletest
* @dependencies simpletest_missing_module
*/
class MissingDependentModuleUnitTest extends KernelTestBase {
/**
* Ensure that this test will not be loaded despite its dependency.
*/
function testFail() {
$this->fail('Running test with missing required module.');
}
}

View file

@ -20,9 +20,6 @@ use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\Test\TestRunnerKernel;
use Drupal\Core\Url;
use Drupal\simpletest\RandomGeneratorTrait;
use Drupal\simpletest\SessionTestTrait;
use Drupal\simpletest\WebAssert;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
@ -39,11 +36,6 @@ use Symfony\Component\HttpFoundation\Request;
* @ingroup testing
*/
abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
/**
* @todo Move these into Drupal\Tests namespace and leave deprecated stubs
* in simpletest module. See https://www.drupal.org/node/2702281
*/
use RandomGeneratorTrait;
use SessionTestTrait;
@ -342,7 +334,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
$driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
}
else {
$driver = new $this->minkDefaultDriverClass();
$driver = new $this->minkDefaultDriverClass();
}
return $driver;
}
@ -534,7 +526,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* @param string $name
* (optional) Name of the session. Defaults to the active session.
*
* @return \Drupal\simpletest\WebAssert
* @return \Drupal\Tests\WebAssert
* A new web-assert option for asserting the presence of elements with.
*/
public function assertSession($name = NULL) {

View file

@ -441,7 +441,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*/
public function testGetForInstantiationWithVariousArgumentLengths() {
$args = array();
for ($i=0; $i < 12; $i++) {
for ($i = 0; $i < 12; $i++) {
$instantiation_service = $this->container->get('service_test_instantiation_'. $i);
$this->assertEquals($args, $instantiation_service->getArguments());
$args[] = 'arg_' . $i;
@ -480,7 +480,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*/
public function testGetForFactoryClass() {
$service = $this->container->get('service.provider');
$factory_service= $this->container->get('factory_class');
$factory_service = $this->container->get('factory_class');
$this->assertInstanceOf(get_class($service), $factory_service);
$this->assertEquals('bar', $factory_service->getSomeParameter(), 'Correct parameter was passed via the factory class instantiation.');
@ -892,7 +892,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
// Test multiple arguments.
$args = array();
for ($i=0; $i < 12; $i++) {
for ($i = 0; $i < 12; $i++) {
$services['service_test_instantiation_' . $i] = array(
'class' => '\Drupal\Tests\Component\DependencyInjection\MockInstantiationService',
// Also test a collection that does not need resolving.

View file

@ -113,11 +113,11 @@ class DrupalComponentTest extends UnitTestCase {
$file_uri = vfsStream::url('root/Test.php');
try {
$pass = true;
$pass = TRUE;
$this->assertNoCoreUsage($file_uri);
}
catch (\PHPUnit_Framework_AssertionFailedError $e) {
$pass = false;
$pass = FALSE;
}
$this->assertEquals($expected_pass, $pass, $expected_pass ?
'Test caused a false positive' :

View file

@ -37,7 +37,7 @@ abstract class MTimeProtectedFileStorageBase extends PhpStorageTestBase {
$this->secret = $this->randomMachineName();
$this->settings = array(
'directory' => $this->directory,
'directory' => $this->directory,
'bin' => 'test',
'secret' => $this->secret,
);
@ -69,7 +69,7 @@ abstract class MTimeProtectedFileStorageBase extends PhpStorageTestBase {
$php = new $this->storageClass($this->settings);
$name = 'simpletest.php';
$php->save($name, '<?php');
$expected_root_directory = $this->directory . '/test';
$expected_root_directory = $this->directory . '/test';
if (substr($name, -4) === '.php') {
$expected_directory = $expected_root_directory . '/' . substr($name, 0, -4);
}

View file

@ -154,4 +154,3 @@ class DefaultFactoryTest extends UnitTestCase {
}
}

View file

@ -5,8 +5,8 @@ namespace Drupal\Tests\Component\Plugin\Discovery;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait
* @uses Drupal\Component\Plugin\Discovery\DiscoveryTrait
* @coversDefaultClass \Drupal\Component\Plugin\Discovery\DiscoveryCachedTrait
* @uses \Drupal\Component\Plugin\Discovery\DiscoveryTrait
* @group Plugin
*/
class DiscoveryCachedTraitTest extends UnitTestCase {

View file

@ -6,7 +6,7 @@ use Drupal\Tests\UnitTestCase;
/**
* @group Plugin
* @coversDefaultClass Drupal\Component\Plugin\Discovery\DiscoveryTrait
* @coversDefaultClass \Drupal\Component\Plugin\Discovery\DiscoveryTrait
*/
class DiscoveryTraitTest extends UnitTestCase {
@ -58,9 +58,9 @@ class DiscoveryTraitTest extends UnitTestCase {
/**
* @covers ::doGetDefinition
* @expectedException Drupal\Component\Plugin\Exception\PluginNotFoundException
* @expectedException \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @dataProvider providerDoGetDefinitionException
* @uses Drupal\Component\Plugin\Exception\PluginNotFoundException
* @uses \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function testDoGetDefinitionException($expected, $definitions, $plugin_id) {
// Mock the trait.
@ -96,9 +96,9 @@ class DiscoveryTraitTest extends UnitTestCase {
/**
* @covers ::getDefinition
* @expectedException Drupal\Component\Plugin\Exception\PluginNotFoundException
* @expectedException \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @dataProvider providerDoGetDefinitionException
* @uses Drupal\Component\Plugin\Exception\PluginNotFoundException
* @uses \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function testGetDefinitionException($expected, $definitions, $plugin_id) {
// Since getDefinition is a wrapper around doGetDefinition(), we can re-use

View file

@ -6,7 +6,7 @@ use Drupal\Tests\UnitTestCase;
/**
* @group Plugin
* @coversDefaultClass Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator
* @coversDefaultClass \Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator
*/
class StaticDiscoveryDecoratorTest extends UnitTestCase {
@ -17,7 +17,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
* \Callable in the mock object. The return value of this callback is
* never used.
*
* @return mock
* @return \PHPUnit_Framework_MockObject_MockObject
* Mocked object with expectation of registerDefinitionsCallback() being
* called once.
*/

View file

@ -14,7 +14,7 @@ use Drupal\Tests\UnitTestCase;
/**
* @group Plugin
* @coversDefaultClass Drupal\Component\Plugin\Factory\ReflectionFactory
* @coversDefaultClass \Drupal\Component\Plugin\Factory\ReflectionFactory
*/
class ReflectionFactoryTest extends UnitTestCase {

View file

@ -50,7 +50,7 @@ class PlainTextOutputTest extends UnitTestCase {
$safe_string = $this->prophesize(MarkupInterface::class);
$safe_string->__toString()->willReturn('<em>"this"</em>');
$safe_string = $safe_string->reveal();
$data['escaped-html-with-quotes-and-placeholders'] = [$expected, 'The @tag tag makes your text look like @result.', ['@tag' =>'<em>', '@result' => $safe_string]];
$data['escaped-html-with-quotes-and-placeholders'] = [$expected, 'The @tag tag makes your text look like @result.', ['@tag' => '<em>', '@result' => $safe_string]];
$safe_string = $this->prophesize(MarkupInterface::class);
$safe_string->__toString()->willReturn($string);

View file

@ -320,4 +320,4 @@ class HtmlTest extends UnitTestCase {
$result = Html::serialize($document);
$this->assertSame('', $result);
}
}
}

View file

@ -70,8 +70,8 @@ class NumberTest extends UnitTestCase {
// Valid float steps.
array(42, 10.5, TRUE),
array(1, 1/3, TRUE),
array(-100, 100/7, TRUE),
array(1, 1 / 3, TRUE),
array(-100, 100 / 7, TRUE),
array(1000, -10, TRUE),
// Valid and very small float steps.
@ -83,7 +83,7 @@ class NumberTest extends UnitTestCase {
array(-10, 4, FALSE),
// Invalid float steps.
array(6, 5/7, FALSE),
array(6, 5 / 7, FALSE),
array(10.3, 10.25, FALSE),
// Step mismatches very close to being valid.
@ -102,12 +102,12 @@ class NumberTest extends UnitTestCase {
// Try obvious fits.
array(11.3, 10.3, 1, TRUE),
array(100, 10, 50, TRUE),
array(-100, 90/7, -10, TRUE),
array(2/7 + 5/9, 1/7, 5/9, TRUE),
array(-100, 90 / 7, -10, TRUE),
array(2 / 7 + 5 / 9, 1 / 7, 5 / 9, TRUE),
// Ensure a small offset is still invalid.
array(10.3, 10.3, 0.0001, FALSE),
array(1/5, 1/7, 1/11, FALSE),
array(1 / 5, 1 / 7, 1 / 11, FALSE),
// Try negative values and offsets.
array(1000, 10, -5, FALSE),

View file

@ -77,6 +77,15 @@ class ComposerIntegrationTest extends UnitTestCase {
}
}
/**
* Tests composer.lock hash.
*/
public function testComposerLockHash() {
$json = file_get_contents($this->root . '/composer.json');
$lock = json_decode(file_get_contents($this->root . '/composer.lock'), TRUE);
$this->assertSame(md5($json), $lock['hash']);
}
/**
* Tests core's composer.json replace section.
*

View file

@ -276,7 +276,7 @@ class CssOptimizerUnitTest extends UnitTestCase {
* Tests a CSS asset with 'type' => 'external'.
*/
function testTypeExternal() {
$this->setExpectedException('Exception', 'Only file or inline CSS assets can be optimized.');
$this->setExpectedException('Exception', 'Only file CSS assets can be optimized.');
$css_asset = array(
'group' => -100,

View file

@ -61,7 +61,7 @@ class LibraryDependencyResolverTest extends UnitTestCase {
->method('getLibrariesByExtension')
->with('test')
->will($this->returnValue($this->libraryData));
$this->libraryDependencyResolver= new LibraryDependencyResolver($this->libraryDiscovery);
$this->libraryDependencyResolver = new LibraryDependencyResolver($this->libraryDiscovery);
}

View file

@ -72,11 +72,11 @@ class PercentagesTest extends UnitTestCase {
// but for the last pass through, when 500 out of 501 items have been
// processed, we do not want to round up to 100%, since that would
// erroneously indicate that the processing is complete.
array('total' => 1, 'current' => 100/501, '20'),
array('total' => 1, 'current' => 200/501, '40'),
array('total' => 1, 'current' => 300/501, '60'),
array('total' => 1, 'current' => 400/501, '80'),
array('total' => 1, 'current' => 500/501, '99.8'),
array('total' => 1, 'current' => 100 / 501, '20'),
array('total' => 1, 'current' => 200 / 501, '40'),
array('total' => 1, 'current' => 300 / 501, '60'),
array('total' => 1, 'current' => 400 / 501, '80'),
array('total' => 1, 'current' => 500 / 501, '99.8'),
);
}

View file

@ -263,7 +263,7 @@ class BazCacheContext implements CalculatedCacheContextInterface {
* {@inheritdoc}
*/
public function getContext($parameter = NULL) {
if (!is_string($parameter) || strlen($parameter) === 0) {
if (!is_string($parameter) || strlen($parameter) === 0) {
throw new \Exception();
}
return str_rot13($parameter);

View file

@ -0,0 +1,43 @@
<?php
namespace Drupal\Tests\Core\Cache\Context;
use Drupal\Core\Cache\Context\PathParentCacheContext;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\Core\Cache\Context\PathParentCacheContext
* @group Cache
*/
class PathParentCacheContextTest extends UnitTestCase {
/**
* @covers ::getContext
*
* @dataProvider providerTestGetContext
*/
public function testgetContext($original_path, $context) {
$request_stack = new RequestStack();
$request = Request::create($original_path);
$request_stack->push($request);
$cache_context = new PathParentCacheContext($request_stack);
$this->assertSame($cache_context->getContext(), $context);
}
/**
* Provides a list of paths and expected cache contexts.
*/
public function providerTestGetContext() {
return [
['/some/path', 'some'],
['/some/other-path', 'some'],
['/some/other/path', 'some/other'],
['/some/other/path?q=foo&b=bar', 'some/other'],
['/some', ''],
['/', ''],
];
}
}

View file

@ -378,4 +378,3 @@ class ValidHandler implements HandlerInterface {
}
class InvalidHandler {
}

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Core\DrupalKernel;
use Composer\Autoload\ClassLoader;
use Drupal\Core\DrupalKernel;
use Drupal\Core\Site\Settings;
use Drupal\Tests\UnitTestCase;
@ -24,7 +25,7 @@ class DiscoverServiceProvidersTest extends UnitTestCase {
),
));
$kernel = new DrupalKernel('prod', new \Composer\Autoload\ClassLoader());
$kernel = new DrupalKernel('prod', new ClassLoader());
$kernel->discoverServiceProviders();
$expect = array(
@ -44,7 +45,7 @@ class DiscoverServiceProvidersTest extends UnitTestCase {
*/
public function testDiscoverServiceNoContainerYamls() {
new Settings([]);
$kernel = new DrupalKernel('prod', new \Composer\Autoload\ClassLoader());
$kernel = new DrupalKernel('prod', new ClassLoader());
$kernel->discoverServiceProviders();
$expect = [

View file

@ -37,12 +37,12 @@ namespace Drupal\Tests\Core\DrupalKernel {
$method = new \ReflectionMethod('Drupal\Core\DrupalKernel', 'setupTrustedHosts');
$method->setAccessible(TRUE);
$valid_host = $method->invoke(null, $request, $trusted_host_patterns);
$valid_host = $method->invoke(NULL, $request, $trusted_host_patterns);
$this->assertSame($expected, $valid_host, $message);
// Reset the trusted hosts because it is statically stored on the request.
$method->invoke(null, $request, []);
$method->invoke(NULL, $request, []);
// Reset the request factory because it is statically stored on the request.
Request::setFactory(NULL);
}
@ -144,4 +144,4 @@ namespace {
return FALSE;
}
}
}
}

View file

@ -545,7 +545,7 @@ class SqlContentEntityStorageSchemaTest extends UnitTestCase {
'default_langcode' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => true,
'not null' => TRUE,
),
),
'primary key' => array('id', 'langcode'),
@ -712,7 +712,7 @@ class SqlContentEntityStorageSchemaTest extends UnitTestCase {
'default_langcode' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => true,
'not null' => TRUE,
),
),
'primary key' => array('id', 'langcode'),
@ -750,7 +750,7 @@ class SqlContentEntityStorageSchemaTest extends UnitTestCase {
'default_langcode' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => true,
'not null' => TRUE,
),
),
'primary key' => array('revision_id', 'langcode'),
@ -859,51 +859,51 @@ class SqlContentEntityStorageSchemaTest extends UnitTestCase {
'bundle' => array(
'type' => 'varchar_ascii',
'length' => 128,
'not null' => true,
'not null' => TRUE,
'default' => '',
'description' => 'The field instance bundle to which this row belongs, used when deleting a field instance',
),
'deleted' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => true,
'not null' => TRUE,
'default' => 0,
'description' => 'A boolean indicating whether this data item has been deleted',
),
'entity_id' => array(
'type' => 'int',
'unsigned' => true,
'not null' => true,
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'The entity id this data is attached to',
),
'revision_id' => array(
'type' => 'int',
'unsigned' => true,
'not null' => true,
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'The entity revision id this data is attached to, which for an unversioned entity type is the same as the entity id',
),
'langcode' => array(
'type' => 'varchar_ascii',
'length' => 32,
'not null' => true,
'not null' => TRUE,
'default' => '',
'description' => 'The language code for this data item.',
),
'delta' => array(
'type' => 'int',
'unsigned' => true,
'not null' => true,
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'The sequence number for this data item, used for multi-value fields',
),
$field_name . '_shape' => array(
'type' => 'varchar',
'length' => 32,
'not null' => false,
'not null' => FALSE,
),
$field_name . '_color' => array(
'type' => 'varchar',
'length' => 32,
'not null' => false,
'not null' => FALSE,
),
),
'primary key' => array('entity_id', 'deleted', 'delta', 'langcode'),
@ -1004,51 +1004,51 @@ class SqlContentEntityStorageSchemaTest extends UnitTestCase {
'bundle' => array(
'type' => 'varchar_ascii',
'length' => 128,
'not null' => true,
'not null' => TRUE,
'default' => '',
'description' => 'The field instance bundle to which this row belongs, used when deleting a field instance',
),
'deleted' => array(
'type' => 'int',
'size' => 'tiny',
'not null' => true,
'not null' => TRUE,
'default' => 0,
'description' => 'A boolean indicating whether this data item has been deleted',
),
'entity_id' => array(
'type' => 'varchar_ascii',
'length' => 128,
'not null' => true,
'not null' => TRUE,
'description' => 'The entity id this data is attached to',
),
'revision_id' => array(
'type' => 'varchar_ascii',
'length' => 128,
'not null' => true,
'not null' => TRUE,
'description' => 'The entity revision id this data is attached to, which for an unversioned entity type is the same as the entity id',
),
'langcode' => array(
'type' => 'varchar_ascii',
'length' => 32,
'not null' => true,
'not null' => TRUE,
'default' => '',
'description' => 'The language code for this data item.',
),
'delta' => array(
'type' => 'int',
'unsigned' => true,
'not null' => true,
'unsigned' => TRUE,
'not null' => TRUE,
'description' => 'The sequence number for this data item, used for multi-value fields',
),
$field_name . '_shape' => array(
'type' => 'varchar',
'length' => 32,
'not null' => false,
'not null' => FALSE,
),
$field_name . '_color' => array(
'type' => 'varchar',
'length' => 32,
'not null' => false,
'not null' => FALSE,
),
),
'primary key' => array('entity_id', 'deleted', 'delta', 'langcode'),

View file

@ -31,7 +31,7 @@ class CustomPageExceptionHtmlSubscriberTest extends UnitTestCase {
/**
* The mocked config factory
*
* @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
* @var \Drupal\Core\Config\ConfigFactoryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $configFactory;
@ -162,4 +162,3 @@ class CustomPageExceptionHtmlSubscriberTest extends UnitTestCase {
}
}

View file

@ -238,7 +238,7 @@ class ModuleHandlerTest extends UnitTestCase {
* @covers ::loadAllIncludes
*/
public function testLoadAllIncludes() {
$this->assertTrue(true);
$this->assertTrue(TRUE);
$module_handler = $this->getMockBuilder('Drupal\Core\Extension\ModuleHandler')
->setConstructorArgs(array(
$this->root,

View file

@ -738,7 +738,7 @@ class FormBuilderTest extends FormTestBase {
*/
public function testValueCallableIsSafe($callback, $expected) {
$method = new \ReflectionMethod(FormBuilder::class, 'valueCallableIsSafe');
$method->setAccessible(true);
$method->setAccessible(TRUE);
$is_safe = $method->invoke($this->formBuilder, $callback);
$this->assertSame($expected, $is_safe);
}

View file

@ -113,7 +113,6 @@ abstract class FormTestBase extends UnitTestCase {
protected $elementInfo;
/**
*
* The event dispatcher.
*
* @var \Symfony\Component\EventDispatcher\EventDispatcherInterface|\PHPUnit_Framework_MockObject_MockObject

View file

@ -203,7 +203,7 @@ class FormValidatorTest extends UnitTestCase {
array(
array(array('test1')),
array(
'#is_button' => true,
'#is_button' => TRUE,
'#value' => 'baz',
'#name' => 'op',
'#parents' => array('submit'),

View file

@ -161,4 +161,3 @@ class NaughtyRecursiveLogger implements LoggerInterface {
$this->channel->log(rand(0, 7), $message, $context);
}
}

View file

@ -491,4 +491,3 @@ class LocalTaskManagerTest extends UnitTestCase {
}
}

View file

@ -2,8 +2,8 @@
namespace Drupal\Tests\Core\PageCache;
use Drupal\Core\PageCache\RequestPolicy\NoSessionOpen;
use Drupal\Core\PageCache\RequestPolicyInterface;
use Drupal\Core\PageCache\RequestPolicy;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
@ -29,7 +29,7 @@ class NoSessionOpenTest extends UnitTestCase {
protected function setUp() {
$this->sessionConfiguration = $this->getMock('Drupal\Core\Session\SessionConfigurationInterface');
$this->policy = new RequestPolicy\NoSessionOpen($this->sessionConfiguration);
$this->policy = new NoSessionOpen($this->sessionConfiguration);
}
/**

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Core\ParamConverter;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Core\ParamConverter\EntityConverter;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\Routing\Route;
@ -116,7 +117,7 @@ class EntityConverterTest extends UnitTestCase {
$this->entityManager->expects($this->once())
->method('getStorage')
->with('invalid_id')
->willThrowException(new \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException('invalid_id'));
->willThrowException(new InvalidPluginDefinitionException('invalid_id'));
$this->entityConverter->convert('id', ['type' => 'entity:invalid_id'], 'foo', ['foo' => 'id']);
}

View file

@ -252,7 +252,7 @@ class AliasManagerTest extends UnitTestCase {
* @covers ::writeCache
*/
public function testGetAliasByPathCachedMatch() {
$path_part1 = $this->randomMachineName();
$path_part1 = $this->randomMachineName();
$path_part2 = $this->randomMachineName();
$path = '/' . $path_part1 . '/' . $path_part2;
$alias = $this->randomMachineName();

View file

@ -444,4 +444,3 @@ class PathValidatorTest extends UnitTestCase {
}
}

View file

@ -10,7 +10,7 @@ use Drupal\Tests\UnitTestCase;
*
* @group Plugin
*
* @coversDefaultClass Drupal\Core\Plugin\Context\ContextDefinition
* @coversDefaultClass \Drupal\Core\Plugin\Context\ContextDefinition
*/
class ContextDefinitionTest extends UnitTestCase {
@ -113,7 +113,7 @@ class ContextDefinitionTest extends UnitTestCase {
* @dataProvider providerGetDataDefinition
* @covers ::getDataDefinition
* @uses \Drupal
* @uses Drupal\Component\Utility\SafeMarkup
* @uses \Drupal\Component\Utility\SafeMarkup
*/
public function testGetDataDefinitionInvalidType($is_multiple) {
// Since we're trying to make getDataDefinition() throw an exception in

View file

@ -29,7 +29,7 @@ class DerivativeDiscoveryDecoratorTest extends UnitTestCase {
/**
* Tests the getDerivativeFetcher method.
*
* @see \Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator::getDerivativeFetcher().
* @see \Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator::getDerivativeFetcher().
*/
public function testGetDerivativeFetcher() {
$definitions = array();

View file

@ -401,12 +401,12 @@ class BubbleableMetadataTest extends UnitTestCase {
* @return array
*/
public function providerTestMergeAttachmentsFeedMerging() {
$feed_a = [
$feed_a = [
'aggregator/rss',
'Feed title',
];
$feed_b = [
$feed_b = [
'taxonomy/term/1/feed',
'RSS - foo',
];
@ -533,12 +533,12 @@ class BubbleableMetadataTest extends UnitTestCase {
* @return array
*/
public function providerTestMergeAttachmentsHtmlHeadLinkMerging() {
$rel = [
$rel = [
'rel' => 'rel',
'href' => 'http://rel.example.com',
];
$shortlink = [
$shortlink = [
'rel' => 'shortlink',
'href' => 'http://shortlink.example.com',
];

View file

@ -10,9 +10,12 @@ namespace Drupal\Tests\Core\Render;
use Drupal\Component\Utility\Html;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Render\Markup;
use Drupal\Core\Render\RenderContext;
/**
* @coversDefaultClass \Drupal\Core\Render\Renderer
* @covers \Drupal\Core\Render\RenderCache
* @covers \Drupal\Core\Render\PlaceholderingRenderCache
* @group Render
*/
class RendererPlaceholdersTest extends RendererTestBase {
@ -781,6 +784,40 @@ class RendererPlaceholdersTest extends RendererTestBase {
$this->assertPlaceholderRenderCache(FALSE, [], []);
}
/**
* @covers ::render
* @covers ::doRender
* @covers \Drupal\Core\Render\RenderCache::get
* @covers \Drupal\Core\Render\PlaceholderingRenderCache::get
* @covers \Drupal\Core\Render\PlaceholderingRenderCache::set
* @covers ::replacePlaceholders
*
* @dataProvider providerPlaceholders
*/
public function testPlaceholderingDisabledForPostRequests($test_element, $args) {
$this->setUpUnusedCache();
$this->setUpRequest('POST');
$element = $test_element;
// Render without replacing placeholders, to allow this test to see which
// #attached[placeholders] there are, if any.
$this->renderer->executeInRenderContext(new RenderContext(), function () use (&$element) {
return $this->renderer->render($element);
});
// Only test cases where the placeholders have been specified manually are
// allowed to have placeholders. This means that of the different situations
// listed in providerPlaceholders(), only type B can have attached
// placeholders. Everything else, whether:
// 1. manual placeholdering
// 2. automatic placeholdering via already-present cacheability metadata
// 3. automatic placeholdering via bubbled cacheability metadata
// All three of those should NOT result in placeholders.
if (!isset($test_element['#attached']['placeholders'])) {
$this->assertFalse(isset($element['#attached']['placeholders']), 'No placeholders created.');
}
}
/**
* Tests a placeholder that adds another placeholder.
*
@ -998,7 +1035,7 @@ HTML;
$dom = Html::load($cached_element['#markup']);
$xpath = new \DOMXPath($dom);
$parent = $xpath->query('//details/summary[text()="Parent"]')->length;
$child = $xpath->query('//details/div[@class="details-wrapper"]/details/summary[text()="Child"]')->length;
$child = $xpath->query('//details/div[@class="details-wrapper"]/details/summary[text()="Child"]')->length;
$subchild = $xpath->query('//details/div[@class="details-wrapper"]/details/div[@class="details-wrapper" and text()="Subchild"]')->length;
$this->assertTrue($parent && $child && $subchild, 'The correct data is cached: the stored #markup is not affected by placeholder #lazy_builder callbacks.');

View file

@ -106,7 +106,7 @@ class RendererTestBase extends UnitTestCase {
'auto_placeholder_conditions' => [
'max-age' => 0,
'contexts' => ['session', 'user'],
'tags' => ['current-temperature'],
'tags' => ['current-temperature'],
],
];

View file

@ -101,7 +101,7 @@ class NegotiationMiddlewareTest extends UnitTestCase {
$request->setRequestFormat('html')->shouldBeCalled();
// Some getContentType calls we don't really care about but have to mock.
$request->get('ajax_iframe_upload', false)->shouldBeCalled();
$request->get('ajax_iframe_upload', FALSE)->shouldBeCalled();
$request_mock = $request->reveal();
$request_mock->query = new ParameterBag([]);
@ -126,7 +126,7 @@ class NegotiationMiddlewareTest extends UnitTestCase {
// Some calls we don't care about.
$request->setRequestFormat('html')->shouldBeCalled();
$request->get('ajax_iframe_upload', false)->shouldBeCalled();
$request->get('ajax_iframe_upload', FALSE)->shouldBeCalled();
$request_mock = $request->reveal();
$request_mock->query = new ParameterBag([]);

View file

@ -435,7 +435,7 @@ class AttributeTest extends UnitTestCase {
* The number of results that are found.
*/
protected function getXPathResultCount($query, $html) {
$document = new \DOMDocument;
$document = new \DOMDocument();
$document->loadHTML($html);
$xpath = new \DOMXPath($document);

View file

@ -315,7 +315,6 @@ class RecursiveContextualValidatorTest extends UnitTestCase {
}
/**
*
* Builds some example type data object.
*
* @return \Drupal\Core\TypedData\TypedDataInterface|\PHPUnit_Framework_MockObject_MockObject

View file

@ -512,7 +512,7 @@ class UrlTest extends UnitTestCase {
$route_match = new RouteMatch('test_route', $route, ['foo' => (object) [1]], ['foo' => 1]);
$url = Url::fromRouteMatch($route_match);
$this->assertSame('test_route', $url->getRouteName());
$this->assertEquals(['foo' => '1'] , $url->getRouteParameters());
$this->assertEquals(['foo' => '1'], $url->getRouteParameters());
}
/**

View file

@ -519,7 +519,7 @@ class LinkGeneratorTest extends UnitTestCase {
}
// Execute the query.
$document = new \DOMDocument;
$document = new \DOMDocument();
$document->loadHTML($html);
$xpath = new \DOMXPath($document);
@ -538,7 +538,7 @@ class LinkGeneratorTest extends UnitTestCase {
* The number of results that are found.
*/
protected function assertNoXPathResults($query, $html) {
$document = new \DOMDocument;
$document = new \DOMDocument();
$document->loadHTML($html);
$xpath = new \DOMXPath($document);

View file

@ -15,7 +15,7 @@ use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass Drupal\Core\Validation\Plugin\Validation\Constraint\PrimitiveTypeConstraintValidator
* @coversDefaultClass \Drupal\Core\Validation\Plugin\Validation\Constraint\PrimitiveTypeConstraintValidator
* @group validation
*/
class PrimitiveTypeConstraintValidatorTest extends UnitTestCase {

View file

@ -0,0 +1,126 @@
<?php
namespace Drupal\Tests;
use Drupal\Component\Utility\Random;
/**
* Provides random generator utility methods.
*/
trait RandomGeneratorTrait {
/**
* The random generator.
*
* @var \Drupal\Component\Utility\Random
*/
protected $randomGenerator;
/**
* Generates a pseudo-random string of ASCII characters of codes 32 to 126.
*
* Do not use this method when special characters are not possible (e.g., in
* machine or file names that have already been validated); instead, use
* \Drupal\simpletest\TestBase::randomMachineName(). If $length is greater
* than 3 the random string will include at least one ampersand ('&') and
* at least one greater than ('>') character to ensure coverage for special
* characters and avoid the introduction of random test failures.
*
* @param int $length
* Length of random string to generate.
*
* @return string
* Pseudo-randomly generated unique string including special characters.
*
* @see \Drupal\Component\Utility\Random::string()
*/
public function randomString($length = 8) {
if ($length < 4) {
return $this->getRandomGenerator()->string($length, TRUE, array($this, 'randomStringValidate'));
}
// To prevent the introduction of random test failures, ensure that the
// returned string contains a character that needs to be escaped in HTML by
// injecting an ampersand into it.
$replacement_pos = floor($length / 2);
// Remove 2 from the length to account for the ampersand and greater than
// characters.
$string = $this->getRandomGenerator()->string($length - 2, TRUE, array($this, 'randomStringValidate'));
return substr_replace($string, '>&', $replacement_pos, 0);
}
/**
* Callback for random string validation.
*
* @see \Drupal\Component\Utility\Random::string()
*
* @param string $string
* The random string to validate.
*
* @return bool
* TRUE if the random string is valid, FALSE if not.
*/
public function randomStringValidate($string) {
// Consecutive spaces causes issues for
// \Drupal\simpletest\WebTestBase::assertLink().
if (preg_match('/\s{2,}/', $string)) {
return FALSE;
}
// Starting or ending with a space means that length might not be what is
// expected.
if (preg_match('/^\s|\s$/', $string)) {
return FALSE;
}
return TRUE;
}
/**
* Generates a unique random string containing letters and numbers.
*
* Do not use this method when testing unvalidated user input. Instead, use
* \Drupal\simpletest\TestBase::randomString().
*
* @param int $length
* Length of random string to generate.
*
* @return string
* Randomly generated unique string.
*
* @see \Drupal\Component\Utility\Random::name()
*/
protected function randomMachineName($length = 8) {
return $this->getRandomGenerator()->name($length, TRUE);
}
/**
* Generates a random PHP object.
*
* @param int $size
* The number of random keys to add to the object.
*
* @return \stdClass
* The generated object, with the specified number of random keys. Each key
* has a random string value.
*
* @see \Drupal\Component\Utility\Random::object()
*/
public function randomObject($size = 4) {
return $this->getRandomGenerator()->object($size);
}
/**
* Gets the random generator for the utility methods.
*
* @return \Drupal\Component\Utility\Random
* The random generator.
*/
protected function getRandomGenerator() {
if (!is_object($this->randomGenerator)) {
$this->randomGenerator = new Random();
}
return $this->randomGenerator;
}
}

View file

@ -0,0 +1,40 @@
<?php
namespace Drupal\Tests;
use Symfony\Component\HttpFoundation\Request;
/**
* Provides methods to generate and get session name in tests.
*/
trait SessionTestTrait {
/**
* The name of the session cookie.
*
* @var string
*/
protected $sessionName;
/**
* Generates a session cookie name.
*
* @param string $data
* The data to generate session name.
*/
protected function generateSessionName($data) {
$prefix = (Request::createFromGlobals()->isSecure() ? 'SSESS' : 'SESS');
$this->sessionName = $prefix . substr(hash('sha256', $data), 0, 32);
}
/**
* Returns the session name in use on the child site.
*
* @return string
* The name of the session cookie.
*/
protected function getSessionName() {
return $this->sessionName;
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Drupal\Tests;
use Behat\Mink\WebAssert as MinkWebAssert;
use Behat\Mink\Element\TraversableElement;
use Behat\Mink\Exception\ElementNotFoundException;
/**
* Defines a class with methods for asserting presence of elements during tests.
*/
class WebAssert extends MinkWebAssert {
/**
* Checks that specific button exists on the current page.
*
* @param string $button
* One of id|name|label|value for the button.
* @param \Behat\Mink\Element\TraversableElement $container
* (optional) The document to check against. Defaults to the current page.
*
* @return \Behat\Mink\Element\NodeElement
* The matching element.
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
* When the element doesn't exist.
*/
public function buttonExists($button, TraversableElement $container = NULL) {
$container = $container ?: $this->session->getPage();
$node = $container->findButton($button);
if ($node === NULL) {
throw new ElementNotFoundException($this->session, 'button', 'id|name|label|value', $button);
}
return $node;
}
/**
* Checks that specific select field exists on the current page.
*
* @param string $select
* One of id|name|label|value for the select field.
* @param \Behat\Mink\Element\TraversableElement $container
* (optional) The document to check against. Defaults to the current page.
*
* @return \Behat\Mink\Element\NodeElement
* The matching element
*
* @throws \Behat\Mink\Exception\ElementNotFoundException
* When the element doesn't exist.
*/
public function selectExists($select, TraversableElement $container = NULL) {
$container = $container ?: $this->session->getPage();
$node = $container->find('named', array(
'select',
$this->session->getSelectorsHandler()->xpathLiteral($select),
));
if ($node === NULL) {
throw new ElementNotFoundException($this->session, 'select', 'id|name|label|value', $select);
}
return $node;
}
}