Update to Drupal 8.2.0. For more information, see https://www.drupal.org/project/drupal/releases/8.2.0

This commit is contained in:
Pantheon Automation 2016-10-06 15:16:20 -07:00 committed by Greg Anderson
parent 2f563ab520
commit f1c8716f57
1732 changed files with 52334 additions and 11780 deletions

View file

@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\Core\Access;
use Drupal\Core\Access\AccessResultForbidden;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Access\AccessResultForbidden
* @group Access
*/
class AccessResultForbiddenTest extends UnitTestCase {
/**
* Tests the construction of an AccessResultForbidden object.
*
* @covers ::__construct
* @covers ::getReason
*/
public function testConstruction() {
$a = new AccessResultForbidden();
$this->assertEquals(NULL, $a->getReason());
$reason = $this->getRandomGenerator()->string();
$b = new AccessResultForbidden($reason);
$this->assertEquals($reason, $b->getReason());
}
/**
* Test setReason()
*
* @covers ::setReason
*/
public function testSetReason() {
$a = new AccessResultForbidden();
$reason = $this->getRandomGenerator()->string();
$return = $a->setReason($reason);
$this->assertSame($reason, $a->getReason());
$this->assertSame($a, $return);
}
}

View file

@ -10,6 +10,7 @@ namespace Drupal\Tests\Core\Access;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\AccessResultInterface;
use Drupal\Core\Access\AccessResultNeutral;
use Drupal\Core\Access\AccessResultReasonInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheableDependencyInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
@ -112,6 +113,23 @@ class AccessResultTest extends UnitTestCase {
$verify($b);
}
/**
* @covers ::forbidden
*/
public function testAccessForbiddenReason() {
$verify = function (AccessResult $access, $reason) {
$this->assertInstanceOf(AccessResultReasonInterface::class, $access);
$this->assertSame($reason, $access->getReason());
};
$b = AccessResult::forbidden();
$verify($b, NULL);
$reason = $this->getRandomGenerator()->string();
$b = AccessResult::forbidden($reason);
$verify($b, $reason);
}
/**
* @covers ::allowedIf
* @covers ::isAllowed

View file

@ -1,41 +1,6 @@
<?php
namespace {
/**
* CssCollectionRenderer uses file_create_url() & file_url_transform_relative(),
* which *are* available when using the Simpletest test runner, but not when
* using the PHPUnit test runner; hence this hack.
*/
if (!function_exists('file_create_url')) {
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
function file_create_url($uri) {
return 'file_create_url:' . $uri;
}
}
if (!function_exists('file_url_transform_relative')) {
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
function file_url_transform_relative($uri) {
return 'file_url_transform_relative:' . $uri;
}
}
}
namespace Drupal\Tests\Core\Asset {
namespace Drupal\Tests\Core\Asset;
use Drupal\Core\Asset\CssCollectionRenderer;
use Drupal\Tests\UnitTestCase;
@ -502,4 +467,53 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
}
}
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
if (!function_exists('Drupal\Tests\Core\Asset\file_create_url')) {
function file_create_url($uri) {
return 'file_create_url:' . $uri;
}
}
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
if (!function_exists('Drupal\Tests\Core\Asset\file_url_transform_relative')) {
function file_url_transform_relative($uri) {
return 'file_url_transform_relative:' . $uri;
}
}
/**
* CssCollectionRenderer uses file_create_url() & file_url_transform_relative(),
* which *are* available when using the Simpletest test runner, but not when
* using the PHPUnit test runner; hence this hack.
*/
namespace Drupal\Core\Asset;
if (!function_exists('Drupal\Core\Asset\file_create_url')) {
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
function file_create_url($uri) {
return \Drupal\Tests\Core\Asset\file_create_url($uri);
}
}
if (!function_exists('Drupal\Core\Asset\file_url_transform_relative')) {
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
function file_url_transform_relative($uri) {
return \Drupal\Tests\Core\Asset\file_url_transform_relative($uri);
}
}

View file

@ -1,48 +1,6 @@
<?php
namespace {
/**
* CssOptimizer uses file_create_url(), file_uri_scheme() and
* file_url_transform_relative(), which *are* available when using the
* Simpletest test runner, but not when using the PHPUnit test runner; hence
* this hack.
*/
if (!function_exists('file_create_url')) {
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
function file_create_url($uri) {
return 'file_create_url:' . $uri;
}
}
if (!function_exists('file_uri_scheme')) {
function file_uri_scheme($uri) {
return FALSE;
}
}
if (!function_exists('file_url_transform_relative')) {
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
function file_url_transform_relative($uri) {
return 'file_url_transform_relative:' . $uri;
}
}
}
namespace Drupal\Tests\Core\Asset {
namespace Drupal\Tests\Core\Asset;
use Drupal\Core\Asset\CssOptimizer;
use Drupal\Tests\UnitTestCase;
@ -292,4 +250,60 @@ class CssOptimizerUnitTest extends UnitTestCase {
}
}
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
if (!function_exists('Drupal\Tests\Core\Asset\file_create_url')) {
function file_create_url($uri) {
return 'file_create_url:' . $uri;
}
}
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
if (!function_exists('Drupal\Tests\Core\Asset\file_url_transform_relative')) {
function file_url_transform_relative($uri) {
return 'file_url_transform_relative:' . $uri;
}
}
/**
* CssCollectionRenderer uses file_create_url() & file_url_transform_relative(),
* which *are* available when using the Simpletest test runner, but not when
* using the PHPUnit test runner; hence this hack.
*/
namespace Drupal\Core\Asset;
if (!function_exists('Drupal\Core\Asset\file_create_url')) {
/**
* Temporary mock for file_create_url(), until that is moved into
* Component/Utility.
*/
function file_create_url($uri) {
return \Drupal\Tests\Core\Asset\file_create_url($uri);
}
}
if (!function_exists('Drupal\Core\Asset\file_url_transform_relative')) {
/**
* Temporary mock of file_url_transform_relative, until that is moved into
* Component/Utility.
*/
function file_url_transform_relative($uri) {
return \Drupal\Tests\Core\Asset\file_url_transform_relative($uri);
}
}
if (!function_exists('Drupal\Core\Asset\file_uri_scheme')) {
function file_uri_scheme($uri) {
return FALSE;
}
}

View file

@ -211,34 +211,6 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$this->assertEquals(\Drupal::VERSION, $libraries['core-versioned']['js'][0]['version']);
}
/**
* Tests the version property with ISO dates.
*
* We want to make sure that versions defined in the YAML file are the same
* versions that are parsed.
*
* For example, ISO dates are converted into UNIX time by the YAML parser.
*
* @covers ::buildByExtension
*/
public function testNonStringVersion() {
$this->moduleHandler->expects($this->atLeastOnce())
->method('moduleExists')
->with('versions')
->will($this->returnValue(TRUE));
$path = __DIR__ . '/library_test_files';
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'versions', $path);
$libraries = $this->libraryDiscoveryParser->buildByExtension('versions');
// As an example, we defined an ISO date in the YAML file and the YAML
// parser converts it into a UNIX timestamp.
$this->assertNotEquals('2014-12-13', $libraries['invalid-version']['version']);
// An example of an ISO date as a string which parses correctly.
$this->assertEquals('2014-12-13', $libraries['valid-version']['version']);
}
/**
* Tests that the version property of external libraries is handled.
@ -357,7 +329,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
* @covers ::buildByExtension
*/
public function testLibraryWithDependencies() {
$this->moduleHandler->expects($this->atLeastOnce())
$this->moduleHandler->expects($this->atLeastOnce())
->method('moduleExists')
->with('dependencies')
->will($this->returnValue(TRUE));

View file

@ -20,13 +20,3 @@ core-versioned:
core-versioned.css: {}
js:
core-versioned.js: {}
invalid-version:
version: 2014-12-13
js:
versioned.js: {}
valid-version:
version: "2014-12-13"
js:
versioned.js: {}

View file

@ -69,6 +69,42 @@ class CacheFactoryTest extends UnitTestCase {
$this->assertSame($render_bin, $actual_bin);
}
/**
* Test that the cache factory uses the correct default bin backend.
*
* @covers ::__construct
* @covers ::get
*/
public function testCacheFactoryWithDefaultBinBackend() {
// Ensure the default bin backends are used before the configured default.
$settings = new Settings(array(
'cache' => array(
'default' => 'cache.backend.unused',
),
));
$default_bin_backends = [
'render' => 'cache.backend.custom',
];
$cache_factory = new CacheFactory($settings, $default_bin_backends);
$container = new ContainerBuilder();
$cache_factory->setContainer($container);
$custom_default_backend_factory = $this->getMock('\Drupal\Core\Cache\CacheFactoryInterface');
$container->set('cache.backend.custom', $custom_default_backend_factory);
$render_bin = $this->getMock('\Drupal\Core\Cache\CacheBackendInterface');
$custom_default_backend_factory->expects($this->once())
->method('get')
->with('render')
->will($this->returnValue($render_bin));
$actual_bin = $cache_factory->get('render');
$this->assertSame($render_bin, $actual_bin);
}
/**
* Test that the cache factory picks the correct per-bin service.
*
@ -76,14 +112,22 @@ class CacheFactoryTest extends UnitTestCase {
* @covers ::get
*/
public function testCacheFactoryWithSpecifiedPerBinBackend() {
// Ensure the per-bin configuration is used before the configured default
// and per-bin defaults.
$settings = new Settings(array(
'cache' => array(
'default' => 'cache.backend.unused',
'bins' => array(
'render' => 'cache.backend.custom',
),
),
));
$cache_factory = new CacheFactory($settings);
$default_bin_backends = [
'render' => 'cache.backend.unused',
];
$cache_factory = new CacheFactory($settings, $default_bin_backends);
$container = new ContainerBuilder();
$cache_factory->setContainer($container);

View file

@ -121,14 +121,14 @@ class CacheableMetadataTest extends UnitTestCase {
* Data provider for testSetCacheMaxAge.
*/
public function providerSetCacheMaxAge() {
return [
[0 , FALSE],
['http', TRUE],
['0', TRUE],
[new \stdClass(), TRUE],
[300, FALSE],
[[], TRUE],
[8.0, TRUE]
return [
[0 , FALSE],
['http', TRUE],
['0', TRUE],
[new \stdClass(), TRUE],
[300, FALSE],
[[], TRUE],
[8.0, TRUE]
];
}

View file

@ -33,21 +33,6 @@ class ChainedFastBackendTest extends UnitTestCase {
*/
protected $bin;
/**
* Tests that chained fast backend cannot be constructed with two instances of
* the same service.
*/
public function testConsistentAndFastBackendCannotBeTheSameService() {
// ToDo: It should throw a proper exception. See https://www.drupal.org/node/2751847.
$this->setExpectedException(\PHPUnit_Framework_Error::class, 'Consistent cache backend and fast cache backend cannot use the same service.');
$cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$chained_fast_backend = new ChainedFastBackend(
$cache,
$cache,
'foo'
);
}
/**
* Tests a get() on the fast backend, with no hit on the consistent backend.
*/

View file

@ -43,6 +43,16 @@ class ConditionAccessResolverTraitTest extends UnitTestCase {
$condition_exception->expects($this->any())
->method('execute')
->will($this->throwException(new ContextException()));
$condition_exception->expects($this->atLeastOnce())
->method('isNegated')
->will($this->returnValue(FALSE));
$condition_negated = $this->getMock('Drupal\Core\Condition\ConditionInterface');
$condition_negated->expects($this->any())
->method('execute')
->will($this->throwException(new ContextException()));
$condition_negated->expects($this->atLeastOnce())
->method('isNegated')
->will($this->returnValue(TRUE));
$conditions = array();
$data[] = array($conditions, 'and', TRUE);
@ -79,6 +89,14 @@ class ConditionAccessResolverTraitTest extends UnitTestCase {
$conditions = array($condition_exception, $condition_false);
$data[] = array($conditions, 'or', FALSE);
$data[] = array($conditions, 'and', FALSE);
$conditions = array($condition_negated);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', TRUE);
$conditions = array($condition_negated, $condition_negated);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', TRUE);
return $data;
}

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\Tests\Core\Config\Entity {
namespace Drupal\Tests\Core\Config\Entity;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
@ -941,12 +941,11 @@ class ConfigEntityStorageTest extends UnitTestCase {
}
namespace Drupal\Core\Config\Entity;
if (!defined('SAVED_NEW')) {
define('SAVED_NEW', 1);
}
namespace {
if (!defined('SAVED_NEW')) {
define('SAVED_NEW', 1);
}
if (!defined('SAVED_UPDATED')) {
define('SAVED_UPDATED', 2);
}
if (!defined('SAVED_UPDATED')) {
define('SAVED_UPDATED', 2);
}

View file

@ -14,7 +14,8 @@ use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
@ -280,7 +281,8 @@ class MockContainerInjection implements ContainerInjectionInterface {
}
}
class MockContainerAware extends ContainerAware {
class MockContainerAware implements ContainerAwareInterface {
use ContainerAwareTrait;
public function getResult() {
return 'This is container aware.';
}

View file

@ -114,7 +114,7 @@ class ConditionTest extends UnitTestCase {
$data[] = [" (name LIKE :db_condition_placeholder_0 ESCAPE '\\\\') ", 'name', '%muh%', 'LIKE', [':db_condition_placeholder_0' => '%muh%']];
$data[] = [" (name NOT LIKE :db_condition_placeholder_0 ESCAPE '\\\\') ", 'name', '%muh%', 'NOT LIKE', [':db_condition_placeholder_0' => '%muh%']];
$data[] = [" (name BETWEEN :db_condition_placeholder_0 AND :db_condition_placeholder_1) ", 'name', [1, 2], 'BETWEEN', [':db_condition_placeholder_0' => 1, ':db_condition_placeholder_1' => 2]];
// $data[] = [" (name NOT BETWEEN :db_condition_placeholder_0 AND :db_condition_placeholder_1) ", 'name', [1, 2], 'NOT BETWEEN', [':db_condition_placeholder_0' => 1, ':db_condition_placeholder_1' => 2]];
$data[] = [" (name NOT BETWEEN :db_condition_placeholder_0 AND :db_condition_placeholder_1) ", 'name', [1, 2], 'NOT BETWEEN', [':db_condition_placeholder_0' => 1, ':db_condition_placeholder_1' => 2]];
// $data[] = [' ( STRCMP (name, :db_condition_placeholder_0) ) ', '', ['test-string'], 'STRCMP', [':db_condition_placeholder_0' => 'test-string']];
// $data[] = [' (EXISTS ) ', '', NULL, 'EXISTS'];
// $data[] = [' (name NOT EXISTS ) ', 'name', NULL, 'NOT EXISTS'];

View file

@ -40,6 +40,11 @@ class PostgresqlConnectionTest extends UnitTestCase {
array('"camelCase"', 'camelCase'),
array('"camelCase"', '"camelCase"'),
array('"camelCase"', 'camel/Case'),
// Sometimes, table names are following the pattern database.schema.table.
array('"camelCase".nocase.nocase', 'camelCase.nocase.nocase'),
array('nocase."camelCase".nocase', 'nocase.camelCase.nocase'),
array('nocase.nocase."camelCase"', 'nocase.nocase.camelCase'),
array('"camelCase"."camelCase"."camelCase"', 'camelCase.camelCase.camelCase'),
);
}

View file

@ -0,0 +1,44 @@
<?php
namespace Drupal\Tests\Core\DependencyInjection\Compiler;
use Drupal\Core\DependencyInjection\Compiler\AuthenticationProviderPass;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\Serializer\Serializer;
/**
* @coversDefaultClass \Drupal\Core\DependencyInjection\Compiler\AuthenticationProviderPass
* @group DependencyInjection
*/
class AuthenticationProviderPassTest extends \PHPUnit_Framework_TestCase {
/**
* @covers ::process
*/
public function testEncoders() {
$container = new ContainerBuilder();
$container->setDefinition('serializer', new Definition(Serializer::class, [[], []]));
$definition = new Definition('TestClass');
$definition->addTag('authentication_provider', ['provider_id' => 'bunny_auth']);
$definition->addTag('_provider', ['provider' => 'test_provider_a']);
$container->setDefinition('test_provider_a.authentication.bunny_auth', $definition);
$definition = new Definition('TestClass');
$definition->addTag('authentication_provider', ['provider_id' => 'llama_auth', 'priority' => 100]);
$definition->addTag('_provider', ['provider' => 'test_provider_a']);
$container->setDefinition('test_provider_a.authentication.llama_auth', $definition);
$definition = new Definition('TestClass');
$definition->addTag('authentication_provider', ['provider_id' => 'camel_auth', 'priority' => -100]);
$definition->addTag('_provider', ['provider' => 'test_provider_b']);
$container->setDefinition('test_provider_b.authentication.camel_auth', $definition);
$compiler_pass = new AuthenticationProviderPass();
$compiler_pass->process($container);
$this->assertEquals(['bunny_auth' => 'test_provider_a', 'llama_auth' => 'test_provider_a', 'camel_auth' => 'test_provider_b'], $container->getParameter('authentication_providers'));
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Drupal\Tests\Core\DependencyInjection;
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\YamlFileLoader;
use org\bovigo\vfs\vfsStream;
/**
* @coversDefaultClass \Drupal\Core\DependencyInjection\YamlFileLoader
* @group DependencyInjection
*/
class YamlFileLoaderTest extends \PHPUnit_Framework_TestCase {
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
FileCacheFactory::setPrefix('example');
}
public function testParseDefinitionsWithProvider() {
$yml = <<<YAML
services:
example_service:
class: \Drupal\Core\ExampleClass
YAML;
vfsStream::setup('drupal', NULL, [
'modules/example/example.yml' => $yml,
]);
$builder = new ContainerBuilder();
$yaml_file_loader = new YamlFileLoader($builder);
$yaml_file_loader->load('vfs://drupal/modules/example/example.yml');
$this->assertEquals(['_provider' => [['provider' => 'example']]], $builder->getDefinition('example_service')->getTags());
}
}

View file

@ -126,12 +126,12 @@ EOD;
]
]]);
define('DRUPAL_ROOT', $vfs_root->url('drupal_root'));
$request = new Request();
$request->server->set('SERVER_NAME', 'www.example.org');
$request->server->set('SERVER_PORT', '8888');
$request->server->set('SCRIPT_NAME', '/index.php');
$this->assertEquals('sites/example', DrupalKernel::findSitePath($request));
$this->assertEquals('sites/example', DrupalKernel::findSitePath($request, TRUE, $vfs_root->url('drupal_root')));
$this->assertEquals('sites/example', DrupalKernel::findSitePath($request, FALSE, $vfs_root->url('drupal_root')));
}
}

View file

@ -5,7 +5,7 @@
* Contains \Drupal\Tests\Core\Entity\EntityResolverManagerTest.
*/
namespace Drupal\Tests\Core\Entity {
namespace Drupal\Tests\Core\Entity;
use Drupal\Core\Entity\Entity;
use Drupal\Core\Entity\EntityInterface;
@ -90,7 +90,7 @@ class EntityResolverManagerTest extends UnitTestCase {
public function providerTestSetRouteOptionsWithStandardRoute() {
return array(
array('Drupal\Tests\Core\Entity\BasicControllerClass::exampleControllerMethod'),
array('test_function_controller'),
array('Drupal\Tests\Core\Entity\test_function_controller'),
);
}
@ -120,7 +120,7 @@ class EntityResolverManagerTest extends UnitTestCase {
public function providerTestSetRouteOptionsWithStandardRouteWithArgument() {
return array(
array('Drupal\Tests\Core\Entity\BasicControllerClass::exampleControllerMethodWithArgument'),
array('test_function_controller_with_argument'),
array('Drupal\Tests\Core\Entity\test_function_controller_with_argument'),
);
}
@ -150,7 +150,7 @@ class EntityResolverManagerTest extends UnitTestCase {
public function providerTestSetRouteOptionsWithContentController() {
return array(
array('Drupal\Tests\Core\Entity\BasicControllerClass::exampleControllerMethodWithArgument'),
array('test_function_controller_with_argument'),
array('Drupal\Tests\Core\Entity\test_function_controller_with_argument'),
);
}
@ -183,7 +183,7 @@ class EntityResolverManagerTest extends UnitTestCase {
public function providerTestSetRouteOptionsWithEntityTypeNoUpcasting() {
return array(
array('Drupal\Tests\Core\Entity\BasicControllerClass::exampleControllerWithEntityNoUpcasting'),
array('test_function_controller_no_upcasting'),
array('Drupal\Tests\Core\Entity\test_function_controller_no_upcasting'),
);
}
@ -217,7 +217,7 @@ class EntityResolverManagerTest extends UnitTestCase {
public function providerTestSetRouteOptionsWithEntityTypeUpcasting() {
return array(
array('Drupal\Tests\Core\Entity\BasicControllerClass::exampleControllerWithEntityUpcasting'),
array('test_function_controller_entity_upcasting'),
array('Drupal\Tests\Core\Entity\test_function_controller_entity_upcasting'),
);
}
@ -547,21 +547,14 @@ class BasicFormNoContainerInjectionInterface implements FormInterface {
}
function test_function_controller() {
}
namespace {
use Drupal\Core\Entity\EntityInterface;
function test_function_controller() {
}
function test_function_controller_with_argument($argument) {
}
function test_function_controller_no_upcasting($entity_test) {
}
function test_function_controller_entity_upcasting(EntityInterface $entity_test) {
}
function test_function_controller_with_argument($argument) {
}
function test_function_controller_no_upcasting($entity_test) {
}
function test_function_controller_entity_upcasting(EntityInterface $entity_test) {
}

View file

@ -165,6 +165,15 @@ class EntityTypeTest extends UnitTestCase {
$this->assertSame($controller, $entity_type->getStorageClass());
}
/**
* Tests the setStorageClass() method.
*/
public function testSetStorageClass() {
$controller = $this->getTestHandlerClass();
$entity_type = $this->setUpEntityType(array());
$this->assertSame($entity_type, $entity_type->setStorageClass($controller));
}
/**
* Tests the getListBuilderClass() method.
*/

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\Tests\Core\Entity\KeyValueStore {
namespace Drupal\Tests\Core\Entity\KeyValueStore;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\Core\DependencyInjection\ContainerBuilder;
@ -696,13 +696,11 @@ class KeyValueEntityStorageTest extends UnitTestCase {
}
}
namespace Drupal\Core\Entity\KeyValueStore;
namespace {
if (!defined('SAVED_NEW')) {
define('SAVED_NEW', 1);
}
if (!defined('SAVED_UPDATED')) {
define('SAVED_UPDATED', 2);
}
if (!defined('SAVED_NEW')) {
define('SAVED_NEW', 1);
}
if (!defined('SAVED_UPDATED')) {
define('SAVED_UPDATED', 2);
}

View file

@ -252,6 +252,52 @@ class DefaultHtmlRouteProviderTest extends UnitTestCase {
return $data;
}
/**
* @covers ::getCollectionRoute
* @dataProvider providerTestGetCollectionRoute
*/
public function testGetCollectionRoute(Route $expected = NULL, EntityTypeInterface $entity_type) {
$route = $this->routeProvider->getCollectionRoute($entity_type);
$this->assertEquals($expected, $route);
}
public function providerTestGetCollectionRoute() {
$data = [];
$entity_type1 = $this->getEntityType();
$entity_type1->hasLinkTemplate('collection')->willReturn(FALSE);
$data['no_collection_link_template'] = [NULL, $entity_type1->reveal()];
$entity_type2 = $this->getEntityType();
$entity_type2->hasLinkTemplate('collection')->willReturn(TRUE);
$entity_type2->hasListBuilderClass()->willReturn(FALSE);
$data['no_list_builder'] = [NULL, $entity_type2->reveal()];
$entity_type3 = $this->getEntityType($entity_type2);
$entity_type3->hasListBuilderClass()->willReturn(TRUE);
$entity_type3->getAdminPermission()->willReturn(FALSE);
$data['no_admin_permission'] = [NULL, $entity_type3->reveal()];
$entity_type4 = $this->getEntityType($entity_type3);
$entity_type4->getAdminPermission()->willReturn('administer the entity type');
$entity_type4->id()->willReturn('the_entity_type_id');
$entity_type4->getLabel()->willReturn('The entity type');
$entity_type4->getLinkTemplate('collection')->willReturn('/the/collection/link/template');
$entity_type4->isSubclassOf(FieldableEntityInterface::class)->willReturn(FALSE);
$route = (new Route('/the/collection/link/template'))
->setDefaults([
'_entity_list' => 'the_entity_type_id',
'_title' => '@label entities',
'_title_arguments' => ['@label' => 'The entity type'],
])
->setRequirements([
'_permission' => 'administer the entity type',
]);
$data['collection_route'] = [clone $route, $entity_type4->reveal()];
return $data;
}
/**
* @covers ::getEntityTypeIdKeyType
*/
@ -313,5 +359,8 @@ class TestDefaultHtmlRouteProvider extends DefaultHtmlRouteProvider {
public function getCanonicalRoute(EntityTypeInterface $entity_type) {
return parent::getCanonicalRoute($entity_type);
}
public function getCollectionRoute(EntityTypeInterface $entity_type) {
return parent::getCollectionRoute($entity_type);
}
}

View file

@ -1314,16 +1314,16 @@ class SqlContentEntityStorageTest extends UnitTestCase {
$this->fieldDefinitions = $this->mockFieldDefinitions(array('id'));
$this->fieldDefinitions['id']->expects($this->any())
->method('getType')
->will($this->returnValue('integer'));
->method('getType')
->will($this->returnValue('integer'));
$this->setUpEntityStorage();
$this->entityType->expects($this->any())
->method('getKey')
->will($this->returnValueMap(array(
array('id', 'id'),
)));
->method('getKey')
->will($this->returnValueMap(
array(array('id', 'id'))
));
$method = new \ReflectionMethod($this->entityStorage, 'cleanIds');
$method->setAccessible(TRUE);

View file

@ -14,6 +14,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\RequestContext;
/**
* @coversDefaultClass \Drupal\Core\EventSubscriber\CustomPageExceptionHtmlSubscriber
@ -127,6 +128,12 @@ class CustomPageExceptionHtmlSubscriberTest extends UnitTestCase {
public function testHandleWithPostRequest() {
$request = Request::create('/test', 'POST', array('name' => 'druplicon', 'pass' => '12345'));
$request_context = new RequestContext();
$request_context->fromRequest($request);
$this->accessUnawareRouter->expects($this->any())
->method('getContext')
->willReturn($request_context);
$this->kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new HtmlResponse($request->getMethod());
}));
@ -148,6 +155,12 @@ class CustomPageExceptionHtmlSubscriberTest extends UnitTestCase {
$request = Request::create('/test', 'GET', array('name' => 'druplicon', 'pass' => '12345'));
$request->attributes->set(AccessAwareRouterInterface::ACCESS_RESULT, AccessResult::forbidden()->addCacheTags(['druplicon']));
$request_context = new RequestContext();
$request_context->fromRequest($request);
$this->accessUnawareRouter->expects($this->any())
->method('getContext')
->willReturn($request_context);
$this->kernel->expects($this->once())->method('handle')->will($this->returnCallback(function (Request $request) {
return new Response($request->getMethod() . ' ' . UrlHelper::buildQuery($request->query->all()));
}));

View file

@ -147,7 +147,7 @@ type: module
description: 'testing info file parsing'
simple_string: 'A simple string'
version: "VERSION"
double_colon: dummyClassName::
double_colon: dummyClassName::method
COMMONTEST;
vfsStream::setup('modules');
@ -159,7 +159,7 @@ COMMONTEST;
$info_values = $this->infoParser->parse(vfsStream::url('modules/fixtures/common_test.info.txt'));
$this->assertEquals($info_values['simple_string'], 'A simple string', 'Simple string value was parsed correctly.');
$this->assertEquals($info_values['version'], \Drupal::VERSION, 'Constant value was parsed correctly.');
$this->assertEquals($info_values['double_colon'], 'dummyClassName::', 'Value containing double-colon was parsed correctly.');
$this->assertEquals($info_values['double_colon'], 'dummyClassName::method', 'Value containing double-colon was parsed correctly.');
}
}

View file

@ -137,6 +137,20 @@ class ThemeHandlerTest extends UnitTestCase {
$this->assertEquals(array('seven/global-styling'), $info->info['libraries']);
}
/**
* Tests empty libraries in theme.info.yml file.
*/
public function testThemeLibrariesEmpty() {
$theme = new Extension($this->root, 'theme', '/core/modules/system/tests/themes/test_theme_libraries_empty', 'test_theme_libraries_empty.info.yml');
try {
$this->themeHandler->addTheme($theme);
$this->assertTrue(TRUE, 'Empty libraries key in theme.info.yml does not cause PHP warning');
}
catch (\Exception $e) {
$this->fail('Empty libraries key in theme.info.yml causes PHP warning.');
}
}
/**
* Tests rebuild the theme data with theme parents.
*/

View file

@ -24,6 +24,7 @@ abstract class BaseFieldDefinitionTestBase extends UnitTestCase {
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// getModuleAndPath() returns an array of the module name and directory.
list($module_name, $module_dir) = $this->getModuleAndPath();

File diff suppressed because it is too large Load diff

View file

@ -142,75 +142,6 @@ class FormStateTest extends UnitTestCase {
$form_state->setErrorByName('test', 'message');
}
/**
* Tests that setting the value for an element adds to the values.
*
* @covers ::setValueForElement
*/
public function testSetValueForElement() {
$element = array(
'#parents' => array(
'foo',
'bar',
),
);
$value = $this->randomMachineName();
$form_state = new FormState();
$form_state->setValueForElement($element, $value);
$expected = array(
'foo' => array(
'bar' => $value,
),
);
$this->assertSame($expected, $form_state->getValues());
}
/**
* @covers ::getValue
*
* @dataProvider providerTestGetValue
*/
public function testGetValue($key, $expected, $default = NULL) {
$form_state = (new FormState())->setValues([
'foo' => 'one',
'bar' => array(
'baz' => 'two',
),
]);
$this->assertSame($expected, $form_state->getValue($key, $default));
}
public function providerTestGetValue() {
$data = array();
$data[] = array(
'foo', 'one',
);
$data[] = array(
array('bar', 'baz'), 'two',
);
$data[] = array(
array('foo', 'bar', 'baz'), NULL,
);
$data[] = array(
'baz', 'baz', 'baz',
);
return $data;
}
/**
* @covers ::setValue
*
* @dataProvider providerTestSetValue
*/
public function testSetValue($key, $value, $expected) {
$form_state = (new FormState())->setValues([
'bar' => 'wrong',
]);
$form_state->setValue($key, $value);
$this->assertSame($expected, $form_state->getValues());
}
/**
* @covers ::prepareCallback
*/
@ -243,102 +174,6 @@ class FormStateTest extends UnitTestCase {
$this->assertEquals($callback, $processed_callback);
}
public function providerTestSetValue() {
$data = array();
$data[] = array(
'foo', 'one', array('bar' => 'wrong', 'foo' => 'one'),
);
$data[] = array(
array('bar', 'baz'), 'two', array('bar' => array('baz' => 'two')),
);
$data[] = array(
array('foo', 'bar', 'baz'), NULL, array('bar' => 'wrong', 'foo' => array('bar' => array('baz' => NULL))),
);
return $data;
}
/**
* @covers ::hasValue
*
* @dataProvider providerTestHasValue
*/
public function testHasValue($key, $expected) {
$form_state = (new FormState())->setValues([
'foo' => 'one',
'bar' => array(
'baz' => 'two',
),
'true' => TRUE,
'false' => FALSE,
'null' => NULL,
]);
$this->assertSame($expected, $form_state->hasValue($key));
}
public function providerTestHasValue() {
$data = array();
$data[] = array(
'foo', TRUE,
);
$data[] = array(
array('bar', 'baz'), TRUE,
);
$data[] = array(
array('foo', 'bar', 'baz'), FALSE,
);
$data[] = array(
'true', TRUE,
);
$data[] = array(
'false', TRUE,
);
$data[] = array(
'null', FALSE,
);
return $data;
}
/**
* @covers ::isValueEmpty
*
* @dataProvider providerTestIsValueEmpty
*/
public function testIsValueEmpty($key, $expected) {
$form_state = (new FormState())->setValues([
'foo' => 'one',
'bar' => array(
'baz' => 'two',
),
'true' => TRUE,
'false' => FALSE,
'null' => NULL,
]);
$this->assertSame($expected, $form_state->isValueEmpty($key));
}
public function providerTestIsValueEmpty() {
$data = array();
$data[] = array(
'foo', FALSE,
);
$data[] = array(
array('bar', 'baz'), FALSE,
);
$data[] = array(
array('foo', 'bar', 'baz'), TRUE,
);
$data[] = array(
'true', FALSE,
);
$data[] = array(
'false', TRUE,
);
$data[] = array(
'null', TRUE,
);
return $data;
}
/**
* @covers ::loadInclude
*/
@ -584,6 +419,19 @@ class FormStateTest extends UnitTestCase {
$this->assertSame($form_state->cleanValues()->getValues(), ['value_to_keep' => 'magic_ponies']);
}
/**
* @covers ::setValues
* @covers ::getValues
*/
public function testGetValues() {
$values = [
'foo' => 'bar',
];
$form_state = new FormState();
$form_state->setValues($values);
$this->assertSame($values, $form_state->getValues());
}
}
/**

View file

@ -0,0 +1,263 @@
<?php
namespace Drupal\Tests\Core\Form;
use Drupal\Core\Form\FormStateValuesTrait;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Form\FormStateValuesTrait
*
* @group Form
*/
class FormStateValuesTraitTest extends UnitTestCase {
/**
* Tests that setting the value for an element adds to the values.
*
* @covers ::setValueForElement
*/
public function testSetValueForElement() {
$element = [
'#parents' => [
'foo',
'bar',
],
];
$value = $this->randomMachineName();
$form_state = new FormStateValuesTraitStub();
$form_state->setValueForElement($element, $value);
$expected = [
'foo' => [
'bar' => $value,
],
];
$this->assertSame($expected, $form_state->getValues());
}
/**
* @covers ::getValue
*
* @dataProvider providerGetValue
*/
public function testGetValue($key, $expected, $default = NULL) {
$form_state = (new FormStateValuesTraitStub())->setValues([
'foo' => 'one',
'bar' => [
'baz' => 'two',
],
]);
$this->assertSame($expected, $form_state->getValue($key, $default));
}
/**
* Provides data to self::testGetValue().
*
* @return array[]
* Items are arrays of two items:
* - The key for which to get the value (string)
* - The expected value (mixed).
* - The default value (mixed).
*/
public function providerGetValue() {
$data = [];
$data[] = [
'foo', 'one',
];
$data[] = [
['bar', 'baz'], 'two',
];
$data[] = [
['foo', 'bar', 'baz'], NULL,
];
$data[] = [
'baz', 'baz', 'baz',
];
$data[] = [
NULL,
[
'foo' => 'one',
'bar' => [
'baz' => 'two',
],
],
];
return $data;
}
/**
* @covers ::getValue
*/
public function testGetValueModifyReturn() {
$initial_values = $values = [
'foo' => 'one',
'bar' => [
'baz' => 'two',
],
];
$form_state = (new FormStateValuesTraitStub())->setValues($values);
$value = &$form_state->getValue(NULL);
$this->assertSame($initial_values, $value);
$value = ['bing' => 'bang'];
$this->assertSame(['bing' => 'bang'], $form_state->getValues());
$this->assertSame('bang', $form_state->getValue('bing'));
$this->assertSame(['bing' => 'bang'], $form_state->getValue(NULL));
}
/**
* @covers ::setValue
*
* @dataProvider providerSetValue
*/
public function testSetValue($key, $value, $expected) {
$form_state = (new FormStateValuesTraitStub())->setValues([
'bar' => 'wrong',
]);
$form_state->setValue($key, $value);
$this->assertSame($expected, $form_state->getValues());
}
/**
* Provides data to self::testSetValue().
*
* @return array[]
* Items are arrays of two items:
* - The key for which to set a new value (string)
* - The new value to set (mixed).
* - The expected form state values after setting the new value (mixed[]).
*/
public function providerSetValue() {
$data = [];
$data[] = [
'foo', 'one', ['bar' => 'wrong', 'foo' => 'one'],
];
$data[] = [
['bar', 'baz'], 'two', ['bar' => ['baz' => 'two']],
];
$data[] = [
['foo', 'bar', 'baz'], NULL, ['bar' => 'wrong', 'foo' => ['bar' => ['baz' => NULL]]],
];
return $data;
}
/**
* @covers ::hasValue
*
* @dataProvider providerHasValue
*/
public function testHasValue($key, $expected) {
$form_state = (new FormStateValuesTraitStub())->setValues([
'foo' => 'one',
'bar' => [
'baz' => 'two',
],
'true' => TRUE,
'false' => FALSE,
'null' => NULL,
]);
$this->assertSame($expected, $form_state->hasValue($key));
}
/**
* Provides data to self::testHasValue().
*
* @return array[]
* Items are arrays of two items:
* - The key to check for in the form state (string)
* - Whether the form state has an item with that key (bool).
*/
public function providerHasValue() {
$data = [];
$data[] = [
'foo', TRUE,
];
$data[] = [
['bar', 'baz'], TRUE,
];
$data[] = [
['foo', 'bar', 'baz'], FALSE,
];
$data[] = [
'true', TRUE,
];
$data[] = [
'false', TRUE,
];
$data[] = [
'null', FALSE,
];
return $data;
}
/**
* @covers ::isValueEmpty
*
* @dataProvider providerIsValueEmpty
*/
public function testIsValueEmpty($key, $expected) {
$form_state = (new FormStateValuesTraitStub())->setValues([
'foo' => 'one',
'bar' => [
'baz' => 'two',
],
'true' => TRUE,
'false' => FALSE,
'null' => NULL,
]);
$this->assertSame($expected, $form_state->isValueEmpty($key));
}
/**
* Provides data to self::testIsValueEmpty().
*
* @return array[]
* Items are arrays of two items:
* - The key to check for in the form state (string)
* - Whether the value is empty or not (bool).
*/
public function providerIsValueEmpty() {
$data = [];
$data[] = [
'foo', FALSE,
];
$data[] = [
['bar', 'baz'], FALSE,
];
$data[] = [
['foo', 'bar', 'baz'], TRUE,
];
$data[] = [
'true', FALSE,
];
$data[] = [
'false', TRUE,
];
$data[] = [
'null', TRUE,
];
return $data;
}
}
class FormStateValuesTraitStub {
use FormStateValuesTrait;
/**
* The submitted form values.
*
* @var mixed[]
*/
protected $values = [];
/**
* {@inheritdoc}
*/
public function &getValues() {
return $this->values;
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\Tests\Core\Form {
namespace Drupal\Tests\Core\Form;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormBuilder;
@ -147,6 +147,9 @@ abstract class FormTestBase extends UnitTestCase {
protected function setUp() {
parent::setUp();
// Add functions to the global namespace for testing.
require_once __DIR__ . '/fixtures/form_base_test.inc';
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->formCache = $this->getMock('Drupal\Core\Form\FormCacheInterface');
@ -311,35 +314,3 @@ abstract class FormTestBase extends UnitTestCase {
}
}
}
namespace {
function test_form_id() {
$form['test'] = array(
'#type' => 'textfield',
'#title' => 'Test',
);
$form['options'] = array(
'#type' => 'radios',
'#options' => array(
'foo' => 'foo',
'bar' => 'bar',
),
);
$form['value'] = array(
'#type' => 'value',
'#value' => 'bananas',
);
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}
}

View file

@ -0,0 +1,312 @@
<?php
namespace Drupal\Tests\Core\Form;
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\SubformState;
use Drupal\Core\Form\SubformStateInterface;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Form\SubformState
*
* @group Form
*/
class SubformStateTest extends UnitTestCase {
/**
* The form state's values test fixture.
*
* @var mixed[]
*/
protected $formStateValues = [
'foo' => 'bar',
'dog' => [
'breed' => 'Pit bull',
'name' => 'Dodger',
],
];
/**
* The parent form.
*
* @var mixed[]
*/
protected $parentForm = [
'#parents' => [],
'foo' => [
'#parents' => ['foo'],
'#array_parents' => ['foo'],
],
'dog' => [
'#parents' => ['dog'],
'#array_parents' => ['dog'],
'breed' => [
'#parents' => ['dog', 'breed'],
'#array_parents' => ['dog', 'breed'],
],
'name' => [
'#parents' => ['dog', 'name'],
'#array_parents' => ['dog', 'name'],
],
],
];
/**
* @covers ::getValues
* @covers ::getParents
*
* @dataProvider providerGetValues
*
* @param string[] $parents
* @param string $expected
*/
public function testGetValues(array $parents, $expected) {
$parent_form_state = new FormState();
$parent_form_state->setValues($this->formStateValues);
$subform = NestedArray::getValue($this->parentForm, $parents);
$subform_state = SubformState::createForSubform($subform, $this->parentForm, $parent_form_state);
$subform_state_values = &$subform_state->getValues();
$this->assertSame($expected, $subform_state_values);
// Modify the retrieved values and confirm they are modified by reference in
// the parent form state.
$subform_state_values['fish'] = 'Jim';
$this->assertSame($subform_state_values, $subform_state->getValues());
}
/**
* Provides data to self::testGetValues().
*/
public function providerGetValues() {
$data = [];
$data['exist'] = [
['dog'],
$this->formStateValues['dog'],
];
return $data;
}
/**
* @covers ::getValues
* @covers ::getParents
*
* @dataProvider providerGetValuesBroken
*
* @expectedException \UnexpectedValueException
*
* @param string[] $parents
* @param string $expected
*/
public function testGetValuesBroken(array $parents, $expected) {
$this->testGetValues($parents, $expected);
}
/**
* Provides data to self::testGetValuesBroken().
*/
public function providerGetValuesBroken() {
$data = [];
$data['exist'] = [
['foo'],
$this->formStateValues['foo'],
];
$data['nested'] = [
['dog', 'name'],
'Dodger',
];
return $data;
}
/**
* @covers ::getValue
*
* @dataProvider providerTestGetValue
*/
public function testGetValue($parents, $key, $expected, $default = NULL) {
$parent_form_state = new FormState();
$parent_form_state->setValues($this->formStateValues);
$subform = NestedArray::getValue($this->parentForm, $parents);
$subform_state = SubformState::createForSubform($subform, $this->parentForm, $parent_form_state);
$subform_state_value = &$subform_state->getValue($key, $default);
$this->assertSame($expected, $subform_state_value);
// Modify the retrieved values and confirm they are modified by reference in
// the parent form state.
$subform_state_value = 'Jim';
$this->assertSame($subform_state_value, $subform_state->getValue($key));
}
/**
* Provides data to self::testGetValue().
*/
public function providerTestGetValue() {
$data = [];
$data['exist'] = [
['dog'],
'name',
'Dodger',
];
return $data;
}
/**
* @covers ::getValue
*
* @dataProvider providerTestGetValueBroken
*
* @expectedException \UnexpectedValueException
*/
public function testGetValueBroken(array $parents, $key, $expected, $default = NULL) {
$this->testGetValue($parents, $key, $expected, $default);
}
/**
* Provides data to self::testGetValueBroken().
*/
public function providerTestGetValueBroken() {
$data = [];
$data['nested'] = [
['dog', 'name'],
NULL,
'Dodger',
];
return $data;
}
/**
* @covers ::setValues
*
* @dataProvider providerTestSetValues
*/
public function testSetValues($parents, $new_values, $expected) {
$parent_form_state = new FormState();
$parent_form_state->setValues($this->formStateValues);
$subform = NestedArray::getValue($this->parentForm, $parents);
$subform_state = SubformState::createForSubform($subform, $this->parentForm, $parent_form_state);
$this->assertSame($subform_state, $subform_state->setValues($new_values));
$this->assertSame($expected, $parent_form_state->getValues());
}
/**
* Provides data to self::testSetValues().
*/
public function providerTestSetValues() {
$data = [];
$data['exist'] = [
['dog'],
[],
[
'foo' => 'bar',
'dog' => [],
],
];
return $data;
}
/**
* @covers ::setValues
*
* @dataProvider providerTestSetValuesBroken
*
* @expectedException \UnexpectedValueException
*/
public function testSetValuesBroken($parents, $new_values, $expected) {
$this->testSetValues($parents, $new_values, $expected);
}
/**
* Provides data to self::testSetValuesBroken().
*/
public function providerTestSetValuesBroken() {
$data = [];
$data['exist'] = [
['foo'],
[],
[
'foo' => [],
'dog' => $this->formStateValues['dog'],
],
];
return $data;
}
/**
* @covers ::getCompleteFormState
*/
public function testGetCompleteFormStateWithParentCompleteForm() {
$parent_form_state = $this->prophesize(FormStateInterface::class);
$subform_state = SubformState::createForSubform($this->parentForm['dog'], $this->parentForm, $parent_form_state->reveal());
$this->assertSame($parent_form_state->reveal(), $subform_state->getCompleteFormState());
}
/**
* @covers ::getCompleteFormState
*/
public function testGetCompleteFormStateWithParentSubform() {
$complete_form_state = $this->prophesize(FormStateInterface::class);
$parent_form_state = $this->prophesize(SubformStateInterface::class);
$parent_form_state->getCompleteFormState()
->willReturn($complete_form_state->reveal())
->shouldBeCalled();
$subform_state = SubformState::createForSubform($this->parentForm['dog'], $this->parentForm, $parent_form_state->reveal());
$this->assertSame($complete_form_state->reveal(), $subform_state->getCompleteFormState());
}
/**
* @covers ::setLimitValidationErrors
*/
public function testSetLimitValidationErrors() {
$parent_limit_validation_errors = ['dog', 'name'];
$limit_validation_errors = ['name'];
$parent_form_state = $this->prophesize(FormStateInterface::class);
$parent_form_state->setLimitValidationErrors($parent_limit_validation_errors)
->shouldBeCalled();
$subform_state = SubformState::createForSubform($this->parentForm['dog'], $this->parentForm, $parent_form_state->reveal());
$this->assertSame($subform_state, $subform_state->setLimitValidationErrors($limit_validation_errors));
}
/**
* @covers ::getLimitValidationErrors
*/
public function testGetLimitValidationErrors() {
$parent_limit_validation_errors = ['dog', 'name'];
$limit_validation_errors = ['name'];
$parent_form_state = $this->prophesize(FormStateInterface::class);
$parent_form_state->getLimitValidationErrors()
->willReturn($parent_limit_validation_errors)
->shouldBeCalled();
$subform_state = SubformState::createForSubform($this->parentForm['dog'], $this->parentForm, $parent_form_state->reveal());
$this->assertSame($limit_validation_errors, $subform_state->getLimitValidationErrors());
}
/**
* @covers ::setErrorByName
*/
public function testSetErrorByName() {
$parent_form_error_name = 'dog][name';
$subform_error_name = 'name';
$message = 'De kat krabt de krullen van de trap.';
$parent_form_state = $this->prophesize(FormStateInterface::class);
$parent_form_state->setErrorByName($parent_form_error_name, $message)
->shouldBeCalled();
$subform_state = SubformState::createForSubform($this->parentForm['dog'], $this->parentForm, $parent_form_state->reveal());
$this->assertSame($subform_state, $subform_state->setErrorByName($subform_error_name, $message));
}
}

View file

@ -0,0 +1,38 @@
<?php
/**
* @file
* Functions in the global namespace for \Drupal\Tests\Core\Form\FormTestBase.
*/
/**
* Creates a test form.
*
* @return array
* The form array
*/
function test_form_id() {
$form['test'] = array(
'#type' => 'textfield',
'#title' => 'Test',
);
$form['options'] = array(
'#type' => 'radios',
'#options' => array(
'foo' => 'foo',
'bar' => 'bar',
),
);
$form['value'] = array(
'#type' => 'value',
'#value' => 'bananas',
);
$form['actions'] = array(
'#type' => 'actions',
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => 'Submit',
);
return $form;
}

View file

@ -1,4 +1,5 @@
<?php
/**
* @file
* Contains \Drupal\Tests\Core\Mail\MailManagerTest.
@ -6,6 +7,8 @@
namespace Drupal\Tests\Core\Mail;
use Drupal\Core\Render\RenderContext;
use Drupal\Core\Render\RendererInterface;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Mail\MailManager;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
@ -44,6 +47,13 @@ class MailManagerTest extends UnitTestCase {
*/
protected $discovery;
/**
* The renderer.
*
* @var \Drupal\Core\Render\RendererInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $renderer;
/**
* The mail manager under test.
*
@ -96,8 +106,9 @@ class MailManagerTest extends UnitTestCase {
));
$logger_factory = $this->getMock('\Drupal\Core\Logger\LoggerChannelFactoryInterface');
$string_translation = $this->getStringTranslationStub();
$this->renderer = $this->getMock(RendererInterface::class);
// Construct the manager object and override its discovery.
$this->mailManager = new TestMailManager(new \ArrayObject(), $this->cache, $this->moduleHandler, $this->configFactory, $logger_factory, $string_translation);
$this->mailManager = new TestMailManager(new \ArrayObject(), $this->cache, $this->moduleHandler, $this->configFactory, $logger_factory, $string_translation, $this->renderer);
$this->mailManager->setDiscovery($this->discovery);
}
@ -109,7 +120,7 @@ class MailManagerTest extends UnitTestCase {
public function testGetInstance() {
$interface = array(
'default' => 'php_mail',
'example_testkey' => 'test_mail_collector',
'default' => 'test_mail_collector',
);
$this->setUpMailManager($interface);
@ -124,6 +135,28 @@ class MailManagerTest extends UnitTestCase {
$this->assertInstanceOf('Drupal\Core\Mail\Plugin\Mail\TestMailCollector', $instance);
}
/**
* Tests that mails are sent in a separate render context.
*
* @covers ::mail
*/
public function testMailInRenderContext() {
$interface = array(
'default' => 'php_mail',
'example_testkey' => 'test_mail_collector',
);
$this->setUpMailManager($interface);
$this->renderer->expects($this->exactly(1))
->method('executeInRenderContext')
->willReturnCallback(function (RenderContext $render_context, $callback) {
$message = $callback();
$this->assertEquals('example', $message['module']);
});
$this->mailManager->mail('example', 'key', 'to@example.org', 'en');
}
}
/**
@ -140,4 +173,26 @@ class TestMailManager extends MailManager {
$this->discovery = $discovery;
}
/**
* {@inheritdoc}
*/
public function doMail($module, $key, $to, $langcode, $params = array(), $reply = NULL, $send = TRUE) {
// Build a simplified message array and return it.
$message = array(
'id' => $module . '_' . $key,
'module' => $module,
'key' => $key,
'to' => $to,
'from' => 'from@example.org',
'reply-to' => $reply,
'langcode' => $langcode,
'params' => $params,
'send' => TRUE,
'subject' => '',
'body' => array(),
);
return $message;
}
}

View file

@ -162,9 +162,9 @@ class LocalActionManagerTest extends UnitTestCase {
->method('getTitle')
->will($this->returnValue($plugin_definition['title']));
$this->controllerResolver->expects($this->any())
->method('getArguments')
->with($this->request, array($plugin, 'getTitle'))
->will($this->returnValue(array()));
->method('getArguments')
->with($this->request, array($plugin, 'getTitle'))
->will($this->returnValue(array()));
$plugin->expects($this->any())
->method('getWeight')

View file

@ -441,7 +441,7 @@ class LocalTaskManagerTest extends UnitTestCase {
// Ensure that all cacheability metadata is merged together.
$this->assertEquals(['tag.example1', 'tag.example2'], $cacheability->getCacheTags());
$this->assertEquals(['context.example1', 'context.example2', 'route', 'user.permissions'], $cacheability->getCacheContexts());
}
}
protected function setupFactoryAndLocalTaskPlugins(array $definitions, $active_plugin_id) {
$map = [];

View file

@ -2,6 +2,9 @@
namespace Drupal\Tests\Core\Plugin;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Tests\UnitTestCase;
/**
@ -57,6 +60,25 @@ class DefaultPluginManagerTest extends UnitTestCase {
$this->namespaces['Drupal\plugin_test'] = $this->root . '/core/modules/system/tests/modules/plugin_test/src';
}
/**
* Tests the plugin manager with a plugin that extends a non-installed class.
*/
public function testDefaultPluginManagerWithPluginExtendingNonInstalledClass() {
$definitions = array();
$definitions['extending_non_installed_class'] = array(
'id' => 'extending_non_installed_class',
'label' => 'A plugin whose class is extending from a non-installed module class',
'color' => 'pink',
'class' => 'Drupal\plugin_test\Plugin\plugin_test\fruit\ExtendingNonInstalledClass',
'provider' => 'plugin_test',
);
$module_handler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$plugin_manager = new TestPluginManager($this->namespaces, $definitions, $module_handler, 'test_alter_hook', '\Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface');
$plugin_manager->getDefinition('plugin_test', FALSE);
$this->assertTrue(TRUE, 'No PHP fatal error occurred when retrieving the definitions of a module with plugins that depend on a non-installed module class should not cause a PHP fatal.');
}
/**
* Tests the plugin manager with a disabled module.
*/
@ -301,4 +323,133 @@ class DefaultPluginManagerTest extends UnitTestCase {
$this->assertInternalType('array', $plugin_manager->getDefinitions());
}
/**
* @covers ::getCacheContexts
*/
public function testGetCacheContexts() {
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$plugin_manager = new TestPluginManager($this->namespaces, $this->expectedDefinitions, $module_handler->reveal(), NULL);
$cache_contexts = $plugin_manager->getCacheContexts();
$this->assertInternalType('array', $cache_contexts);
array_map(function ($cache_context) {
$this->assertInternalType('string', $cache_context);
}, $cache_contexts);
}
/**
* @covers ::getCacheTags
*/
public function testGetCacheTags() {
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$plugin_manager = new TestPluginManager($this->namespaces, $this->expectedDefinitions, $module_handler->reveal(), NULL);
$cache_tags = $plugin_manager->getCacheTags();
$this->assertInternalType('array', $cache_tags);
array_map(function ($cache_tag) {
$this->assertInternalType('string', $cache_tag);
}, $cache_tags);
}
/**
* @covers ::getCacheMaxAge
*/
public function testGetCacheMaxAge() {
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$plugin_manager = new TestPluginManager($this->namespaces, $this->expectedDefinitions, $module_handler->reveal(), NULL);
$cache_max_age = $plugin_manager->getCacheMaxAge();
$this->assertInternalType('int', $cache_max_age);
}
/**
* @covers ::processDefinition
* @dataProvider providerTestProcessDefinition
*/
public function testProcessDefinition($definition, $expected) {
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$plugin_manager = new TestPluginManagerWithDefaults($this->namespaces, $this->expectedDefinitions, $module_handler->reveal(), NULL);
$plugin_manager->processDefinition($definition, 'the_plugin_id');
$this->assertEquals($expected, $definition);
}
public function providerTestProcessDefinition() {
$data = [];
$data['merge'][] = [
'foo' => [
'bar' => [
'asdf',
],
],
];
$data['merge'][] = [
'foo' => [
'bar' => [
'baz',
'asdf',
],
],
];
$object_definition = (object) [
'foo' => [
'bar' => [
'asdf',
],
],
];
$data['object_definition'] = [$object_definition, clone $object_definition];
$data['no_form'][] = ['class' => TestPluginForm::class];
$data['no_form'][] = [
'class' => TestPluginForm::class,
'foo' => ['bar' => ['baz']],
];
$data['default_form'][] = ['class' => TestPluginForm::class, 'forms' => ['configure' => 'stdClass']];
$data['default_form'][] = [
'class' => TestPluginForm::class,
'forms' => ['configure' => 'stdClass'],
'foo' => ['bar' => ['baz']],
];
return $data;
}
}
class TestPluginManagerWithDefaults extends TestPluginManager {
/**
* {@inheritdoc}
*/
protected $defaults = [
'foo' => [
'bar' => [
'baz',
],
],
];
}
class TestPluginForm implements PluginFormInterface {
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
return [];
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
}
}

View file

@ -111,14 +111,14 @@ class DerivativeDiscoveryDecoratorTest extends UnitTestCase {
* @see \Drupal\Component\Plugin\Discovery\DerivativeDiscoveryDecorator::getDeriver().\
*
* @expectedException \Drupal\Component\Plugin\Exception\InvalidDeriverException
* @expectedExceptionMessage Plugin (invalid_discovery) deriver "\Drupal\system\Tests\Plugin\DerivativeTest" must implement \Drupal\Component\Plugin\Derivative\DeriverInterface.
* @expectedExceptionMessage Plugin (invalid_discovery) deriver "\Drupal\KernelTests\Core\Plugin\DerivativeTest" must implement \Drupal\Component\Plugin\Derivative\DeriverInterface.
*/
public function testInvalidDerivativeFetcher() {
$definitions = array();
// Do this with a class that doesn't implement the interface.
$definitions['invalid_discovery'] = array(
'id' => 'invalid_discovery',
'deriver' => '\Drupal\system\Tests\Plugin\DerivativeTest',
'deriver' => '\Drupal\KernelTests\Core\Plugin\DerivativeTest',
);
$this->discoveryMain->expects($this->any())
->method('getDefinitions')

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\Tests\Core\Plugin\Discovery {
namespace Drupal\Tests\Core\Plugin\Discovery;
use Drupal\Core\Plugin\Discovery\HookDiscovery;
use Drupal\Tests\UnitTestCase;
@ -61,11 +61,11 @@ class HookDiscoveryTest extends UnitTestCase {
$this->moduleHandler->expects($this->at(1))
->method('invoke')
->with('hook_discovery_test', 'test_plugin')
->will($this->returnValue(hook_discovery_test_test_plugin()));
->will($this->returnValue($this->hookDiscoveryTestTestPlugin()));
$this->moduleHandler->expects($this->at(2))
->method('invoke')
->with('hook_discovery_test2', 'test_plugin')
->will($this->returnValue(hook_discovery_test2_test_plugin()));
->will($this->returnValue($this->hookDiscoveryTest2TestPlugin()));
$definitions = $this->hookDiscovery->getDefinitions();
@ -94,8 +94,8 @@ class HookDiscoveryTest extends UnitTestCase {
$this->moduleHandler->expects($this->any())
->method('invoke')
->will($this->returnValueMap(array(
array('hook_discovery_test', 'test_plugin', array(), hook_discovery_test_test_plugin()),
array('hook_discovery_test2', 'test_plugin', array(), hook_discovery_test2_test_plugin()),
array('hook_discovery_test', 'test_plugin', array(), $this->hookDiscoveryTestTestPlugin()),
array('hook_discovery_test2', 'test_plugin', array(), $this->hookDiscoveryTest2TestPlugin()),
)
));
@ -129,20 +129,16 @@ class HookDiscoveryTest extends UnitTestCase {
$this->hookDiscovery->getDefinition('test_non_existant', TRUE);
}
}
}
namespace {
function hook_discovery_test_test_plugin() {
protected function hookDiscoveryTestTestPlugin() {
return array(
'test_id_1' => array('class' => 'Drupal\plugin_test\Plugin\plugin_test\fruit\Apple'),
'test_id_2' => array('class' => 'Drupal\plugin_test\Plugin\plugin_test\fruit\Orange'),
);
}
function hook_discovery_test2_test_plugin() {
protected function hookDiscoveryTest2TestPlugin() {
return array(
'test_id_3' => array('class' => 'Drupal\plugin_test\Plugin\plugin_test\fruit\Cherry'),
);
}
}

View file

@ -0,0 +1,156 @@
<?php
namespace Drupal\Tests\Core\Plugin;
use Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException;
use Drupal\Component\Plugin\PluginAwareInterface;
use Drupal\Core\DependencyInjection\ClassResolverInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Plugin\PluginFormFactory;
use Drupal\Core\Plugin\PluginWithFormsInterface;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
/**
* @coversDefaultClass \Drupal\Core\Plugin\PluginFormFactory
* @group Plugin
*/
class PluginFormFactoryTest extends UnitTestCase {
/**
* The class resolver.
*
* @var \Drupal\Core\DependencyInjection\ClassResolverInterface|\Prophecy\Prophecy\ProphecyInterface
*/
protected $classResolver;
/**
* The manager being tested.
*
* @var \Drupal\Core\Plugin\PluginFormFactory
*/
protected $manager;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->classResolver = $this->prophesize(ClassResolverInterface::class);
$this->manager = new PluginFormFactory($this->classResolver->reveal());
}
/**
* @covers ::createInstance
*/
public function testCreateInstance() {
$plugin_form = $this->prophesize(PluginFormInterface::class);
$expected = $plugin_form->reveal();
$this->classResolver->getInstanceFromDefinition(get_class($expected))->willReturn($expected);
$plugin = $this->prophesize(PluginWithFormsInterface::class);
$plugin->hasFormClass('standard_class')->willReturn(TRUE);
$plugin->getFormClass('standard_class')->willReturn(get_class($expected));
$form_object = $this->manager->createInstance($plugin->reveal(), 'standard_class');
$this->assertSame($expected, $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstanceUsingPlugin() {
$this->classResolver->getInstanceFromDefinition(Argument::cetera())->shouldNotBeCalled();
$plugin = $this->prophesize(PluginWithFormsInterface::class)->willImplement(PluginFormInterface::class);
$plugin->hasFormClass('configure')->willReturn(TRUE);
$plugin->getFormClass('configure')->willReturn(get_class($plugin->reveal()));
$form_object = $this->manager->createInstance($plugin->reveal(), 'configure');
$this->assertSame($plugin->reveal(), $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstanceUsingPluginWithSlashes() {
$this->classResolver->getInstanceFromDefinition(Argument::cetera())->shouldNotBeCalled();
$plugin = $this->prophesize(PluginWithFormsInterface::class)->willImplement(PluginFormInterface::class);
$plugin->hasFormClass('configure')->willReturn(TRUE);
$plugin->getFormClass('configure')->willReturn('\\' . get_class($plugin->reveal()));
$form_object = $this->manager->createInstance($plugin->reveal(), 'configure');
$this->assertSame($plugin->reveal(), $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstanceDefaultFallback() {
$this->classResolver->getInstanceFromDefinition(Argument::cetera())->shouldNotBeCalled();
$plugin = $this->prophesize(PluginWithFormsInterface::class)->willImplement(PluginFormInterface::class);
$plugin->hasFormClass('missing')->willReturn(FALSE);
$plugin->hasFormClass('fallback')->willReturn(TRUE);
$plugin->getFormClass('fallback')->willReturn(get_class($plugin->reveal()));
$form_object = $this->manager->createInstance($plugin->reveal(), 'missing', 'fallback');
$this->assertSame($plugin->reveal(), $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstancePluginAware() {
$plugin_form = $this->prophesize(PluginFormInterface::class)->willImplement(PluginAwareInterface::class);
$expected = $plugin_form->reveal();
$this->classResolver->getInstanceFromDefinition(get_class($expected))->willReturn($expected);
$plugin = $this->prophesize(PluginWithFormsInterface::class);
$plugin->hasFormClass('operation_aware')->willReturn(TRUE);
$plugin->getFormClass('operation_aware')->willReturn(get_class($expected));
$plugin_form->setPlugin($plugin->reveal())->shouldBeCalled();
$form_object = $this->manager->createInstance($plugin->reveal(), 'operation_aware');
$this->assertSame($expected, $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstanceDefinitionException() {
$this->setExpectedException(InvalidPluginDefinitionException::class, 'The "the_plugin_id" plugin did not specify a "anything" form class');
$plugin = $this->prophesize(PluginWithFormsInterface::class);
$plugin->getPluginId()->willReturn('the_plugin_id');
$plugin->hasFormClass('anything')->willReturn(FALSE);
$form_object = $this->manager->createInstance($plugin->reveal(), 'anything');
$this->assertSame(NULL, $form_object);
}
/**
* @covers ::createInstance
*/
public function testCreateInstanceInvalidException() {
$this->setExpectedException(InvalidPluginDefinitionException::class, 'The "the_plugin_id" plugin did not specify a valid "invalid" form class, must implement \Drupal\Core\Plugin\PluginFormInterface');
$expected = new \stdClass();
$this->classResolver->getInstanceFromDefinition(get_class($expected))->willReturn($expected);
$plugin = $this->prophesize(PluginWithFormsInterface::class);
$plugin->getPluginId()->willReturn('the_plugin_id');
$plugin->hasFormClass('invalid')->willReturn(TRUE);
$plugin->getFormClass('invalid')->willReturn(get_class($expected));
$form_object = $this->manager->createInstance($plugin->reveal(), 'invalid');
$this->assertSame(NULL, $form_object);
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Drupal\Tests\Core\Plugin;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Plugin\PluginWithFormsInterface;
use Drupal\Core\Plugin\PluginWithFormsTrait;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Plugin\PluginWithFormsTrait
* @group Plugin
*/
class PluginWithFormsTraitTest extends UnitTestCase {
/**
* @covers ::getFormClass
* @covers ::hasFormClass
* @dataProvider providerGetFormClass
*/
public function testGetFormClass(PluginWithFormsInterface $block_plugin, $operation, $expected_class) {
$this->assertSame($expected_class, $block_plugin->getFormClass($operation));
$this->assertSame($expected_class !== NULL, $block_plugin->hasFormClass($operation));
}
/**
* @return array
*/
public function providerGetFormClass() {
$block_plugin_without_forms = new TestClass([], 'block_plugin_without_forms', [
'provider' => 'block_test',
]);
// A block plugin that has a form defined for the 'poke' operation.
$block_plugin_with_forms = new TestClass([], 'block_plugin_with_forms', [
'provider' => 'block_test',
'forms' => [
'poke' => static::class,
],
]);
return [
'block plugin without forms, "configure" operation' => [$block_plugin_without_forms, 'configure', TestClass::class],
'block plugin without forms, "tickle" operation' => [$block_plugin_without_forms, 'tickle', NULL],
'block plugin withut forms, "poke" operation' => [$block_plugin_without_forms, 'poke', NULL],
'block plugin with forms, "configure" operation' => [$block_plugin_with_forms, 'configure', TestClass::class],
'block plugin with forms, "tickle" operation' => [$block_plugin_with_forms, 'tickle', NULL],
'block plugin with forms, "poke" operation' => [$block_plugin_with_forms, 'poke', static::class],
];
}
}
class TestClass extends PluginBase implements PluginWithFormsInterface, PluginFormInterface {
use PluginWithFormsTrait;
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
return [];
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
}
}

View file

@ -1,11 +1,11 @@
<?php
namespace Drupal\Tests\Core\Render\Element {
namespace Drupal\Tests\Core\Render\Element;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Render\Element\MachineName;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
@ -103,12 +103,10 @@ class MachineNameTest extends UnitTestCase {
}
}
namespace Drupal\Core\Render\Element;
namespace Drupal\Core\Render\Element {
if (!function_exists('t')) {
function t($string, array $args = []) {
return strtr($string, $args);
}
if (!function_exists('t')) {
function t($string, array $args = []) {
return strtr($string, $args);
}
}

View file

@ -58,6 +58,8 @@ class ElementInfoManagerTest extends UnitTestCase {
* @covers ::__construct
*/
protected function setUp() {
parent::setUp();
$this->cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$this->cacheTagsInvalidator = $this->getMock('Drupal\Core\Cache\CacheTagsInvalidatorInterface');
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');

View file

@ -326,9 +326,9 @@ class RendererBubblingTest extends RendererTestBase {
],
'grandgrandchild' => [
'#access_callback' => function () use (&$current_user_role) {
// Only role C can access this subtree.
return $current_user_role === 'C';
},
// Only role C can access this subtree.
return $current_user_role === 'C';
},
'#cache' => [
'contexts' => ['bar'],
'tags' => ['d'],

View file

@ -545,7 +545,7 @@ class RendererPlaceholdersTest extends RendererTestBase {
}
/**
* @param FALSE|array $cid_parts
* @param false|array $cid_parts
* @param array $expected_data
* FALSE if no render cache item is expected, a render array with the
* expected values if a render cache item is expected.

View file

@ -140,6 +140,32 @@ class RendererTest extends RendererTestBase {
'#children' => 'foo',
'child' => ['#markup' => 'bar'],
], 'foo'];
// Ensure that content added to #markup via a #pre_render callback is safe.
$data[] = [[
'#markup' => 'foo',
'#pre_render' => [function($elements) {
$elements['#markup'] .= '<script>alert("bar");</script>';
return $elements;
}]
], 'fooalert("bar");'];
// Test #allowed_tags in combination with #markup and #pre_render.
$data[] = [[
'#markup' => 'foo',
'#allowed_tags' => array('script'),
'#pre_render' => [function($elements) {
$elements['#markup'] .= '<script>alert("bar");</script>';
return $elements;
}]
], 'foo<script>alert("bar");</script>'];
// Ensure output is escaped when adding content to #check_plain through
// a #pre_render callback.
$data[] = [[
'#plain_text' => 'foo',
'#pre_render' => [function($elements) {
$elements['#plain_text'] .= '<script>alert("bar");</script>';
return $elements;
}]
], 'foo&lt;script&gt;alert(&quot;bar&quot;);&lt;/script&gt;'];
// Part 2: render arrays using #theme and #theme_wrappers.

View file

@ -8,6 +8,7 @@ use Drupal\Core\Routing\AccessAwareRouterInterface;
use Drupal\Tests\UnitTestCase;
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Route;
/**
@ -105,6 +106,22 @@ class AccessAwareRouterTest extends UnitTestCase {
$this->assertSame($expected, $parameters);
}
/**
* Tests the matchRequest() function for access denied with reason message.
*/
public function testCheckAccessResultWithReason() {
$this->setupRouter();
$request = new Request();
$reason = $this->getRandomGenerator()->string();
$access_result = AccessResult::forbidden($reason);
$this->accessManager->expects($this->once())
->method('checkRequest')
->with($request)
->willReturn($access_result);
$this->setExpectedException(AccessDeniedHttpException::class, $reason);
$this->router->matchRequest($request);
}
/**
* Ensure that methods are passed to the wrapped router.
*

View file

@ -0,0 +1,127 @@
<?php
namespace Drupal\Tests\Core\Routing;
use Drupal\Core\Routing\MethodFilter;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
/**
* @coversDefaultClass \Drupal\Core\Routing\MethodFilter
* @group Routing
*/
class MethodFilterTest extends \PHPUnit_Framework_TestCase {
/**
* @covers ::applies
* @dataProvider providerApplies
*/
public function testApplies(array $route_methods, $expected_applies) {
$route = new Route('/test', [], [], [], '', [], $route_methods);
$method_filter = new MethodFilter();
$this->assertSame($expected_applies, $method_filter->applies($route));
}
/**
* Data provider for testApplies().
*
* @return array
*/
public function providerApplies() {
return [
'only GET' => [['GET'], TRUE],
'only PATCH' => [['PATCH'], TRUE],
'only POST' => [['POST'], TRUE],
'only DELETE' => [['DELETE'], TRUE],
'only HEAD' => [['HEAD'], TRUE],
'all' => [['GET', 'PATCH', 'POST', 'DELETE', 'HEAD'], TRUE],
'none' => [[], FALSE],
];
}
/**
* @covers ::filter
*/
public function testWithAllowedMethod() {
$request = Request::create('/test', 'GET');
$collection = new RouteCollection();
$collection->add('test_route.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection_before = clone $collection;
$method_filter = new MethodFilter();
$result_collection = $method_filter->filter($collection, $request);
$this->assertEquals($collection_before, $result_collection);
}
/**
* @covers ::filter
*/
public function testWithAllowedMethodAndMultipleMatchingRoutes() {
$request = Request::create('/test', 'GET');
$collection = new RouteCollection();
$collection->add('test_route.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection->add('test_route2.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection->add('test_route3.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection_before = clone $collection;
$method_filter = new MethodFilter();
$result_collection = $method_filter->filter($collection, $request);
$this->assertEquals($collection_before, $result_collection);
}
/**
* @covers ::filter
*/
public function testMethodNotAllowedException() {
$request = Request::create('/test', 'PATCH');
$collection = new RouteCollection();
$collection->add('test_route.get', new Route('/test', [], [], [], '', [], ['GET']));
$this->setExpectedException(MethodNotAllowedException::class);
$method_filter = new MethodFilter();
$method_filter->filter($collection, $request);
}
/**
* @covers ::filter
*/
public function testMethodNotAllowedExceptionWithMultipleRoutes() {
$request = Request::create('/test', 'PATCH');
$collection = new RouteCollection();
$collection->add('test_route.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection->add('test_route2.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection->add('test_route3.get', new Route('/test', [], [], [], '', [], ['GET']));
$this->setExpectedException(MethodNotAllowedException::class);
$method_filter = new MethodFilter();
$method_filter->filter($collection, $request);
}
/**
* @covers ::filter
*/
public function testFilteredMethods() {
$request = Request::create('/test', 'PATCH');
$collection = new RouteCollection();
$collection->add('test_route.get', new Route('/test', [], [], [], '', [], ['GET']));
$collection->add('test_route2.get', new Route('/test', [], [], [], '', [], ['PATCH']));
$collection->add('test_route3.get', new Route('/test', [], [], [], '', [], ['POST']));
$expected_collection = new RouteCollection();
$expected_collection->add('test_route2.get', new Route('/test', [], [], [], '', [], ['PATCH']));
$method_filter = new MethodFilter();
$result_collection = $method_filter->filter($collection, $request);
$this->assertEquals($expected_collection, $result_collection);
}
}

View file

@ -101,7 +101,7 @@ class RedirectDestinationTest extends UnitTestCase {
// A request with a destination query.
$data[] = [$request, '/example'];
// A request without a destination query,
// A request without a destination query,
$request = Request::create('/');
$data[] = [$request, '/current-path'];

View file

@ -7,8 +7,8 @@
namespace Drupal\Tests\Core\Routing;
use Drupal\Component\Discovery\YamlDiscovery;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Discovery\YamlDiscovery;
use Drupal\Core\Routing\RouteBuilder;
use Drupal\Core\Routing\RouteBuildEvent;
use Drupal\Core\Routing\RoutingEvents;
@ -53,7 +53,7 @@ class RouteBuilderTest extends UnitTestCase {
/**
* The mocked YAML discovery.
*
* @var \Drupal\Component\Discovery\YamlDiscovery|\PHPUnit_Framework_MockObject_MockObject
* @var \Drupal\Core\Discovery\YamlDiscovery|\PHPUnit_Framework_MockObject_MockObject
*/
protected $yamlDiscovery;
@ -82,7 +82,7 @@ class RouteBuilderTest extends UnitTestCase {
$this->dispatcher = $this->getMock('\Symfony\Component\EventDispatcher\EventDispatcherInterface');
$this->moduleHandler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$this->controllerResolver = $this->getMock('Drupal\Core\Controller\ControllerResolverInterface');
$this->yamlDiscovery = $this->getMockBuilder('\Drupal\Component\Discovery\YamlDiscovery')
$this->yamlDiscovery = $this->getMockBuilder('\Drupal\Core\Discovery\YamlDiscovery')
->disableOriginalConstructor()
->getMock();
$this->checkProvider = $this->getMock('\Drupal\Core\Access\CheckProviderInterface');
@ -284,14 +284,14 @@ class TestRouteBuilder extends RouteBuilder {
/**
* The mocked YAML discovery.
*
* @var \Drupal\Component\Discovery\YamlDiscovery|\PHPUnit_Framework_MockObject_MockObject
* @var \Drupal\Core\Discovery\YamlDiscovery|\PHPUnit_Framework_MockObject_MockObject
*/
protected $yamlDiscovery;
/**
* Sets the YAML discovery.
*
* @param \Drupal\Component\Discovery\YamlDiscovery $yaml_discovery
* @param \Drupal\Core\Discovery\YamlDiscovery $yaml_discovery
* The YAML discovery to set.
*/
public function setYamlDiscovery(YamlDiscovery $yaml_discovery) {

View file

@ -0,0 +1,64 @@
<?php
namespace Drupal\Tests\Core\Serialization;
use Drupal\Component\Serialization\SerializationInterface;
use Drupal\Core\Serialization\Yaml;
use Drupal\Core\Site\Settings;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Serialization\Yaml
* @group Serialization
*/
class YamlTest extends UnitTestCase {
/**
* Test that the overridden serializer is called.
*
* @covers ::getSerializer
* @runInSeparateProcess
*/
public function testGetSeralization() {
new Settings(['yaml_parser_class' => YamlParserProxy::class]);
$this->assertEquals(YamlParserProxy::class, Settings::get('yaml_parser_class'));
$mock = $this->getMockBuilder('\stdClass')
->setMethods(['encode', 'decode', 'getFileExtension'])
->getMock();
$mock
->expects($this->once())
->method('decode');
YamlParserProxy::setMock($mock);
Yaml::decode('---');
new Settings([]);
}
}
class YamlParserProxy implements SerializationInterface {
/**
* @var \Drupal\Component\Serialization\SerializationInterface
*/
protected static $mock;
public static function setMock($mock) {
static::$mock = $mock;
}
public static function encode($data) {
return static::$mock->encode($data);
}
public static function decode($raw) {
return static::$mock->decode($raw);
}
public static function getFileExtension() {
return static::$mock->getFileExtension();
}
}

View file

@ -1,6 +1,6 @@
<?php
namespace Drupal\Tests\Core\Session {
namespace Drupal\Tests\Core\Session;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Session\PermissionsHashGenerator;
@ -246,19 +246,15 @@ class PermissionsHashGeneratorTest extends UnitTestCase {
}
}
namespace Drupal\Core\Session;
namespace {
// @todo remove once user_role_permissions() can be injected.
if (!function_exists('user_role_permissions')) {
function user_role_permissions(array $roles) {
$role_permissions = array();
foreach ($roles as $rid) {
$role_permissions[$rid] = array();
}
return $role_permissions;
// @todo remove once user_role_permissions() can be injected.
if (!function_exists('user_role_permissions')) {
function user_role_permissions(array $roles) {
$role_permissions = array();
foreach ($roles as $rid) {
$role_permissions[$rid] = array();
}
return $role_permissions;
}
}

View file

@ -5,9 +5,9 @@ namespace Drupal\Tests\Core\Session;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Session\UserSession;
use Drupal\Tests\UnitTestCase;
use Drupal\user\RoleInterface;
use Drupal\user\RoleInterface;
/**
/**
* @coversDefaultClass \Drupal\Core\Session\UserSession
* @group Session
*/

View file

@ -95,11 +95,11 @@ class SettingsTest extends UnitTestCase {
* @return array
*/
public function providerTestGetHashSaltEmpty() {
return array(
array(array()),
array(array('hash_salt' => '')),
array(array('hash_salt' => NULL)),
);
return array(
array(array()),
array(array('hash_salt' => '')),
array(array('hash_salt' => NULL)),
);
}
/**

View file

@ -46,7 +46,7 @@ class NegotiationMiddlewareTest extends UnitTestCase {
*/
public function testAjaxIframeUpload() {
$request = new Request();
$request->attributes->set('ajax_iframe_upload', '1');
$request->request->set('ajax_iframe_upload', '1');
$this->assertSame('iframeupload', $this->contentNegotiation->getContentType($request));
}
@ -101,9 +101,11 @@ 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_data = $this->prophesize(ParameterBag::class);
$request_data->get('ajax_iframe_upload', FALSE)->shouldBeCalled();
$request_mock = $request->reveal();
$request_mock->query = new ParameterBag([]);
$request_mock->request = $request_data->reveal();
// Calling kernel app with default arguments.
$this->app->handle($request_mock, HttpKernelInterface::MASTER_REQUEST, TRUE)
@ -126,9 +128,11 @@ class NegotiationMiddlewareTest extends UnitTestCase {
// Some calls we don't care about.
$request->setRequestFormat('html')->shouldBeCalled();
$request->get('ajax_iframe_upload', FALSE)->shouldBeCalled();
$request_data = $this->prophesize(ParameterBag::class);
$request_data->get('ajax_iframe_upload', FALSE)->shouldBeCalled();
$request_mock = $request->reveal();
$request_mock->query = new ParameterBag([]);
$request_mock->request = $request_data->reveal();
// Trigger handle.
$this->contentNegotiation->registerFormat('david', 'geeky/david');

View file

@ -49,9 +49,9 @@ class ReverseProxyMiddlewareTest extends UnitTestCase {
* @dataProvider reverseProxyEnabledProvider
*/
public function testReverseProxyEnabled($provided_settings) {
// Enable reverse proxy and add test values.
$settings = new Settings(array('reverse_proxy' => 1) + $provided_settings);
$this->trustedHeadersAreSet($settings);
// Enable reverse proxy and add test values.
$settings = new Settings(array('reverse_proxy' => 1) + $provided_settings);
$this->trustedHeadersAreSet($settings);
}
/**

View file

@ -68,8 +68,8 @@ class TranslatableMarkupTest extends UnitTestCase {
->method('translateString')
->with($text)
->willReturnCallback(function () {
throw new \Exception('Yes you may.');
});
throw new \Exception('Yes you may.');
});
// We set a custom error handler because of https://github.com/sebastianbergmann/phpunit/issues/487
set_error_handler([$this, 'errorHandler']);

View file

@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\Core\Test;
use Drupal\Core\Test\TestDatabase;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Test\TestDatabase
* @group Template
*/
class TestDatabaseTest extends UnitTestCase {
/**
* @covers ::__construct
*/
public function testConstructorException() {
$this->setExpectedException(\InvalidArgumentException::class, "Invalid database prefix: blah1253");
new TestDatabase('blah1253');
}
/**
* @covers ::__construct
* @covers ::getDatabasePrefix
* @covers ::getTestSitePath
*
* @dataProvider providerTestConstructor
*/
public function testConstructor($db_prefix, $expected_db_prefix, $expected_site_path) {
$test_db = new TestDatabase($db_prefix);
$this->assertEquals($expected_db_prefix, $test_db->getDatabasePrefix());
$this->assertEquals($expected_site_path, $test_db->getTestSitePath());
}
/**
* Data provider for self::testConstructor()
*/
public function providerTestConstructor() {
return [
['test1234', 'test1234', 'sites/simpletest/1234'],
['test123456test234567', 'test123456test234567', 'sites/simpletest/234567']
];
}
}

View file

@ -0,0 +1,127 @@
<?php
namespace Drupal\Tests\Core\Theme;
use Drupal\Core\Access\CsrfTokenGenerator;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Theme\AjaxBasePageNegotiator;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
/**
* @coversDefaultClass \Drupal\Core\Theme\AjaxBasePageNegotiator
* @group Theme
*/
class AjaxBasePageNegotiatorTest extends UnitTestCase {
/**
* @var \Drupal\Core\Theme\AjaxBasePageNegotiator
*
* The AJAX base page negotiator.
*/
protected $negotiator;
/**
* @var \Drupal\Core\Access\CsrfTokenGenerator|\Prophecy\Prophecy\ProphecyInterface
*
* The CSRF token generator.
*/
protected $tokenGenerator;
/**
* @var \Symfony\Component\HttpFoundation\RequestStack
*
* The request stack.
*/
protected $requestStack;
/**
* {@inheritdoc}
*/
public function setUp() {
parent::setUp();
$this->tokenGenerator = $this->prophesize(CsrfTokenGenerator::class);
$config_factory = $this->getConfigFactoryStub(['system.theme' => ['default' => 'bartik']]);
$this->requestStack = new RequestStack();
$this->negotiator = new AjaxBasePageNegotiator($this->tokenGenerator->reveal(), $config_factory, $this->requestStack);
}
/**
* @covers ::applies
* @dataProvider providerTestApplies
*/
public function testApplies($request_data, $expected) {
$request = new Request([], $request_data);
$route_match = RouteMatch::createFromRequest($request);
$this->requestStack->push($request);
$result = $this->negotiator->applies($route_match);
$this->assertSame($expected, $result);
}
public function providerTestApplies() {
$data = [];
$data['empty'] = [[], FALSE];
$data['no_theme'] = [['ajax_page_state' => ['theme' => '', 'theme_token' => '']], FALSE];
$data['valid_theme_empty_theme_token'] = [['ajax_page_state' => ['theme' => 'seven', 'theme_token' => '']], TRUE];
$data['valid_theme_valid_theme_token'] = [['ajax_page_state' => ['theme' => 'seven', 'theme_token' => 'valid_theme_token']], TRUE];
return $data;
}
/**
* @covers ::determineActiveTheme
*/
public function testDetermineActiveThemeValidToken() {
$theme = 'seven';
$theme_token = 'valid_theme_token';
$request = new Request([], ['ajax_page_state' => ['theme' => $theme, 'theme_token' => $theme_token]]);
$this->requestStack->push($request);
$route_match = RouteMatch::createFromRequest($request);
$this->tokenGenerator->validate($theme_token, $theme)->willReturn(TRUE);
$result = $this->negotiator->determineActiveTheme($route_match);
$this->assertSame($theme, $result);
}
/**
* @covers ::determineActiveTheme
*/
public function testDetermineActiveThemeInvalidToken() {
$theme = 'seven';
$theme_token = 'invalid_theme_token';
$request = new Request([], ['ajax_page_state' => ['theme' => $theme, 'theme_token' => $theme_token]]);
$this->requestStack->push($request);
$route_match = RouteMatch::createFromRequest($request);
$this->tokenGenerator->validate($theme_token, $theme)->willReturn(FALSE);
$result = $this->negotiator->determineActiveTheme($route_match);
$this->assertSame(NULL, $result);
}
/**
* @covers ::determineActiveTheme
*/
public function testDetermineActiveThemeDefaultTheme() {
$theme = 'bartik';
// When the theme is the system default, an empty string is provided as the
// theme token. See system_js_settings_alter().
$theme_token = '';
$request = new Request([], ['ajax_page_state' => ['theme' => $theme, 'theme_token' => $theme_token]]);
$this->requestStack->push($request);
$route_match = RouteMatch::createFromRequest($request);
$this->tokenGenerator->validate(Argument::cetera())->shouldNotBeCalled();
$result = $this->negotiator->determineActiveTheme($route_match);
$this->assertSame($theme, $result);
}
}

View file

@ -24,7 +24,7 @@ class PhpTransliterationTest extends UnitTestCase {
* The string which was not transliterated yet.
* @param string $expected
* The string expected after the transliteration.
* @param string|NULL $printable
* @param string|null $printable
* (optional) An alternative version of the original string which is
* printable in the output.
*

View file

@ -154,7 +154,7 @@ class UrlTest extends UnitTestCase {
return $urls;
}
/**
/**
* This constraint checks whether a Request object has the right path.
*
* @param string $path
@ -811,7 +811,7 @@ class UrlTest extends UnitTestCase {
* Creates a mock access manager for the access tests.
*
* @param bool $access
* @param \Drupal\Core\Session\AccountInterface|NULL $account
* @param \Drupal\Core\Session\AccountInterface|null $account
*
* @return \Drupal\Core\Access\AccessManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/

View file

@ -112,7 +112,7 @@ class ErrorTest extends UnitTestCase {
/**
* Creates a mock backtrace item.
*
* @param string|NULL $function
* @param string|null $function
* (optional) The function name to use in the backtrace item.
* @param string $class
* (optional) The class to use in the backtrace item.

View file

@ -1,8 +1,9 @@
<?php
namespace Drupal\Tests\Core\Utility {
namespace Drupal\Tests\Core\Utility;
use Drupal\Component\Render\MarkupInterface;
use Drupal\Core\GeneratedNoLink;
use Drupal\Core\GeneratedUrl;
use Drupal\Core\Language\Language;
use Drupal\Core\Link;
@ -148,6 +149,26 @@ class LinkGeneratorTest extends UnitTestCase {
), $result);
}
/**
* Tests the generate() method with the <nolink> route.
*
* @covers ::generate
*/
public function testGenerateNoLink() {
$this->urlGenerator->expects($this->never())
->method('generateFromRoute');
$this->moduleHandler->expects($this->once())
->method('alter')
->with('link', $this->isType('array'));
$url = Url::fromRoute('<nolink>');
$url->setUrlGenerator($this->urlGenerator);
$result = $this->linkGenerator->generate('Test', $url);
$this->assertTrue($result instanceof GeneratedNoLink);
$this->assertSame('<span>Test</span>', (string) $result);
}
/**
* Tests the generate() method with an external URL.
*
@ -575,5 +596,3 @@ class LinkGeneratorTest extends UnitTestCase {
}
}
}

View file

@ -77,11 +77,11 @@ class UnroutedUrlAssemblerTest extends UnitTestCase {
* @dataProvider providerTestAssembleWithExternalUrl
*/
public function testAssembleWithExternalUrl($uri, array $options, $expected) {
$this->setupRequestStack(FALSE);
$this->assertEquals($expected, $this->unroutedUrlAssembler->assemble($uri, $options));
$generated_url = $this->unroutedUrlAssembler->assemble($uri, $options, TRUE);
$this->assertEquals($expected, $generated_url->getGeneratedUrl());
$this->assertInstanceOf('\Drupal\Core\Render\BubbleableMetadata', $generated_url);
$this->setupRequestStack(FALSE);
$this->assertEquals($expected, $this->unroutedUrlAssembler->assemble($uri, $options));
$generated_url = $this->unroutedUrlAssembler->assemble($uri, $options, TRUE);
$this->assertEquals($expected, $generated_url->getGeneratedUrl());
$this->assertInstanceOf('\Drupal\Core\Render\BubbleableMetadata', $generated_url);
}
/**