Update to Drupal 8.0-dev-2015-11-17. Commits through da81cd220, Tue Nov 17 15:53:49 2015 +0000, Issue #2617224 by Wim Leers: Move around/fix some documentation.

This commit is contained in:
Pantheon Automation 2015-11-17 13:42:33 -08:00 committed by Greg Anderson
parent 4afb23bbd3
commit 7784f4c23d
929 changed files with 19798 additions and 5304 deletions

View file

@ -0,0 +1,79 @@
<?php
/**
* @file \Drupal\KernelTests\Core\Cache\CacheCollectorTest.
*/
namespace Drupal\KernelTests\Core\Cache;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\KernelTests\KernelTestBase;
use Drupal\Tests\Core\Cache\CacheCollectorHelper;
use Symfony\Component\DependencyInjection\Reference;
/**
* Tests DatabaseBackend cache tag implementation.
*
* @group Cache
*/
class CacheCollectorTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system'];
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->installSchema('system', ['semaphore']);
}
/**
* {@inheritdoc}
*/
public function register(ContainerBuilder $container) {
parent::register($container);
// Change container to database cache backends.
$container
->register('cache_factory', 'Drupal\Core\Cache\CacheFactory')
->addArgument(new Reference('settings'))
->addMethodCall('setContainer', [new Reference('service_container')]);
// Change container to use database lock backends.
$container
->register('lock', 'Drupal\Core\Lock\DatabaseLockBackend')
->addArgument(new Reference('database'));
}
/**
* Tests setting and invalidating
*
* @dataProvider providerTestInvalidCharacters
*/
public function testCacheCollector($cid, $key, $value) {
$collector = new CacheCollectorHelper($cid, $this->container->get('cache.default'), $this->container->get('lock'));
$this->assertNull($collector->get($key));
$collector->set($key, $value);
$this->assertEquals($value, $collector->get($key));
$collector->destruct();
// @todo Shouldn't this be empty after destruction?
$this->assertEquals($value, $collector->get($key));
}
/**
* Data provider for ::testCacheCollector().
*/
public function providerTestInvalidCharacters() {
return [
// Nothing special.
['foo', 'bar', 'baz'],
// Invalid characters in CID.
['éøïвβ中國書۞', 'foo', 'bar'],
// Really long CID.
[$this->randomString(1024), 'foo', 'bar'],
];
}
}

View file

@ -0,0 +1,86 @@
<?php
/**
* @file
* Contains \Drupal\KernelTests\Core\Path\AliasStorageTest.
*/
namespace Drupal\KernelTests\Core\Path;
use Drupal\Core\Language\LanguageInterface;
use Drupal\KernelTests\KernelTestBase;
/**
* @coversDefaultClass \Drupal\Core\Path\AliasStorage
* @group path
*/
class AliasStorageTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system'];
/** @var \Drupal\Core\Path\AliasStorage */
protected $storage;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', 'url_alias');
$this->storage = $this->container->get('path.alias_storage');
}
/**
* @covers ::load
*/
public function testLoad() {
$this->storage->save('/test-source-Case', '/test-alias-Case');
$expected = [
'pid' => 1,
'alias' => '/test-alias-Case',
'source' => '/test-source-Case',
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
];
$this->assertEquals($expected, $this->storage->load(['alias' => '/test-alias-Case']));
$this->assertEquals($expected, $this->storage->load(['alias' => '/test-alias-case']));
$this->assertEquals($expected, $this->storage->load(['source' => '/test-source-Case']));
$this->assertEquals($expected, $this->storage->load(['source' => '/test-source-case']));
}
/**
* @covers ::lookupPathAlias
*/
public function testLookupPathAlias() {
$this->storage->save('/test-source-Case', '/test-alias');
$this->assertEquals('/test-alias', $this->storage->lookupPathAlias('/test-source-Case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
$this->assertEquals('/test-alias', $this->storage->lookupPathAlias('/test-source-case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
}
/**
* @covers ::lookupPathSource
*/
public function testLookupPathSource() {
$this->storage->save('/test-source', '/test-alias-Case');
$this->assertEquals('/test-source', $this->storage->lookupPathSource('/test-alias-Case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
$this->assertEquals('/test-source', $this->storage->lookupPathSource('/test-alias-case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
}
/**
* @covers ::aliasExists
*/
public function testAliasExists() {
$this->storage->save('/test-source-Case', '/test-alias-Case');
$this->assertTrue($this->storage->aliasExists('/test-alias-Case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
$this->assertTrue($this->storage->aliasExists('/test-alias-case', LanguageInterface::LANGCODE_NOT_SPECIFIED));
}
}

View file

@ -0,0 +1,43 @@
<?php
/**
* @file
* Contains \Drupal\KernelTests\Core\Theme\MaintenanceThemeTest.
*/
namespace Drupal\KernelTests\Core\Theme;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests themes and base themes are correctly loaded.
*
* @group Installer
*/
class MaintenanceThemeTest extends KernelTestBase {
/**
* Tests that the maintenance theme initializes the theme and its base themes.
*/
public function testMaintenanceTheme() {
$this->setSetting('maintenance_theme', 'seven');
// Get the maintenance theme loaded.
drupal_maintenance_theme();
// Do we have an active theme?
$this->assertTrue(\Drupal::theme()->hasActiveTheme());
$active_theme = \Drupal::theme()->getActiveTheme();
$this->assertEquals('seven', $active_theme->getName());
$base_themes = $active_theme->getBaseThemes();
$base_theme_names = array_keys($base_themes);
$this->assertSame(['classy', 'stable'], $base_theme_names);
// Ensure Classy has the correct base themes and amount of base themes.
$classy_base_themes = $base_themes['classy']->getBaseThemes();
$classy_base_theme_names = array_keys($classy_base_themes);
$this->assertSame(['stable'], $classy_base_theme_names);
}
}

View file

@ -0,0 +1,108 @@
<?php
/**
* @file
* Contains \Drupal\KernelTests\Core\Theme\StableTemplateOverrideTest.
*/
namespace Drupal\KernelTests\Core\Theme;
use Drupal\Core\Theme\Registry;
use Drupal\KernelTests\KernelTestBase;
/**
* Tests Stable's template overrides.
*
* @group Theme
*/
class StableTemplateOverrideTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'user'];
/**
* An array of template names to skip, without the extension.
*
* @var string[]
*/
protected $templatesToSkip = [
'views-form-views-form',
];
/**
* The theme handler.
*
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* A list of all core modules.
*
* @var string[]
*/
protected $allModules;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->themeHandler = $this->container->get('theme_handler');
$this->container->get('theme_installer')->install(['stable']);
$this->installSchema('system', 'router');
$this->installAllModules();
}
/**
* Installs all core modules.
*/
protected function installAllModules() {
// Needed for system_rebuild_module_data().
include_once $this->root . '/core/modules/system/system.module';
// Enable all core modules.
$all_modules = system_rebuild_module_data();
$all_modules = array_filter($all_modules, function ($module) {
// Filter contrib, hidden, already enabled modules and modules in the
// Testing package.
if ($module->origin !== 'core' || !empty($module->info['hidden']) || $module->status == TRUE || $module->info['package'] == 'Testing') {
return FALSE;
}
return TRUE;
});
$this->allModules = array_keys($all_modules);
sort($this->allModules);
$module_installer = $this->container->get('module_installer');
$module_installer->install($this->allModules);
$this->installConfig(['system', 'user']);
}
/**
* Ensures that Stable overrides all relevant core templates.
*/
public function testStableTemplateOverrides() {
$registry = new Registry(\Drupal::root(), \Drupal::cache(), \Drupal::lock(), \Drupal::moduleHandler(), $this->themeHandler, \Drupal::service('theme.initialization'), 'stable');
$registry->setThemeManager(\Drupal::theme());
$registry_full = $registry->get();
foreach ($registry_full as $hook => $info) {
if (isset($info['template'])) {
// Allow skipping templates.
if (in_array($info['template'], $this->templatesToSkip)) {
continue;
}
$this->assertEquals('core/themes/stable', $info['theme path'], $info['template'] . '.html.twig overridden in Stable.');
}
}
}
}

View file

@ -0,0 +1,50 @@
<?php
/**
* @file
* Contains \Drupal\KernelTests\RequestProcessing\RedirectOnExceptionTest.
*/
namespace Drupal\KernelTests\RequestProcessing;
use Drupal\KernelTests\KernelTestBase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Tests redirects on exception pages.
*
* @group request_processing
*/
class RedirectOnExceptionTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
public static $modules = ['system', 'test_page_test'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->installSchema('system', ['router', 'url_alias']);
\Drupal::service('router.builder')->rebuild();
}
public function testRedirectOn404() {
\Drupal::configFactory()->getEditable('system.site')
->set('page.404', '/test-http-response-exception/' . Response::HTTP_PERMANENTLY_REDIRECT)
->save();
/** @var \Symfony\Component\HttpKernel\HttpKernelInterface $http_kernel */
$http_kernel = \Drupal::service('http_kernel');
// Foo doesn't exist, so this triggers the 404 page.
$request = Request::create('/foo');
$response = $http_kernel->handle($request);
$this->assertEquals(Response::HTTP_PERMANENTLY_REDIRECT, $response->getStatusCode());
}
}

View file

@ -0,0 +1,168 @@
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Asset\AssetResolverTest.
*/
namespace Drupal\Tests\Core\Asset;
use Drupal\Core\Asset\AssetResolver;
use Drupal\Core\Asset\AttachedAssets;
use Drupal\Core\Asset\AttachedAssetsInterface;
use Drupal\Core\Cache\MemoryBackend;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Asset\AssetResolver
* @group Asset
*/
class AssetResolverTest extends UnitTestCase {
/**
* The tested asset resolver service.
*
* @var \Drupal\Core\Asset\AssetResolver
*/
protected $assetResolver;
/**
* The mocked library discovery service.
*
* @var \Drupal\Core\Asset\LibraryDiscoveryInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $libraryDiscovery;
/**
* The mocked library dependency resolver.
*
* @var \Drupal\Core\Asset\LibraryDependencyResolverInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $libraryDependencyResolver;
/**
* The mocked module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $moduleHandler;
/**
* The mocked theme manager.
*
* @var \Drupal\Core\Theme\ThemeManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $themeManager;
/**
* The mocked language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $languageManager;
/**
* The cache backend to use.
*
* @var \Drupal\Core\Cache\CacheBackendInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $cache;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->libraryDiscovery = $this->getMockBuilder('Drupal\Core\Asset\LibraryDiscovery')
->disableOriginalConstructor()
->getMock();
$this->libraryDependencyResolver = $this->getMock('\Drupal\Core\Asset\LibraryDependencyResolverInterface');
$this->libraryDependencyResolver->expects($this->any())
->method('getLibrariesWithDependencies')
->willReturnArgument(0);
$this->moduleHandler = $this->getMock('\Drupal\Core\Extension\ModuleHandlerInterface');
$this->themeManager = $this->getMock('\Drupal\Core\Theme\ThemeManagerInterface');
$active_theme = $this->getMockBuilder('\Drupal\Core\Theme\ActiveTheme')
->disableOriginalConstructor()
->getMock();
$active_theme->expects($this->any())
->method('getName')
->willReturn('bartik');
$this->themeManager->expects($this->any())
->method('getActiveTheme')
->willReturn($active_theme);
$this->languageManager = $this->getMock('\Drupal\Core\Language\LanguageManagerInterface');
$english = $this->getMock('\Drupal\Core\Language\LanguageInterface');
$english->expects($this->any())
->method('getId')
->willReturn('en');
$japanese = $this->getMock('\Drupal\Core\Language\LanguageInterface');
$japanese->expects($this->any())
->method('getId')
->willReturn('jp');
$this->languageManager = $this->getMock('\Drupal\Core\Language\LanguageManagerInterface');
$this->languageManager->expects($this->any())
->method('getCurrentLanguage')
->will($this->onConsecutiveCalls($english, $english, $japanese, $japanese));
$this->cache = new TestMemoryBackend('llama');
$this->assetResolver = new AssetResolver($this->libraryDiscovery, $this->libraryDependencyResolver, $this->moduleHandler, $this->themeManager, $this->languageManager, $this->cache);
}
/**
* @covers ::getCssAssets
* @dataProvider providerAttachedAssets
*/
public function testGetCssAssets(AttachedAssetsInterface $assets_a, AttachedAssetsInterface $assets_b, $expected_cache_item_count) {
$this->assetResolver->getCssAssets($assets_a, FALSE);
$this->assetResolver->getCssAssets($assets_b, FALSE);
$this->assertCount($expected_cache_item_count, $this->cache->getAllCids());
}
/**
* @covers ::getJsAssets
* @dataProvider providerAttachedAssets
*/
public function testGetJsAssets(AttachedAssetsInterface $assets_a, AttachedAssetsInterface $assets_b, $expected_cache_item_count) {
$this->assetResolver->getJsAssets($assets_a, FALSE);
$this->assetResolver->getJsAssets($assets_b, FALSE);
$this->assertCount($expected_cache_item_count, $this->cache->getAllCids());
$this->assetResolver->getJsAssets($assets_a, FALSE);
$this->assetResolver->getJsAssets($assets_b, FALSE);
$this->assertCount($expected_cache_item_count * 2, $this->cache->getAllCids());
}
public function providerAttachedAssets() {
$time = time();
return [
'same libraries, different timestamps' => [
(new AttachedAssets())->setAlreadyLoadedLibraries([])->setLibraries(['core/drupal'])->setSettings(['currentTime' => $time]),
(new AttachedAssets())->setAlreadyLoadedLibraries([])->setLibraries(['core/drupal'])->setSettings(['currentTime' => $time + 100]),
1
],
'different libraries, same timestamps' => [
(new AttachedAssets())->setAlreadyLoadedLibraries([])->setLibraries(['core/drupal'])->setSettings(['currenttime' => $time]),
(new AttachedAssets())->setAlreadyLoadedLibraries([])->setLibraries(['core/drupal', 'core/jquery'])->setSettings(['currentTime' => $time]),
2
],
];
}
}
if (!defined('CSS_AGGREGATE_DEFAULT')) {
define('CSS_AGGREGATE_DEFAULT', 0);
}
if (!defined('JS_DEFAULT')) {
define('JS_DEFAULT', 0);
}
class TestMemoryBackend extends MemoryBackend {
public function getAllCids() {
return array_keys($this->cache);
}
}

View file

@ -10,20 +10,6 @@ namespace Drupal\Tests\Core\Asset;
use Drupal\Core\Asset\LibraryDiscoveryParser;
use Drupal\Tests\UnitTestCase;
if (!defined('CSS_AGGREGATE_DEFAULT')) {
define('CSS_AGGREGATE_DEFAULT', 0);
define('CSS_AGGREGATE_THEME', 100);
define('CSS_BASE', -200);
define('CSS_LAYOUT', -100);
define('CSS_COMPONENT', 0);
define('CSS_STATE', 100);
define('CSS_THEME', 200);
define('JS_SETTING', -200);
define('JS_LIBRARY', -100);
define('JS_DEFAULT', 0);
define('JS_THEME', 100);
}
/**
* @coversDefaultClass \Drupal\Core\Asset\LibraryDiscoveryParser
* @group Asset
@ -575,3 +561,37 @@ class TestLibraryDiscoveryParser extends LibraryDiscoveryParser {
}
}
if (!defined('CSS_AGGREGATE_DEFAULT')) {
define('CSS_AGGREGATE_DEFAULT', 0);
}
if (!defined('CSS_AGGREGATE_THEME')) {
define('CSS_AGGREGATE_THEME', 100);
}
if (!defined('CSS_BASE')) {
define('CSS_BASE', -200);
}
if (!defined('CSS_LAYOUT')) {
define('CSS_LAYOUT', -100);
}
if (!defined('CSS_COMPONENT')) {
define('CSS_COMPONENT', 0);
}
if (!defined('CSS_STATE')) {
define('CSS_STATE', 100);
}
if (!defined('CSS_THEME')) {
define('CSS_THEME', 200);
}
if (!defined('JS_SETTING')) {
define('JS_SETTING', -200);
}
if (!defined('JS_LIBRARY')) {
define('JS_LIBRARY', -100);
}
if (!defined('JS_DEFAULT')) {
define('JS_DEFAULT', 0);
}
if (!defined('JS_THEME')) {
define('JS_THEME', 100);
}

View file

@ -71,4 +71,20 @@ class AttributesTest extends UnitTestCase {
}
}
/**
* Test AttributeValueBase copy.
*/
public function testAttributeValueBaseCopy() {
$original_attributes = new Attribute([
'checked' => TRUE,
'class' => ['who', 'is', 'on'],
'id' => 'first',
]);
$attributes['selected'] = $original_attributes['checked'];
$attributes['id'] = $original_attributes['id'];
$attributes = new Attribute($attributes);
$this->assertSame((string) $original_attributes, ' checked class="who is on" id="first"', 'Original boolean value used with original name.');
$this->assertSame((string) $attributes, ' selected id="first"', 'Original boolean value used with new name.');
}
}

View file

@ -0,0 +1,112 @@
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Datetime\DateHelperTest.
*/
namespace Drupal\Tests\Core\Datetime;
use Drupal\Core\Datetime\DateHelper;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Datetime\DateHelper
* @group Datetime
*/
class DateHelperTest extends UnitTestCase {
/**
* @covers ::weekDaysOrdered
* @dataProvider providerTestWeekDaysOrdered
*/
public function testWeekDaysOrdered($first_day, $expected) {
$container = new ContainerBuilder();
$config = ['system.date' => ['first_day' => $first_day]];
$container->set('config.factory', $this->getConfigFactoryStub($config));
\Drupal::setContainer($container);
$weekdays = DateHelper::weekDaysUntranslated();
// self::assertSame() MUST be used here as it checks for array key order.
$this->assertSame($expected, DateHelper::weekDaysOrdered($weekdays));
}
public function providerTestWeekDaysOrdered() {
$data = [];
$data[] = [0, [
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
]];
$data[] = [1, [
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
0 => 'Sunday',
]];
$data[] = [2, [
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
0 => 'Sunday',
1 => 'Monday',
]];
$data[] = [3, [
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
]];
$data[] = [4, [
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
]];
$data[] = [5, [
5 => 'Friday',
6 => 'Saturday',
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
]];
$data[] = [6, [
6 => 'Saturday',
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
]];
$data[] = [7, [
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
]];
return $data;
}
}

View file

@ -86,6 +86,16 @@ class DrupalTest extends UnitTestCase {
$this->assertNotNull(\Drupal::entityManager());
}
/**
* Tests the entityTypeManager() method.
*
* @covers ::entityTypeManager
*/
public function testEntityTypeManager() {
$this->setMockContainerService('entity_type.manager');
$this->assertNotNull(\Drupal::entityTypeManager());
}
/**
* Tests the database() method.
*

View file

@ -59,7 +59,7 @@ class ParamConversionEnhancerTest extends UnitTestCase {
$expected['id'] = 'something_better!';
$expected['_raw_variables'] = new ParameterBag($raw_variables);
$this->paramConverterManager->expects($this->any())
$this->paramConverterManager->expects($this->once())
->method('convert')
->with($this->isType('array'))
->will($this->returnValue($expected));
@ -67,6 +67,12 @@ class ParamConversionEnhancerTest extends UnitTestCase {
$result = $this->paramConversionEnhancer->enhance($defaults, new Request());
$this->assertEquals($expected, $result);
// Now run with the results as the new defaults to ensure that the
// conversion is just run once.
$result = $this->paramConversionEnhancer->enhance($result, new Request());
$this->assertEquals($expected, $result);
}
/**

View file

@ -57,6 +57,8 @@ class EntityLinkTest extends UnitTestCase {
}
/**
* Tests for the Entity::link() method
*
* @covers ::link
*
* @dataProvider providerTestLink
@ -98,7 +100,7 @@ class EntityLinkTest extends UnitTestCase {
/** @var \Drupal\Core\Entity\Entity $entity */
$entity = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', [
['id' => $entity_id, 'label' => $entity_label, 'langcode' => 'es'],
$entity_type_id
$entity_type_id,
]);
$expected_link = Link::createFromRoute(
@ -116,6 +118,64 @@ class EntityLinkTest extends UnitTestCase {
$this->assertSame($expected, $entity->link($link_text, $link_rel, $link_options));
}
/**
* Tests for the Entity::toLink() method
*
* @covers ::toLink
*
* @dataProvider providerTestLink
*/
public function testToLink($entity_label, $link_text, $expected_text, $link_rel = 'canonical', array $link_options = []) {
$language = new Language(['id' => 'es']);
$link_options += ['language' => $language];
$this->languageManager->expects($this->any())
->method('getLanguage')
->with('es')
->willReturn($language);
$route_name_map = [
'canonical' => 'entity.test_entity_type.canonical',
'edit-form' => 'entity.test_entity_type.edit_form',
];
$route_name = $route_name_map[$link_rel];
$entity_id = 'test_entity_id';
$entity_type_id = 'test_entity_type';
$expected = '<a href="/test_entity_type/test_entity_id">' . $expected_text . '</a>';
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->once())
->method('getLinkTemplates')
->willReturn($route_name_map);
$entity_type->expects($this->any())
->method('getKey')
->willReturnMap([
['label', 'label'],
['langcode', 'langcode'],
]);
$this->entityManager
->expects($this->any())
->method('getDefinition')
->with($entity_type_id)
->will($this->returnValue($entity_type));
/** @var \Drupal\Core\Entity\Entity $entity */
$entity = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', [
['id' => $entity_id, 'label' => $entity_label, 'langcode' => 'es'],
$entity_type_id,
]);
$expected_link = Link::createFromRoute(
$expected_text,
$route_name,
[$entity_type_id => $entity_id],
['entity_type' => $entity_type_id, 'entity' => $entity] + $link_options
);
$result_link = $entity->toLink($link_text, $link_rel, $link_options);
$this->assertEquals($expected_link, $result_link);
}
/**
* Provides test data for testLink().
*/

View file

@ -175,11 +175,11 @@ class EntityTypeBundleInfoTest extends UnitTestCase {
$apple = $this->prophesize(EntityTypeInterface::class);
$apple->getLabel()->willReturn('Apple');
$apple->getBundleOf()->willReturn(NULL);
$apple->getBundleEntityType()->willReturn(NULL);
$banana = $this->prophesize(EntityTypeInterface::class);
$banana->getLabel()->willReturn('Banana');
$banana->getBundleOf()->willReturn(NULL);
$banana->getBundleEntityType()->willReturn(NULL);
$this->setUpEntityTypeDefinitions([
'apple' => $apple,
@ -223,11 +223,11 @@ class EntityTypeBundleInfoTest extends UnitTestCase {
$apple = $this->prophesize(EntityTypeInterface::class);
$apple->getLabel()->willReturn('Apple');
$apple->getBundleOf()->willReturn(NULL);
$apple->getBundleEntityType()->willReturn(NULL);
$banana = $this->prophesize(EntityTypeInterface::class);
$banana->getLabel()->willReturn('Banana');
$banana->getBundleOf()->willReturn(NULL);
$banana->getBundleEntityType()->willReturn(NULL);
$this->setUpEntityTypeDefinitions([
'apple' => $apple,
@ -271,4 +271,49 @@ class EntityTypeBundleInfoTest extends UnitTestCase {
$this->assertSame('cached data', $bundle_info);
}
/**
* @covers ::getAllBundleInfo
*/
public function testGetAllBundleInfoWithEntityBundleInfo() {
// Ensure that EntityTypeBundleInfo::getAllBundleInfo() does not add
// additional bundles if hook_entity_bundle_info() defines some and the
// entity_type does not define a bundle entity type.
$this->moduleHandler->invokeAll('entity_bundle_info')->willReturn([
'banana' => [
'fig' => [
'label' => 'Fig banana',
],
],
]);
$this->moduleHandler->alter('entity_bundle_info', Argument::type('array'))->willReturn(NULL);
$apple = $this->prophesize(EntityTypeInterface::class);
$apple->getLabel()->willReturn('Apple');
$apple->getBundleEntityType()->willReturn(NULL);
$banana = $this->prophesize(EntityTypeInterface::class);
$banana->getLabel()->willReturn('Banana');
$banana->getBundleEntityType()->willReturn(NULL);
$this->setUpEntityTypeDefinitions([
'apple' => $apple,
'banana' => $banana,
]);
$expected = [
'banana' => [
'fig' => [
'label' => 'Fig banana',
],
],
'apple' => [
'apple' => [
'label' => 'Apple',
],
],
];
$bundle_info = $this->entityTypeBundleInfo->getAllBundleInfo();
$this->assertSame($expected, $bundle_info);
}
}

View file

@ -28,6 +28,8 @@ class EntityUrlTest extends UnitTestCase {
protected $entityManager;
/**
* The mocked URL generator.
*
* @var \Drupal\Core\Routing\UrlGeneratorInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $urlGenerator;
@ -50,12 +52,15 @@ class EntityUrlTest extends UnitTestCase {
/**
* Tests the urlInfo() method.
*
* Note that urlInfo() is a deprecated alias for toUrl().
* See testToUrl().
*
* @covers ::urlInfo
*
* @dataProvider providerTestUrlInfo
* @dataProvider providerTestToUrl
*/
public function testUrlInfo($entity_class, $link_template, $expected, $langcode = NULL) {
/** @var $entity \Drupal\Core\Entity\EntityInterface */
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $this->getMockForAbstractClass($entity_class, array(array('id' => 'test_entity_id'), 'test_entity_type'));
$uri = $this->getTestUrlInfo($entity, $link_template, [], $langcode);
@ -75,27 +80,57 @@ class EntityUrlTest extends UnitTestCase {
}
}
}
/**
* Tests the toUrl() method.
*
* @covers ::toUrl
*
* @dataProvider providerTestToUrl
*/
public function testToUrl($entity_class, $link_template, $expected, $langcode = NULL) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $this->getMockForAbstractClass($entity_class, array(array('id' => 'test_entity_id'), 'test_entity_type'));
$uri = $this->getTestToUrl($entity, $link_template, [], $langcode);
$this->assertSame($expected, $uri->getRouteName());
$this->assertSame($entity, $uri->getOption('entity'));
if ($langcode) {
$this->assertEquals($langcode, $uri->getOption('language')->getId());
}
else {
if ($entity instanceof ConfigEntityInterface) {
// Config entities do not provide a language with their URIs.
$this->assertEquals(NULL, $uri->getOption('language'));
}
else {
$this->assertEquals(LanguageInterface::LANGCODE_NOT_SPECIFIED, $uri->getOption('language')->getId());
}
}
}
/**
* @covers ::urlInfo
* Tests for Entity::toUrl() exercising different language options.
*
* @covers ::toUrl
*/
public function testUrlInfoWithSpecificLanguageInOptions() {
/** @var $entity \Drupal\Core\Entity\EntityInterface */
public function testToUrlWithSpecificLanguageInOptions() {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', array(array('id' => 'test_entity_id'), 'test_entity_type'));
// Ensure that a specified language overrides the current translation
// language.
$uri = $this->getTestUrlInfo($entity, 'edit-form', [], 'en');
$uri = $this->getTestToUrl($entity, 'edit-form', [], 'en');
$this->assertEquals('en', $uri->getOption('language')->getId());
$uri = $this->getTestUrlInfo($entity, 'edit-form', ['language' => new Language(['id' => 'fr'])], 'en');
$uri = $this->getTestToUrl($entity, 'edit-form', ['language' => new Language(['id' => 'fr'])], 'en');
$this->assertEquals('fr', $uri->getOption('language')->getId());
}
/**
* Provides test data for testUrlInfo().
*/
public function providerTestUrlInfo() {
public function providerTestToUrl() {
return array(
array('Drupal\Core\Entity\Entity', 'edit-form', 'entity.test_entity_type.edit_form', NULL),
// Specify a langcode.
@ -108,19 +143,20 @@ class EntityUrlTest extends UnitTestCase {
}
/**
* Tests the urlInfo() method with an invalid link template.
* Tests the toUrl() method with an invalid link template.
*
* @covers ::urlInfo
* @covers ::toUrl
*
* @expectedException \Drupal\Core\Entity\Exception\UndefinedLinkTemplateException
*
* @expectedExceptionMessage No link template 'canonical' found for the 'test_entity_type' entity type
*
* @dataProvider providerTestUrlInfoForInvalidLinkTemplate
* @dataProvider providerTestToUrlForInvalidLinkTemplate
*/
public function testUrlInfoForInvalidLinkTemplate($entity_class, $link_template) {
/** @var $entity \Drupal\Core\Entity\EntityInterface */
public function testToUrlForInvalidLinkTemplate($entity_class, $link_template) {
/** @var \Drupal\Core\Entity\EntityInterface $entity */
$entity = $this->getMockForAbstractClass($entity_class, array(array('id' => 'test_entity_id'), 'test_entity_type'));
$uri = $this->getTestUrlInfo($entity, $link_template);
$uri = $this->getTestToUrl($entity, $link_template);
$this->assertEmpty($uri);
}
@ -128,7 +164,7 @@ class EntityUrlTest extends UnitTestCase {
/**
* Provides test data for testUrlInfoForInvalidLinkTemplate().
*/
public function providerTestUrlInfoForInvalidLinkTemplate() {
public function providerTestToUrlForInvalidLinkTemplate() {
return array(
array('Drupal\Core\Entity\Entity', 'canonical'),
array('Drupal\Core\Entity\Entity', FALSE),
@ -139,6 +175,9 @@ class EntityUrlTest extends UnitTestCase {
/**
* Creates a \Drupal\Core\Url object based on the entity and link template.
*
* Method urlInfo() is deprecated and replaced with toUrl().
* See also getTestToUrl().
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The test entity.
* @param string $link_template
@ -184,17 +223,64 @@ class EntityUrlTest extends UnitTestCase {
}
/**
* Tests the urlInfo() method when an entity is still "new".
* Creates a \Drupal\Core\Url object based on the entity and link template.
*
* @param \Drupal\Core\Entity\EntityInterface $entity
* The test entity.
* @param string $link_template
* The link template.
* @param string $langcode
* The langcode.
*
* @return \Drupal\Core\Url
* The URL for this entity's link template.
*/
protected function getTestToUrl(EntityInterface $entity, $link_template, array $options = [], $langcode = NULL) {
$entity_type = $this->getMock('Drupal\Core\Entity\EntityTypeInterface');
$entity_type->expects($this->any())
->method('getLinkTemplates')
->will($this->returnValue(array(
'edit-form' => 'test_entity_type.edit',
)));
if ($langcode) {
$entity->langcode = $langcode;
}
$this->entityManager
->expects($this->any())
->method('getDefinition')
->with('test_entity_type')
->will($this->returnValue($entity_type));
// If no link template is given, call without a value to test the default.
if ($link_template) {
$uri = $entity->toUrl($link_template, $options);
}
else {
if ($entity instanceof ConfigEntityInterface) {
$uri = $entity->toUrl('edit-form', $options);
}
else {
$uri = $entity->toUrl('canonical', $options);
}
}
return $uri;
}
/**
* Tests the toUrl() method when an entity is still "new".
*
* @see \Drupal\Core\Entity\EntityInterface::isNew()
*
* @covers ::urlInfo
* @covers ::toUrl
*
* @expectedException \Drupal\Core\Entity\EntityMalformedException
*/
public function testUrlInfoForNewEntity() {
public function testToUrlForNewEntity() {
$entity = $this->getMockForAbstractClass('Drupal\Core\Entity\Entity', array(array(), 'test_entity_type'));
$entity->urlInfo();
$entity->toUrl();
}
/**
@ -236,7 +322,7 @@ class EntityUrlTest extends UnitTestCase {
if ($route_name === 'entity.test_entity_type.canonical' && $route_parameters === array('test_entity_type' => 'test_entity_id') && array_keys($options) === ['absolute', 'entity_type', 'entity', 'language'] && $options['language'] == $language) {
return 'http://drupal/entity/test_entity_type/test_entity_id';
}
});
});
$this->assertSame('/entity/test_entity_type/test_entity_id', $valid_entity->url());
$this->assertSame('http://drupal/entity/test_entity_type/test_entity_id', $valid_entity->url('canonical', array('absolute' => TRUE)));

View file

@ -0,0 +1,155 @@
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Entity\Routing\DefaultHtmlRouteProviderTest.
*/
namespace Drupal\Tests\Core\Entity\Routing;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\FieldableEntityInterface;
use Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Symfony\Component\Routing\Route;
/**
* @coversDefaultClass \Drupal\Core\Entity\Routing\DefaultHtmlRouteProvider
* @group Entity
*/
class DefaultHtmlRouteProviderTest extends UnitTestCase {
/**
* @covers ::getEntityTypeIdKeyType
*/
public function testGetEntityTypeIdKeyType() {
$entity_manager = $this->prophesize(EntityManagerInterface::class);
$route_provider = new TestDefaultHtmlRouteProvider($entity_manager->reveal());
$entity_type = $this->prophesize(EntityTypeInterface::class);
$entity_type->isSubclassOf(FieldableEntityInterface::class)->willReturn(TRUE);
$entity_type_id = 'the_entity_type_id';
$entity_type->id()->willReturn($entity_type_id);
$entity_type->getKey('id')->willReturn('id');
$field_storage_definition = $this->prophesize(FieldStorageDefinitionInterface::class);
$field_storage_definition->getType()->willReturn('integer');
$entity_manager->getFieldStorageDefinitions($entity_type_id)->willReturn(['id' => $field_storage_definition]);
$type = $route_provider->getEntityTypeIdKeyType($entity_type->reveal());
$this->assertSame('integer', $type);
}
/**
* @covers ::getEntityTypeIdKeyType
*/
public function testGetEntityTypeIdKeyTypeNotFieldable() {
$entity_manager = $this->prophesize(EntityManagerInterface::class);
$route_provider = new TestDefaultHtmlRouteProvider($entity_manager->reveal());
$entity_type = $this->prophesize(EntityTypeInterface::class);
$entity_type->isSubclassOf(FieldableEntityInterface::class)->willReturn(FALSE);
$entity_manager->getFieldStorageDefinitions(Argument::any())->shouldNotBeCalled();
$type = $route_provider->getEntityTypeIdKeyType($entity_type->reveal());
$this->assertNull($type);
}
/**
* @covers ::getCanonicalRoute
* @dataProvider providerTestGetCanonicalRoute
*/
public function testGetCanonicalRoute($entity_type_prophecy, $expected, $field_storage_definition = NULL) {
$entity_manager = $this->prophesize(EntityManagerInterface::class);
$route_provider = new TestDefaultHtmlRouteProvider($entity_manager->reveal());
$entity_type = $entity_type_prophecy->reveal();
if ($field_storage_definition) {
$entity_manager->getFieldStorageDefinitions($entity_type->id())
->willReturn([$entity_type->getKey('id') => $field_storage_definition]);
}
$route = $route_provider->getCanonicalRoute($entity_type);
$this->assertEquals($expected, $route);
}
public function providerTestGetCanonicalRoute() {
$data = [];
$entity_type1 = $this->prophesize(EntityTypeInterface::class);
$entity_type1->hasLinkTemplate('canonical')->willReturn(FALSE);
$data['no_canonical_link_template'] = [$entity_type1, NULL];
$entity_type2 = $this->prophesize(EntityTypeInterface::class);
$entity_type2->hasLinkTemplate('canonical')->willReturn(TRUE);
$entity_type2->hasViewBuilderClass()->willReturn(FALSE);
$data['no_view_builder'] = [$entity_type2, NULL];
$entity_type3 = $this->prophesize(EntityTypeInterface::class);
$entity_type3->hasLinkTemplate('canonical')->willReturn(TRUE);
$entity_type3->hasViewBuilderClass()->willReturn(TRUE);
$entity_type3->id()->willReturn('the_entity_type_id');
$entity_type3->getLinkTemplate('canonical')->willReturn('/the/canonical/link/template');
$entity_type3->isSubclassOf(FieldableEntityInterface::class)->willReturn(FALSE);
$route3 = (new Route('/the/canonical/link/template'))
->setDefaults([
'_entity_view' => 'the_entity_type_id.full',
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
->setRequirements([
'_entity_access' => 'the_entity_type_id.view',
])
->setOptions([
'parameters' => [
'the_entity_type_id' => [
'type' => 'entity:the_entity_type_id',
],
],
]);
$data['id_key_type_null'] = [$entity_type3, $route3];
$entity_type4 = $this->prophesize(EntityTypeInterface::class);
$entity_type4->hasLinkTemplate('canonical')->willReturn(TRUE);
$entity_type4->hasViewBuilderClass()->willReturn(TRUE);
$entity_type4->id()->willReturn('the_entity_type_id');
$entity_type4->getLinkTemplate('canonical')->willReturn('/the/canonical/link/template');
$entity_type4->isSubclassOf(FieldableEntityInterface::class)->willReturn(TRUE);
$entity_type4->getKey('id')->willReturn('id');
$route4 = (new Route('/the/canonical/link/template'))
->setDefaults([
'_entity_view' => 'the_entity_type_id.full',
'_title_callback' => '\Drupal\Core\Entity\Controller\EntityController::title',
])
->setRequirements([
'_entity_access' => 'the_entity_type_id.view',
'the_entity_type_id' => '\d+',
])
->setOptions([
'parameters' => [
'the_entity_type_id' => [
'type' => 'entity:the_entity_type_id',
],
],
]);
$field_storage_definition = $this->prophesize(FieldStorageDefinitionInterface::class);
$field_storage_definition->getType()->willReturn('integer');
$data['id_key_type_integer'] = [$entity_type4, $route4, $field_storage_definition];
return $data;
}
}
class TestDefaultHtmlRouteProvider extends DefaultHtmlRouteProvider {
public function getEntityTypeIdKeyType(EntityTypeInterface $entity_type) {
return parent::getEntityTypeIdKeyType($entity_type);
}
public function getCanonicalRoute(EntityTypeInterface $entity_type) {
return parent::getCanonicalRoute($entity_type);
}
}

View file

@ -150,11 +150,16 @@ class PathProcessorTest extends UnitTestCase {
$current_user = $this->getMockBuilder('Drupal\Core\Session\AccountInterface')
->getMock();
// Create a config event subscriber stub.
$config_subscriber = $this->getMockBuilder('Drupal\language\EventSubscriber\ConfigSubscriber')
->disableOriginalConstructor()
->getMock();
// Create the processors.
$alias_processor = new PathProcessorAlias($alias_manager);
$decode_processor = new PathProcessorDecode();
$front_processor = new PathProcessorFront($config_factory_stub);
$language_processor = new PathProcessorLanguage($config_factory_stub, $this->languageManager, $negotiator, $current_user);
$language_processor = new PathProcessorLanguage($config_factory_stub, $this->languageManager, $negotiator, $current_user, $config_subscriber);
// First, test the processor manager with the processors in the incorrect
// order. The alias processor will run before the language processor, meaning

View file

@ -43,6 +43,8 @@ class TranslationManagerTest extends UnitTestCase {
// @todo support locale_get_plural
[2, 'Singular', '@count @arg', array('@arg' => '<script>'), array(), '2 &lt;script&gt;'],
[2, 'Singular', '@count %arg', array('%arg' => '<script>'), array(), '2 <em class="placeholder">&lt;script&gt;</em>'],
[1, 'Singular', '@count plural', array(), array('langcode' => NULL), 'Singular'],
[1, 'Singular', '@count plural', array(), array('langcode' => 'es'), 'Singular'],
);
}
@ -50,12 +52,15 @@ class TranslationManagerTest extends UnitTestCase {
* @dataProvider providerTestFormatPlural
*/
public function testFormatPlural($count, $singular, $plural, array $args = array(), array $options = array(), $expected) {
$langcode = empty($options['langcode']) ? 'fr' : $options['langcode'];
$translator = $this->getMock('\Drupal\Core\StringTranslation\Translator\TranslatorInterface');
$translator->expects($this->once())
->method('getStringTranslation')
->will($this->returnCallback(function ($langcode, $string) {
->with($langcode, $this->anything(), $this->anything())
->will($this->returnCallback(function ($langcode, $string, $context) {
return $string;
}));
$this->translationManager->setDefaultLangcode('fr');
$this->translationManager->addTranslator($translator);
$result = $this->translationManager->formatPlural($count, $singular, $plural, $args, $options);
$this->assertEquals($expected, $result);