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:
parent
2f563ab520
commit
f1c8716f57
1732 changed files with 52334 additions and 11780 deletions
|
@ -8,13 +8,14 @@ use Behat\Mink\Mink;
|
|||
use Behat\Mink\Session;
|
||||
use Drupal\Component\FileCache\FileCacheFactory;
|
||||
use Drupal\Component\Serialization\Json;
|
||||
use Drupal\Component\Serialization\Yaml;
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Utility\SafeMarkup;
|
||||
use Drupal\Component\Utility\UrlHelper;
|
||||
use Drupal\Core\Cache\Cache;
|
||||
use Drupal\Core\Config\Testing\ConfigSchemaChecker;
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\Core\DrupalKernel;
|
||||
use Drupal\Core\Serialization\Yaml;
|
||||
use Drupal\Core\Session\AccountInterface;
|
||||
use Drupal\Core\Session\AnonymousUserSession;
|
||||
use Drupal\Core\Session\UserSession;
|
||||
|
@ -56,6 +57,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
use ContentTypeCreationTrait {
|
||||
createContentType as drupalCreateContentType;
|
||||
}
|
||||
use ConfigTestTrait;
|
||||
use UserCreationTrait {
|
||||
createRole as drupalCreateRole;
|
||||
createUser as drupalCreateUser;
|
||||
|
@ -153,6 +155,44 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
*/
|
||||
protected $configImporter;
|
||||
|
||||
/**
|
||||
* Set to TRUE to strict check all configuration saved.
|
||||
*
|
||||
* @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $strictConfigSchema = TRUE;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* The test runner will merge the $modules lists from this class, the class
|
||||
* it extends, and so on up the class hierarchy. It is not necessary to
|
||||
* include modules in your list that a parent class has already declared.
|
||||
*
|
||||
* @var string[]
|
||||
*
|
||||
* @see \Drupal\Tests\BrowserTestBase::installDrupal()
|
||||
*/
|
||||
public static $modules = [];
|
||||
|
||||
/**
|
||||
* An array of config object names that are excluded from schema checking.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected static $configSchemaCheckerExclusions = array(
|
||||
// Following are used to test lack of or partial schema. Where partial
|
||||
// schema is provided, that is explicitly tested in specific tests.
|
||||
'config_schema_test.noschema',
|
||||
'config_schema_test.someschema',
|
||||
'config_schema_test.schema_data_types',
|
||||
'config_schema_test.no_schema_data_types',
|
||||
// Used to test application of schema to filtering of configuration.
|
||||
'config_test.dynamic.system',
|
||||
);
|
||||
|
||||
/**
|
||||
* The profile to install as a basis for testing.
|
||||
*
|
||||
|
@ -358,7 +398,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
}
|
||||
|
||||
if (is_array($this->minkDefaultDriverArgs)) {
|
||||
// Use ReflectionClass to instantiate class with received params.
|
||||
// Use ReflectionClass to instantiate class with received params.
|
||||
$reflector = new \ReflectionClass($this->minkDefaultDriverClass);
|
||||
$driver = $reflector->newInstanceArgs($this->minkDefaultDriverArgs);
|
||||
}
|
||||
|
@ -628,17 +668,29 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
* Drupal path or URL to load into Mink controlled browser.
|
||||
* @param array $options
|
||||
* (optional) Options to be forwarded to the url generator.
|
||||
* @param string[] $headers
|
||||
* An array containing additional HTTP request headers, the array keys are
|
||||
* the header names and the array values the header values. This is useful
|
||||
* to set for example the "Accept-Language" header for requesting the page
|
||||
* in a different language. Note that not all headers are supported, for
|
||||
* example the "Accept" header is always overridden by the browser. For
|
||||
* testing REST APIs it is recommended to directly use an HTTP client such
|
||||
* as Guzzle instead.
|
||||
*
|
||||
* @return string
|
||||
* The retrieved HTML string, also available as $this->getRawContent()
|
||||
*/
|
||||
protected function drupalGet($path, array $options = array()) {
|
||||
protected function drupalGet($path, array $options = array(), array $headers = array()) {
|
||||
$options['absolute'] = TRUE;
|
||||
$url = $this->buildUrl($path, $options);
|
||||
|
||||
$session = $this->getSession();
|
||||
|
||||
$this->prepareRequest();
|
||||
foreach ($headers as $header_name => $header_value) {
|
||||
$session->setRequestHeader($header_name, $header_value);
|
||||
}
|
||||
|
||||
$session->visit($url);
|
||||
$out = $session->getPage()->getContent();
|
||||
|
||||
|
@ -989,6 +1041,17 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
}
|
||||
// Copy the testing-specific service overrides in place.
|
||||
copy($settings_services_file, $directory . '/services.yml');
|
||||
if ($this->strictConfigSchema) {
|
||||
// Add a listener to validate configuration schema on save.
|
||||
$content = file_get_contents($directory . '/services.yml');
|
||||
$services = Yaml::decode($content);
|
||||
$services['services']['simpletest.config_schema_checker'] = [
|
||||
'class' => ConfigSchemaChecker::class,
|
||||
'arguments' => ['@config.typed', $this->getConfigSchemaExclusions()],
|
||||
'tags' => [['name' => 'event_subscriber']]
|
||||
];
|
||||
file_put_contents($directory . '/services.yml', Yaml::encode($services));
|
||||
}
|
||||
|
||||
// Since Drupal is bootstrapped already, install_begin_request() will not
|
||||
// bootstrap into DRUPAL_BOOTSTRAP_CONFIGURATION (again). Hence, we have to
|
||||
|
@ -1151,14 +1214,9 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
* @see BrowserTestBase::prepareEnvironment()
|
||||
*/
|
||||
private function prepareDatabasePrefix() {
|
||||
// Ensure that the generated test site directory does not exist already,
|
||||
// which may happen with a large amount of concurrent threads and
|
||||
// long-running tests.
|
||||
do {
|
||||
$suffix = mt_rand(100000, 999999);
|
||||
$this->siteDirectory = 'sites/simpletest/' . $suffix;
|
||||
$this->databasePrefix = 'simpletest' . $suffix;
|
||||
} while (is_dir(DRUPAL_ROOT . '/' . $this->siteDirectory));
|
||||
$test_db = new TestDatabase();
|
||||
$this->siteDirectory = $test_db->getTestSitePath();
|
||||
$this->databasePrefix = $test_db->getDatabasePrefix();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1565,10 +1623,14 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
*
|
||||
* @param string|\Drupal\Component\Render\MarkupInterface $label
|
||||
* Text between the anchor tags.
|
||||
* @param int $index
|
||||
* (optional) The index number for cases where multiple links have the same
|
||||
* text. Defaults to 0.
|
||||
*/
|
||||
protected function clickLink($label) {
|
||||
protected function clickLink($label, $index = 0) {
|
||||
$label = (string) $label;
|
||||
$this->getSession()->getPage()->clickLink($label);
|
||||
$links = $this->getSession()->getPage()->findAll('named', ['link', $label]);
|
||||
$links[$index]->click();
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -1685,4 +1747,23 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
|
|||
$file_cache->delete($filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the config schema exclusions for this test.
|
||||
*
|
||||
* @return string[]
|
||||
* An array of config object names that are excluded from schema checking.
|
||||
*/
|
||||
protected function getConfigSchemaExclusions() {
|
||||
$class = get_class($this);
|
||||
$exceptions = [];
|
||||
while ($class) {
|
||||
if (property_exists($class, 'configSchemaCheckerExclusions')) {
|
||||
$exceptions = array_merge($exceptions, $class::$configSchemaCheckerExclusions);
|
||||
}
|
||||
$class = get_parent_class($class);
|
||||
}
|
||||
// Filter out any duplicates.
|
||||
return array_unique($exceptions);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Contains \Drupal\Tests\Component\Assertion\InspectorTest.
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\Component\ClassFinder;
|
||||
|
||||
use Composer\Autoload\ClassLoader;
|
||||
use Drupal\Component\ClassFinder\ClassFinder;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\Component\ClassFinder\ClassFinder
|
||||
* @group ClassFinder
|
||||
*/
|
||||
class ClassFinderTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::findFile
|
||||
*/
|
||||
public function testFindFile() {
|
||||
$finder = new ClassFinder();
|
||||
|
||||
// The full path is returned therefore only tests with
|
||||
// assertStringEndsWith() so the test is portable.
|
||||
$this->assertStringEndsWith('core/tests/Drupal/Tests/UnitTestCase.php', $finder->findFile(UnitTestCase::class));
|
||||
$class = 'Not\\A\\Class';
|
||||
$this->assertNull($finder->findFile($class));
|
||||
|
||||
// Register an autoloader that can find this class.
|
||||
$loader = new ClassLoader();
|
||||
$loader->addClassMap([$class => __FILE__]);
|
||||
$loader->register();
|
||||
$this->assertEquals(__FILE__, $finder->findFile($class));
|
||||
// This shouldn't prevent us from finding the original file.
|
||||
$this->assertStringEndsWith('core/tests/Drupal/Tests/UnitTestCase.php', $finder->findFile(UnitTestCase::class));
|
||||
|
||||
// Clean up the additional autoloader after the test.
|
||||
$loader->unregister();
|
||||
}
|
||||
|
||||
}
|
|
@ -172,10 +172,24 @@ class ContainerAwareEventDispatcherTest extends SymfonyContainerAwareEventDispat
|
|||
$this->assertTrue($otherService->preFooInvoked);
|
||||
}
|
||||
|
||||
public function testGetListenerPriority()
|
||||
public function testGetListenerPriorityWithServices()
|
||||
{
|
||||
// Override the parent test as our implementation doesn't define
|
||||
// getListenerPriority().
|
||||
$container = new ContainerBuilder();
|
||||
$container->register('listener_service', TestEventListener::class);
|
||||
|
||||
$listeners = array(
|
||||
'test_event' => array(
|
||||
5 => array(
|
||||
array('service' => array('listener_service', 'preFoo')),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
$dispatcher = new ContainerAwareEventDispatcher($container, $listeners);
|
||||
$listenerService = $container->get('listener_service');
|
||||
$actualPriority = $dispatcher->getListenerPriority('test_event', [$listenerService, 'preFoo']);
|
||||
|
||||
$this->assertSame(5, $actualPriority);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -2,6 +2,8 @@
|
|||
|
||||
namespace Drupal\Tests\Component\FileCache;
|
||||
|
||||
use Drupal\Component\FileCache\FileCache;
|
||||
use Drupal\Component\FileCache\NullFileCache;
|
||||
use Drupal\Component\FileCache\FileCacheFactory;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
|
@ -17,18 +19,15 @@ class FileCacheFactoryTest extends UnitTestCase {
|
|||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$settings = [
|
||||
'collection' => 'test-23',
|
||||
'cache_backend_class' => '\Drupal\Tests\Component\FileCache\StaticFileCacheBackend',
|
||||
'cache_backend_configuration' => [
|
||||
'bin' => 'dog',
|
||||
$configuration = [
|
||||
'test_foo_settings' => [
|
||||
'collection' => 'test-23',
|
||||
'cache_backend_class' => '\Drupal\Tests\Component\FileCache\StaticFileCacheBackend',
|
||||
'cache_backend_configuration' => [
|
||||
'bin' => 'dog',
|
||||
],
|
||||
],
|
||||
];
|
||||
$configuration = FileCacheFactory::getConfiguration();
|
||||
if (!$configuration) {
|
||||
$configuration = [];
|
||||
}
|
||||
$configuration += [ 'test_foo_settings' => $settings ];
|
||||
FileCacheFactory::setConfiguration($configuration);
|
||||
FileCacheFactory::setPrefix('prefix');
|
||||
}
|
||||
|
@ -65,6 +64,97 @@ class FileCacheFactoryTest extends UnitTestCase {
|
|||
FileCacheFactory::get('test_foo_settings', []);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::get
|
||||
*/
|
||||
public function testGetDisabledFileCache() {
|
||||
// Ensure the returned FileCache is an instance of FileCache::class.
|
||||
$file_cache = FileCacheFactory::get('test_foo_settings', []);
|
||||
$this->assertInstanceOf(FileCache::class, $file_cache);
|
||||
|
||||
$configuration = FileCacheFactory::getConfiguration();
|
||||
$configuration[FileCacheFactory::DISABLE_CACHE] = TRUE;
|
||||
FileCacheFactory::setConfiguration($configuration);
|
||||
|
||||
// Ensure the returned FileCache is now an instance of NullFileCache::class.
|
||||
$file_cache = FileCacheFactory::get('test_foo_settings', []);
|
||||
$this->assertInstanceOf(NullFileCache::class, $file_cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::get
|
||||
*
|
||||
* @dataProvider configurationDataProvider
|
||||
*/
|
||||
public function testGetConfigurationOverrides($configuration, $arguments, $class) {
|
||||
FileCacheFactory::setConfiguration($configuration);
|
||||
|
||||
$file_cache = FileCacheFactory::get('test_foo_settings', $arguments);
|
||||
$this->assertInstanceOf($class, $file_cache);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testGetConfigurationOverrides().
|
||||
*/
|
||||
public function configurationDataProvider() {
|
||||
$data = [];
|
||||
|
||||
// Get a unique FileCache class.
|
||||
$file_cache = $this->getMockBuilder(FileCache::class)
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
$class = get_class($file_cache);
|
||||
|
||||
// Test fallback configuration.
|
||||
$data['fallback-configuration'] = [[
|
||||
], [], FileCache::class];
|
||||
|
||||
// Test default configuration.
|
||||
$data['default-configuration'] = [[
|
||||
'default' => [
|
||||
'class' => $class,
|
||||
],
|
||||
], [], $class];
|
||||
|
||||
// Test specific per collection setting.
|
||||
$data['collection-setting'] = [[
|
||||
'test_foo_settings' => [
|
||||
'class' => $class,
|
||||
],
|
||||
], [], $class];
|
||||
|
||||
|
||||
// Test default configuration plus specific per collection setting.
|
||||
$data['default-plus-collection-setting'] = [[
|
||||
'default' => [
|
||||
'class' => '\stdClass',
|
||||
],
|
||||
'test_foo_settings' => [
|
||||
'class' => $class,
|
||||
],
|
||||
], [], $class];
|
||||
|
||||
// Test default configuration plus class specific override.
|
||||
$data['default-plus-class-override'] = [[
|
||||
'default' => [
|
||||
'class' => '\stdClass',
|
||||
],
|
||||
], [ 'class' => $class ], $class];
|
||||
|
||||
// Test default configuration plus class specific override plus specific
|
||||
// per collection setting.
|
||||
$data['default-plus-class-plus-collection-setting'] = [[
|
||||
'default' => [
|
||||
'class' => '\stdClass',
|
||||
],
|
||||
'test_foo_settings' => [
|
||||
'class' => $class,
|
||||
],
|
||||
], [ 'class' => '\stdClass'], $class];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getConfiguration
|
||||
* @covers ::setConfiguration
|
||||
|
|
|
@ -230,7 +230,7 @@ public function testMethod($parameter)
|
|||
|
||||
EOS;
|
||||
|
||||
$this->assertEquals($this->buildExpectedClass($class, $method_body), $result);
|
||||
$this->assertEquals($this->buildExpectedClass($class, $method_body), $result);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -13,6 +13,20 @@ use Drupal\Tests\UnitTestCase;
|
|||
*/
|
||||
class FormattableMarkupTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* The error message of the last error in the error handler.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $lastErrorMessage;
|
||||
|
||||
/**
|
||||
* The error number of the last error in the error handler.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $lastErrorNumber;
|
||||
|
||||
/**
|
||||
* @covers ::__toString
|
||||
* @covers ::jsonSerialize
|
||||
|
@ -35,4 +49,54 @@ class FormattableMarkupTest extends UnitTestCase {
|
|||
$this->assertEquals(strlen($string), $formattable_string->count());
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom error handler that saves the last error.
|
||||
*
|
||||
* We need this custom error handler because we cannot rely on the error to
|
||||
* exception conversion as __toString is never allowed to leak any kind of
|
||||
* exception.
|
||||
*
|
||||
* @param int $error_number
|
||||
* The error number.
|
||||
* @param string $error_message
|
||||
* The error message.
|
||||
*/
|
||||
public function errorHandler($error_number, $error_message) {
|
||||
$this->lastErrorNumber = $error_number;
|
||||
$this->lastErrorMessage = $error_message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::__toString
|
||||
* @dataProvider providerTestUnexpectedPlaceholder
|
||||
*/
|
||||
public function testUnexpectedPlaceholder($string, $arguments, $error_number, $error_message) {
|
||||
// We set a custom error handler because of https://github.com/sebastianbergmann/phpunit/issues/487
|
||||
set_error_handler([$this, 'errorHandler']);
|
||||
// We want this to trigger an error.
|
||||
$markup = new FormattableMarkup($string, $arguments);
|
||||
// Cast it to a string which will generate the errors.
|
||||
$output = (string) $markup;
|
||||
restore_error_handler();
|
||||
// The string should not change.
|
||||
$this->assertEquals($string, $output);
|
||||
$this->assertEquals($error_number, $this->lastErrorNumber);
|
||||
$this->assertEquals($error_message, $this->lastErrorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for FormattableMarkupTest::testUnexpectedPlaceholder().
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function providerTestUnexpectedPlaceholder() {
|
||||
return [
|
||||
['Non alpha starting character: ~placeholder', ['~placeholder' => 'replaced'], E_USER_ERROR, 'Invalid placeholder (~placeholder) in string: Non alpha starting character: ~placeholder'],
|
||||
['Alpha starting character: placeholder', ['placeholder' => 'replaced'], E_USER_DEPRECATED, 'Invalid placeholder (placeholder) in string: Alpha starting character: placeholder'],
|
||||
// Ensure that where the placeholder is located in the the string is
|
||||
// irrelevant.
|
||||
['placeholder', ['placeholder' => 'replaced'], E_USER_DEPRECATED, 'Invalid placeholder (placeholder) in string: placeholder'],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,83 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\Component\Serialization;
|
||||
|
||||
use Drupal\Component\Serialization\YamlPecl;
|
||||
|
||||
/**
|
||||
* Tests the YamlPecl serialization implementation.
|
||||
*
|
||||
* @group Drupal
|
||||
* @group Serialization
|
||||
* @coversDefaultClass \Drupal\Component\Serialization\YamlPecl
|
||||
* @requires extension yaml
|
||||
*/
|
||||
class YamlPeclTest extends YamlTestBase {
|
||||
|
||||
/**
|
||||
* Tests encoding and decoding basic data structures.
|
||||
*
|
||||
* @covers ::encode
|
||||
* @covers ::decode
|
||||
* @dataProvider providerEncodeDecodeTests
|
||||
*/
|
||||
public function testEncodeDecode($data) {
|
||||
$this->assertEquals($data, YamlPecl::decode(YamlPecl::encode($data)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests decoding YAML node anchors.
|
||||
*
|
||||
* @covers ::decode
|
||||
* @dataProvider providerDecodeTests
|
||||
*/
|
||||
public function testDecode($string, $data) {
|
||||
$this->assertEquals($data, YamlPecl::decode($string));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests our encode settings.
|
||||
*
|
||||
* @covers ::encode
|
||||
*/
|
||||
public function testEncode() {
|
||||
$this->assertEquals('---
|
||||
foo:
|
||||
bar: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sapien ex, venenatis vitae nisi eu, posuere luctus dolor. Nullam convallis
|
||||
...
|
||||
', YamlPecl::encode(['foo' => ['bar' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sapien ex, venenatis vitae nisi eu, posuere luctus dolor. Nullam convallis']]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests YAML boolean callback.
|
||||
*
|
||||
* @param string $string
|
||||
* String value for the YAML boolean.
|
||||
* @param string|bool $expected
|
||||
* The expected return value.
|
||||
*
|
||||
* @covers ::applyBooleanCallbacks
|
||||
* @dataProvider providerBoolTest
|
||||
*/
|
||||
public function testApplyBooleanCallbacks($string, $expected) {
|
||||
$this->assertEquals($expected, YamlPecl::applyBooleanCallbacks($string, 'bool', NULL));
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getFileExtension
|
||||
*/
|
||||
public function testGetFileExtension() {
|
||||
$this->assertEquals('yml', YamlPecl::getFileExtension());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that invalid YAML throws an exception.
|
||||
*
|
||||
* @covers ::errorHandler
|
||||
* @expectedException \Drupal\Component\Serialization\Exception\InvalidDataTypeException
|
||||
*/
|
||||
public function testError() {
|
||||
YamlPecl::decode('foo: [ads');
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,65 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\Component\Serialization;
|
||||
|
||||
use Drupal\Component\Serialization\YamlSymfony;
|
||||
|
||||
/**
|
||||
* Tests the YamlSymfony serialization implementation.
|
||||
*
|
||||
* @group Drupal
|
||||
* @group Serialization
|
||||
* @coversDefaultClass \Drupal\Component\Serialization\YamlSymfony
|
||||
*/
|
||||
class YamlSymfonyTest extends YamlTestBase {
|
||||
|
||||
/**
|
||||
* Tests encoding and decoding basic data structures.
|
||||
*
|
||||
* @covers ::encode
|
||||
* @covers ::decode
|
||||
* @dataProvider providerEncodeDecodeTests
|
||||
*/
|
||||
public function testEncodeDecode($data) {
|
||||
$this->assertEquals($data, YamlSymfony::decode(YamlSymfony::encode($data)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests decoding YAML node anchors.
|
||||
*
|
||||
* @covers ::decode
|
||||
* @dataProvider providerDecodeTests
|
||||
*/
|
||||
public function testDecode($string, $data) {
|
||||
$this->assertEquals($data, YamlSymfony::decode($string));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests our encode settings.
|
||||
*
|
||||
* @covers ::encode
|
||||
*/
|
||||
public function testEncode() {
|
||||
$this->assertEquals('foo:
|
||||
bar: \'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sapien ex, venenatis vitae nisi eu, posuere luctus dolor. Nullam convallis\'
|
||||
', YamlSymfony::encode(['foo' => ['bar' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sapien ex, venenatis vitae nisi eu, posuere luctus dolor. Nullam convallis']]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getFileExtension
|
||||
*/
|
||||
public function testGetFileExtension() {
|
||||
$this->assertEquals('yml', YamlSymfony::getFileExtension());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that invalid YAML throws an exception.
|
||||
*
|
||||
* @covers ::decode
|
||||
* @expectedException \Drupal\Component\Serialization\Exception\InvalidDataTypeException
|
||||
*/
|
||||
public function testError() {
|
||||
YamlSymfony::decode('foo: [ads');
|
||||
}
|
||||
|
||||
}
|
|
@ -2,7 +2,11 @@
|
|||
|
||||
namespace Drupal\Tests\Component\Serialization;
|
||||
|
||||
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
|
||||
use Drupal\Component\Serialization\SerializationInterface;
|
||||
use Drupal\Component\Serialization\Yaml;
|
||||
use Drupal\Component\Serialization\YamlPecl;
|
||||
use Drupal\Component\Serialization\YamlSymfony;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
|
@ -12,47 +16,118 @@ use Drupal\Tests\UnitTestCase;
|
|||
class YamlTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* @covers ::decode
|
||||
* @var \PHPUnit_Framework_MockObject_MockObject
|
||||
*/
|
||||
public function testDecode() {
|
||||
// Test that files without line break endings are properly interpreted.
|
||||
$yaml = 'foo: bar';
|
||||
$expected = array(
|
||||
'foo' => 'bar',
|
||||
);
|
||||
$this->assertSame($expected, Yaml::decode($yaml));
|
||||
$yaml .= "\n";
|
||||
$this->assertSame($expected, Yaml::decode($yaml));
|
||||
$yaml .= "\n";
|
||||
$this->assertSame($expected, Yaml::decode($yaml));
|
||||
protected $mockParser;
|
||||
|
||||
$yaml = "{}\n";
|
||||
$expected = array();
|
||||
$this->assertSame($expected, Yaml::decode($yaml));
|
||||
public function setUp() {
|
||||
parent::setUp();
|
||||
$this->mockParser = $this->getMockBuilder('\stdClass')
|
||||
->setMethods(['encode', 'decode', 'getFileExtension'])
|
||||
->getMock();
|
||||
YamlParserProxy::setMock($this->mockParser);
|
||||
}
|
||||
|
||||
$yaml = '';
|
||||
$this->assertNULL(Yaml::decode($yaml));
|
||||
$yaml .= "\n";
|
||||
$this->assertNULL(Yaml::decode($yaml));
|
||||
$yaml .= "\n";
|
||||
$this->assertNULL(Yaml::decode($yaml));
|
||||
public function tearDown() {
|
||||
YamlParserProxy::setMock(NULL);
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::encode
|
||||
* @covers ::decode
|
||||
*/
|
||||
public function testEncode() {
|
||||
$decoded = array(
|
||||
'foo' => 'bar',
|
||||
);
|
||||
$this->assertSame('foo: bar' . "\n", Yaml::encode($decoded));
|
||||
public function testDecode() {
|
||||
$this->mockParser
|
||||
->expects($this->once())
|
||||
->method('decode');
|
||||
YamlStub::decode('test');
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getFileExtension
|
||||
*/
|
||||
public function testGetFileExtension() {
|
||||
$this->assertEquals('yml', Yaml::getFileExtension());
|
||||
$this->mockParser
|
||||
->expects($this->never())
|
||||
->method('getFileExtension');
|
||||
$this->assertEquals('yml', YamlStub::getFileExtension());
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests all YAML files are decoded in the same way with Symfony and PECL.
|
||||
*
|
||||
* This test is a little bit slow but it tests that we do not have any bugs in
|
||||
* our YAML that might not be decoded correctly in any of our implementations.
|
||||
*
|
||||
* @todo This should exist as an integration test not part of our unit tests.
|
||||
* https://www.drupal.org/node/2597730
|
||||
*
|
||||
* @requires extension yaml
|
||||
* @dataProvider providerYamlFilesInCore
|
||||
*/
|
||||
public function testYamlFiles($file) {
|
||||
$data = file_get_contents($file);
|
||||
try {
|
||||
$this->assertEquals(YamlSymfony::decode($data), YamlPecl::decode($data), $file);
|
||||
}
|
||||
catch (InvalidDataTypeException $e) {
|
||||
// Provide file context to the failure so the exception message is useful.
|
||||
$this->fail("Exception thrown parsing $file:\n" . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider that lists all YAML files in core.
|
||||
*/
|
||||
public function providerYamlFilesInCore() {
|
||||
$files = [];
|
||||
$dirs = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(__DIR__ . '/../../../../../', \RecursiveDirectoryIterator::FOLLOW_SYMLINKS));
|
||||
foreach ($dirs as $dir) {
|
||||
$pathname = $dir->getPathname();
|
||||
// Exclude vendor.
|
||||
if ($dir->getExtension() == 'yml' && strpos($pathname, '/../../../../../vendor') === FALSE) {
|
||||
if (strpos($dir->getRealPath(), 'invalid_file') !== FALSE) {
|
||||
// There are some intentionally invalid files provided for testing
|
||||
// library API behaviours, ignore them.
|
||||
continue;
|
||||
}
|
||||
$files[] = [$dir->getRealPath()];
|
||||
}
|
||||
}
|
||||
return $files;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class YamlStub extends Yaml {
|
||||
|
||||
public static function getSerializer() {
|
||||
return '\Drupal\Tests\Component\Serialization\YamlParserProxy';
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,99 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\Component\Serialization;
|
||||
|
||||
/**
|
||||
* Provides standard data to validate different YAML implementations.
|
||||
*/
|
||||
abstract class YamlTestBase extends \PHPUnit_Framework_TestCase {
|
||||
|
||||
/**
|
||||
* Some data that should be able to be serialized.
|
||||
*/
|
||||
public function providerEncodeDecodeTests() {
|
||||
return [
|
||||
[
|
||||
'foo' => 'bar',
|
||||
'id' => 'schnitzel',
|
||||
'ponies' => ['nope', 'thanks'],
|
||||
'how' => [
|
||||
'about' => 'if',
|
||||
'i' => 'ask',
|
||||
'nicely',
|
||||
],
|
||||
'the' => [
|
||||
'answer' => [
|
||||
'still' => 'would',
|
||||
'be' => 'Y',
|
||||
],
|
||||
],
|
||||
'how_many_times' => 123,
|
||||
'should_i_ask' => FALSE,
|
||||
1,
|
||||
FALSE,
|
||||
[1, FALSE],
|
||||
[10],
|
||||
[0 => '123456'],
|
||||
],
|
||||
[NULL]
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Some data that should be able to be de-serialized.
|
||||
*/
|
||||
public function providerDecodeTests() {
|
||||
$data = [
|
||||
// NULL files.
|
||||
['', NULL],
|
||||
["\n", NULL],
|
||||
["---\n...\n", NULL],
|
||||
|
||||
// Node anchors.
|
||||
[
|
||||
"
|
||||
jquery.ui:
|
||||
version: &jquery_ui 1.10.2
|
||||
|
||||
jquery.ui.accordion:
|
||||
version: *jquery_ui
|
||||
",
|
||||
[
|
||||
'jquery.ui' => [
|
||||
'version' => '1.10.2',
|
||||
],
|
||||
'jquery.ui.accordion' => [
|
||||
'version' => '1.10.2',
|
||||
],
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// 1.2 Bool values.
|
||||
foreach ($this->providerBoolTest() as $test) {
|
||||
$data[] = ['bool: ' . $test[0], ['bool' => $test[1]]];
|
||||
}
|
||||
$data = array_merge($data, $this->providerBoolTest());
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests different boolean serialization and de-serialization.
|
||||
*/
|
||||
public function providerBoolTest() {
|
||||
return [
|
||||
['true', TRUE],
|
||||
['TRUE', TRUE],
|
||||
['True', TRUE],
|
||||
['y', 'y'],
|
||||
['Y', 'Y'],
|
||||
['false', FALSE],
|
||||
['FALSE', FALSE],
|
||||
['False', FALSE],
|
||||
['n', 'n'],
|
||||
['N', 'N'],
|
||||
];
|
||||
}
|
||||
|
||||
}
|
|
@ -5,7 +5,7 @@
|
|||
* Contains \Drupal\Tests\Component\Utility\ArgumentsResolverTest.
|
||||
*/
|
||||
|
||||
namespace Drupal\Tests\Component\Utility {
|
||||
namespace Drupal\Tests\Component\Utility;
|
||||
|
||||
use Drupal\Component\Utility\ArgumentsResolver;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
@ -187,7 +187,7 @@ class ArgumentsResolverTest extends UnitTestCase {
|
|||
$data = [];
|
||||
$data[] = [function($foo) {}];
|
||||
$data[] = [[new TestClass(), 'access']];
|
||||
$data[] = ['test_access_arguments_resolver_access'];
|
||||
$data[] = ['Drupal\Tests\Component\Utility\test_access_arguments_resolver_access'];
|
||||
return $data;
|
||||
}
|
||||
|
||||
|
@ -214,9 +214,5 @@ interface TestInterface1 {
|
|||
interface TestInterface2 {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
namespace {
|
||||
function test_access_arguments_resolver_access($foo) {
|
||||
}
|
||||
function test_access_arguments_resolver_access($foo) {
|
||||
}
|
||||
|
|
|
@ -22,20 +22,6 @@ use Drupal\Tests\UnitTestCase;
|
|||
*/
|
||||
class SafeMarkupTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* The error message of the last error in the error handler.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $lastErrorMessage;
|
||||
|
||||
/**
|
||||
* The error number of the last error in the error handler.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
protected $lastErrorNumber;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
|
@ -137,7 +123,7 @@ class SafeMarkupTest extends UnitTestCase {
|
|||
UrlHelper::setAllowedProtocols(['http', 'https', 'mailto']);
|
||||
|
||||
$result = SafeMarkup::format($string, $args);
|
||||
$this->assertEquals($expected, $result, $message);
|
||||
$this->assertEquals($expected, (string) $result, $message);
|
||||
$this->assertEquals($expected_is_safe, $result instanceof MarkupInterface, 'SafeMarkup::format correctly sets the result as safe or not safe.');
|
||||
|
||||
foreach ($args as $arg) {
|
||||
|
@ -171,42 +157,10 @@ class SafeMarkupTest extends UnitTestCase {
|
|||
$tests['non-url-with-colon'] = ['Hey giraffe <a href=":url">MUUUH</a>', [':url' => "llamas: they are not URLs"], 'Hey giraffe <a href=" they are not URLs">MUUUH</a>', '', TRUE];
|
||||
$tests['non-url-with-html'] = ['Hey giraffe <a href=":url">MUUUH</a>', [':url' => "<span>not a url</span>"], 'Hey giraffe <a href="<span>not a url</span>">MUUUH</a>', '', TRUE];
|
||||
|
||||
// Tests non-standard placeholders that will not replace.
|
||||
$tests['non-standard-placeholder'] = ['Hey hey', ['risky' => "<script>alert('foo');</script>"], 'Hey hey', '', TRUE];
|
||||
return $tests;
|
||||
}
|
||||
/**
|
||||
* Custom error handler that saves the last error.
|
||||
*
|
||||
* We need this custom error handler because we cannot rely on the error to
|
||||
* exception conversion as __toString is never allowed to leak any kind of
|
||||
* exception.
|
||||
*
|
||||
* @param int $error_number
|
||||
* The error number.
|
||||
* @param string $error_message
|
||||
* The error message.
|
||||
*/
|
||||
public function errorHandler($error_number, $error_message) {
|
||||
$this->lastErrorNumber = $error_number;
|
||||
$this->lastErrorMessage = $error_message;
|
||||
}
|
||||
|
||||
/**
|
||||
* String formatting with SafeMarkup::format() and an unsupported placeholder.
|
||||
*
|
||||
* When you call SafeMarkup::format() with an unsupported placeholder, an
|
||||
* InvalidArgumentException should be thrown.
|
||||
*/
|
||||
public function testUnexpectedFormat() {
|
||||
|
||||
// We set a custom error handler because of https://github.com/sebastianbergmann/phpunit/issues/487
|
||||
set_error_handler([$this, 'errorHandler']);
|
||||
// We want this to trigger an error.
|
||||
$error = SafeMarkup::format('Broken placeholder: ~placeholder', ['~placeholder' => 'broken'])->__toString();
|
||||
restore_error_handler();
|
||||
|
||||
$this->assertEquals(E_USER_ERROR, $this->lastErrorNumber);
|
||||
$this->assertEquals('Invalid placeholder (~placeholder) in string: Broken placeholder: ~placeholder', $this->lastErrorMessage);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -505,6 +505,18 @@ class XssTest extends UnitTestCase {
|
|||
'Image tag with alt and title attribute',
|
||||
array('img')
|
||||
),
|
||||
array(
|
||||
'<a href="https://www.drupal.org/" rel="dc:publisher">Drupal</a>',
|
||||
'<a href="https://www.drupal.org/" rel="dc:publisher">Drupal</a>',
|
||||
'Link tag with rel attribute',
|
||||
array('a')
|
||||
),
|
||||
array(
|
||||
'<span property="dc:subject">Drupal 8: The best release ever.</span>',
|
||||
'<span property="dc:subject">Drupal 8: The best release ever.</span>',
|
||||
'Span tag with property attribute',
|
||||
array('span')
|
||||
),
|
||||
array(
|
||||
'<img src="http://example.com/foo.jpg" data-caption="Drupal 8: The best release ever.">',
|
||||
'<img src="http://example.com/foo.jpg" data-caption="Drupal 8: The best release ever.">',
|
||||
|
|
59
core/tests/Drupal/Tests/ConfigTestTrait.php
Normal file
59
core/tests/Drupal/Tests/ConfigTestTrait.php
Normal file
|
@ -0,0 +1,59 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests;
|
||||
|
||||
use Drupal\Core\Config\ConfigImporter;
|
||||
use Drupal\Core\Config\StorageComparer;
|
||||
use Drupal\Core\Config\StorageInterface;
|
||||
|
||||
/**
|
||||
* Provides helper methods to deal with config system objects in tests.
|
||||
*/
|
||||
trait ConfigTestTrait {
|
||||
|
||||
/**
|
||||
* Returns a ConfigImporter object to import test configuration.
|
||||
*
|
||||
* @return \Drupal\Core\Config\ConfigImporter
|
||||
* The config importer object.
|
||||
*/
|
||||
protected function configImporter() {
|
||||
if (!$this->configImporter) {
|
||||
// Set up the ConfigImporter object for testing.
|
||||
$storage_comparer = new StorageComparer(
|
||||
$this->container->get('config.storage.sync'),
|
||||
$this->container->get('config.storage'),
|
||||
$this->container->get('config.manager')
|
||||
);
|
||||
$this->configImporter = new ConfigImporter(
|
||||
$storage_comparer,
|
||||
$this->container->get('event_dispatcher'),
|
||||
$this->container->get('config.manager'),
|
||||
$this->container->get('lock'),
|
||||
$this->container->get('config.typed'),
|
||||
$this->container->get('module_handler'),
|
||||
$this->container->get('module_installer'),
|
||||
$this->container->get('theme_handler'),
|
||||
$this->container->get('string_translation')
|
||||
);
|
||||
}
|
||||
// Always recalculate the changelist when called.
|
||||
return $this->configImporter->reset();
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies configuration objects from source storage to target storage.
|
||||
*
|
||||
* @param \Drupal\Core\Config\StorageInterface $source_storage
|
||||
* The source config storage service.
|
||||
* @param \Drupal\Core\Config\StorageInterface $target_storage
|
||||
* The target config storage service.
|
||||
*/
|
||||
protected function copyConfig(StorageInterface $source_storage, StorageInterface $target_storage) {
|
||||
$target_storage->deleteAll();
|
||||
foreach ($source_storage->listAll() as $name) {
|
||||
$target_storage->write($name, $source_storage->read($name));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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));
|
||||
|
|
|
@ -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: {}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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]
|
||||
];
|
||||
}
|
||||
|
||||
|
|
|
@ -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.
|
||||
*/
|
||||
|
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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.';
|
||||
}
|
||||
|
|
|
@ -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'];
|
||||
|
|
|
@ -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'),
|
||||
);
|
||||
}
|
||||
|
||||
|
|
|
@ -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'));
|
||||
}
|
||||
|
||||
}
|
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
|
@ -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')));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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) {
|
||||
}
|
||||
|
|
|
@ -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.
|
||||
*/
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
|
|
|
@ -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()));
|
||||
}));
|
||||
|
|
|
@ -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.');
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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.
|
||||
*/
|
||||
|
|
|
@ -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();
|
||||
|
|
1563
core/tests/Drupal/Tests/Core/Form/FormStateDecoratorBaseTest.php
Normal file
1563
core/tests/Drupal/Tests/Core/Form/FormStateDecoratorBaseTest.php
Normal file
File diff suppressed because it is too large
Load diff
|
@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
263
core/tests/Drupal/Tests/Core/Form/FormStateValuesTraitTest.php
Normal file
263
core/tests/Drupal/Tests/Core/Form/FormStateValuesTraitTest.php
Normal 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;
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
312
core/tests/Drupal/Tests/Core/Form/SubformStateTest.php
Normal file
312
core/tests/Drupal/Tests/Core/Form/SubformStateTest.php
Normal 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));
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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')
|
||||
|
|
|
@ -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 = [];
|
||||
|
|
|
@ -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) {
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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')
|
||||
|
|
|
@ -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'),
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
156
core/tests/Drupal/Tests/Core/Plugin/PluginFormFactoryTest.php
Normal file
156
core/tests/Drupal/Tests/Core/Plugin/PluginFormFactoryTest.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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) {
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -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');
|
||||
|
|
|
@ -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'],
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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<script>alert("bar");</script>'];
|
||||
|
||||
// Part 2: render arrays using #theme and #theme_wrappers.
|
||||
|
||||
|
|
|
@ -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.
|
||||
*
|
||||
|
|
127
core/tests/Drupal/Tests/Core/Routing/MethodFilterTest.php
Normal file
127
core/tests/Drupal/Tests/Core/Routing/MethodFilterTest.php
Normal 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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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'];
|
||||
|
||||
|
|
|
@ -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) {
|
||||
|
|
64
core/tests/Drupal/Tests/Core/Serialization/YamlTest.php
Normal file
64
core/tests/Drupal/Tests/Core/Serialization/YamlTest.php
Normal 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();
|
||||
}
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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
|
||||
*/
|
||||
|
|
|
@ -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)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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');
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -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']);
|
||||
|
|
45
core/tests/Drupal/Tests/Core/Test/TestDatabaseTest.php
Normal file
45
core/tests/Drupal/Tests/Core/Test/TestDatabaseTest.php
Normal 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']
|
||||
];
|
||||
}
|
||||
|
||||
}
|
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
|
@ -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.
|
||||
*
|
||||
|
|
|
@ -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
|
||||
*/
|
||||
|
|
|
@ -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.
|
||||
|
|
|
@ -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 {
|
|||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
171
core/tests/Drupal/Tests/TestFileCreationTrait.php
Normal file
171
core/tests/Drupal/Tests/TestFileCreationTrait.php
Normal file
|
@ -0,0 +1,171 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests;
|
||||
|
||||
use Drupal\Core\StreamWrapper\PublicStream;
|
||||
|
||||
/**
|
||||
* Provides methods to create test files from given values.
|
||||
*
|
||||
* This trait is meant to be used only by test classes.
|
||||
*/
|
||||
trait TestFileCreationTrait {
|
||||
|
||||
/**
|
||||
* Whether the files were copied to the test files directory.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $generatedTestFiles = FALSE;
|
||||
|
||||
/**
|
||||
* Gets a list of files that can be used in tests.
|
||||
*
|
||||
* The first time this method is called, it will call
|
||||
* $this->generateFile() to generate binary and ASCII text files in the
|
||||
* public:// directory. It will also copy all files in
|
||||
* core/modules/simpletest/files to public://. These contain image, SQL, PHP,
|
||||
* JavaScript, and HTML files.
|
||||
*
|
||||
* All filenames are prefixed with their type and have appropriate extensions:
|
||||
* - text-*.txt
|
||||
* - binary-*.txt
|
||||
* - html-*.html and html-*.txt
|
||||
* - image-*.png, image-*.jpg, and image-*.gif
|
||||
* - javascript-*.txt and javascript-*.script
|
||||
* - php-*.txt and php-*.php
|
||||
* - sql-*.txt and sql-*.sql
|
||||
*
|
||||
* Any subsequent calls will not generate any new files, or copy the files
|
||||
* over again. However, if a test class adds a new file to public:// that
|
||||
* is prefixed with one of the above types, it will get returned as well, even
|
||||
* on subsequent calls.
|
||||
*
|
||||
* @param $type
|
||||
* File type, possible values: 'binary', 'html', 'image', 'javascript',
|
||||
* 'php', 'sql', 'text'.
|
||||
* @param $size
|
||||
* (optional) File size in bytes to match. Defaults to NULL, which will not
|
||||
* filter the returned list by size.
|
||||
*
|
||||
* @return array[]
|
||||
* List of files in public:// that match the filter(s).
|
||||
*/
|
||||
protected function getTestFiles($type, $size = NULL) {
|
||||
if (empty($this->generatedTestFiles)) {
|
||||
// Generate binary test files.
|
||||
$lines = [64, 1024];
|
||||
$count = 0;
|
||||
foreach ($lines as $line) {
|
||||
$this->generateFile('binary-' . $count++, 64, $line, 'binary');
|
||||
}
|
||||
|
||||
// Generate ASCII text test files.
|
||||
$lines = [16, 256, 1024, 2048, 20480];
|
||||
$count = 0;
|
||||
foreach ($lines as $line) {
|
||||
$this->generateFile('text-' . $count++, 64, $line, 'text');
|
||||
}
|
||||
|
||||
// Copy other test files from simpletest.
|
||||
$original = drupal_get_path('module', 'simpletest') . '/files';
|
||||
$files = file_scan_directory($original, '/(html|image|javascript|php|sql)-.*/');
|
||||
foreach ($files as $file) {
|
||||
file_unmanaged_copy($file->uri, PublicStream::basePath());
|
||||
}
|
||||
|
||||
$this->generatedTestFiles = TRUE;
|
||||
}
|
||||
|
||||
$files = [];
|
||||
// Make sure type is valid.
|
||||
if (in_array($type, ['binary', 'html', 'image', 'javascript', 'php', 'sql', 'text'])) {
|
||||
$files = file_scan_directory('public://', '/' . $type . '\-.*/');
|
||||
|
||||
// If size is set then remove any files that are not of that size.
|
||||
if ($size !== NULL) {
|
||||
foreach ($files as $file) {
|
||||
$stats = stat($file->uri);
|
||||
if ($stats['size'] != $size) {
|
||||
unset($files[$file->uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
usort($files, [$this, 'compareFiles']);
|
||||
return $files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares two files based on size and file name.
|
||||
*
|
||||
* Callback for uasort() within \TestFileCreationTrait::getTestFiles().
|
||||
*
|
||||
* @param \stdClass $file1
|
||||
* The first file.
|
||||
* @param \stdClass $file2
|
||||
* The second class.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
protected function compareFiles($file1, $file2) {
|
||||
$compare_size = filesize($file1->uri) - filesize($file2->uri);
|
||||
if ($compare_size) {
|
||||
// Sort by file size.
|
||||
return $compare_size;
|
||||
}
|
||||
else {
|
||||
// The files were the same size, so sort alphabetically.
|
||||
return strnatcmp($file1->name, $file2->name);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a test file.
|
||||
*
|
||||
* @param string $filename
|
||||
* The name of the file, including the path. The suffix '.txt' is appended
|
||||
* to the supplied file name and the file is put into the public:// files
|
||||
* directory.
|
||||
* @param int $width
|
||||
* The number of characters on one line.
|
||||
* @param int $lines
|
||||
* The number of lines in the file.
|
||||
* @param string $type
|
||||
* (optional) The type, one of:
|
||||
* - text: The generated file contains random ASCII characters.
|
||||
* - binary: The generated file contains random characters whose codes are
|
||||
* in the range of 0 to 31.
|
||||
* - binary-text: The generated file contains random sequence of '0' and '1'
|
||||
* values.
|
||||
*
|
||||
* @return string
|
||||
* The name of the file, including the path.
|
||||
*/
|
||||
public static function generateFile($filename, $width, $lines, $type = 'binary-text') {
|
||||
$text = '';
|
||||
for ($i = 0; $i < $lines; $i++) {
|
||||
// Generate $width - 1 characters to leave space for the "\n" character.
|
||||
for ($j = 0; $j < $width - 1; $j++) {
|
||||
switch ($type) {
|
||||
case 'text':
|
||||
$text .= chr(rand(32, 126));
|
||||
break;
|
||||
case 'binary':
|
||||
$text .= chr(rand(0, 31));
|
||||
break;
|
||||
case 'binary-text':
|
||||
default:
|
||||
$text .= rand(0, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
$text .= "\n";
|
||||
}
|
||||
|
||||
// Create filename.
|
||||
file_put_contents('public://' . $filename . '.txt', $text);
|
||||
return $filename;
|
||||
}
|
||||
|
||||
}
|
|
@ -4,6 +4,10 @@ namespace Drupal\Tests\TestSuites;
|
|||
|
||||
use org\bovigo\vfs\vfsStream;
|
||||
|
||||
// The test suite class is not part of the autoloader, we need to include it
|
||||
// manually.
|
||||
require_once __DIR__ . '/../../../TestSuites/TestSuiteBase.php';
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\Tests\TestSuites\TestSuiteBase
|
||||
*
|
||||
|
|
|
@ -0,0 +1,54 @@
|
|||
<?php
|
||||
|
||||
namespace Drupal\Tests\Traits\Core\Config;
|
||||
|
||||
use \Drupal\Core\Config\Schema\SchemaIncompleteException;
|
||||
|
||||
/**
|
||||
* Adds a test for the configuration schema checker use in tests.
|
||||
*/
|
||||
trait SchemaConfigListenerTestTrait {
|
||||
|
||||
/**
|
||||
* Tests \Drupal\Core\Config\Testing\ConfigSchemaChecker.
|
||||
*/
|
||||
public function testConfigSchemaChecker() {
|
||||
// Test a non-existing schema.
|
||||
$message = 'Expected SchemaIncompleteException thrown';
|
||||
try {
|
||||
$this->config('config_schema_test.schemaless')->set('foo', 'bar')->save();
|
||||
$this->fail($message);
|
||||
}
|
||||
catch (SchemaIncompleteException $e) {
|
||||
$this->pass($message);
|
||||
$this->assertEqual('No schema for config_schema_test.schemaless', $e->getMessage());
|
||||
}
|
||||
|
||||
// Test a valid schema.
|
||||
$message = 'Unexpected SchemaIncompleteException thrown';
|
||||
$config = $this->config('config_test.types')->set('int', 10);
|
||||
try {
|
||||
$config->save();
|
||||
$this->pass($message);
|
||||
}
|
||||
catch (SchemaIncompleteException $e) {
|
||||
$this->fail($message);
|
||||
}
|
||||
|
||||
// Test an invalid schema.
|
||||
$message = 'Expected SchemaIncompleteException thrown';
|
||||
$config = $this->config('config_test.types')
|
||||
->set('foo', 'bar')
|
||||
->set('array', 1);
|
||||
try {
|
||||
$config->save();
|
||||
$this->fail($message);
|
||||
}
|
||||
catch (SchemaIncompleteException $e) {
|
||||
$this->pass($message);
|
||||
$this->assertEqual('Schema errors for config_test.types with the following errors: config_test.types:array variable type is integer but applied schema class is Drupal\Core\Config\Schema\Sequence, config_test.types:foo missing schema', $e->getMessage());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
|
@ -42,7 +42,9 @@ abstract class UnitTestCase extends \PHPUnit_Framework_TestCase {
|
|||
|
||||
// Ensure that the NullFileCache implementation is used for the FileCache as
|
||||
// unit tests should not be relying on caches implicitly.
|
||||
FileCacheFactory::setConfiguration(['default' => ['class' => '\Drupal\Component\FileCache\NullFileCache']]);
|
||||
FileCacheFactory::setConfiguration([FileCacheFactory::DISABLE_CACHE => TRUE]);
|
||||
// Ensure that FileCacheFactory has a prefix.
|
||||
FileCacheFactory::setPrefix('prefix');
|
||||
|
||||
$this->root = dirname(dirname(substr(__DIR__, 0, -strlen(__NAMESPACE__))));
|
||||
}
|
||||
|
|
Reference in a new issue