Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -5,25 +5,22 @@ namespace Drupal\Tests;
use Behat\Mink\Driver\GoutteDriver;
use Behat\Mink\Element\Element;
use Behat\Mink\Mink;
use Behat\Mink\Selector\SelectorsHandler;
use Behat\Mink\Session;
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Component\Serialization\Json;
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;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Core\Test\FunctionalTestSetupTrait;
use Drupal\Core\Test\TestRunnerKernel;
use Drupal\Core\Test\TestSetupTrait;
use Drupal\Core\Url;
use Drupal\Core\Test\TestDatabase;
use Drupal\Core\Utility\Error;
use Drupal\FunctionalTests\AssertLegacyTrait;
use Drupal\simpletest\AssertHelperTrait;
use Drupal\simpletest\ContentTypeCreationTrait;
@ -32,6 +29,8 @@ use Drupal\simpletest\NodeCreationTrait;
use Drupal\simpletest\UserCreationTrait;
use Symfony\Component\CssSelector\CssSelectorConverter;
use Symfony\Component\HttpFoundation\Request;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Provides a test case for functional Drupal tests.
@ -43,6 +42,9 @@ use Symfony\Component\HttpFoundation\Request;
* @ingroup testing
*/
abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
use FunctionalTestSetupTrait;
use TestSetupTrait;
use AssertHelperTrait;
use BlockCreationTrait {
placeBlock as drupalPlaceBlock;
@ -62,20 +64,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
createRole as drupalCreateRole;
createUser as drupalCreateUser;
}
/**
* Class loader.
*
* @var object
*/
protected $classLoader;
/**
* The site directory of this test run.
*
* @var string
*/
protected $siteDirectory;
use XdebugRequestTrait;
/**
* The database prefix of this test run.
@ -84,13 +73,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
*/
protected $databasePrefix;
/**
* The site directory of the original parent site.
*
* @var string
*/
protected $originalSiteDirectory;
/**
* Time limit in seconds for the test.
*
@ -98,37 +80,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
*/
protected $timeLimit = 500;
/**
* The public file directory for the test environment.
*
* This is set in BrowserTestBase::prepareEnvironment().
*
* @var string
*/
protected $publicFilesDirectory;
/**
* The private file directory for the test environment.
*
* This is set in BrowserTestBase::prepareEnvironment().
*
* @var string
*/
protected $privateFilesDirectory;
/**
* The temp file directory for the test environment.
*
* This is set in BrowserTestBase::prepareEnvironment(). This value has to
* match the temporary directory created in install_base_system() for test
* installs.
*
* @see install_base_system()
*
* @var string
*/
protected $tempFilesDirectory;
/**
* The translation file directory for the test environment.
*
@ -138,20 +89,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
*/
protected $translationFilesDirectory;
/**
* The DrupalKernel instance used in the test.
*
* @var \Drupal\Core\DrupalKernel
*/
protected $kernel;
/**
* The dependency injection container used in the test.
*
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
protected $container;
/**
* The config importer that can be used in a test.
*
@ -159,15 +96,6 @@ 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.
*
@ -181,22 +109,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
*/
protected 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.
*
@ -211,20 +123,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
*/
protected $loggedInUser = FALSE;
/**
* The root user.
*
* @var \Drupal\Core\Session\UserSession
*/
protected $rootUser;
/**
* The config directories used in this test.
*
* @var array
*/
protected $configDirectories = array();
/**
* An array of custom translations suitable for drupal_rewrite_settings().
*
@ -356,13 +254,26 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
if ($driver instanceof GoutteDriver) {
// Turn off curl timeout. Having a timeout is not a problem in a normal
// test running, but it is a problem when debugging.
// test running, but it is a problem when debugging. Also, disable SSL
// peer verification so that testing under HTTPS always works.
/** @var \GuzzleHttp\Client $client */
$client = $this->container->get('http_client_factory')->fromOptions(['timeout' => NULL]);
$client = $this->container->get('http_client_factory')->fromOptions([
'timeout' => NULL,
'verify' => FALSE,
]);
// Inject a Guzzle middleware to generate debug output for every request
// performed in the test.
$handler_stack = $client->getConfig('handler');
$handler_stack->push($this->getResponseLogHandler());
$driver->getClient()->setClient($client);
}
$session = new Session($driver);
$selectors_handler = new SelectorsHandler([
'hidden_field_selector' => new HiddenFieldSelector()
]);
$session = new Session($driver, $selectors_handler);
$this->mink = new Mink();
$this->mink->registerSession('default', $session);
$this->mink->setDefaultSessionName('default');
@ -418,6 +329,43 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
return $driver;
}
/**
* Provides a Guzzle middleware handler to log every response received.
*
* @return callable
* The callable handler that will do the logging.
*/
protected function getResponseLogHandler() {
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
return $handler($request, $options)
->then(function (ResponseInterface $response) use ($request) {
if ($this->htmlOutputEnabled) {
$caller = $this->getTestMethodCaller();
$html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
$html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
// On redirect responses (status code starting with '3') we need
// to remove the meta tag that would do a browser refresh. We
// don't want to redirect developers away when they look at the
// debug output file in their browser.
$body = $response->getBody();
$status_code = (string) $response->getStatusCode();
if ($status_code[0] === '3') {
$body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
}
$html_output .= '<hr />' . $body;
$html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
$this->htmlOutput($html_output);
}
return $response;
});
};
};
}
/**
* Registers additional Mink sessions.
*
@ -482,29 +430,10 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
// Setup Mink.
$session = $this->initMink();
// In order to debug web tests you need to either set a cookie, have the
// Xdebug session in the URL or set an environment variable in case of CLI
// requests. If the developer listens to connection when running tests, by
// default the cookie is not forwarded to the client side, so you cannot
// debug the code running on the test site. In order to make debuggers work
// this bit of information is forwarded. Make sure that the debugger listens
// to at least three external connections.
$request = \Drupal::request();
$cookie_params = $request->cookies;
if ($cookie_params->has('XDEBUG_SESSION')) {
$session->setCookie('XDEBUG_SESSION', $cookie_params->get('XDEBUG_SESSION'));
}
// For CLI requests, the information is stored in $_SERVER.
$server = $request->server;
if ($server->has('XDEBUG_CONFIG')) {
// $_SERVER['XDEBUG_CONFIG'] has the form "key1=value1 key2=value2 ...".
$pairs = explode(' ', $server->get('XDEBUG_CONFIG'));
foreach ($pairs as $pair) {
list($key, $value) = explode('=', $pair);
// Account for key-value pairs being separated by multiple spaces.
if (trim($key) == 'idekey') {
$session->setCookie('XDEBUG_SESSION', trim($value));
}
$cookies = $this->extractCookiesFromRequest(\Drupal::request());
foreach ($cookies as $cookie_name => $values) {
foreach ($values as $value) {
$session->setCookie($cookie_name, $value);
}
}
@ -564,7 +493,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
}
// Delete test site directory.
file_unmanaged_delete_recursive($this->siteDirectory, array($this, 'filePreDeleteCallback'));
file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
}
/**
@ -643,7 +572,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* @return string
* An absolute URL stsring.
*/
protected function buildUrl($path, array $options = array()) {
protected function buildUrl($path, array $options = []) {
if ($path instanceof Url) {
$url_options = $path->getOptions();
$options = $url_options + $options;
@ -691,7 +620,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* @return string
* The retrieved HTML string, also available as $this->getRawContent()
*/
protected function drupalGet($path, array $options = array(), array $headers = array()) {
protected function drupalGet($path, array $options = [], array $headers = []) {
$options['absolute'] = TRUE;
$url = $this->buildUrl($path, $options);
@ -708,7 +637,9 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
// Ensure that any changes to variables in the other thread are picked up.
$this->refreshVariables();
if ($this->htmlOutputEnabled) {
// Log only for JavascriptTestBase tests because for Goutte we log with
// ::getResponseLogHandler.
if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
$html_output = 'GET request to: ' . $url .
'<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
$html_output .= '<hr />' . $out;
@ -782,16 +713,16 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
$this->drupalLogout();
}
$this->drupalGet('user');
$this->drupalGet('user/login');
$this->assertSession()->statusCodeEquals(200);
$this->submitForm(array(
$this->submitForm([
'name' => $account->getUsername(),
'pass' => $account->passRaw,
), t('Log in'));
], t('Log in'));
// @see BrowserTestBase::drupalUserIsLoggedIn()
$account->sessionId = $this->getSession()->getCookie($this->getSessionName());
$this->assertTrue($this->drupalUserIsLoggedIn($account), SafeMarkup::format('User %name successfully logged in.', array('name' => $account->getUsername())));
$this->assertTrue($this->drupalUserIsLoggedIn($account), new FormattableMarkup('User %name successfully logged in.', ['%name' => $account->getAccountName()]));
$this->loggedInUser = $account;
$this->container->get('current_user')->setAccount($account);
@ -807,7 +738,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
// idea being if you were properly logged out you should be seeing a login
// screen.
$assert_session = $this->assertSession();
$this->drupalGet('user/logout', array('query' => array('destination' => 'user')));
$this->drupalGet('user/logout', ['query' => ['destination' => 'user']]);
$assert_session->statusCodeEquals(200);
$assert_session->fieldExists('name');
$assert_session->fieldExists('pass');
@ -878,7 +809,10 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
// Ensure that any changes to variables in the other thread are picked up.
$this->refreshVariables();
if ($this->htmlOutputEnabled) {
// Log only for JavascriptTestBase tests because for Goutte we log with
// ::getResponseLogHandler.
if ($this->htmlOutputEnabled && !($this->getSession()->getDriver() instanceof GoutteDriver)) {
$out = $this->getSession()->getPage()->getContent();
$html_output = 'POST request to: ' . $action .
'<hr />Ending URL: ' . $this->getSession()->getCurrentUrl();
@ -886,6 +820,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
$html_output .= $this->getHtmlOutputHeaders();
$this->htmlOutput($html_output);
}
}
/**
@ -931,6 +866,8 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* $edit = array();
* $edit['name[]'] = array('value1', 'value2');
* @endcode
* @todo change $edit to disallow NULL as a value for Drupal 9.
* https://www.drupal.org/node/2802401
* @param string $submit
* Value of the submit button whose click is to be emulated. For example,
* t('Save'). The processing of the request depends on this value. For
@ -956,11 +893,14 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* @param array $options
* Options to be forwarded to the url generator.
*/
protected function drupalPostForm($path, array $edit, $submit, array $options = array()) {
protected function drupalPostForm($path, $edit, $submit, array $options = []) {
if (is_object($submit)) {
// Cast MarkupInterface objects to string.
$submit = (string) $submit;
}
if ($edit === NULL) {
$edit = [];
}
if (is_array($edit)) {
$edit = $this->castSafeStrings($edit);
}
@ -1001,157 +941,14 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* Installs Drupal into the Simpletest site.
*/
public function installDrupal() {
// Define information about the user 1 account.
$this->rootUser = new UserSession(array(
'uid' => 1,
'name' => 'admin',
'mail' => 'admin@example.com',
'passRaw' => $this->randomMachineName(),
));
// The child site derives its session name from the database prefix when
// running web tests.
$this->generateSessionName($this->databasePrefix);
// Get parameters for install_drupal() before removing global variables.
$parameters = $this->installParameters();
// Prepare installer settings that are not install_drupal() parameters.
// Copy and prepare an actual settings.php, so as to resemble a regular
// installation.
// Not using File API; a potential error must trigger a PHP warning.
$directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
copy(DRUPAL_ROOT . '/sites/default/default.settings.php', $directory . '/settings.php');
// The public file system path is created during installation. Additionally,
// during tests:
// - The temporary directory is set and created by install_base_system().
// - The private file directory is created post install by this method.
// @see system_requirements()
// @see TestBase::prepareEnvironment()
// @see install_base_system()
$settings['settings']['file_public_path'] = (object) array(
'value' => $this->publicFilesDirectory,
'required' => TRUE,
);
$settings['settings']['file_private_path'] = (object) [
'value' => $this->privateFilesDirectory,
'required' => TRUE,
];
$this->writeSettings($settings);
// Allow for test-specific overrides.
$settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSiteDirectory . '/settings.testing.php';
if (file_exists($settings_testing_file)) {
// Copy the testing-specific settings.php overrides in place.
copy($settings_testing_file, $directory . '/settings.testing.php');
// Add the name of the testing class to settings.php and include the
// testing specific overrides.
file_put_contents($directory . '/settings.php', "\n\$test_class = '" . get_class($this) . "';\n" . 'include DRUPAL_ROOT . \'/\' . $site_path . \'/settings.testing.php\';' . "\n", FILE_APPEND);
}
$settings_services_file = DRUPAL_ROOT . '/' . $this->originalSiteDirectory . '/testing.services.yml';
if (!file_exists($settings_services_file)) {
// Otherwise, use the default services as a starting point for overrides.
$settings_services_file = DRUPAL_ROOT . '/sites/default/default.services.yml';
}
// 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
// reload the newly written custom settings.php manually.
Settings::initialize(DRUPAL_ROOT, $directory, $this->classLoader);
// Execute the non-interactive installer.
require_once DRUPAL_ROOT . '/core/includes/install.core.inc';
install_drupal($parameters);
// Import new settings.php written by the installer.
Settings::initialize(DRUPAL_ROOT, $directory, $this->classLoader);
foreach ($GLOBALS['config_directories'] as $type => $path) {
$this->configDirectories[$type] = $path;
}
// After writing settings.php, the installer removes write permissions from
// the site directory. To allow drupal_generate_test_ua() to write a file
// containing the private key for drupal_valid_test_ua(), the site directory
// has to be writable.
// TestBase::restoreEnvironment() will delete the entire site directory. Not
// using File API; a potential error must trigger a PHP warning.
chmod($directory, 0777);
// During tests, cacheable responses should get the debugging cacheability
// headers by default.
$this->setContainerParameter('http.response.debug_cacheability_headers', TRUE);
$request = \Drupal::request();
$this->kernel = DrupalKernel::createFromRequest($request, $this->classLoader, 'prod', TRUE);
$this->kernel->prepareLegacyRequest($request);
// Force the container to be built from scratch instead of loaded from the
// disk. This forces us to not accidentally load the parent site.
$container = $this->kernel->rebuildContainer();
$config = $container->get('config.factory');
// Manually create the private directory.
file_prepare_directory($this->privateFilesDirectory, FILE_CREATE_DIRECTORY);
// Manually configure the test mail collector implementation to prevent
// tests from sending out emails and collect them in state instead.
// While this should be enforced via settings.php prior to installation,
// some tests expect to be able to test mail system implementations.
$config->getEditable('system.mail')
->set('interface.default', 'test_mail_collector')
->save();
// By default, verbosely display all errors and disable all production
// environment optimizations for all tests to avoid needless overhead and
// ensure a sane default experience for test authors.
// @see https://www.drupal.org/node/2259167
$config->getEditable('system.logging')
->set('error_level', 'verbose')
->save();
$config->getEditable('system.performance')
->set('css.preprocess', FALSE)
->set('js.preprocess', FALSE)
->save();
// Collect modules to install.
$class = get_class($this);
$modules = array();
while ($class) {
if (property_exists($class, 'modules')) {
$modules = array_merge($modules, $class::$modules);
}
$class = get_parent_class($class);
}
if ($modules) {
$modules = array_unique($modules);
$success = $container->get('module_installer')->install($modules, TRUE);
$this->assertTrue($success, SafeMarkup::format('Enabled modules: %modules', array('%modules' => implode(', ', $modules))));
$this->rebuildContainer();
}
// Reset/rebuild all data structures after enabling the modules, primarily
// to synchronize all data structures and caches between the test runner and
// the child site.
// Affects e.g. StreamWrapperManagerInterface::getWrappers().
// @see \Drupal\Core\DrupalKernel::bootCode()
// @todo Test-specific setUp() methods may set up further fixtures; find a
// way to execute this after setUp() is done, or to eliminate it entirely.
$this->resetAll();
$this->kernel->prepareLegacyRequest($request);
$this->initUserSession();
$this->prepareSettings();
$this->doInstall();
$this->initSettings();
$container = $this->initKernel(\Drupal::request());
$this->initConfig($container);
$this->installModulesFromClassProperty($container);
$this->rebuildAll();
}
/**
@ -1168,99 +965,38 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
unset($connection_info['default']['namespace']);
unset($connection_info['default']['pdo']);
unset($connection_info['default']['init_commands']);
$parameters = array(
$parameters = [
'interactive' => FALSE,
'parameters' => array(
'parameters' => [
'profile' => $this->profile,
'langcode' => 'en',
),
'forms' => array(
'install_settings_form' => array(
],
'forms' => [
'install_settings_form' => [
'driver' => $driver,
$driver => $connection_info['default'],
),
'install_configure_form' => array(
],
'install_configure_form' => [
'site_name' => 'Drupal',
'site_mail' => 'simpletest@example.com',
'account' => array(
'account' => [
'name' => $this->rootUser->name,
'mail' => $this->rootUser->getEmail(),
'pass' => array(
'pass1' => $this->rootUser->passRaw,
'pass2' => $this->rootUser->passRaw,
),
),
'pass' => [
'pass1' => $this->rootUser->pass_raw,
'pass2' => $this->rootUser->pass_raw,
],
],
// form_type_checkboxes_value() requires NULL instead of FALSE values
// for programmatic form submissions to disable a checkbox.
'update_status_module' => array(
1 => NULL,
2 => NULL,
),
),
),
);
'enable_update_status_module' => NULL,
'enable_update_status_emails' => NULL,
],
],
];
return $parameters;
}
/**
* Generates a database prefix for running tests.
*
* The database prefix is used by prepareEnvironment() to setup a public files
* directory for the test to be run, which also contains the PHP error log,
* which is written to in case of a fatal error. Since that directory is based
* on the database prefix, all tests (even unit tests) need to have one, in
* order to access and read the error log.
*
* The generated database table prefix is used for the Drupal installation
* being performed for the test. It is also used by the cookie value of
* SIMPLETEST_USER_AGENT by the Mink controlled browser. During early Drupal
* bootstrap, the cookie is parsed, and if it matches, all database queries
* use the database table prefix that has been generated here.
*
* @see drupal_valid_test_ua()
* @see BrowserTestBase::prepareEnvironment()
*/
private function prepareDatabasePrefix() {
$test_db = new TestDatabase();
$this->siteDirectory = $test_db->getTestSitePath();
$this->databasePrefix = $test_db->getDatabasePrefix();
}
/**
* Changes the database connection to the prefixed one.
*
* @see BrowserTestBase::prepareEnvironment()
*/
private function changeDatabasePrefix() {
if (empty($this->databasePrefix)) {
$this->prepareDatabasePrefix();
}
// If the test is run with argument dburl then use it.
$db_url = getenv('SIMPLETEST_DB');
if (!empty($db_url)) {
$database = Database::convertDbUrlToConnectionInfo($db_url, DRUPAL_ROOT);
Database::addConnectionInfo('default', 'default', $database);
}
// Clone the current connection and replace the current prefix.
$connection_info = Database::getConnectionInfo('default');
if (is_null($connection_info)) {
throw new \InvalidArgumentException('There is no database connection so no tests can be run. You must provide a SIMPLETEST_DB environment variable to run PHPUnit based functional tests outside of run-tests.sh.');
}
else {
Database::renameConnection('default', 'simpletest_original_default');
foreach ($connection_info as $target => $value) {
// Replace the full table prefix definition to ensure that no table
// prefixes of the test runner leak into the test.
$connection_info[$target]['prefix'] = array(
'default' => $value['prefix']['default'] . $this->databasePrefix,
);
}
Database::addConnectionInfo('default', 'default', $connection_info['default']);
}
}
/**
* Prepares the current environment for running the test.
*
@ -1282,7 +1018,7 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
$kernel->prepareLegacyRequest($request);
$this->prepareDatabasePrefix();
$this->originalSiteDirectory = $kernel->findSitePath($request);
$this->originalSite = $kernel->findSitePath($request);
// Create test directory ahead of installation so fatal errors and debug
// information can be logged during installation process.
@ -1327,10 +1063,10 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
drupal_valid_test_ua($this->databasePrefix);
// Reset settings.
new Settings(array(
new Settings([
// For performance, simply use the database prefix as hash salt.
'hash_salt' => $this->databasePrefix,
));
]);
drupal_set_time_limit($this->timeLimit);
@ -1343,163 +1079,6 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
$callbacks = [];
}
/**
* Returns the database connection to the site running Simpletest.
*
* @return \Drupal\Core\Database\Connection
* The database connection to use for inserting assertions.
*/
public static function getDatabaseConnection() {
return TestDatabase::getConnection();
}
/**
* Rewrites the settings.php file of the test site.
*
* @param array $settings
* An array of settings to write out, in the format expected by
* drupal_rewrite_settings().
*
* @see drupal_rewrite_settings()
*/
protected function writeSettings(array $settings) {
include_once DRUPAL_ROOT . '/core/includes/install.inc';
$filename = $this->siteDirectory . '/settings.php';
// system_requirements() removes write permissions from settings.php
// whenever it is invoked.
// Not using File API; a potential error must trigger a PHP warning.
chmod($filename, 0666);
drupal_rewrite_settings($settings, $filename);
}
/**
* Rebuilds \Drupal::getContainer().
*
* Use this to build a new kernel and service container. For example, when the
* list of enabled modules is changed via the Mink controlled browser, in
* which case the test process still contains an old kernel and service
* container with an old module list.
*
* @see BrowserTestBase::prepareEnvironment()
* @see BrowserTestBase::restoreEnvironment()
*
* @todo Fix https://www.drupal.org/node/2021959 so that module enable/disable
* changes are immediately reflected in \Drupal::getContainer(). Until then,
* tests can invoke this workaround when requiring services from newly
* enabled modules to be immediately available in the same request.
*/
protected function rebuildContainer() {
// Rebuild the kernel and bring it back to a fully bootstrapped state.
$this->container = $this->kernel->rebuildContainer();
// Make sure the url generator has a request object, otherwise calls to
// $this->drupalGet() will fail.
$this->prepareRequestForGenerator();
}
/**
* Creates a mock request and sets it on the generator.
*
* This is used to manipulate how the generator generates paths during tests.
* It also ensures that calls to $this->drupalGet() will work when running
* from run-tests.sh because the url generator no longer looks at the global
* variables that are set there but relies on getting this information from a
* request object.
*
* @param bool $clean_urls
* Whether to mock the request using clean urls.
* @param array $override_server_vars
* An array of server variables to override.
*
* @return Request
* The mocked request object.
*/
protected function prepareRequestForGenerator($clean_urls = TRUE, $override_server_vars = array()) {
$request = Request::createFromGlobals();
$server = $request->server->all();
if (basename($server['SCRIPT_FILENAME']) != basename($server['SCRIPT_NAME'])) {
// We need this for when the test is executed by run-tests.sh.
// @todo Remove this once run-tests.sh has been converted to use a Request
// object.
$cwd = getcwd();
$server['SCRIPT_FILENAME'] = $cwd . '/' . basename($server['SCRIPT_NAME']);
$base_path = rtrim($server['REQUEST_URI'], '/');
}
else {
$base_path = $request->getBasePath();
}
if ($clean_urls) {
$request_path = $base_path ? $base_path . '/user' : 'user';
}
else {
$request_path = $base_path ? $base_path . '/index.php/user' : '/index.php/user';
}
$server = array_merge($server, $override_server_vars);
$request = Request::create($request_path, 'GET', array(), array(), array(), $server);
// Ensure the request time is REQUEST_TIME to ensure that API calls
// in the test use the right timestamp.
$request->server->set('REQUEST_TIME', REQUEST_TIME);
$this->container->get('request_stack')->push($request);
// The request context is normally set by the router_listener from within
// its KernelEvents::REQUEST listener. In the Simpletest parent site this
// event is not fired, therefore it is necessary to updated the request
// context manually here.
$this->container->get('router.request_context')->fromRequest($request);
return $request;
}
/**
* Resets all data structures after having enabled new modules.
*
* This method is called by \Drupal\simpletest\BrowserTestBase::setUp() after
* enabling the requested modules. It must be called again when additional
* modules are enabled later.
*/
protected function resetAll() {
// Clear all database and static caches and rebuild data structures.
drupal_flush_all_caches();
$this->container = \Drupal::getContainer();
// Reset static variables and reload permissions.
$this->refreshVariables();
}
/**
* Refreshes in-memory configuration and state information.
*
* Useful after a page request is made that changes configuration or state in
* a different thread.
*
* In other words calling a settings page with $this->submitForm() with a
* changed value would update configuration to reflect that change, but in the
* thread that made the call (thread running the test) the changed values
* would not be picked up.
*
* This method clears the cache and loads a fresh copy.
*/
protected function refreshVariables() {
// Clear the tag cache.
$this->container->get('cache_tags.invalidator')->resetChecksums();
// @todo Replace drupal_static() usage within classes and provide a
// proper interface for invoking reset() on a cache backend:
// https://www.drupal.org/node/2311945.
drupal_static_reset('Drupal\Core\Cache\CacheBackendInterface::tagCache');
drupal_static_reset('Drupal\Core\Cache\DatabaseBackend::deletedTags');
drupal_static_reset('Drupal\Core\Cache\DatabaseBackend::invalidatedTags');
foreach (Cache::getBins() as $backend) {
if (is_callable(array($backend, 'reset'))) {
$backend->reset();
}
}
$this->container->get('config.factory')->reset();
$this->container->get('state')->resetCache();
}
/**
* Returns whether a given user account is logged in.
*
@ -1576,15 +1155,28 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
* HTML output headers.
*/
protected function getHtmlOutputHeaders() {
$headers = array_map(function($headers) {
if (is_array($headers)) {
return implode(';', array_map('trim', $headers));
return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
}
/**
* Formats HTTP headers as string for HTML output logging.
*
* @param array[] $headers
* Headers that should be formatted.
*
* @return string
* The formatted HTML string.
*/
protected function formatHtmlOutputHeaders(array $headers) {
$flattened_headers = array_map(function($header) {
if (is_array($header)) {
return implode(';', array_map('trim', $header));
}
else {
return $headers;
return $header;
}
}, $this->getSession()->getResponseHeaders());
return '<hr />Headers: <pre>' . Html::escape(var_export($headers, TRUE)) . '</pre>';
}, $headers);
return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
}
/**
@ -1680,6 +1272,19 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
return $this->container->get('config.factory')->getEditable($name);
}
/**
* Returns all response headers.
*
* @return array
* The HTTP headers values.
*
* @deprecated Scheduled for removal in Drupal 9.0.0.
* Use $this->getSession()->getResponseHeaders() instead.
*/
protected function drupalGetHeaders() {
return $this->getSession()->getResponseHeaders();
}
/**
* Gets the value of an HTTP response header.
*
@ -1734,43 +1339,34 @@ abstract class BrowserTestBase extends \PHPUnit_Framework_TestCase {
}
/**
* Changes parameters in the services.yml file.
* Retrieves the current calling line in the class under test.
*
* @param string $name
* The name of the parameter.
* @param mixed $value
* The value of the parameter.
* @return array
* An associative array with keys 'file', 'line' and 'function'.
*/
protected function setContainerParameter($name, $value) {
$filename = $this->siteDirectory . '/services.yml';
chmod($filename, 0666);
$services = Yaml::decode(file_get_contents($filename));
$services['parameters'][$name] = $value;
file_put_contents($filename, Yaml::encode($services));
// Ensure that the cache is deleted for the yaml file loader.
$file_cache = FileCacheFactory::get('container_yaml_loader');
$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);
protected function getTestMethodCaller() {
$backtrace = debug_backtrace();
// Find the test class that has the test method.
while ($caller = Error::getLastCaller($backtrace)) {
if (isset($caller['class']) && $caller['class'] === get_class($this)) {
break;
}
$class = get_parent_class($class);
// If the test method is implemented by a test class's parent then the
// class name of $this will not be part of the backtrace.
// In that case we process the backtrace until the caller is not a
// subclass of $this and return the previous caller.
if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
// Return the last caller since that has to be the test class.
$caller = $last_caller;
break;
}
// Otherwise we have not reached our test class yet: save the last caller
// and remove an element from to backtrace to process the next call.
$last_caller = $caller;
array_shift($backtrace);
}
// Filter out any duplicates.
return array_unique($exceptions);
return $caller;
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace Drupal\Tests\Component\Annotation\Plugin\Discovery;
use Drupal\Component\Annotation\Plugin;
use Drupal\Component\Annotation\Plugin\Discovery\AnnotationBridgeDecorator;
use Drupal\Component\Plugin\Definition\PluginDefinition;
use Drupal\Component\Plugin\Discovery\DiscoveryInterface;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Component\Annotation\Plugin\Discovery\AnnotationBridgeDecorator
* @group Plugin
*/
class AnnotationBridgeDecoratorTest extends UnitTestCase {
/**
* @covers ::getDefinitions
*/
public function testGetDefinitions() {
$definitions = [];
$definitions['object'] = new ObjectDefinition(['id' => 'foo']);
$definitions['array'] = ['id' => 'bar'];
$discovery = $this->prophesize(DiscoveryInterface::class);
$discovery->getDefinitions()->willReturn($definitions);
$decorator = new AnnotationBridgeDecorator($discovery->reveal(), TestAnnotation::class);
$expected = [
'object' => new ObjectDefinition(['id' => 'foo']),
'array' => new ObjectDefinition(['id' => 'bar']),
];
$this->assertEquals($expected, $decorator->getDefinitions());
}
}
class TestAnnotation extends Plugin {
/**
* {@inheritdoc}
*/
public function get() {
return new ObjectDefinition($this->definition);
}
}
class ObjectDefinition extends PluginDefinition {
/**
* ObjectDefinition constructor.
*
* @param array $definition
*/
public function __construct(array $definition) {
foreach ($definition as $property => $value) {
$this->{$property} = $value;
}
}
}

View file

@ -80,41 +80,41 @@ class ZfExtensionManagerSfContainerTest extends UnitTestCase {
* array('-' => '', '_' => '', ' ' => '', '\\' => '', '/' => '')
*/
public function canonicalizeNameProvider() {
return array(
array(
return [
[
'foobar',
'foobar',
),
array(
],
[
'foo-bar',
'foobar',
),
array(
],
[
'foo_bar',
'foobar',
),
array(
],
[
'foo bar',
'foobar',
),
array(
],
[
'foo\\bar',
'foobar',
),
array(
],
[
'foo/bar',
'foobar',
),
],
// There is also a strtolower in canonicalizeName.
array(
[
'Foo/bAr',
'foobar',
),
array(
],
[
'foo/-_\\ bar',
'foobar',
),
);
],
];
}
}

View file

@ -98,11 +98,13 @@ class DateTimePlusTest extends UnitTestCase {
* Input argument for DateTimePlus.
* @param string $timezone
* Timezone argument for DateTimePlus.
* @param string $class
* The Exception subclass to expect to be thrown.
*
* @dataProvider providerTestInvalidDateArrays
* @expectedException \Exception
*/
public function testInvalidDateArrays($input, $timezone) {
public function testInvalidDateArrays($input, $timezone, $class) {
$this->setExpectedException($class);
$this->assertInstanceOf(
'\Drupal\Component\DateTimePlus',
DateTimePlus::createFromArray($input, $timezone)
@ -234,11 +236,13 @@ class DateTimePlusTest extends UnitTestCase {
* Format argument for DateTimePlus.
* @param string $message
* Message to print if no errors are thrown by the invalid dates.
* @param string $class
* The Exception subclass to expect to be thrown.
*
* @dataProvider providerTestInvalidDates
* @expectedException \Exception
*/
public function testInvalidDates($input, $timezone, $format, $message) {
public function testInvalidDates($input, $timezone, $format, $message, $class) {
$this->setExpectedException($class);
DateTimePlus::createFromFormat($format, $input, $timezone);
}
@ -289,21 +293,21 @@ class DateTimePlusTest extends UnitTestCase {
* @see DateTimePlusTest::testDates()
*/
public function providerTestDates() {
return array(
return [
// String input.
// Create date object from datetime string.
array('2009-03-07 10:30', 'America/Chicago', '2009-03-07T10:30:00-06:00'),
['2009-03-07 10:30', 'America/Chicago', '2009-03-07T10:30:00-06:00'],
// Same during daylight savings time.
array('2009-06-07 10:30', 'America/Chicago', '2009-06-07T10:30:00-05:00'),
['2009-06-07 10:30', 'America/Chicago', '2009-06-07T10:30:00-05:00'],
// Create date object from date string.
array('2009-03-07', 'America/Chicago', '2009-03-07T00:00:00-06:00'),
['2009-03-07', 'America/Chicago', '2009-03-07T00:00:00-06:00'],
// Same during daylight savings time.
array('2009-06-07', 'America/Chicago', '2009-06-07T00:00:00-05:00'),
['2009-06-07', 'America/Chicago', '2009-06-07T00:00:00-05:00'],
// Create date object from date string.
array('2009-03-07 10:30', 'Australia/Canberra', '2009-03-07T10:30:00+11:00'),
['2009-03-07 10:30', 'Australia/Canberra', '2009-03-07T10:30:00+11:00'],
// Same during daylight savings time.
array('2009-06-07 10:30', 'Australia/Canberra', '2009-06-07T10:30:00+10:00'),
);
['2009-06-07 10:30', 'Australia/Canberra', '2009-06-07T10:30:00+10:00'],
];
}
/**
@ -316,17 +320,17 @@ class DateTimePlusTest extends UnitTestCase {
* @see DateTimePlusTest::testDates()
*/
public function providerTestDateArrays() {
return array(
return [
// Array input.
// Create date object from date array, date only.
array(array('year' => 2010, 'month' => 2, 'day' => 28), 'America/Chicago', '2010-02-28T00:00:00-06:00'),
[['year' => 2010, 'month' => 2, 'day' => 28], 'America/Chicago', '2010-02-28T00:00:00-06:00'],
// Create date object from date array with hour.
array(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), 'America/Chicago', '2010-02-28T10:00:00-06:00'),
[['year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10], 'America/Chicago', '2010-02-28T10:00:00-06:00'],
// Create date object from date array, date only.
array(array('year' => 2010, 'month' => 2, 'day' => 28), 'Europe/Berlin', '2010-02-28T00:00:00+01:00'),
[['year' => 2010, 'month' => 2, 'day' => 28], 'Europe/Berlin', '2010-02-28T00:00:00+01:00'],
// Create date object from date array with hour.
array(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10), 'Europe/Berlin', '2010-02-28T10:00:00+01:00'),
);
[['year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 10], 'Europe/Berlin', '2010-02-28T10:00:00+01:00'],
];
}
/**
@ -343,16 +347,16 @@ class DateTimePlusTest extends UnitTestCase {
* @see testDateFormats()
*/
public function providerTestDateFormat() {
return array(
return [
// Create a year-only date.
array('2009', NULL, 'Y', 'Y', '2009'),
['2009', NULL, 'Y', 'Y', '2009'],
// Create a month and year-only date.
array('2009-10', NULL, 'Y-m', 'Y-m', '2009-10'),
['2009-10', NULL, 'Y-m', 'Y-m', '2009-10'],
// Create a time-only date.
array('T10:30:00', NULL, '\TH:i:s', 'H:i:s', '10:30:00'),
['T10:30:00', NULL, '\TH:i:s', 'H:i:s', '10:30:00'],
// Create a time-only date.
array('10:30:00', NULL, 'H:i:s', 'H:i:s', '10:30:00'),
);
['10:30:00', NULL, 'H:i:s', 'H:i:s', '10:30:00'],
];
}
/**
@ -368,20 +372,20 @@ class DateTimePlusTest extends UnitTestCase {
* @see testInvalidDates
*/
public function providerTestInvalidDates() {
return array(
return [
// Test for invalid month names when we are using a short version
// of the month.
array('23 abc 2012', NULL, 'd M Y', "23 abc 2012 contains an invalid month name and did not produce errors."),
['23 abc 2012', NULL, 'd M Y', "23 abc 2012 contains an invalid month name and did not produce errors.", \InvalidArgumentException::class],
// Test for invalid hour.
array('0000-00-00T45:30:00', NULL, 'Y-m-d\TH:i:s', "0000-00-00T45:30:00 contains an invalid hour and did not produce errors."),
['0000-00-00T45:30:00', NULL, 'Y-m-d\TH:i:s', "0000-00-00T45:30:00 contains an invalid hour and did not produce errors.", \UnexpectedValueException::class],
// Test for invalid day.
array('0000-00-99T05:30:00', NULL, 'Y-m-d\TH:i:s', "0000-00-99T05:30:00 contains an invalid day and did not produce errors."),
['0000-00-99T05:30:00', NULL, 'Y-m-d\TH:i:s', "0000-00-99T05:30:00 contains an invalid day and did not produce errors.", \UnexpectedValueException::class],
// Test for invalid month.
array('0000-75-00T15:30:00', NULL, 'Y-m-d\TH:i:s', "0000-75-00T15:30:00 contains an invalid month and did not produce errors."),
['0000-75-00T15:30:00', NULL, 'Y-m-d\TH:i:s', "0000-75-00T15:30:00 contains an invalid month and did not produce errors.", \UnexpectedValueException::class],
// Test for invalid year.
array('11-08-01T15:30:00', NULL, 'Y-m-d\TH:i:s', "11-08-01T15:30:00 contains an invalid year and did not produce errors."),
['11-08-01T15:30:00', NULL, 'Y-m-d\TH:i:s', "11-08-01T15:30:00 contains an invalid year and did not produce errors.", \UnexpectedValueException::class],
);
];
}
/**
@ -395,20 +399,20 @@ class DateTimePlusTest extends UnitTestCase {
* @see testInvalidDateArrays
*/
public function providerTestInvalidDateArrays() {
return array(
return [
// One year larger than the documented upper limit of checkdate().
array(array('year' => 32768, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0), 'America/Chicago'),
[['year' => 32768, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], 'America/Chicago', \InvalidArgumentException::class],
// One year smaller than the documented lower limit of checkdate().
array(array('year' => 0, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0), 'America/Chicago'),
[['year' => 0, 'month' => 1, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], 'America/Chicago', \InvalidArgumentException::class],
// Test for invalid month from date array.
array(array('year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0), 'America/Chicago'),
[['year' => 2010, 'month' => 27, 'day' => 8, 'hour' => 8, 'minute' => 0, 'second' => 0], 'America/Chicago', \InvalidArgumentException::class],
// Test for invalid hour from date array.
array(array('year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0), 'America/Chicago'),
[['year' => 2010, 'month' => 2, 'day' => 28, 'hour' => 80, 'minute' => 0, 'second' => 0], 'America/Chicago', \InvalidArgumentException::class],
// Test for invalid minute from date array.
array(array('year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0), 'America/Chicago'),
[['year' => 2010, 'month' => 7, 'day' => 8, 'hour' => 8, 'minute' => 88, 'second' => 0], 'America/Chicago', \InvalidArgumentException::class],
// Regression test for https://www.drupal.org/node/2084455.
array(array('hour' => 59, 'minute' => 1, 'second' => 1), 'America/Chicago'),
);
[['hour' => 59, 'minute' => 1, 'second' => 1], 'America/Chicago', \InvalidArgumentException::class],
];
}
/**
@ -430,17 +434,17 @@ class DateTimePlusTest extends UnitTestCase {
// Detect the system timezone.
$system_timezone = date_default_timezone_get();
return array(
return [
// Create a date object with an unspecified timezone, which should
// end up using the system timezone.
array($date_string, NULL, $system_timezone, 'DateTimePlus uses the system timezone when there is no site timezone.'),
[$date_string, NULL, $system_timezone, 'DateTimePlus uses the system timezone when there is no site timezone.'],
// Create a date object with a specified timezone name.
array($date_string, 'America/Yellowknife', 'America/Yellowknife', 'DateTimePlus uses the specified timezone if provided.'),
[$date_string, 'America/Yellowknife', 'America/Yellowknife', 'DateTimePlus uses the specified timezone if provided.'],
// Create a date object with a timezone object.
array($date_string, new \DateTimeZone('Australia/Canberra'), 'Australia/Canberra', 'DateTimePlus uses the specified timezone if provided.'),
[$date_string, new \DateTimeZone('Australia/Canberra'), 'Australia/Canberra', 'DateTimePlus uses the specified timezone if provided.'],
// Create a date object with another date object.
array(new DateTimePlus('now', 'Pacific/Midway'), NULL, 'Pacific/Midway', 'DateTimePlus uses the specified timezone if provided.'),
);
[new DateTimePlus('now', 'Pacific/Midway'), NULL, 'Pacific/Midway', 'DateTimePlus uses the specified timezone if provided.'],
];
}
/**
@ -453,46 +457,46 @@ class DateTimePlusTest extends UnitTestCase {
* @see testTimestamp()
*/
public function providerTestTimestamp() {
return array(
return [
// Create date object from a unix timestamp and display it in
// local time.
array(
[
'input' => 0,
'initial' => array(
'initial' => [
'timezone' => 'UTC',
'format' => 'c',
'expected_date' => '1970-01-01T00:00:00+00:00',
'expected_timezone' => 'UTC',
'expected_offset' => 0,
),
'transform' => array(
],
'transform' => [
'timezone' => 'America/Los_Angeles',
'format' => 'c',
'expected_date' => '1969-12-31T16:00:00-08:00',
'expected_timezone' => 'America/Los_Angeles',
'expected_offset' => '-28800',
),
),
],
],
// Create a date using the timestamp of zero, then display its
// value both in UTC and the local timezone.
array(
[
'input' => 0,
'initial' => array(
'initial' => [
'timezone' => 'America/Los_Angeles',
'format' => 'c',
'expected_date' => '1969-12-31T16:00:00-08:00',
'expected_timezone' => 'America/Los_Angeles',
'expected_offset' => '-28800',
),
'transform' => array(
],
'transform' => [
'timezone' => 'UTC',
'format' => 'c',
'expected_date' => '1970-01-01T00:00:00+00:00',
'expected_timezone' => 'UTC',
'expected_offset' => 0,
),
),
);
],
],
];
}
/**
@ -505,63 +509,63 @@ class DateTimePlusTest extends UnitTestCase {
* @see testDateTimestamp()
*/
public function providerTestDateTimestamp() {
return array(
return [
// Create date object from datetime string in UTC, and convert
// it to a local date.
array(
[
'input' => '1970-01-01 00:00:00',
'initial' => array(
'initial' => [
'timezone' => 'UTC',
'format' => 'c',
'expected_date' => '1970-01-01T00:00:00+00:00',
'expected_timezone' => 'UTC',
'expected_offset' => 0,
),
'transform' => array(
],
'transform' => [
'timezone' => 'America/Los_Angeles',
'format' => 'c',
'expected_date' => '1969-12-31T16:00:00-08:00',
'expected_timezone' => 'America/Los_Angeles',
'expected_offset' => '-28800',
),
),
],
],
// Convert the local time to UTC using string input.
array(
[
'input' => '1969-12-31 16:00:00',
'initial' => array(
'initial' => [
'timezone' => 'America/Los_Angeles',
'format' => 'c',
'expected_date' => '1969-12-31T16:00:00-08:00',
'expected_timezone' => 'America/Los_Angeles',
'expected_offset' => '-28800',
),
'transform' => array(
],
'transform' => [
'timezone' => 'UTC',
'format' => 'c',
'expected_date' => '1970-01-01T00:00:00+00:00',
'expected_timezone' => 'UTC',
'expected_offset' => 0,
),
),
],
],
// Convert the local time to UTC using string input.
array(
[
'input' => '1969-12-31 16:00:00',
'initial' => array(
'initial' => [
'timezone' => 'Europe/Warsaw',
'format' => 'c',
'expected_date' => '1969-12-31T16:00:00+01:00',
'expected_timezone' => 'Europe/Warsaw',
'expected_offset' => '+3600',
),
'transform' => array(
],
'transform' => [
'timezone' => 'UTC',
'format' => 'c',
'expected_date' => '1969-12-31T15:00:00+00:00',
'expected_timezone' => 'UTC',
'expected_offset' => 0,
),
),
);
],
],
];
}
/**
@ -586,60 +590,60 @@ class DateTimePlusTest extends UnitTestCase {
$negative_1_hour = new \DateInterval('PT1H');
$negative_1_hour->invert = 1;
return array(
return [
// There should be a 19 hour time interval between
// new years in Sydney and new years in LA in year 2000.
array(
[
'input2' => DateTimePlus::createFromFormat('Y-m-d H:i:s', '2000-01-01 00:00:00', new \DateTimeZone('Australia/Sydney')),
'input1' => DateTimePlus::createFromFormat('Y-m-d H:i:s', '2000-01-01 00:00:00', new \DateTimeZone('America/Los_Angeles')),
'absolute' => FALSE,
'expected' => $positive_19_hours,
),
],
// In 1970 Sydney did not observe daylight savings time
// So there is only a 18 hour time interval.
array(
[
'input2' => DateTimePlus::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00', new \DateTimeZone('Australia/Sydney')),
'input1' => DateTimePlus::createFromFormat('Y-m-d H:i:s', '1970-01-01 00:00:00', new \DateTimeZone('America/Los_Angeles')),
'absolute' => FALSE,
'expected' => $positive_18_hours,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600, new \DateTimeZone('America/Los_Angeles')),
'input2' => DateTimePlus::createFromFormat('U', 0, new \DateTimeZone('UTC')),
'absolute' => FALSE,
'expected' => $negative_1_hour,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => DateTimePlus::createFromFormat('U', 0),
'absolute' => FALSE,
'expected' => $negative_1_hour,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => \DateTime::createFromFormat('U', 0),
'absolute' => FALSE,
'expected' => $negative_1_hour,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => DateTimePlus::createFromFormat('U', 0),
'absolute' => TRUE,
'expected' => $positive_1_hour,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => \DateTime::createFromFormat('U', 0),
'absolute' => TRUE,
'expected' => $positive_1_hour,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 0),
'input2' => DateTimePlus::createFromFormat('U', 0),
'absolute' => FALSE,
'expected' => $empty_interval,
),
);
],
];
}
/**
@ -652,18 +656,126 @@ class DateTimePlusTest extends UnitTestCase {
* @see DateTimePlusTest::testInvalidDateDiff()
*/
public function providerTestInvalidDateDiff() {
return array(
array(
return [
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => '1970-01-01 00:00:00',
'absolute' => FALSE,
),
array(
],
[
'input1' => DateTimePlus::createFromFormat('U', 3600),
'input2' => NULL,
'absolute' => FALSE,
),
);
],
];
}
/**
* Tests invalid values passed to constructor.
*
* @param string $time
* A date/time string.
* @param string[] $errors
* An array of error messages.
*
* @covers ::__construct
*
* @dataProvider providerTestInvalidConstructor
*/
public function testInvalidConstructor($time, array $errors) {
$date = new DateTimePlus($time);
$this->assertEquals(TRUE, $date->hasErrors());
$this->assertEquals($errors, $date->getErrors());
}
/**
* Provider for testInvalidConstructor().
*
* @return array
* An array of invalid date/time strings, and corresponding error messages.
*/
public function providerTestInvalidConstructor() {
return [
[
'YYYY-MM-DD',
[
'The timezone could not be found in the database',
'Unexpected character',
'Double timezone specification',
],
],
[
'2017-MM-DD',
[
'Unexpected character',
'The timezone could not be found in the database',
],
],
[
'YYYY-03-DD',
[
'The timezone could not be found in the database',
'Unexpected character',
'Double timezone specification',
],
],
[
'YYYY-MM-07',
[
'The timezone could not be found in the database',
'Unexpected character',
'Double timezone specification',
],
],
[
'2017-13-55',
[
'Unexpected character',
],
],
[
'YYYY-MM-DD hh:mm:ss',
[
'The timezone could not be found in the database',
'Unexpected character',
'Double timezone specification',
],
],
[
'2017-03-07 25:70:80',
[
'Unexpected character',
'Double time specification',
],
],
[
'lorem ipsum dolor sit amet',
[
'The timezone could not be found in the database',
'Double timezone specification',
],
],
];
}
/**
* Tests the $settings['validate_format'] parameter in ::createFromFormat().
*/
public function testValidateFormat() {
// Check that an input that does not strictly follow the input format will
// produce the desired date. In this case the year string '11' doesn't
// precisely match the 'Y' formater parameter, but PHP will parse it
// regardless. However, when formatted with the same string, the year will
// be output with four digits. With the ['validate_format' => FALSE]
// $settings, this will not thrown an exception.
$date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', ['validate_format' => FALSE]);
$this->assertEquals('0011-03-31 17:44:00', $date->format('Y-m-d H:i:s'));
// Parse the same date with ['validate_format' => TRUE] and make sure we
// get the expected exception.
$this->setExpectedException(\UnexpectedValueException::class);
$date = DateTimePlus::createFromFormat('Y-m-d H:i:s', '11-03-31 17:44:00', 'UTC', ['validate_format' => TRUE]);
}
}

View file

@ -0,0 +1,123 @@
<?php
namespace Drupal\Tests\Component\Datetime;
use Drupal\Component\Datetime\Time;
use Drupal\Tests\UnitTestCase;
use Symfony\Component\HttpFoundation\Request;
/**
* @coversDefaultClass \Drupal\Component\Datetime\Time
* @group Datetime
*
* Isolate the tests to prevent side effects from altering system time.
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class TimeTest extends UnitTestCase {
/**
* The mocked request stack.
*
* @var \Symfony\Component\HttpFoundation\RequestStack|\PHPUnit_Framework_MockObject_MockObject
*/
protected $requestStack;
/**
* The mocked time class.
*
* @var \Drupal\Component\Datetime\Time
*/
protected $time;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->requestStack = $this->getMock('Symfony\Component\HttpFoundation\RequestStack');
$this->time = new Time($this->requestStack);
}
/**
* Tests the getRequestTime method.
*
* @covers ::getRequestTime
*/
public function testGetRequestTime() {
$expected = 12345678;
$request = Request::createFromGlobals();
$request->server->set('REQUEST_TIME', $expected);
// Mocks a the request stack getting the current request.
$this->requestStack->expects($this->any())
->method('getCurrentRequest')
->willReturn($request);
$this->assertEquals($expected, $this->time->getRequestTime());
}
/**
* Tests the getRequestMicroTime method.
*
* @covers ::getRequestMicroTime
*/
public function testGetRequestMicroTime() {
$expected = 1234567.89;
$request = Request::createFromGlobals();
$request->server->set('REQUEST_TIME_FLOAT', $expected);
// Mocks a the request stack getting the current request.
$this->requestStack->expects($this->any())
->method('getCurrentRequest')
->willReturn($request);
$this->assertEquals($expected, $this->time->getRequestMicroTime());
}
/**
* Tests the getCurrentTime method.
*
* @covers ::getCurrentTime
*/
public function testGetCurrentTime() {
$expected = 12345678;
$this->assertEquals($expected, $this->time->getCurrentTime());
}
/**
* Tests the getCurrentMicroTime method.
*
* @covers ::getCurrentMicroTime
*/
public function testGetCurrentMicroTime() {
$expected = 1234567.89;
$this->assertEquals($expected, $this->time->getCurrentMicroTime());
}
}
namespace Drupal\Component\Datetime;
/**
* Shadow time() system call.
*
* @returns int
*/
function time() {
return 12345678;
}
/**
* Shadow microtime system call.
*
* @returns float
*/
function microtime() {
return 1234567.89;
}

View file

@ -7,8 +7,14 @@
namespace Drupal\Tests\Component\DependencyInjection;
use Drupal\Component\Utility\Crypt;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Prophecy\Argument;
/**
@ -59,12 +65,11 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* Tests that passing a non-supported format throws an InvalidArgumentException.
*
* @covers ::__construct
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testConstruct() {
$container_definition = $this->getMockContainerDefinition();
$container_definition['machine_format'] = !$this->machineFormat;
$this->setExpectedException(InvalidArgumentException::class);
$container = new $this->containerClass($container_definition);
}
@ -85,10 +90,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::getParameter
* @covers ::getParameterAlternatives
* @covers ::getAlternatives
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException
*/
public function testGetParameterIfNotFound() {
$this->setExpectedException(ParameterNotFoundException::class);
$this->container->getParameter('parameter_that_does_not_exist');
}
@ -96,10 +100,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* Tests that Container::getParameter() works properly for NULL parameters.
*
* @covers ::getParameter
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException
*/
public function testGetParameterIfNotFoundBecauseNull() {
$this->setExpectedException(ParameterNotFoundException::class);
$this->container->getParameter(NULL);
}
@ -130,11 +133,10 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* Tests that Container::setParameter() in a frozen case works properly.
*
* @covers ::setParameter
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\LogicException
*/
public function testSetParameterWithFrozenContainer() {
$this->container = new $this->containerClass($this->containerDefinition);
$this->setExpectedException(LogicException::class);
$this->container->setParameter('some_config', 'new_value');
}
@ -235,11 +237,11 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
/**
* Tests that Container::get() for circular dependencies works properly.
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @covers ::get
* @covers ::createService
*/
public function testGetForCircularServices() {
$this->setExpectedException(ServiceCircularReferenceException::class);
$this->container->get('circular_dependency');
}
@ -250,10 +252,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::createService
* @covers ::getAlternatives
* @covers ::getServiceAlternatives
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
*/
public function testGetForNonExistantService() {
$this->setExpectedException(ServiceNotFoundException::class);
$this->container->get('service_not_exists');
}
@ -295,8 +296,6 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::get
* @covers ::createService
* @covers ::resolveServicesAndParameters
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetForParameterDependencyWithExceptionOnSecondCall() {
$service = $this->container->get('service_parameter_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE);
@ -304,6 +303,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
// Reset the service.
$this->container->set('service_parameter_not_exists', NULL);
$this->setExpectedException(InvalidArgumentException::class);
$this->container->get('service_parameter_not_exists');
}
@ -313,10 +313,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::get
* @covers ::createService
* @covers ::resolveServicesAndParameters
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetForNonExistantParameterDependencyWithException() {
$this->setExpectedException(InvalidArgumentException::class);
$this->container->get('service_parameter_not_exists');
}
@ -339,10 +338,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::createService
* @covers ::resolveServicesAndParameters
* @covers ::getAlternatives
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
*/
public function testGetForNonExistantServiceDependencyWithException() {
$this->setExpectedException(ServiceNotFoundException::class);
$this->container->get('service_dependency_not_exists');
}
@ -360,10 +358,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* Tests that Container::get() for NULL service works properly.
* @covers ::get
* @covers ::createService
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
*/
public function testGetForNonExistantNULLService() {
$this->setExpectedException(ServiceNotFoundException::class);
$this->container->get(NULL);
}
@ -386,11 +383,10 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::get
* @covers ::createService
* @covers ::getAlternatives
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
*/
public function testGetForNonExistantServiceWithExceptionOnSecondCall() {
$this->assertNull($this->container->get('service_not_exists', ContainerInterface::NULL_ON_INVALID_REFERENCE), 'Not found service does nto throw exception.');
$this->setExpectedException(ServiceNotFoundException::class);
$this->container->get('service_not_exists');
}
@ -424,10 +420,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*
* @covers ::get
* @covers ::createService
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testGetForSyntheticServiceWithException() {
$this->setExpectedException(RuntimeException::class);
$this->container->get('synthetic');
}
@ -451,7 +446,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::resolveServicesAndParameters
*/
public function testGetForInstantiationWithVariousArgumentLengths() {
$args = array();
$args = [];
for ($i = 0; $i < 12; $i++) {
$instantiation_service = $this->container->get('service_test_instantiation_' . $i);
$this->assertEquals($args, $instantiation_service->getArguments());
@ -464,10 +459,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*
* @covers ::get
* @covers ::createService
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testGetForWrongFactory() {
$this->setExpectedException(RuntimeException::class);
$this->container->get('wrong_factory');
}
@ -503,10 +497,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*
* @covers ::get
* @covers ::createService
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetForConfiguratorWithException() {
$this->setExpectedException(InvalidArgumentException::class);
$this->container->get('configurable_service_exception');
}
@ -602,10 +595,9 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::get
* @covers ::createService
* @covers ::resolveServicesAndParameters
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testResolveServicesAndParametersForInvalidArgument() {
$this->setExpectedException(InvalidArgumentException::class);
$this->container->get('invalid_argument_service');
}
@ -615,12 +607,11 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::get
* @covers ::createService
* @covers ::resolveServicesAndParameters
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testResolveServicesAndParametersForInvalidArguments() {
// In case the machine-optimized format is not used, we need to simulate the
// test failure.
$this->setExpectedException(InvalidArgumentException::class);
if (!$this->machineFormat) {
throw new InvalidArgumentException('Simulating the test failure.');
}
@ -671,16 +662,15 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
* @covers ::hasScope
* @covers ::isScopeActive
*
* @expectedException \BadMethodCallException
*
* @dataProvider scopeExceptionTestProvider
*/
public function testScopeFunctionsWithException($method, $argument) {
$callable = array(
$callable = [
$this->container,
$method,
);
];
$this->setExpectedException(\BadMethodCallException::class);
$callable($argument);
}
@ -694,13 +684,13 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*/
public function scopeExceptionTestProvider() {
$scope = $this->prophesize('\Symfony\Component\DependencyInjection\ScopeInterface')->reveal();
return array(
array('enterScope', 'test_scope'),
array('leaveScope', 'test_scope'),
array('hasScope', 'test_scope'),
array('isScopeActive', 'test_scope'),
array('addScope', $scope),
);
return [
['enterScope', 'test_scope'],
['leaveScope', 'test_scope'],
['hasScope', 'test_scope'],
['isScopeActive', 'test_scope'],
['addScope', $scope],
];
}
/**
@ -728,7 +718,7 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*/
protected function getMockContainerDefinition() {
$fake_service = new \stdClass();
$parameters = array();
$parameters = [];
$parameters['some_parameter_class'] = get_class($fake_service);
$parameters['some_private_config'] = 'really_private_lama';
$parameters['some_config'] = 'foo';
@ -737,262 +727,262 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
// Also test alias resolving.
$parameters['service_from_parameter'] = $this->getServiceCall('service.provider_alias');
$services = array();
$services['service_container'] = array(
$services = [];
$services['service_container'] = [
'class' => '\Drupal\service_container\DependencyInjection\Container',
);
$services['other.service'] = array(
];
$services['other.service'] = [
'class' => get_class($fake_service),
);
];
$services['non_shared_service'] = array(
$services['non_shared_service'] = [
'class' => get_class($fake_service),
'shared' => FALSE,
);
];
$services['other.service_class_from_parameter'] = array(
$services['other.service_class_from_parameter'] = [
'class' => $this->getParameterCall('some_parameter_class'),
);
$services['late.service'] = array(
];
$services['late.service'] = [
'class' => get_class($fake_service),
);
$services['service.provider'] = array(
];
$services['service.provider'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('other.service'),
$this->getParameterCall('some_config'),
)),
'properties' => $this->getCollection(array('_someProperty' => 'foo')),
'calls' => array(
array('setContainer', $this->getCollection(array(
]),
'properties' => $this->getCollection(['_someProperty' => 'foo']),
'calls' => [
['setContainer', $this->getCollection([
$this->getServiceCall('service_container'),
))),
array('setOtherConfigParameter', $this->getCollection(array(
])],
['setOtherConfigParameter', $this->getCollection([
$this->getParameterCall('some_other_config'),
))),
),
])],
],
'priority' => 0,
);
];
// Test private services.
$private_service = array(
$private_service = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('other.service'),
$this->getParameterCall('some_private_config'),
)),
]),
'public' => FALSE,
);
];
$services['service_using_private'] = array(
$services['service_using_private'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getPrivateServiceCall(NULL, $private_service),
$this->getParameterCall('some_config'),
)),
);
$services['another_service_using_private'] = array(
]),
];
$services['another_service_using_private'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getPrivateServiceCall(NULL, $private_service),
$this->getParameterCall('some_config'),
)),
);
]),
];
// Test shared private services.
$id = 'private_service_shared_1';
$services['service_using_shared_private'] = array(
$services['service_using_shared_private'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getPrivateServiceCall($id, $private_service, TRUE),
$this->getParameterCall('some_config'),
)),
);
$services['another_service_using_shared_private'] = array(
]),
];
$services['another_service_using_shared_private'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getPrivateServiceCall($id, $private_service, TRUE),
$this->getParameterCall('some_config'),
)),
);
]),
];
// Tests service with invalid argument.
$services['invalid_argument_service'] = array(
$services['invalid_argument_service'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
1, // Test passing non-strings, too.
(object) array(
(object) [
'type' => 'invalid',
),
)),
);
],
]),
];
$services['invalid_arguments_service'] = array(
$services['invalid_arguments_service'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => (object) array(
'arguments' => (object) [
'type' => 'invalid',
),
);
],
];
// Test service that needs deep-traversal.
$services['service_using_array'] = array(
$services['service_using_array'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
$this->getCollection(array(
'arguments' => $this->getCollection([
$this->getCollection([
$this->getServiceCall('other.service'),
)),
]),
$this->getParameterCall('some_private_config'),
)),
);
]),
];
$services['service_with_optional_dependency'] = array(
$services['service_with_optional_dependency'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('service.does_not_exist', ContainerInterface::NULL_ON_INVALID_REFERENCE),
$this->getParameterCall('some_private_config'),
)),
]),
);
];
$services['factory_service'] = array(
$services['factory_service'] = [
'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
'factory' => array(
'factory' => [
$this->getServiceCall('service.provider'),
'getFactoryMethod',
),
'arguments' => $this->getCollection(array(
],
'arguments' => $this->getCollection([
$this->getParameterCall('factory_service_class'),
)),
);
$services['factory_class'] = array(
]),
];
$services['factory_class'] = [
'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
'factory' => '\Drupal\Tests\Component\DependencyInjection\MockService::getFactoryMethod',
'arguments' => array(
'arguments' => [
'\Drupal\Tests\Component\DependencyInjection\MockService',
array(NULL, 'bar'),
),
'calls' => array(
array('setContainer', $this->getCollection(array(
[NULL, 'bar'],
],
'calls' => [
['setContainer', $this->getCollection([
$this->getServiceCall('service_container'),
))),
),
);
])],
],
];
$services['wrong_factory'] = array(
$services['wrong_factory'] = [
'class' => '\Drupal\service_container\ServiceContainer\ControllerInterface',
'factory' => (object) array('I am not a factory, but I pretend to be.'),
);
'factory' => (object) ['I am not a factory, but I pretend to be.'],
];
$services['circular_dependency'] = array(
$services['circular_dependency'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('circular_dependency'),
)),
);
$services['synthetic'] = array(
]),
];
$services['synthetic'] = [
'synthetic' => TRUE,
);
];
// The file could have been named as a .php file. The reason it is a .data
// file is that SimpleTest tries to load it. SimpleTest does not like such
// fixtures and hence we use a neutral name like .data.
$services['container_test_file_service_test'] = array(
$services['container_test_file_service_test'] = [
'class' => '\stdClass',
'file' => __DIR__ . '/Fixture/container_test_file_service_test_service_function.data',
);
];
// Test multiple arguments.
$args = array();
$args = [];
for ($i = 0; $i < 12; $i++) {
$services['service_test_instantiation_' . $i] = array(
$services['service_test_instantiation_' . $i] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockInstantiationService',
// Also test a collection that does not need resolving.
'arguments' => $this->getCollection($args, FALSE),
);
];
$args[] = 'arg_' . $i;
}
$services['service_parameter_not_exists'] = array(
$services['service_parameter_not_exists'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('service.provider'),
$this->getParameterCall('not_exists'),
)),
);
$services['service_dependency_not_exists'] = array(
]),
];
$services['service_dependency_not_exists'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getServiceCall('service_not_exists'),
$this->getParameterCall('some_config'),
)),
);
]),
];
$services['service_with_parameter_service'] = array(
$services['service_with_parameter_service'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$this->getParameterCall('service_from_parameter'),
// Also test deep collections that don't need resolving.
$this->getCollection(array(
$this->getCollection([
1,
), FALSE),
)),
);
], FALSE),
]),
];
// To ensure getAlternatives() finds something.
$services['service_not_exists_similar'] = array(
$services['service_not_exists_similar'] = [
'synthetic' => TRUE,
);
];
// Test configurator.
$services['configurator'] = array(
$services['configurator'] = [
'synthetic' => TRUE,
);
$services['configurable_service'] = array(
];
$services['configurable_service'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => array(),
'configurator' => array(
'arguments' => [],
'configurator' => [
$this->getServiceCall('configurator'),
'configureService'
),
);
$services['configurable_service_exception'] = array(
],
];
$services['configurable_service_exception'] = [
'class' => '\Drupal\Tests\Component\DependencyInjection\MockService',
'arguments' => array(),
'arguments' => [],
'configurator' => 'configurator_service_test_does_not_exist',
);
];
$aliases = array();
$aliases = [];
$aliases['service.provider_alias'] = 'service.provider';
$aliases['late.service_alias'] = 'late.service';
return array(
return [
'aliases' => $aliases,
'parameters' => $parameters,
'services' => $services,
'frozen' => TRUE,
'machine_format' => $this->machineFormat,
);
];
}
/**
* Helper function to return a service definition.
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return (object) array(
return (object) [
'type' => 'service',
'id' => $id,
'invalidBehavior' => $invalid_behavior,
);
];
}
/**
* Helper function to return a service definition.
*/
protected function getParameterCall($name) {
return (object) array(
return (object) [
'type' => 'parameter',
'name' => $name,
);
];
}
/**
@ -1000,26 +990,26 @@ class ContainerTest extends \PHPUnit_Framework_TestCase {
*/
protected function getPrivateServiceCall($id, $service_definition, $shared = FALSE) {
if (!$id) {
$hash = sha1(serialize($service_definition));
$hash = Crypt::hashBase64(serialize($service_definition));
$id = 'private__' . $hash;
}
return (object) array(
return (object) [
'type' => 'private_service',
'id' => $id,
'value' => $service_definition,
'shared' => $shared,
);
];
}
/**
* Helper function to return a machine-optimized collection.
*/
protected function getCollection($collection, $resolve = TRUE) {
return (object) array(
return (object) [
'type' => 'collection',
'value' => $collection,
'resolve' => $resolve,
);
];
}
}
@ -1188,7 +1178,7 @@ class MockService {
* @return object
* The instantiated service object.
*/
public static function getFactoryMethod($class, $arguments = array()) {
public static function getFactoryMethod($class, $arguments = []) {
$r = new \ReflectionClass($class);
$service = ($r->getConstructor() === NULL) ? $r->newInstance() : $r->newInstanceArgs($arguments);

View file

@ -7,12 +7,15 @@
namespace Drupal\Tests\Component\DependencyInjection\Dumper {
use Drupal\Component\Utility\Crypt;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Parameter;
use Symfony\Component\ExpressionLanguage\Expression;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
/**
* @coversDefaultClass \Drupal\Component\DependencyInjection\Dumper\OptimizedPhpArrayDumper
@ -61,15 +64,15 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
protected function setUp() {
// Setup a mock container builder.
$this->containerBuilder = $this->prophesize('\Symfony\Component\DependencyInjection\ContainerBuilder');
$this->containerBuilder->getAliases()->willReturn(array());
$this->containerBuilder->getAliases()->willReturn([]);
$this->containerBuilder->getParameterBag()->willReturn(new ParameterBag());
$this->containerBuilder->getDefinitions()->willReturn(NULL);
$this->containerBuilder->isFrozen()->willReturn(TRUE);
$definition = array();
$definition['aliases'] = array();
$definition['parameters'] = array();
$definition['services'] = array();
$definition = [];
$definition['aliases'] = [];
$definition['parameters'] = [];
$definition['services'] = [];
$definition['frozen'] = TRUE;
$definition['machine_format'] = $this->machineFormat;
@ -113,17 +116,17 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* - aliases as expected in the container definition.
*/
public function getAliasesDataProvider() {
return array(
array(array(), array()),
array(
array('foo' => 'foo.alias'),
array('foo' => 'foo.alias'),
),
array(
array('foo' => 'foo.alias', 'foo.alias' => 'foo.alias.alias'),
array('foo' => 'foo.alias.alias', 'foo.alias' => 'foo.alias.alias'),
),
);
return [
[[], []],
[
['foo' => 'foo.alias'],
['foo' => 'foo.alias'],
],
[
['foo' => 'foo.alias', 'foo.alias' => 'foo.alias.alias'],
['foo' => 'foo.alias.alias', 'foo.alias' => 'foo.alias.alias'],
],
];
}
/**
@ -163,34 +166,34 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* - frozen value
*/
public function getParametersDataProvider() {
return array(
array(array(), array(), TRUE),
array(
array('foo' => 'value_foo'),
array('foo' => 'value_foo'),
return [
[[], [], TRUE],
[
['foo' => 'value_foo'],
['foo' => 'value_foo'],
TRUE,
),
array(
array('foo' => array('llama' => 'yes')),
array('foo' => array('llama' => 'yes')),
],
[
['foo' => ['llama' => 'yes']],
['foo' => ['llama' => 'yes']],
TRUE,
),
array(
array('foo' => '%llama%', 'llama' => 'yes'),
array('foo' => '%%llama%%', 'llama' => 'yes'),
],
[
['foo' => '%llama%', 'llama' => 'yes'],
['foo' => '%%llama%%', 'llama' => 'yes'],
TRUE,
),
array(
array('foo' => '%llama%', 'llama' => 'yes'),
array('foo' => '%llama%', 'llama' => 'yes'),
],
[
['foo' => '%llama%', 'llama' => 'yes'],
['foo' => '%llama%', 'llama' => 'yes'],
FALSE,
),
array(
array('reference' => new Reference('referenced_service')),
array('reference' => $this->getServiceCall('referenced_service')),
],
[
['reference' => new Reference('referenced_service')],
['reference' => $this->getServiceCall('referenced_service')],
TRUE,
),
);
],
];
}
/**
@ -235,164 +238,164 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* - frozen value
*/
public function getDefinitionsDataProvider() {
$base_service_definition = array(
$base_service_definition = [
'class' => '\stdClass',
'public' => TRUE,
'file' => FALSE,
'synthetic' => FALSE,
'lazy' => FALSE,
'arguments' => array(),
'arguments' => [],
'arguments_count' => 0,
'properties' => array(),
'calls' => array(),
'properties' => [],
'calls' => [],
'scope' => ContainerInterface::SCOPE_CONTAINER,
'shared' => TRUE,
'factory' => FALSE,
'configurator' => FALSE,
);
];
// Test basic flags.
$service_definitions[] = array() + $base_service_definition;
$service_definitions[] = [] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'public' => FALSE,
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'file' => 'test_include.php',
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'synthetic' => TRUE,
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'shared' => FALSE,
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'lazy' => TRUE,
) + $base_service_definition;
] + $base_service_definition;
// Test a basic public Reference.
$service_definitions[] = array(
'arguments' => array('foo', new Reference('bar')),
$service_definitions[] = [
'arguments' => ['foo', new Reference('bar')],
'arguments_count' => 2,
'arguments_expected' => $this->getCollection(array('foo', $this->getServiceCall('bar'))),
) + $base_service_definition;
'arguments_expected' => $this->getCollection(['foo', $this->getServiceCall('bar')]),
] + $base_service_definition;
// Test a public reference that should not throw an Exception.
$reference = new Reference('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE);
$service_definitions[] = array(
'arguments' => array($reference),
$service_definitions[] = [
'arguments' => [$reference],
'arguments_count' => 1,
'arguments_expected' => $this->getCollection(array($this->getServiceCall('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE))),
) + $base_service_definition;
'arguments_expected' => $this->getCollection([$this->getServiceCall('bar', ContainerInterface::NULL_ON_INVALID_REFERENCE)]),
] + $base_service_definition;
// Test a private shared service, denoted by having a Reference.
$private_definition = array(
$private_definition = [
'class' => '\stdClass',
'public' => FALSE,
'arguments_count' => 0,
);
];
$service_definitions[] = array(
'arguments' => array('foo', new Reference('private_definition')),
$service_definitions[] = [
'arguments' => ['foo', new Reference('private_definition')],
'arguments_count' => 2,
'arguments_expected' => $this->getCollection(array(
'arguments_expected' => $this->getCollection([
'foo',
$this->getPrivateServiceCall('private_definition', $private_definition, TRUE),
)),
) + $base_service_definition;
]),
] + $base_service_definition;
// Test a private non-shared service, denoted by having a Definition.
$private_definition_object = new Definition('\stdClass');
$private_definition_object->setPublic(FALSE);
$service_definitions[] = array(
'arguments' => array('foo', $private_definition_object),
$service_definitions[] = [
'arguments' => ['foo', $private_definition_object],
'arguments_count' => 2,
'arguments_expected' => $this->getCollection(array(
'arguments_expected' => $this->getCollection([
'foo',
$this->getPrivateServiceCall(NULL, $private_definition),
)),
) + $base_service_definition;
]),
] + $base_service_definition;
// Test a deep collection without a reference.
$service_definitions[] = array(
'arguments' => array(array(array('foo'))),
$service_definitions[] = [
'arguments' => [[['foo']]],
'arguments_count' => 1,
) + $base_service_definition;
] + $base_service_definition;
// Test a deep collection with a reference to resolve.
$service_definitions[] = array(
'arguments' => array(array(new Reference('bar'))),
$service_definitions[] = [
'arguments' => [[new Reference('bar')]],
'arguments_count' => 1,
'arguments_expected' => $this->getCollection(array($this->getCollection(array($this->getServiceCall('bar'))))),
) + $base_service_definition;
'arguments_expected' => $this->getCollection([$this->getCollection([$this->getServiceCall('bar')])]),
] + $base_service_definition;
// Test a collection with a variable to resolve.
$service_definitions[] = array(
'arguments' => array(new Parameter('llama_parameter')),
$service_definitions[] = [
'arguments' => [new Parameter('llama_parameter')],
'arguments_count' => 1,
'arguments_expected' => $this->getCollection(array($this->getParameterCall('llama_parameter'))),
) + $base_service_definition;
'arguments_expected' => $this->getCollection([$this->getParameterCall('llama_parameter')]),
] + $base_service_definition;
// Test objects that have _serviceId property.
$drupal_service = new \stdClass();
$drupal_service->_serviceId = 'bar';
$service_definitions[] = array(
'arguments' => array($drupal_service),
$service_definitions[] = [
'arguments' => [$drupal_service],
'arguments_count' => 1,
'arguments_expected' => $this->getCollection(array($this->getServiceCall('bar'))),
) + $base_service_definition;
'arguments_expected' => $this->getCollection([$this->getServiceCall('bar')]),
] + $base_service_definition;
// Test getMethodCalls.
$calls = array(
array('method', $this->getCollection(array())),
array('method2', $this->getCollection(array())),
);
$service_definitions[] = array(
$calls = [
['method', $this->getCollection([])],
['method2', $this->getCollection([])],
];
$service_definitions[] = [
'calls' => $calls,
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'scope' => ContainerInterface::SCOPE_PROTOTYPE,
'shared' => FALSE,
) + $base_service_definition;
] + $base_service_definition;
$service_definitions[] = array(
$service_definitions[] = [
'shared' => FALSE,
) + $base_service_definition;
] + $base_service_definition;
// Test factory.
$service_definitions[] = array(
'factory' => array(new Reference('bar'), 'factoryMethod'),
'factory_expected' => array($this->getServiceCall('bar'), 'factoryMethod'),
) + $base_service_definition;
$service_definitions[] = [
'factory' => [new Reference('bar'), 'factoryMethod'],
'factory_expected' => [$this->getServiceCall('bar'), 'factoryMethod'],
] + $base_service_definition;
// Test invalid factory - needed to test deep dumpValue().
$service_definitions[] = array(
'factory' => array(array('foo', 'llama'), 'factoryMethod'),
) + $base_service_definition;
$service_definitions[] = [
'factory' => [['foo', 'llama'], 'factoryMethod'],
] + $base_service_definition;
// Test properties.
$service_definitions[] = array(
'properties' => array('_value' => 'llama'),
) + $base_service_definition;
$service_definitions[] = [
'properties' => ['_value' => 'llama'],
] + $base_service_definition;
// Test configurator.
$service_definitions[] = array(
'configurator' => array(new Reference('bar'), 'configureService'),
'configurator_expected' => array($this->getServiceCall('bar'), 'configureService'),
) + $base_service_definition;
$service_definitions[] = [
'configurator' => [new Reference('bar'), 'configureService'],
'configurator_expected' => [$this->getServiceCall('bar'), 'configureService'],
] + $base_service_definition;
$services_provided = array();
$services_provided[] = array(
array(),
array(),
);
$services_provided = [];
$services_provided[] = [
[],
[],
];
foreach ($service_definitions as $service_definition) {
$definition = $this->prophesize('\Symfony\Component\DependencyInjection\Definition');
@ -411,7 +414,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$definition->getConfigurator()->willReturn($service_definition['configurator']);
// Preserve order.
$filtered_service_definition = array();
$filtered_service_definition = [];
foreach ($base_service_definition as $key => $value) {
$filtered_service_definition[$key] = $service_definition[$key];
unset($service_definition[$key]);
@ -429,7 +432,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$filtered_service_definition += $service_definition;
// Allow to set _expected values.
foreach (array('arguments', 'factory', 'configurator') as $key) {
foreach (['arguments', 'factory', 'configurator'] as $key) {
$expected = $key . '_expected';
if (isset($filtered_service_definition[$expected])) {
$filtered_service_definition[$key] = $filtered_service_definition[$expected];
@ -441,17 +444,17 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
unset($filtered_service_definition['scope']);
if (isset($filtered_service_definition['public']) && $filtered_service_definition['public'] === FALSE) {
$services_provided[] = array(
array('foo_service' => $definition->reveal()),
array(),
);
$services_provided[] = [
['foo_service' => $definition->reveal()],
[],
];
continue;
}
$services_provided[] = array(
array('foo_service' => $definition->reveal()),
array('foo_service' => $this->serializeDefinition($filtered_service_definition)),
);
$services_provided[] = [
['foo_service' => $definition->reveal()],
['foo_service' => $this->serializeDefinition($filtered_service_definition)],
];
}
return $services_provided;
@ -470,19 +473,17 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* Helper function to return a service definition.
*/
protected function getServiceCall($id, $invalid_behavior = ContainerInterface::EXCEPTION_ON_INVALID_REFERENCE) {
return (object) array(
return (object) [
'type' => 'service',
'id' => $id,
'invalidBehavior' => $invalid_behavior,
);
];
}
/**
* Tests that the correct InvalidArgumentException is thrown for getScope().
*
* @covers ::getServiceDefinition
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetServiceDefinitionWithInvalidScope() {
$bar_definition = new Definition('\stdClass');
@ -490,6 +491,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services);
$this->setExpectedException(InvalidArgumentException::class);
$this->dumper->getArray();
}
@ -502,9 +504,9 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
*/
public function testGetServiceDefinitionWithReferenceToAlias($public) {
$bar_definition = new Definition('\stdClass');
$bar_definition_php_array = array(
$bar_definition_php_array = [
'class' => '\stdClass',
);
];
if (!$public) {
$bar_definition->setPublic(FALSE);
$bar_definition_php_array['public'] = FALSE;
@ -530,21 +532,21 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
else {
$service_definition = $this->getPrivateServiceCall('bar', $bar_definition_php_array, TRUE);
}
$data = array(
$data = [
'class' => '\stdClass',
'arguments' => $this->getCollection(array(
'arguments' => $this->getCollection([
$service_definition,
)),
]),
'arguments_count' => 1,
);
];
$this->assertEquals($this->serializeDefinition($data), $dump['services']['foo'], 'Expected definition matches dump.');
}
public function publicPrivateDataProvider() {
return array(
array(TRUE),
array(FALSE),
);
return [
[TRUE],
[FALSE],
];
}
/**
@ -554,8 +556,6 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* getDecoratedService().
*
* @covers ::getServiceDefinition
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
*/
public function testGetServiceDefinitionForDecoratedService() {
$bar_definition = new Definition('\stdClass');
@ -563,6 +563,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services);
$this->setExpectedException(InvalidArgumentException::class);
$this->dumper->getArray();
}
@ -570,8 +571,6 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* Tests that the correct RuntimeException is thrown for expressions.
*
* @covers ::dumpValue
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testGetServiceDefinitionForExpression() {
$expression = new Expression();
@ -581,6 +580,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services);
$this->setExpectedException(RuntimeException::class);
$this->dumper->getArray();
}
@ -588,8 +588,6 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* Tests that the correct RuntimeException is thrown for dumping an object.
*
* @covers ::dumpValue
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testGetServiceDefinitionForObject() {
$service = new \stdClass();
@ -599,6 +597,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services);
$this->setExpectedException(RuntimeException::class);
$this->dumper->getArray();
}
@ -606,8 +605,6 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
* Tests that the correct RuntimeException is thrown for dumping a resource.
*
* @covers ::dumpValue
*
* @expectedException \Symfony\Component\DependencyInjection\Exception\RuntimeException
*/
public function testGetServiceDefinitionForResource() {
$resource = fopen('php://memory', 'r');
@ -617,6 +614,7 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
$services['bar'] = $bar_definition;
$this->containerBuilder->getDefinitions()->willReturn($services);
$this->setExpectedException(RuntimeException::class);
$this->dumper->getArray();
}
@ -625,36 +623,36 @@ namespace Drupal\Tests\Component\DependencyInjection\Dumper {
*/
protected function getPrivateServiceCall($id, $service_definition, $shared = FALSE) {
if (!$id) {
$hash = sha1(serialize($service_definition));
$hash = Crypt::hashBase64(serialize($service_definition));
$id = 'private__' . $hash;
}
return (object) array(
return (object) [
'type' => 'private_service',
'id' => $id,
'value' => $service_definition,
'shared' => $shared,
);
];
}
/**
* Helper function to return a machine-optimized collection.
*/
protected function getCollection($collection, $resolve = TRUE) {
return (object) array(
return (object) [
'type' => 'collection',
'value' => $collection,
'resolve' => $resolve,
);
];
}
/**
* Helper function to return a parameter definition.
*/
protected function getParameterCall($name) {
return (object) array(
return (object) [
'type' => 'parameter',
'name' => $name,
);
];
}
}

View file

@ -34,12 +34,12 @@ class YamlDiscoveryTest extends UnitTestCase {
file_put_contents($url . '/test_2/test_4.test.yml', '');
// Set up the directories to search.
$directories = array(
$directories = [
'test_1' => $url . '/test_1',
'test_2' => $url . '/test_1',
'test_3' => $url . '/test_2',
'test_4' => $url . '/test_2',
);
];
$discovery = new YamlDiscovery('test', $directories);
$data = $discovery->findAll();
@ -50,12 +50,12 @@ class YamlDiscoveryTest extends UnitTestCase {
$this->assertArrayHasKey('test_3', $data);
$this->assertArrayHasKey('test_4', $data);
foreach (array('test_1', 'test_2', 'test_3') as $key) {
foreach (['test_1', 'test_2', 'test_3'] as $key) {
$this->assertArrayHasKey('name', $data[$key]);
$this->assertEquals($data[$key]['name'], 'test');
}
$this->assertSame(array(), $data['test_4']);
$this->assertSame([], $data['test_4']);
}
}

View file

@ -42,7 +42,7 @@ class DrupalComponentTest extends UnitTestCase {
* An array of class paths.
*/
protected function findPhpClasses($dir) {
$classes = array();
$classes = [];
foreach (new \DirectoryIterator($dir) as $file) {
if ($file->isDir() && !$file->isDot()) {
$classes = array_merge($classes, $this->findPhpClasses($file->getPathname()));
@ -80,26 +80,26 @@ class DrupalComponentTest extends UnitTestCase {
* - File data as a string. This will be used as a virtual file.
*/
public function providerAssertNoCoreUseage() {
return array(
array(
return [
[
TRUE,
'@see \\Drupal\\Core\\Something',
),
array(
],
[
FALSE,
'\\Drupal\\Core\\Something',
),
array(
],
[
FALSE,
"@see \\Drupal\\Core\\Something\n" .
'\\Drupal\\Core\\Something',
),
array(
],
[
FALSE,
"\\Drupal\\Core\\Something\n" .
'@see \\Drupal\\Core\\Something',
),
);
],
];
}
/**

View file

@ -55,12 +55,10 @@ class FileCacheFactoryTest extends UnitTestCase {
/**
* @covers ::get
*
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Required prefix configuration is missing
*/
public function testGetNoPrefix() {
FileCacheFactory::setPrefix(NULL);
$this->setExpectedException(\InvalidArgumentException::class, 'Required prefix configuration is missing');
FileCacheFactory::get('test_foo_settings', []);
}
@ -101,8 +99,8 @@ class FileCacheFactoryTest extends UnitTestCase {
// Get a unique FileCache class.
$file_cache = $this->getMockBuilder(FileCache::class)
->disableOriginalConstructor()
->getMock();
->disableOriginalConstructor()
->getMock();
$class = get_class($file_cache);
// Test fallback configuration.

View file

@ -48,22 +48,22 @@ class PoHeaderTest extends UnitTestCase {
* value.
*/
public function providerTestPluralsFormula() {
return array(
array(
return [
[
'nplurals=1; plural=0;',
array('default' => 0),
),
array(
['default' => 0],
],
[
'nplurals=2; plural=(n > 1);',
array(0 => 0, 1 => 0, 'default' => 1),
),
array(
[0 => 0, 1 => 0, 'default' => 1],
],
[
'nplurals=2; plural=(n!=1);',
array(1 => 0, 'default' => 1),
),
array(
[1 => 0, 'default' => 1],
],
[
'nplurals=2; plural=(((n==1)||((n%10)==1))?(0):1);',
array(
[
1 => 0,
11 => 0,
21 => 0,
@ -85,11 +85,11 @@ class PoHeaderTest extends UnitTestCase {
181 => 0,
191 => 0,
'default' => 1,
),
),
array(
],
],
[
'nplurals=3; plural=((((n%10)==1)&&((n%100)!=11))?(0):(((((n%10)>=2)&&((n%10)<=4))&&(((n%100)<10)||((n%100)>=20)))?(1):2));',
array(
[
1 => 0,
2 => 1,
3 => 1,
@ -163,21 +163,21 @@ class PoHeaderTest extends UnitTestCase {
193 => 1,
194 => 1,
'default' => 2,
),
),
array(
],
],
[
'nplurals=3; plural=((n==1)?(0):(((n>=2)&&(n<=4))?(1):2));',
array(
[
1 => 0,
2 => 1,
3 => 1,
4 => 1,
'default' => 2,
),
),
array(
],
],
[
'nplurals=3; plural=((n==1)?(0):(((n==0)||(((n%100)>0)&&((n%100)<20)))?(1):2));',
array(
[
0 => 1,
1 => 0,
2 => 1,
@ -218,11 +218,11 @@ class PoHeaderTest extends UnitTestCase {
118 => 1,
119 => 1,
'default' => 2,
),
),
array(
],
],
[
'nplurals=3; plural=((n==1)?(0):(((((n%10)>=2)&&((n%10)<=4))&&(((n%100)<10)||((n%100)>=20)))?(1):2));',
array(
[
1 => 0,
2 => 1,
3 => 1,
@ -279,10 +279,10 @@ class PoHeaderTest extends UnitTestCase {
193 => 1,
194 => 1,
'default' => 2,
),),
array(
], ],
[
'nplurals=4; plural=(((n==1)||(n==11))?(0):(((n==2)||(n==12))?(1):(((n>2)&&(n<20))?(2):3)));',
array(
[
1 => 0,
2 => 1,
3 => 2,
@ -303,11 +303,11 @@ class PoHeaderTest extends UnitTestCase {
18 => 2,
19 => 2,
'default' => 3,
),
),
array(
],
],
[
'nplurals=4; plural=(((n%100)==1)?(0):(((n%100)==2)?(1):((((n%100)==3)||((n%100)==4))?(2):3)));',
array(
[
1 => 0,
2 => 1,
3 => 2,
@ -317,11 +317,11 @@ class PoHeaderTest extends UnitTestCase {
103 => 2,
104 => 2,
'default' => 3,
),
),
array(
],
],
[
'nplurals=5; plural=((n==1)?(0):((n==2)?(1):((n<7)?(2):((n<11)?(3):4))));',
array(
[
0 => 2,
1 => 0,
2 => 1,
@ -334,11 +334,11 @@ class PoHeaderTest extends UnitTestCase {
9 => 3,
10 => 3,
'default' => 4,
),
),
array(
],
],
[
'nplurals=6; plural=((n==1)?(0):((n==0)?(1):((n==2)?(2):((((n%100)>=3)&&((n%100)<=10))?(3):((((n%100)>=11)&&((n%100)<=99))?(4):5)))));',
array(
[
0 => 1,
1 => 0,
2 => 2,
@ -362,9 +362,9 @@ class PoHeaderTest extends UnitTestCase {
109 => 3,
110 => 3,
'default' => 4,
),
),
);
],
],
];
}
}

View file

@ -21,59 +21,59 @@ class GraphTest extends UnitTestCase {
// | | |
// | | |
// +---> 4 <-- 7 8 ---> 9
$graph = $this->normalizeGraph(array(
1 => array(2),
2 => array(3, 4),
3 => array(),
4 => array(3),
5 => array(6),
7 => array(4, 5),
8 => array(9),
9 => array(),
));
$graph = $this->normalizeGraph([
1 => [2],
2 => [3, 4],
3 => [],
4 => [3],
5 => [6],
7 => [4, 5],
8 => [9],
9 => [],
]);
$graph_object = new Graph($graph);
$graph = $graph_object->searchAndSort();
$expected_paths = array(
1 => array(2, 3, 4),
2 => array(3, 4),
3 => array(),
4 => array(3),
5 => array(6),
7 => array(4, 3, 5, 6),
8 => array(9),
9 => array(),
);
$expected_paths = [
1 => [2, 3, 4],
2 => [3, 4],
3 => [],
4 => [3],
5 => [6],
7 => [4, 3, 5, 6],
8 => [9],
9 => [],
];
$this->assertPaths($graph, $expected_paths);
$expected_reverse_paths = array(
1 => array(),
2 => array(1),
3 => array(2, 1, 4, 7),
4 => array(2, 1, 7),
5 => array(7),
7 => array(),
8 => array(),
9 => array(8),
);
$expected_reverse_paths = [
1 => [],
2 => [1],
3 => [2, 1, 4, 7],
4 => [2, 1, 7],
5 => [7],
7 => [],
8 => [],
9 => [8],
];
$this->assertReversePaths($graph, $expected_reverse_paths);
// Assert that DFS didn't created "missing" vertexes automatically.
$this->assertFalse(isset($graph[6]), 'Vertex 6 has not been created');
$expected_components = array(
array(1, 2, 3, 4, 5, 7),
array(8, 9),
);
$expected_components = [
[1, 2, 3, 4, 5, 7],
[8, 9],
];
$this->assertComponents($graph, $expected_components);
$expected_weights = array(
array(1, 2, 3),
array(2, 4, 3),
array(7, 4, 3),
array(7, 5),
array(8, 9),
);
$expected_weights = [
[1, 2, 3],
[2, 4, 3],
[7, 4, 3],
[7, 5],
[8, 9],
];
$this->assertWeights($graph, $expected_weights);
}
@ -87,10 +87,10 @@ class GraphTest extends UnitTestCase {
* The normalized version of a graph.
*/
protected function normalizeGraph($graph) {
$normalized_graph = array();
$normalized_graph = [];
foreach ($graph as $vertex => $edges) {
// Create vertex even if it hasn't any edges.
$normalized_graph[$vertex] = array();
$normalized_graph[$vertex] = [];
foreach ($edges as $edge) {
$normalized_graph[$vertex]['edges'][$edge] = TRUE;
}
@ -110,7 +110,7 @@ class GraphTest extends UnitTestCase {
foreach ($expected_paths as $vertex => $paths) {
// Build an array with keys = $paths and values = TRUE.
$expected = array_fill_keys($paths, TRUE);
$result = isset($graph[$vertex]['paths']) ? $graph[$vertex]['paths'] : array();
$result = isset($graph[$vertex]['paths']) ? $graph[$vertex]['paths'] : [];
$this->assertEquals($expected, $result, sprintf('Expected paths for vertex %s: %s, got %s', $vertex, $this->displayArray($expected, TRUE), $this->displayArray($result, TRUE)));
}
}
@ -128,7 +128,7 @@ class GraphTest extends UnitTestCase {
foreach ($expected_reverse_paths as $vertex => $paths) {
// Build an array with keys = $paths and values = TRUE.
$expected = array_fill_keys($paths, TRUE);
$result = isset($graph[$vertex]['reverse_paths']) ? $graph[$vertex]['reverse_paths'] : array();
$result = isset($graph[$vertex]['reverse_paths']) ? $graph[$vertex]['reverse_paths'] : [];
$this->assertEquals($expected, $result, sprintf('Expected reverse paths for vertex %s: %s, got %s', $vertex, $this->displayArray($expected, TRUE), $this->displayArray($result, TRUE)));
}
}
@ -144,14 +144,14 @@ class GraphTest extends UnitTestCase {
protected function assertComponents($graph, $expected_components) {
$unassigned_vertices = array_fill_keys(array_keys($graph), TRUE);
foreach ($expected_components as $component) {
$result_components = array();
$result_components = [];
foreach ($component as $vertex) {
$result_components[] = $graph[$vertex]['component'];
unset($unassigned_vertices[$vertex]);
}
$this->assertEquals(1, count(array_unique($result_components)), sprintf('Expected one unique component for vertices %s, got %s', $this->displayArray($component), $this->displayArray($result_components)));
}
$this->assertEquals(array(), $unassigned_vertices, sprintf('Vertices not assigned to a component: %s', $this->displayArray($unassigned_vertices, TRUE)));
$this->assertEquals([], $unassigned_vertices, sprintf('Vertices not assigned to a component: %s', $this->displayArray($unassigned_vertices, TRUE)));
}
/**

View file

@ -33,15 +33,15 @@ class FileStorageReadOnlyTest extends PhpStorageTestBase {
protected function setUp() {
parent::setUp();
$this->standardSettings = array(
$this->standardSettings = [
'directory' => $this->directory,
'bin' => 'test',
);
$this->readonlyStorage = array(
];
$this->readonlyStorage = [
'directory' => $this->directory,
// Let this read from the bin where the other instance is writing.
'bin' => 'test',
);
];
}
/**

View file

@ -24,10 +24,10 @@ class FileStorageTest extends PhpStorageTestBase {
protected function setUp() {
parent::setUp();
$this->standardSettings = array(
$this->standardSettings = [
'directory' => $this->directory,
'bin' => 'test',
);
];
}
/**

View file

@ -19,7 +19,7 @@ class MTimeProtectedFastFileStorageTest extends MTimeProtectedFileStorageBase {
* include the hacked file on the first try but the second test will change
* the directory mtime and so on the second try the file will not be included.
*/
protected $expected = array(TRUE, FALSE);
protected $expected = [TRUE, FALSE];
/**
* The PHP storage class to test.

View file

@ -2,6 +2,8 @@
namespace Drupal\Tests\Component\PhpStorage;
use Drupal\Component\Utility\Crypt;
/**
* Base test class for MTime protected storage.
*/
@ -36,11 +38,11 @@ abstract class MTimeProtectedFileStorageBase extends PhpStorageTestBase {
$this->secret = $this->randomMachineName();
$this->settings = array(
$this->settings = [
'directory' => $this->directory,
'bin' => 'test',
'secret' => $this->secret,
);
];
}
/**
@ -77,7 +79,7 @@ abstract class MTimeProtectedFileStorageBase extends PhpStorageTestBase {
$expected_directory = $expected_root_directory . '/' . $name;
}
$directory_mtime = filemtime($expected_directory);
$expected_filename = $expected_directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';
$expected_filename = $expected_directory . '/' . Crypt::hmacBase64($name, $this->secret . $directory_mtime) . '.php';
// Ensure the file exists and that it and the containing directory have
// minimal permissions. fileperms() can return high bits unrelated to
@ -88,7 +90,7 @@ abstract class MTimeProtectedFileStorageBase extends PhpStorageTestBase {
// Ensure the root directory for the bin has a .htaccess file denying web
// access.
$this->assertSame(file_get_contents($expected_root_directory . '/.htaccess'), call_user_func(array($this->storageClass, 'htaccessLines')));
$this->assertSame(file_get_contents($expected_root_directory . '/.htaccess'), call_user_func([$this->storageClass, 'htaccessLines']));
// Ensure that if the file is replaced with an untrusted one (due to another
// script's file upload vulnerability), it does not get loaded. Since mtime

View file

@ -18,7 +18,7 @@ class MTimeProtectedFileStorageTest extends MTimeProtectedFileStorageBase {
* The default implementation protects against even the filemtime change so
* both iterations will return FALSE.
*/
protected $expected = array(FALSE, FALSE);
protected $expected = [FALSE, FALSE];
/**
* The PHP storage class to test.

View file

@ -30,7 +30,7 @@ class ContextTest extends UnitTestCase {
// Mock a Context object.
$mock_context = $this->getMockBuilder('Drupal\Component\Plugin\Context\Context')
->disableOriginalConstructor()
->setMethods(array('getContextDefinition'))
->setMethods(['getContextDefinition'])
->getMock();
// If the context value exists, getContextValue() behaves like a normal
@ -49,7 +49,7 @@ class ContextTest extends UnitTestCase {
else {
// Create a mock definition.
$mock_definition = $this->getMockBuilder('Drupal\Component\Plugin\Context\ContextDefinitionInterface')
->setMethods(array('isRequired', 'getDataType'))
->setMethods(['isRequired', 'getDataType'])
->getMockForAbstractClass();
// Set expectation for isRequired().
@ -87,7 +87,7 @@ class ContextTest extends UnitTestCase {
*/
public function testDefaultValue() {
$mock_definition = $this->getMockBuilder('Drupal\Component\Plugin\Context\ContextDefinitionInterface')
->setMethods(array('getDefaultValue'))
->setMethods(['getDefaultValue'])
->getMockForAbstractClass();
$mock_definition->expects($this->once())

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\Component\Plugin;
use Drupal\Component\Plugin\Definition\PluginDefinitionInterface;
use Drupal\Component\Plugin\Exception\PluginException;
use Drupal\Component\Plugin\Factory\DefaultFactory;
use Drupal\plugin_test\Plugin\plugin_test\fruit\Cherry;
use Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface;
@ -47,11 +48,9 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a missing class definition.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
* @expectedExceptionMessage The plugin (cherry) did not specify an instance class.
*/
public function testGetPluginClassWithMissingClassWithArrayPluginDefinition() {
$this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.');
DefaultFactory::getPluginClass('cherry', []);
}
@ -59,12 +58,10 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a missing class definition.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
* @expectedExceptionMessage The plugin (cherry) did not specify an instance class.
*/
public function testGetPluginClassWithMissingClassWithObjectPluginDefinition() {
$plugin_definition = $this->getMock(PluginDefinitionInterface::class);
$this->setExpectedException(PluginException::class, 'The plugin (cherry) did not specify an instance class.');
DefaultFactory::getPluginClass('cherry', $plugin_definition);
}
@ -72,11 +69,9 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a not existing class definition.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
* @expectedExceptionMessage Plugin (kiwifruit) instance class "\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit" does not exist.
*/
public function testGetPluginClassWithNotExistingClassWithArrayPluginDefinition() {
$this->setExpectedException(PluginException::class, 'Plugin (kiwifruit) instance class "\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit" does not exist.');
DefaultFactory::getPluginClass('kiwifruit', ['class' => '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit']);
}
@ -84,8 +79,6 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a not existing class definition.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
*/
public function testGetPluginClassWithNotExistingClassWithObjectPluginDefinition() {
$plugin_class = '\Drupal\plugin_test\Plugin\plugin_test\fruit\Kiwifruit';
@ -93,6 +86,7 @@ class DefaultFactoryTest extends UnitTestCase {
$plugin_definition->expects($this->atLeastOnce())
->method('getClass')
->willReturn($plugin_class);
$this->setExpectedException(PluginException::class);
DefaultFactory::getPluginClass('kiwifruit', $plugin_definition);
}
@ -128,12 +122,10 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a required interface but no implementation.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
* @expectedExceptionMessage Plugin "cherry" (Drupal\plugin_test\Plugin\plugin_test\fruit\Kale) must implement interface Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface.
*/
public function testGetPluginClassWithInterfaceAndInvalidClassWithArrayPluginDefinition() {
$plugin_class = Kale::class;
$this->setExpectedException(PluginException::class, 'Plugin "cherry" (Drupal\plugin_test\Plugin\plugin_test\fruit\Kale) must implement interface Drupal\plugin_test\Plugin\plugin_test\fruit\FruitInterface.');
DefaultFactory::getPluginClass('cherry', ['class' => $plugin_class, 'provider' => 'core'], FruitInterface::class);
}
@ -141,8 +133,6 @@ class DefaultFactoryTest extends UnitTestCase {
* Tests getPluginClass() with a required interface but no implementation.
*
* @covers ::getPluginClass
*
* @expectedException \Drupal\Component\Plugin\Exception\PluginException
*/
public function testGetPluginClassWithInterfaceAndInvalidClassWithObjectPluginDefinition() {
$plugin_class = Kale::class;
@ -150,6 +140,7 @@ class DefaultFactoryTest extends UnitTestCase {
$plugin_definition->expects($this->atLeastOnce())
->method('getClass')
->willReturn($plugin_class);
$this->setExpectedException(PluginException::class);
DefaultFactory::getPluginClass('cherry', $plugin_definition, FruitInterface::class);
}

View file

@ -21,11 +21,11 @@ class DiscoveryCachedTraitTest extends UnitTestCase {
* - Plugin name to query for.
*/
public function providerGetDefinition() {
return array(
return [
['definition', [], ['plugin_name' => 'definition'], 'plugin_name'],
['definition', ['plugin_name' => 'definition'], [], 'plugin_name'],
[NULL, ['plugin_name' => 'definition'], [], 'bad_plugin_name'],
);
];
}
/**

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Component\Plugin\Discovery;
use Drupal\Component\Plugin\Exception\PluginNotFoundException;
use Drupal\Tests\UnitTestCase;
/**
@ -19,10 +20,10 @@ class DiscoveryTraitTest extends UnitTestCase {
* - Plugin ID to get, passed to doGetDefinition().
*/
public function providerDoGetDefinition() {
return array(
return [
['definition', ['plugin_name' => 'definition'], 'plugin_name'],
[NULL, ['plugin_name' => 'definition'], 'bad_plugin_name'],
);
];
}
/**
@ -51,14 +52,13 @@ class DiscoveryTraitTest extends UnitTestCase {
* - Plugin ID to get, passed to doGetDefinition().
*/
public function providerDoGetDefinitionException() {
return array(
return [
[FALSE, ['plugin_name' => 'definition'], 'bad_plugin_name'],
);
];
}
/**
* @covers ::doGetDefinition
* @expectedException \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @dataProvider providerDoGetDefinitionException
* @uses \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
@ -69,10 +69,8 @@ class DiscoveryTraitTest extends UnitTestCase {
$method_ref = new \ReflectionMethod($trait, 'doGetDefinition');
$method_ref->setAccessible(TRUE);
// Call doGetDefinition, with $exception_on_invalid always TRUE.
$this->assertSame(
$expected,
$method_ref->invoke($trait, $definitions, $plugin_id, TRUE)
);
$this->setExpectedException(PluginNotFoundException::class);
$method_ref->invoke($trait, $definitions, $plugin_id, TRUE);
}
/**
@ -96,7 +94,6 @@ class DiscoveryTraitTest extends UnitTestCase {
/**
* @covers ::getDefinition
* @expectedException \Drupal\Component\Plugin\Exception\PluginNotFoundException
* @dataProvider providerDoGetDefinitionException
* @uses \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
@ -109,10 +106,8 @@ class DiscoveryTraitTest extends UnitTestCase {
->method('getDefinitions')
->willReturn($definitions);
// Call getDefinition(), with $exception_on_invalid always TRUE.
$this->assertSame(
$expected,
$trait->getDefinition($plugin_id, TRUE)
);
$this->setExpectedException(PluginNotFoundException::class);
$trait->getDefinition($plugin_id, TRUE);
}
/**
@ -123,10 +118,10 @@ class DiscoveryTraitTest extends UnitTestCase {
* - Plugin ID to look for.
*/
public function providerHasDefinition() {
return array(
return [
[TRUE, 'valid'],
[FALSE, 'not_valid'],
);
];
}
/**
@ -135,16 +130,16 @@ class DiscoveryTraitTest extends UnitTestCase {
*/
public function testHasDefinition($expected, $plugin_id) {
$trait = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\DiscoveryTrait')
->setMethods(array('getDefinition'))
->setMethods(['getDefinition'])
->getMockForTrait();
// Set up our mocked getDefinition() to return TRUE for 'valid' and FALSE
// for 'not_valid'.
$trait->expects($this->once())
->method('getDefinition')
->will($this->returnValueMap(array(
->will($this->returnValueMap([
['valid', FALSE, TRUE],
['not_valid', FALSE, FALSE],
)));
]));
// Call hasDefinition().
$this->assertSame(
$expected,

View file

@ -23,7 +23,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
*/
public function getRegisterDefinitionsCallback() {
$mock_callable = $this->getMockBuilder('\stdClass')
->setMethods(array('registerDefinitionsCallback'))
->setMethods(['registerDefinitionsCallback'])
->getMock();
// Set expectations for the callback method.
$mock_callable->expects($this->once())
@ -62,7 +62,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Mock our StaticDiscoveryDecorator.
$mock_decorator = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator')
->disableOriginalConstructor()
->setMethods(array('registeredDefintionCallback'))
->setMethods(['registeredDefintionCallback'])
->getMock();
// Set up the ::$registerDefinitions property.
@ -72,7 +72,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Set the callback object on the mocked decorator.
$ref_register_definitions->setValue(
$mock_decorator,
array($this->getRegisterDefinitionsCallback(), 'registerDefinitionsCallback')
[$this->getRegisterDefinitionsCallback(), 'registerDefinitionsCallback']
);
}
else {
@ -83,11 +83,11 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Set up ::$definitions to an empty array.
$ref_definitions = new \ReflectionProperty($mock_decorator, 'definitions');
$ref_definitions->setAccessible(TRUE);
$ref_definitions->setValue($mock_decorator, array());
$ref_definitions->setValue($mock_decorator, []);
// Mock a decorated object.
$mock_decorated = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\DiscoveryInterface')
->setMethods(array('getDefinitions'))
->setMethods(['getDefinitions'])
->getMockForAbstractClass();
// Return our definitions from getDefinitions().
$mock_decorated->expects($this->once())
@ -132,7 +132,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Mock our StaticDiscoveryDecorator.
$mock_decorator = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\StaticDiscoveryDecorator')
->disableOriginalConstructor()
->setMethods(array('registeredDefintionCallback'))
->setMethods(['registeredDefintionCallback'])
->getMock();
// Set up the ::$registerDefinitions property.
@ -142,7 +142,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Set the callback object on the mocked decorator.
$ref_register_definitions->setValue(
$mock_decorator,
array($this->getRegisterDefinitionsCallback(), 'registerDefinitionsCallback')
[$this->getRegisterDefinitionsCallback(), 'registerDefinitionsCallback']
);
}
else {
@ -153,11 +153,11 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Set up ::$definitions to an empty array.
$ref_definitions = new \ReflectionProperty($mock_decorator, 'definitions');
$ref_definitions->setAccessible(TRUE);
$ref_definitions->setValue($mock_decorator, array());
$ref_definitions->setValue($mock_decorator, []);
// Mock a decorated object.
$mock_decorated = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\DiscoveryInterface')
->setMethods(array('getDefinitions'))
->setMethods(['getDefinitions'])
->getMockForAbstractClass();
// Our mocked method will return any arguments sent to it.
$mock_decorated->expects($this->once())
@ -199,7 +199,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
public function testCall($method, $args) {
// Mock a decorated object.
$mock_decorated = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\DiscoveryInterface')
->setMethods(array($method))
->setMethods([$method])
->getMockForAbstractClass();
// Our mocked method will return any arguments sent to it.
$mock_decorated->expects($this->once())
@ -222,7 +222,7 @@ class StaticDiscoveryDecoratorTest extends UnitTestCase {
// Exercise __call.
$this->assertArrayEquals(
$args,
\call_user_func_array(array($mock_decorated, $method), $args)
\call_user_func_array([$mock_decorated, $method], $args)
);
}

View file

@ -88,7 +88,7 @@ class ReflectionFactoryTest extends UnitTestCase {
public function testCreateInstance($expected, $reflector_name, $plugin_id, $plugin_definition, $configuration) {
// Create a mock DiscoveryInterface which can return our plugin definition.
$mock_discovery = $this->getMockBuilder('Drupal\Component\Plugin\Discovery\DiscoveryInterface')
->setMethods(array('getDefinition', 'getDefinitions', 'hasDefinition'))
->setMethods(['getDefinition', 'getDefinitions', 'hasDefinition'])
->getMock();
$mock_discovery->expects($this->never())->method('getDefinitions');
$mock_discovery->expects($this->never())->method('hasDefinition');

View file

@ -15,11 +15,11 @@ class PluginBaseTest extends UnitTestCase {
* @covers ::getPluginId
*/
public function testGetPluginId($plugin_id, $expected) {
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', array(
array(),
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', [
[],
$plugin_id,
array(),
));
[],
]);
$this->assertEquals($expected, $plugin_base->getPluginId());
}
@ -30,10 +30,10 @@ class PluginBaseTest extends UnitTestCase {
* @return array
*/
public function providerTestGetPluginId() {
return array(
array('base_id', 'base_id'),
array('base_id:derivative', 'base_id:derivative'),
);
return [
['base_id', 'base_id'],
['base_id:derivative', 'base_id:derivative'],
];
}
/**
@ -42,11 +42,11 @@ class PluginBaseTest extends UnitTestCase {
*/
public function testGetBaseId($plugin_id, $expected) {
/** @var \Drupal\Component\Plugin\PluginBase|\PHPUnit_Framework_MockObject_MockObject $plugin_base */
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', array(
array(),
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', [
[],
$plugin_id,
array(),
));
[],
]);
$this->assertEquals($expected, $plugin_base->getBaseId());
}
@ -57,10 +57,10 @@ class PluginBaseTest extends UnitTestCase {
* @return array
*/
public function providerTestGetBaseId() {
return array(
array('base_id', 'base_id'),
array('base_id:derivative', 'base_id'),
);
return [
['base_id', 'base_id'],
['base_id:derivative', 'base_id'],
];
}
@ -70,11 +70,11 @@ class PluginBaseTest extends UnitTestCase {
*/
public function testGetDerivativeId($plugin_id = NULL, $expected = NULL) {
/** @var \Drupal\Component\Plugin\PluginBase|\PHPUnit_Framework_MockObject_MockObject $plugin_base */
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', array(
array(),
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', [
[],
$plugin_id,
array(),
));
[],
]);
$this->assertEquals($expected, $plugin_base->getDerivativeId());
}
@ -85,23 +85,23 @@ class PluginBaseTest extends UnitTestCase {
* @return array
*/
public function providerTestGetDerivativeId() {
return array(
array('base_id', NULL),
array('base_id:derivative', 'derivative'),
);
return [
['base_id', NULL],
['base_id:derivative', 'derivative'],
];
}
/**
* @covers ::getPluginDefinition
*/
public function testGetPluginDefinition() {
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', array(
array(),
$plugin_base = $this->getMockForAbstractClass('Drupal\Component\Plugin\PluginBase', [
[],
'plugin_id',
array('value', array('key' => 'value')),
));
['value', ['key' => 'value']],
]);
$this->assertEquals(array('value', array('key' => 'value')), $plugin_base->getPluginDefinition());
$this->assertEquals(['value', ['key' => 'value']], $plugin_base->getPluginDefinition());
}
}

View file

@ -21,10 +21,10 @@ class PluginManagerBaseTest extends UnitTestCase {
if ('invalid' == $plugin_id) {
throw new PluginNotFoundException($plugin_id);
}
return array(
return [
'plugin_id' => $plugin_id,
'configuration' => $configuration,
);
];
}
/**
@ -32,11 +32,11 @@ class PluginManagerBaseTest extends UnitTestCase {
*/
public function getMockFactoryInterface($expects_count) {
$mock_factory = $this->getMockBuilder('Drupal\Component\Plugin\Factory\FactoryInterface')
->setMethods(array('createInstance'))
->setMethods(['createInstance'])
->getMockForAbstractClass();
$mock_factory->expects($this->exactly($expects_count))
->method('createInstance')
->willReturnCallback(array($this, 'createInstanceCallback'));
->willReturnCallback([$this, 'createInstanceCallback']);
return $mock_factory;
}
@ -55,7 +55,7 @@ class PluginManagerBaseTest extends UnitTestCase {
$factory_ref->setValue($manager, $this->getMockFactoryInterface(1));
// Finally the test.
$configuration_array = array('config' => 'something');
$configuration_array = ['config' => 'something'];
$result = $manager->createInstance('valid', $configuration_array);
$this->assertEquals('valid', $result['plugin_id']);
$this->assertArrayEquals($configuration_array, $result['configuration']);
@ -75,7 +75,7 @@ class PluginManagerBaseTest extends UnitTestCase {
$factory_ref->setAccessible(TRUE);
// Set up the configuration array.
$configuration_array = array('config' => 'something');
$configuration_array = ['config' => 'something'];
// Test with fallback interface and valid plugin_id.
$factory_ref->setValue($manager, $this->getMockFactoryInterface(1));

View file

@ -20,7 +20,7 @@ class StubFallbackPluginManager extends PluginManagerBase implements FallbackPlu
/**
* {@inheritdoc}
*/
public function getFallbackPluginId($plugin_id, array $configuration = array()) {
public function getFallbackPluginId($plugin_id, array $configuration = []) {
// Minimally implement getFallbackPluginId so that we can test it.
return $plugin_id . '_fallback';
}

View file

@ -381,7 +381,7 @@ class TestServiceMethodWithParameter {
class TestServiceComplexMethod {
public function complexMethod($parameter, callable $function, TestServiceNoMethod $test_service = NULL, array &$elements = array()) {
public function complexMethod($parameter, callable $function, TestServiceNoMethod $test_service = NULL, array &$elements = []) {
}

View file

@ -31,23 +31,23 @@ class HtmlEscapedTextTest extends UnitTestCase {
*
* @see testToString()
*/
function providerToString() {
public function providerToString() {
// Checks that invalid multi-byte sequences are escaped.
$tests[] = array("Foo\xC0barbaz", 'Foo<6F>barbaz', 'Escapes invalid sequence "Foo\xC0barbaz"');
$tests[] = array("\xc2\"", '<27>&quot;', 'Escapes invalid sequence "\xc2\""');
$tests[] = array("Fooÿñ", "Fooÿñ", 'Does not escape valid sequence "Fooÿñ"');
$tests[] = ["Foo\xC0barbaz", 'Foo<6F>barbaz', 'Escapes invalid sequence "Foo\xC0barbaz"'];
$tests[] = ["\xc2\"", '<27>&quot;', 'Escapes invalid sequence "\xc2\""'];
$tests[] = ["Fooÿñ", "Fooÿñ", 'Does not escape valid sequence "Fooÿñ"'];
// Checks that special characters are escaped.
$script_tag = $this->prophesize(MarkupInterface::class);
$script_tag->__toString()->willReturn('<script>');
$script_tag = $script_tag->reveal();
$tests[] = array($script_tag, '&lt;script&gt;', 'Escapes &lt;script&gt; even inside an object that implements MarkupInterface.');
$tests[] = array("<script>", '&lt;script&gt;', 'Escapes &lt;script&gt;');
$tests[] = array('<>&"\'', '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters.');
$tests[] = [$script_tag, '&lt;script&gt;', 'Escapes &lt;script&gt; even inside an object that implements MarkupInterface.'];
$tests[] = ["<script>", '&lt;script&gt;', 'Escapes &lt;script&gt;'];
$tests[] = ['<>&"\'', '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters.'];
$specialchars = $this->prophesize(MarkupInterface::class);
$specialchars->__toString()->willReturn('<>&"\'');
$specialchars = $specialchars->reveal();
$tests[] = array($specialchars, '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters even inside an object that implements MarkupInterface.');
$tests[] = [$specialchars, '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters even inside an object that implements MarkupInterface.'];
return $tests;
}

View file

@ -48,9 +48,9 @@ class JsonTest extends UnitTestCase {
// Characters that must be escaped.
// We check for unescaped " separately.
$this->htmlUnsafe = array('<', '>', '\'', '&');
$this->htmlUnsafe = ['<', '>', '\'', '&'];
// The following are the encoded forms of: < > ' & "
$this->htmlUnsafeEscaped = array('\u003C', '\u003E', '\u0027', '\u0026', '\u0022');
$this->htmlUnsafeEscaped = ['\u003C', '\u003E', '\u0027', '\u0026', '\u0022'];
}
/**
@ -100,7 +100,7 @@ class JsonTest extends UnitTestCase {
public function testStructuredReversibility() {
// Verify reversibility for structured data. Also verify that necessary
// characters are escaped.
$source = array(TRUE, FALSE, 0, 1, '0', '1', $this->string, array('key1' => $this->string, 'key2' => array('nested' => TRUE)));
$source = [TRUE, FALSE, 0, 1, '0', '1', $this->string, ['key1' => $this->string, 'key2' => ['nested' => TRUE]]];
$json = Json::encode($source);
foreach ($this->htmlUnsafe as $char) {
$this->assertTrue(strpos($json, $char) === FALSE, sprintf('A JSON encoded string does not contain %s.', $char));

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Component\Serialization;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
use Drupal\Component\Serialization\YamlPecl;
/**
@ -74,9 +75,9 @@ foo:
* Tests that invalid YAML throws an exception.
*
* @covers ::errorHandler
* @expectedException \Drupal\Component\Serialization\Exception\InvalidDataTypeException
*/
public function testError() {
$this->setExpectedException(InvalidDataTypeException::class);
YamlPecl::decode('foo: [ads');
}

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Component\Serialization;
use Drupal\Component\Serialization\Exception\InvalidDataTypeException;
use Drupal\Component\Serialization\YamlSymfony;
/**
@ -56,9 +57,9 @@ class YamlSymfonyTest extends YamlTestBase {
* Tests that invalid YAML throws an exception.
*
* @covers ::decode
* @expectedException \Drupal\Component\Serialization\Exception\InvalidDataTypeException
*/
public function testError() {
$this->setExpectedException(InvalidDataTypeException::class);
YamlSymfony::decode('foo: [ads');
}

View file

@ -40,32 +40,32 @@ class PhpTransliterationTest extends UnitTestCase {
* self::testRemoveDiacritics().
*/
public function providerTestPhpTransliterationRemoveDiacritics() {
return array(
return [
// Test all characters in the Unicode range 0x00bf to 0x017f.
array('ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ', 'AAAAAAÆCEEEEIIII'),
array('ÐÑÒÓÔÕÖרÙÚÛÜÝÞß', 'ÐNOOOOO×OUUUUYÞß'),
array('àáâãäåæçèéêëìíîï', 'aaaaaaæceeeeiiii'),
array('ðñòóôõö÷øùúûüýþÿ', 'ðnooooo÷ouuuuyþy'),
array('ĀāĂ㥹ĆćĈĉĊċČčĎď', 'AaAaAaCcCcCcCcDd'),
array('ĐđĒēĔĕĖėĘęĚěĜĝĞğ', 'DdEeEeEeEeEeGgGg'),
array('ĠġĢģĤĥĦħĨĩĪīĬĭĮį', 'GgGgHhHhIiIiIiIi'),
array('İıIJijĴĵĶķĸĹĺĻļĽľĿ', 'IiIJijJjKkĸLlLlLlL'),
array('ŀŁłŃńŅņŇňʼnŊŋŌōŎŏ', 'lLlNnNnNnʼnŊŋOoOo'),
array('ŐőŒœŔŕŖŗŘřŚśŜŝŞş', 'OoŒœRrRrRrSsSsSs'),
array('ŠšŢţŤťŦŧŨũŪūŬŭŮů', 'SsTtTtTtUuUuUuUu'),
array('ŰűŲųŴŵŶŷŸŹźŻżŽž', 'UuUuWwYyYZzZzZz'),
['ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏ', 'AAAAAAÆCEEEEIIII'],
['ÐÑÒÓÔÕÖרÙÚÛÜÝÞß', 'ÐNOOOOO×OUUUUYÞß'],
['àáâãäåæçèéêëìíîï', 'aaaaaaæceeeeiiii'],
['ðñòóôõö÷øùúûüýþÿ', 'ðnooooo÷ouuuuyþy'],
['ĀāĂ㥹ĆćĈĉĊċČčĎď', 'AaAaAaCcCcCcCcDd'],
['ĐđĒēĔĕĖėĘęĚěĜĝĞğ', 'DdEeEeEeEeEeGgGg'],
['ĠġĢģĤĥĦħĨĩĪīĬĭĮį', 'GgGgHhHhIiIiIiIi'],
['İıIJijĴĵĶķĸĹĺĻļĽľĿ', 'IiIJijJjKkĸLlLlLlL'],
['ŀŁłŃńŅņŇňʼnŊŋŌōŎŏ', 'lLlNnNnNnʼnŊŋOoOo'],
['ŐőŒœŔŕŖŗŘřŚśŜŝŞş', 'OoŒœRrRrRrSsSsSs'],
['ŠšŢţŤťŦŧŨũŪūŬŭŮů', 'SsTtTtTtUuUuUuUu'],
['ŰűŲųŴŵŶŷŸŹźŻżŽž', 'UuUuWwYyYZzZzZz'],
// Test all characters in the Unicode range 0x01CD to 0x024F.
array('ǍǎǏ', 'AaI'),
array('ǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟ', 'iOoUuUuUuUuUuǝAa'),
array('ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ', 'AaǢǣGgGgKkOoOoǮǯ'),
array('ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ', 'jDZDzdzGgǶǷNnAaǼǽOo'),
array('ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏ', 'AaAaEeEeIiIiOoOo'),
array('ȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟ', 'RrRrUuUuSsTtȜȝHh'),
array('ȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯ', 'ȠȡȢȣZzAaEeOoOoOo'),
array('ȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿ', 'OoYylntjȸȹACcLTs'),
array('ɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ', 'zɁɂBUɅEeJjQqRrYy'),
);
['ǍǎǏ', 'AaI'],
['ǐǑǒǓǔǕǖǗǘǙǚǛǜǝǞǟ', 'iOoUuUuUuUuUuǝAa'],
['ǠǡǢǣǤǥǦǧǨǩǪǫǬǭǮǯ', 'AaǢǣGgGgKkOoOoǮǯ'],
['ǰDZDzdzǴǵǶǷǸǹǺǻǼǽǾǿ', 'jDZDzdzGgǶǷNnAaǼǽOo'],
['ȀȁȂȃȄȅȆȇȈȉȊȋȌȍȎȏ', 'AaAaEeEeIiIiOoOo'],
['ȐȑȒȓȔȕȖȗȘșȚțȜȝȞȟ', 'RrRrUuUuSsTtȜȝHh'],
['ȠȡȢȣȤȥȦȧȨȩȪȫȬȭȮȯ', 'ȠȡȢȣZzAaEeOoOoOo'],
['ȰȱȲȳȴȵȶȷȸȹȺȻȼȽȾȿ', 'OoYylntjȸȹACcLTs'],
['ɀɁɂɃɄɅɆɇɈɉɊɋɌɍɎɏ', 'zɁɂBUɅEeJjQqRrYy'],
];
}
/**
@ -117,36 +117,36 @@ class PhpTransliterationTest extends UnitTestCase {
// They are not in our tables, but should at least give us '?' (unknown).
$five_byte = html_entity_decode('&#x10330;&#x10338;', ENT_NOQUOTES, 'UTF-8');
return array(
return [
// Each test case is (language code, input, output).
// Test ASCII in English.
array('en', $random, $random),
['en', $random, $random],
// Test ASCII in some other language with no overrides.
array('fr', $random, $random),
['fr', $random, $random],
// Test 3 and 4-byte characters in a language without overrides.
// Note: if the data tables change, these will need to change too! They
// are set up to test that data table loading works, so values come
// directly from the data files.
array('fr', $three_byte, 'c'),
array('fr', $four_byte, 'wii'),
['fr', $three_byte, 'c'],
['fr', $four_byte, 'wii'],
// Test 5-byte characters.
array('en', $five_byte, '??'),
['en', $five_byte, '??'],
// Test a language with no overrides.
array('en', $two_byte, 'A O U A O aouaohello'),
['en', $two_byte, 'A O U A O aouaohello'],
// Test language overrides provided by core.
array('de', $two_byte, 'Ae Oe Ue A O aeoeueaohello'),
array('de', $random, $random),
array('dk', $two_byte, 'A O U Aa Oe aouaaoehello'),
array('dk', $random, $random),
array('kg', $three_byte, 'ts'),
['de', $two_byte, 'Ae Oe Ue A O aeoeueaohello'],
['de', $random, $random],
['dk', $two_byte, 'A O U Aa Oe aouaaoehello'],
['dk', $random, $random],
['kg', $three_byte, 'ts'],
// Test strings in some other languages.
// Turkish, provided by drupal.org user Kartagis.
array('tr', 'Abayı serdiler bize. Söyleyeceğim yüzlerine. Sanırım hepimiz aynı şeyi düşünüyoruz.', 'Abayi serdiler bize. Soyleyecegim yuzlerine. Sanirim hepimiz ayni seyi dusunuyoruz.'),
['tr', 'Abayı serdiler bize. Söyleyeceğim yüzlerine. Sanırım hepimiz aynı şeyi düşünüyoruz.', 'Abayi serdiler bize. Soyleyecegim yuzlerine. Sanirim hepimiz ayni seyi dusunuyoruz.'],
// Illegal/unknown unicode.
array('en', chr(0xF8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80), '?'),
['en', chr(0xF8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80), '?'],
// Max length.
array('de', $two_byte, 'Ae Oe', '?', 5),
);
['de', $two_byte, 'Ae Oe', '?', 5],
];
}
/**

View file

@ -121,9 +121,6 @@ class ArgumentsResolverTest extends UnitTestCase {
* Tests getArgument() with a wildcard parameter with no typehint.
*
* Without the typehint, the wildcard object will not be passed to the callable.
*
* @expectedException \RuntimeException
* @expectedExceptionMessage requires a value for the "$route" argument.
*/
public function testGetWildcardArgumentNoTypehint() {
$a = $this->getMock('\Drupal\Tests\Component\Utility\TestInterface1');
@ -131,8 +128,8 @@ class ArgumentsResolverTest extends UnitTestCase {
$resolver = new ArgumentsResolver([], [], $wildcards);
$callable = function($route) {};
$arguments = $resolver->getArguments($callable);
$this->assertNull($arguments);
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$route" argument.');
$resolver->getArguments($callable);
}
/**
@ -152,9 +149,6 @@ class ArgumentsResolverTest extends UnitTestCase {
/**
* Tests handleUnresolvedArgument() for a scalar argument.
*
* @expectedException \RuntimeException
* @expectedExceptionMessage requires a value for the "$foo" argument.
*/
public function testHandleNotUpcastedArgument() {
$objects = ['foo' => 'bar'];
@ -162,22 +156,19 @@ class ArgumentsResolverTest extends UnitTestCase {
$resolver = new ArgumentsResolver($scalars, $objects, []);
$callable = function(\stdClass $foo) {};
$arguments = $resolver->getArguments($callable);
$this->assertNull($arguments);
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.');
$resolver->getArguments($callable);
}
/**
* Tests handleUnresolvedArgument() for missing arguments.
*
* @expectedException \RuntimeException
* @expectedExceptionMessage requires a value for the "$foo" argument.
*
* @dataProvider providerTestHandleUnresolvedArgument
*/
public function testHandleUnresolvedArgument($callable) {
$resolver = new ArgumentsResolver([], [], []);
$arguments = $resolver->getArguments($callable);
$this->assertNull($arguments);
$this->setExpectedException(\RuntimeException::class, 'requires a value for the "$foo" argument.');
$resolver->getArguments($callable);
}
/**

View file

@ -40,21 +40,21 @@ class BytesTest extends UnitTestCase {
* value.
*/
public function providerTestToInt() {
return array(
array('1', 1),
array('1 byte', 1),
array('1 KB' , Bytes::KILOBYTE),
array('1 MB' , pow(Bytes::KILOBYTE, 2)),
array('1 GB' , pow(Bytes::KILOBYTE, 3)),
array('1 TB' , pow(Bytes::KILOBYTE, 4)),
array('1 PB' , pow(Bytes::KILOBYTE, 5)),
array('1 EB' , pow(Bytes::KILOBYTE, 6)),
array('1 ZB' , pow(Bytes::KILOBYTE, 7)),
array('1 YB' , pow(Bytes::KILOBYTE, 8)),
array('23476892 bytes', 23476892),
array('76MRandomStringThatShouldBeIgnoredByParseSize.', 79691776), // 76 MB
array('76.24 Giggabyte', 81862076662), // 76.24 GB (with typo)
);
return [
['1', 1],
['1 byte', 1],
['1 KB' , Bytes::KILOBYTE],
['1 MB' , pow(Bytes::KILOBYTE, 2)],
['1 GB' , pow(Bytes::KILOBYTE, 3)],
['1 TB' , pow(Bytes::KILOBYTE, 4)],
['1 PB' , pow(Bytes::KILOBYTE, 5)],
['1 EB' , pow(Bytes::KILOBYTE, 6)],
['1 ZB' , pow(Bytes::KILOBYTE, 7)],
['1 YB' , pow(Bytes::KILOBYTE, 8)],
['23476892 bytes', 23476892],
['76MRandomStringThatShouldBeIgnoredByParseSize.', 79691776], // 76 MB
['76.24 Giggabyte', 81862076662], // 76.24 GB (with typo)
];
}
}

View file

@ -43,35 +43,35 @@ class ColorTest extends UnitTestCase {
* - (optional) Boolean indicating invalid status. Defaults to FALSE.
*/
public function providerTestHexToRgb() {
$invalid = array();
$invalid = [];
// Any invalid arguments should throw an exception.
foreach (array('', '-1', '1', '12', '12345', '1234567', '123456789', '123456789a', 'foo') as $value) {
$invalid[] = array($value, '', TRUE);
foreach (['', '-1', '1', '12', '12345', '1234567', '123456789', '123456789a', 'foo'] as $value) {
$invalid[] = [$value, '', TRUE];
}
// Duplicate all invalid value tests with additional '#' prefix.
// The '#' prefix inherently turns the data type into a string.
foreach ($invalid as $value) {
$invalid[] = array('#' . $value[0], '', TRUE);
$invalid[] = ['#' . $value[0], '', TRUE];
}
// Add invalid data types (hex value must be a string).
foreach (array(
foreach ([
1, 12, 1234, 12345, 123456, 1234567, 12345678, 123456789, 123456789,
-1, PHP_INT_MAX, PHP_INT_MAX + 1, -PHP_INT_MAX, 0x0, 0x010
) as $value) {
$invalid[] = array($value, '', TRUE);
] as $value) {
$invalid[] = [$value, '', TRUE];
}
// And some valid values.
$valid = array(
$valid = [
// Shorthands without alpha.
array('hex' => '#000', 'rgb' => array('red' => 0, 'green' => 0, 'blue' => 0)),
array('hex' => '#fff', 'rgb' => array('red' => 255, 'green' => 255, 'blue' => 255)),
array('hex' => '#abc', 'rgb' => array('red' => 170, 'green' => 187, 'blue' => 204)),
array('hex' => 'cba', 'rgb' => array('red' => 204, 'green' => 187, 'blue' => 170)),
['hex' => '#000', 'rgb' => ['red' => 0, 'green' => 0, 'blue' => 0]],
['hex' => '#fff', 'rgb' => ['red' => 255, 'green' => 255, 'blue' => 255]],
['hex' => '#abc', 'rgb' => ['red' => 170, 'green' => 187, 'blue' => 204]],
['hex' => 'cba', 'rgb' => ['red' => 204, 'green' => 187, 'blue' => 170]],
// Full without alpha.
array('hex' => '#000000', 'rgb' => array('red' => 0, 'green' => 0, 'blue' => 0)),
array('hex' => '#ffffff', 'rgb' => array('red' => 255, 'green' => 255, 'blue' => 255)),
array('hex' => '#010203', 'rgb' => array('red' => 1, 'green' => 2, 'blue' => 3)),
);
['hex' => '#000000', 'rgb' => ['red' => 0, 'green' => 0, 'blue' => 0]],
['hex' => '#ffffff', 'rgb' => ['red' => 255, 'green' => 255, 'blue' => 255]],
['hex' => '#010203', 'rgb' => ['red' => 1, 'green' => 2, 'blue' => 3]],
];
return array_merge($invalid, $valid);
}
@ -101,19 +101,19 @@ class ColorTest extends UnitTestCase {
*/
public function providerTestRbgToHex() {
// Input using named RGB array (e.g., as returned by Color::hexToRgb()).
$tests = array(
array(array('red' => 0, 'green' => 0, 'blue' => 0), '#000000'),
array(array('red' => 255, 'green' => 255, 'blue' => 255), '#ffffff'),
array(array('red' => 119, 'green' => 119, 'blue' => 119), '#777777'),
array(array('red' => 1, 'green' => 2, 'blue' => 3), '#010203'),
);
$tests = [
[['red' => 0, 'green' => 0, 'blue' => 0], '#000000'],
[['red' => 255, 'green' => 255, 'blue' => 255], '#ffffff'],
[['red' => 119, 'green' => 119, 'blue' => 119], '#777777'],
[['red' => 1, 'green' => 2, 'blue' => 3], '#010203'],
];
// Input using indexed RGB array (e.g.: array(10, 10, 10)).
foreach ($tests as $test) {
$tests[] = array(array_values($test[0]), $test[1]);
$tests[] = [array_values($test[0]), $test[1]];
}
// Input using CSS RGB string notation (e.g.: 10, 10, 10).
foreach ($tests as $test) {
$tests[] = array(implode(', ', $test[0]), $test[1]);
$tests[] = [implode(', ', $test[0]), $test[1]];
}
return $tests;
}

View file

@ -0,0 +1,71 @@
<?php
namespace Drupal\Tests\Component\Utility;
use Drupal\Tests\UnitTestCase;
use Drupal\Component\Utility\Crypt;
/**
* Tests random byte generation fallback exception situations.
*
* @group Utility
*
* @runTestsInSeparateProcesses
*
* @coversDefaultClass \Drupal\Component\Utility\Crypt
*/
class CryptRandomFallbackTest extends UnitTestCase {
static protected $functionCalled = 0;
/**
* Allows the test to confirm that the namespaced random_bytes() was called.
*/
public static function functionCalled() {
static::$functionCalled++;
}
/**
* Tests random byte generation using the fallback generator.
*
* If the call to random_bytes() throws an exception, Crypt::random_bytes()
* should still return a useful string of random bytes.
*
* @covers ::randomBytes
*
* @see \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes()
*/
public function testRandomBytesFallback() {
// This loop is a copy of
// \Drupal\Tests\Component\Utility\CryptTest::testRandomBytes().
for ($i = 0; $i < 10; $i++) {
$count = rand(10, 10000);
// Check that different values are being generated.
$this->assertNotEquals(Crypt::randomBytes($count), Crypt::randomBytes($count));
// Check the length.
$this->assertEquals($count, strlen(Crypt::randomBytes($count)));
}
$this->assertEquals(30, static::$functionCalled, 'The namespaced function was called the expected number of times.');
}
}
namespace Drupal\Component\Utility;
use \Drupal\Tests\Component\Utility\CryptRandomFallbackTest;
/**
* Defines a function in same namespace as Drupal\Component\Utility\Crypt.
*
* Forces throwing an exception in this test environment because the function
* in the namespace is used in preference to the global function.
*
* @param int $count
* Matches the global function definition.
*
* @throws \Exception
*/
function random_bytes($count) {
CryptRandomFallbackTest::functionCalled();
throw new \Exception($count);
}

View file

@ -18,6 +18,8 @@ class CryptTest extends UnitTestCase {
* Tests random byte generation.
*
* @covers ::randomBytes
*
* @see \Drupal\Tests\Component\Utility\CryptRandomFallbackTest::testRandomBytesFallback
*/
public function testRandomBytes() {
for ($i = 1; $i < 10; $i++) {
@ -67,7 +69,6 @@ class CryptTest extends UnitTestCase {
* Tests the hmacBase64 method with invalid parameters.
*
* @dataProvider providerTestHmacBase64Invalid
* @expectedException InvalidArgumentException
* @covers ::hmacBase64
*
* @param string $data
@ -76,6 +77,7 @@ class CryptTest extends UnitTestCase {
* Key to use in hashing process.
*/
public function testHmacBase64Invalid($data, $key) {
$this->setExpectedException(\InvalidArgumentException::class);
Crypt::hmacBase64($data, $key);
}
@ -85,16 +87,16 @@ class CryptTest extends UnitTestCase {
* @return array Test data.
*/
public function providerTestHashBase64() {
return array(
array(
return [
[
'data' => 'The SHA (Secure Hash Algorithm) is one of a number of cryptographic hash functions. A cryptographic hash is like a signature for a text or a data file. SHA-256 algorithm generates an almost-unique, fixed size 256-bit (32-byte) hash. Hash is a one way function it cannot be decrypted back. This makes it suitable for password validation, challenge hash authentication, anti-tamper, digital signatures.',
'expectedHash' => '034rT6smZAVRxpq8O98cFFNLIVx_Ph1EwLZQKcmRR_s',
),
array(
],
[
'data' => 'SHA-256 is one of the successor hash functions to SHA-1, and is one of the strongest hash functions available.',
'expected_hash' => 'yuqkDDYqprL71k4xIb6K6D7n76xldO4jseRhEkEE6SI',
),
);
],
];
}
/**
@ -103,13 +105,13 @@ class CryptTest extends UnitTestCase {
* @return array Test data.
*/
public function providerTestHmacBase64() {
return array(
array(
return [
[
'data' => 'Calculates a base-64 encoded, URL-safe sha-256 hmac.',
'key' => 'secret-key',
'expected_hmac' => '2AaH63zwjhekWZlEpAiufyfhAHIzbQhl9Hd9oCi3_c8',
),
);
],
];
}
/**
@ -118,33 +120,33 @@ class CryptTest extends UnitTestCase {
* @return array Test data.
*/
public function providerTestHmacBase64Invalid() {
return array(
array(new \stdClass(), new \stdClass()),
array(new \stdClass(), 'string'),
array(new \stdClass(), 1),
array(new \stdClass(), 0),
array(NULL, new \stdClass()),
array('string', new \stdClass()),
array(1, new \stdClass()),
array(0, new \stdClass()),
array(array(), array()),
array(array(), NULL),
array(array(), 'string'),
array(array(), 1),
array(array(), 0),
array(NULL, array()),
array(1, array()),
array(0, array()),
array('string', array()),
array(array(), NULL),
array(NULL, NULL),
array(NULL, 'string'),
array(NULL, 1),
array(NULL, 0),
array(1, NULL),
array(0, NULL),
array('string', NULL),
);
return [
[new \stdClass(), new \stdClass()],
[new \stdClass(), 'string'],
[new \stdClass(), 1],
[new \stdClass(), 0],
[NULL, new \stdClass()],
['string', new \stdClass()],
[1, new \stdClass()],
[0, new \stdClass()],
[[], []],
[[], NULL],
[[], 'string'],
[[], 1],
[[], 0],
[NULL, []],
[1, []],
[0, []],
['string', []],
[[], NULL],
[NULL, NULL],
[NULL, 'string'],
[NULL, 1],
[NULL, 0],
[1, NULL],
[0, NULL],
['string', NULL],
];
}
}

View file

@ -47,16 +47,16 @@ class EnvironmentTest extends UnitTestCase {
$memory_limit = ini_get('memory_limit');
$twice_avail_memory = ($memory_limit * 2) . 'MB';
return array(
return [
// Minimal amount of memory should be available.
array('30MB', NULL, TRUE),
['30MB', NULL, TRUE],
// Exceed a custom (unlimited) memory limit.
array($twice_avail_memory, -1, TRUE),
[$twice_avail_memory, -1, TRUE],
// Exceed a custom memory limit.
array('30MB', '16MB', FALSE),
['30MB', '16MB', FALSE],
// Available = required.
array('30MB', '30MB', TRUE),
);
['30MB', '30MB', TRUE],
];
}
}

View file

@ -59,25 +59,25 @@ class HtmlTest extends UnitTestCase {
$id1 = 'abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ-0123456789';
$id2 = '¡¢£¤¥';
$id3 = 'css__identifier__with__double__underscores';
return array(
return [
// Verify that no valid ASCII characters are stripped from the identifier.
array($id1, $id1, array()),
[$id1, $id1, []],
// Verify that valid UTF-8 characters are not stripped from the identifier.
array($id2, $id2, array()),
[$id2, $id2, []],
// Verify that invalid characters (including non-breaking space) are stripped from the identifier.
array($id3, $id3),
[$id3, $id3],
// Verify that double underscores are not stripped from the identifier.
array('invalididentifier', 'invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', array()),
['invalididentifier', 'invalid !"#$%&\'()*+,./:;<=>?@[\\]^`{|}~ identifier', []],
// Verify that an identifier starting with a digit is replaced.
array('_cssidentifier', '1cssidentifier', array()),
['_cssidentifier', '1cssidentifier', []],
// Verify that an identifier starting with a hyphen followed by a digit is
// replaced.
array('__cssidentifier', '-1cssidentifier', array()),
['__cssidentifier', '-1cssidentifier', []],
// Verify that an identifier starting with two hyphens is replaced.
array('__cssidentifier', '--cssidentifier', array()),
['__cssidentifier', '--cssidentifier', []],
// Verify that passing double underscores as a filter is processed.
array('_cssidentifier', '__cssidentifier', array('__' => '_')),
);
['_cssidentifier', '__cssidentifier', ['__' => '_']],
];
}
/**
@ -119,18 +119,18 @@ class HtmlTest extends UnitTestCase {
*/
public function providerTestHtmlGetUniqueId() {
$id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
return array(
return [
// Verify that letters, digits, and hyphens are not stripped from the ID.
array($id, $id),
[$id, $id],
// Verify that invalid characters are stripped from the ID.
array('invalididentifier', 'invalid,./:@\\^`{Üidentifier'),
['invalididentifier', 'invalid,./:@\\^`{Üidentifier'],
// Verify Drupal coding standards are enforced.
array('id-name-1', 'ID NAME_[1]'),
['id-name-1', 'ID NAME_[1]'],
// Verify that a repeated ID is made unique.
array('test-unique-id', 'test-unique-id', TRUE),
array('test-unique-id--2', 'test-unique-id'),
array('test-unique-id--3', 'test-unique-id'),
);
['test-unique-id', 'test-unique-id', TRUE],
['test-unique-id--2', 'test-unique-id'],
['test-unique-id--3', 'test-unique-id'],
];
}
/**
@ -168,13 +168,13 @@ class HtmlTest extends UnitTestCase {
* Test data.
*/
public function providerTestHtmlGetUniqueIdWithAjaxIds() {
return array(
array('test-unique-id1--', 'test-unique-id1'),
return [
['test-unique-id1--', 'test-unique-id1'],
// Note, we truncate two hyphens at the end.
// @see \Drupal\Component\Utility\Html::getId()
array('test-unique-id1---', 'test-unique-id1--'),
array('test-unique-id2--', 'test-unique-id2'),
);
['test-unique-id1---', 'test-unique-id1--'],
['test-unique-id2--', 'test-unique-id2'],
];
}
/**
@ -202,17 +202,17 @@ class HtmlTest extends UnitTestCase {
*/
public function providerTestHtmlGetId() {
$id = 'abcdefghijklmnopqrstuvwxyz-0123456789';
return array(
return [
// Verify that letters, digits, and hyphens are not stripped from the ID.
array($id, $id),
[$id, $id],
// Verify that invalid characters are stripped from the ID.
array('invalididentifier', 'invalid,./:@\\^`{Üidentifier'),
['invalididentifier', 'invalid,./:@\\^`{Üidentifier'],
// Verify Drupal coding standards are enforced.
array('id-name-1', 'ID NAME_[1]'),
['id-name-1', 'ID NAME_[1]'],
// Verify that a repeated ID is made unique.
array('test-unique-id', 'test-unique-id'),
array('test-unique-id', 'test-unique-id'),
);
['test-unique-id', 'test-unique-id'],
['test-unique-id', 'test-unique-id'],
];
}
/**
@ -231,29 +231,29 @@ class HtmlTest extends UnitTestCase {
* @see testDecodeEntities()
*/
public function providerDecodeEntities() {
return array(
array('Drupal', 'Drupal'),
array('<script>', '<script>'),
array('&lt;script&gt;', '<script>'),
array('&#60;script&#62;', '<script>'),
array('&amp;lt;script&amp;gt;', '&lt;script&gt;'),
array('"', '"'),
array('&#34;', '"'),
array('&amp;#34;', '&#34;'),
array('&quot;', '"'),
array('&amp;quot;', '&quot;'),
array("'", "'"),
array('&#39;', "'"),
array('&amp;#39;', '&#39;'),
array('©', '©'),
array('&copy;', '©'),
array('&#169;', '©'),
array('→', '→'),
array('&#8594;', '→'),
array('➼', '➼'),
array('&#10172;', '➼'),
array('&euro;', '€'),
);
return [
['Drupal', 'Drupal'],
['<script>', '<script>'],
['&lt;script&gt;', '<script>'],
['&#60;script&#62;', '<script>'],
['&amp;lt;script&amp;gt;', '&lt;script&gt;'],
['"', '"'],
['&#34;', '"'],
['&amp;#34;', '&#34;'],
['&quot;', '"'],
['&amp;quot;', '&quot;'],
["'", "'"],
['&#39;', "'"],
['&amp;#39;', '&#39;'],
['©', '©'],
['&copy;', '©'],
['&#169;', '©'],
['→', '→'],
['&#8594;', '→'],
['➼', '➼'],
['&#10172;', '➼'],
['&euro;', '€'],
];
}
/**
@ -272,21 +272,21 @@ class HtmlTest extends UnitTestCase {
* @see testEscape()
*/
public function providerEscape() {
return array(
array('Drupal', 'Drupal'),
array('&lt;script&gt;', '<script>'),
array('&amp;lt;script&amp;gt;', '&lt;script&gt;'),
array('&amp;#34;', '&#34;'),
array('&quot;', '"'),
array('&amp;quot;', '&quot;'),
array('&#039;', "'"),
array('&amp;#039;', '&#039;'),
array('©', '©'),
array('→', '→'),
array('➼', '➼'),
array('€', '€'),
array('Drup<75>al', "Drup\x80al"),
);
return [
['Drupal', 'Drupal'],
['&lt;script&gt;', '<script>'],
['&amp;lt;script&amp;gt;', '&lt;script&gt;'],
['&amp;#34;', '&#34;'],
['&quot;', '"'],
['&amp;quot;', '&quot;'],
['&#039;', "'"],
['&amp;#039;', '&#039;'],
['©', '©'],
['→', '→'],
['➼', '➼'],
['€', '€'],
['Drup<75>al', "Drup\x80al"],
];
}
/**
@ -332,9 +332,9 @@ class HtmlTest extends UnitTestCase {
/**
* @covers ::transformRootRelativeUrlsToAbsolute
* @dataProvider providerTestTransformRootRelativeUrlsToAbsoluteAssertion
* @expectedException \AssertionError
*/
public function testTransformRootRelativeUrlsToAbsoluteAssertion($scheme_and_host) {
$this->setExpectedException(\AssertionError::class);
Html::transformRootRelativeUrlsToAbsolute('', $scheme_and_host);
}

View file

@ -44,113 +44,113 @@ class ImageTest extends UnitTestCase {
*/
public function providerTestScaleDimensions() {
// Define input / output datasets to test different branch conditions.
$tests = array();
$tests = [];
// Test branch conditions:
// - No height.
// - Upscale, don't need to upscale.
$tests[] = array(
'input' => array(
'dimensions' => array(
$tests[] = [
'input' => [
'dimensions' => [
'width' => 1000,
'height' => 2000,
),
],
'width' => 200,
'height' => NULL,
'upscale' => TRUE,
),
'output' => array(
'dimensions' => array(
],
'output' => [
'dimensions' => [
'width' => 200,
'height' => 400,
),
],
'return_value' => TRUE,
),
);
],
];
// Test branch conditions:
// - No width.
// - Don't upscale, don't need to upscale.
$tests[] = array(
'input' => array(
'dimensions' => array(
$tests[] = [
'input' => [
'dimensions' => [
'width' => 1000,
'height' => 800,
),
],
'width' => NULL,
'height' => 140,
'upscale' => FALSE,
),
'output' => array(
'dimensions' => array(
],
'output' => [
'dimensions' => [
'width' => 175,
'height' => 140,
),
],
'return_value' => TRUE,
),
);
],
];
// Test branch conditions:
// - Source aspect ratio greater than target.
// - Upscale, need to upscale.
$tests[] = array(
'input' => array(
'dimensions' => array(
$tests[] = [
'input' => [
'dimensions' => [
'width' => 8,
'height' => 20,
),
],
'width' => 200,
'height' => 140,
'upscale' => TRUE,
),
'output' => array(
'dimensions' => array(
],
'output' => [
'dimensions' => [
'width' => 56,
'height' => 140,
),
],
'return_value' => TRUE,
),
);
],
];
// Test branch condition: target aspect ratio greater than source.
$tests[] = array(
'input' => array(
'dimensions' => array(
$tests[] = [
'input' => [
'dimensions' => [
'width' => 2000,
'height' => 800,
),
],
'width' => 200,
'height' => 140,
'upscale' => FALSE,
),
'output' => array(
'dimensions' => array(
],
'output' => [
'dimensions' => [
'width' => 200,
'height' => 80,
),
],
'return_value' => TRUE,
),
);
],
];
// Test branch condition: don't upscale, need to upscale.
$tests[] = array(
'input' => array(
'dimensions' => array(
$tests[] = [
'input' => [
'dimensions' => [
'width' => 100,
'height' => 50,
),
],
'width' => 200,
'height' => 140,
'upscale' => FALSE,
),
'output' => array(
'dimensions' => array(
],
'output' => [
'dimensions' => [
'width' => 100,
'height' => 50,
),
],
'return_value' => FALSE,
),
);
],
];
return $tests;
}

View file

@ -32,12 +32,12 @@ class NestedArrayTest extends UnitTestCase {
parent::setUp();
// Create a form structure with a nested element.
$this->form['details']['element'] = array(
$this->form['details']['element'] = [
'#value' => 'Nested element',
);
];
// Set up parent array.
$this->parents = array('details', 'element');
$this->parents = ['details', 'element'];
}
/**
@ -76,10 +76,10 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::setValue
*/
public function testSetValue() {
$new_value = array(
$new_value = [
'#value' => 'New value',
'#required' => TRUE,
);
];
// Verify setting the value of a nested element.
NestedArray::setValue($this->form, $this->parents, $new_value);
@ -93,11 +93,11 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::setValue
*/
public function testSetValueForce() {
$new_value = array(
$new_value = [
'one',
);
];
$this->form['details']['non-array-parent'] = 'string';
$parents = array('details', 'non-array-parent', 'child');
$parents = ['details', 'non-array-parent', 'child'];
NestedArray::setValue($this->form, $parents, $new_value, TRUE);
$this->assertSame($new_value, $this->form['details']['non-array-parent']['child'], 'The nested element was not forced to the new value.');
}
@ -144,23 +144,23 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::mergeDeepArray
*/
public function testMergeDeepArray() {
$link_options_1 = array(
$link_options_1 = [
'fragment' => 'x',
'attributes' => array('title' => 'X', 'class' => array('a', 'b')),
'attributes' => ['title' => 'X', 'class' => ['a', 'b']],
'language' => 'en',
);
$link_options_2 = array(
];
$link_options_2 = [
'fragment' => 'y',
'attributes' => array('title' => 'Y', 'class' => array('c', 'd')),
'attributes' => ['title' => 'Y', 'class' => ['c', 'd']],
'absolute' => TRUE,
);
$expected = array(
];
$expected = [
'fragment' => 'y',
'attributes' => array('title' => 'Y', 'class' => array('a', 'b', 'c', 'd')),
'attributes' => ['title' => 'Y', 'class' => ['a', 'b', 'c', 'd']],
'language' => 'en',
'absolute' => TRUE,
);
$this->assertSame($expected, NestedArray::mergeDeepArray(array($link_options_1, $link_options_2)), 'NestedArray::mergeDeepArray() returned a properly merged array.');
];
$this->assertSame($expected, NestedArray::mergeDeepArray([$link_options_1, $link_options_2]), 'NestedArray::mergeDeepArray() returned a properly merged array.');
// Test wrapper function, NestedArray::mergeDeep().
$this->assertSame($expected, NestedArray::mergeDeep($link_options_1, $link_options_2), 'NestedArray::mergeDeep() returned a properly merged array.');
}
@ -171,18 +171,18 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::mergeDeepArray
*/
public function testMergeImplicitKeys() {
$a = array(
'subkey' => array('X', 'Y'),
);
$b = array(
'subkey' => array('X'),
);
$a = [
'subkey' => ['X', 'Y'],
];
$b = [
'subkey' => ['X'],
];
// Drupal core behavior.
$expected = array(
'subkey' => array('X', 'Y', 'X'),
);
$actual = NestedArray::mergeDeepArray(array($a, $b));
$expected = [
'subkey' => ['X', 'Y', 'X'],
];
$actual = NestedArray::mergeDeepArray([$a, $b]);
$this->assertSame($expected, $actual, 'drupal_array_merge_deep() creates new numeric keys in the implicit sequence.');
}
@ -192,29 +192,29 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::mergeDeepArray
*/
public function testMergeExplicitKeys() {
$a = array(
'subkey' => array(
$a = [
'subkey' => [
0 => 'A',
1 => 'B',
),
);
$b = array(
'subkey' => array(
],
];
$b = [
'subkey' => [
0 => 'C',
1 => 'D',
),
);
],
];
// Drupal core behavior.
$expected = array(
'subkey' => array(
$expected = [
'subkey' => [
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D',
),
);
$actual = NestedArray::mergeDeepArray(array($a, $b));
],
];
$actual = NestedArray::mergeDeepArray([$a, $b]);
$this->assertSame($expected, $actual, 'drupal_array_merge_deep() creates new numeric keys in the explicit sequence.');
}
@ -228,29 +228,29 @@ class NestedArrayTest extends UnitTestCase {
* @covers ::mergeDeepArray
*/
public function testMergeOutOfSequenceKeys() {
$a = array(
'subkey' => array(
$a = [
'subkey' => [
10 => 'A',
30 => 'B',
),
);
$b = array(
'subkey' => array(
],
];
$b = [
'subkey' => [
20 => 'C',
0 => 'D',
),
);
],
];
// Drupal core behavior.
$expected = array(
'subkey' => array(
$expected = [
'subkey' => [
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D',
),
);
$actual = NestedArray::mergeDeepArray(array($a, $b));
],
];
$actual = NestedArray::mergeDeepArray([$a, $b]);
$this->assertSame($expected, $actual, 'drupal_array_merge_deep() ignores numeric key order when merging.');
}

View file

@ -60,36 +60,36 @@ class NumberTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\Number::testValidStep
*/
public static function providerTestValidStep() {
return array(
return [
// Value and step equal.
array(10.3, 10.3, TRUE),
[10.3, 10.3, TRUE],
// Valid integer steps.
array(42, 21, TRUE),
array(42, 3, TRUE),
[42, 21, TRUE],
[42, 3, TRUE],
// Valid float steps.
array(42, 10.5, TRUE),
array(1, 1 / 3, TRUE),
array(-100, 100 / 7, TRUE),
array(1000, -10, TRUE),
[42, 10.5, TRUE],
[1, 1 / 3, TRUE],
[-100, 100 / 7, TRUE],
[1000, -10, TRUE],
// Valid and very small float steps.
array(1000.12345, 1e-10, TRUE),
array(3.9999999999999, 1e-13, TRUE),
[1000.12345, 1e-10, TRUE],
[3.9999999999999, 1e-13, TRUE],
// Invalid integer steps.
array(100, 30, FALSE),
array(-10, 4, FALSE),
[100, 30, FALSE],
[-10, 4, FALSE],
// Invalid float steps.
array(6, 5 / 7, FALSE),
array(10.3, 10.25, FALSE),
[6, 5 / 7, FALSE],
[10.3, 10.25, FALSE],
// Step mismatches very close to being valid.
array(70 + 9e-7, 10 + 9e-7, FALSE),
array(1936.5, 3e-8, FALSE),
);
[70 + 9e-7, 10 + 9e-7, FALSE],
[1936.5, 3e-8, FALSE],
];
}
/**
@ -98,22 +98,22 @@ class NumberTest extends UnitTestCase {
* @see \Drupal\Test\Component\Utility\NumberTest::testValidStepOffset()
*/
public static function providerTestValidStepOffset() {
return array(
return [
// Try obvious fits.
array(11.3, 10.3, 1, TRUE),
array(100, 10, 50, TRUE),
array(-100, 90 / 7, -10, TRUE),
array(2 / 7 + 5 / 9, 1 / 7, 5 / 9, TRUE),
[11.3, 10.3, 1, TRUE],
[100, 10, 50, TRUE],
[-100, 90 / 7, -10, TRUE],
[2 / 7 + 5 / 9, 1 / 7, 5 / 9, TRUE],
// Ensure a small offset is still invalid.
array(10.3, 10.3, 0.0001, FALSE),
array(1 / 5, 1 / 7, 1 / 11, FALSE),
[10.3, 10.3, 0.0001, FALSE],
[1 / 5, 1 / 7, 1 / 11, FALSE],
// Try negative values and offsets.
array(1000, 10, -5, FALSE),
array(-10, 4, 0, FALSE),
array(-10, 4, -4, FALSE),
);
[1000, 10, -5, FALSE],
[-10, 4, 0, FALSE],
[-10, 4, -4, FALSE],
];
}
/**
@ -144,15 +144,15 @@ class NumberTest extends UnitTestCase {
* - The alphadecimal value.
*/
public function providerTestConversions() {
return array(
array(0, '00'),
array(1, '01'),
array(10, '0a'),
array(20, '0k'),
array(35, '0z'),
array(36, '110'),
array(100, '12s'),
);
return [
[0, '00'],
[1, '01'],
[10, '0a'],
[20, '0k'],
[35, '0z'],
[36, '110'],
[100, '12s'],
];
}
}

View file

@ -29,7 +29,7 @@ class RandomTest extends UnitTestCase {
* @covers ::string
*/
public function testRandomStringUniqueness() {
$strings = array();
$strings = [];
$random = new Random();
for ($i = 0; $i <= 50; $i++) {
$str = $random->string(1, TRUE);
@ -44,7 +44,7 @@ class RandomTest extends UnitTestCase {
* @covers ::name
*/
public function testRandomNamesUniqueness() {
$names = array();
$names = [];
$random = new Random();
for ($i = 0; $i <= 10; $i++) {
$str = $random->name(1, TRUE);
@ -57,12 +57,12 @@ class RandomTest extends UnitTestCase {
* Tests infinite loop prevention whilst generating random names.
*
* @covers ::name
* @expectedException \RuntimeException
*/
public function testRandomNameException() {
// There are fewer than 100 possibilities so an exception should occur to
// prevent infinite loops.
$random = new Random();
$this->setExpectedException(\RuntimeException::class);
for ($i = 0; $i <= 100; $i++) {
$str = $random->name(1, TRUE);
$names[$str] = TRUE;
@ -73,12 +73,12 @@ class RandomTest extends UnitTestCase {
* Tests infinite loop prevention whilst generating random strings.
*
* @covers ::string
* @expectedException \RuntimeException
*/
public function testRandomStringException() {
// There are fewer than 100 possibilities so an exception should occur to
// prevent infinite loops.
$random = new Random();
$this->setExpectedException(\RuntimeException::class);
for ($i = 0; $i <= 100; $i++) {
$str = $random->string(1, TRUE);
$names[$str] = TRUE;
@ -138,7 +138,7 @@ class RandomTest extends UnitTestCase {
public function testRandomStringValidator() {
$random = new Random();
$this->firstStringGenerated = '';
$str = $random->string(1, TRUE, array($this, '_RandomStringValidate'));
$str = $random->string(1, TRUE, [$this, '_RandomStringValidate']);
$this->assertNotEquals($this->firstStringGenerated, $str);
}

View file

@ -15,10 +15,9 @@ class RectangleTest extends UnitTestCase {
* Tests wrong rectangle width.
*
* @covers ::rotate
*
* @expectedException \InvalidArgumentException
*/
public function testWrongWidth() {
$this->setExpectedException(\InvalidArgumentException::class);
$rect = new Rectangle(-40, 20);
}
@ -26,10 +25,9 @@ class RectangleTest extends UnitTestCase {
* Tests wrong rectangle height.
*
* @covers ::rotate
*
* @expectedException \InvalidArgumentException
*/
public function testWrongHeight() {
$this->setExpectedException(\InvalidArgumentException::class);
$rect = new Rectangle(40, 0);
}

View file

@ -56,7 +56,7 @@ class SafeMarkupTest extends UnitTestCase {
* @param string $message
* The message to provide as output for the test.
*/
function testCheckPlain($text, $expected, $message) {
public function testCheckPlain($text, $expected, $message) {
$result = SafeMarkup::checkPlain($text);
$this->assertTrue($result instanceof HtmlEscapedText);
$this->assertEquals($expected, $result, $message);
@ -77,7 +77,7 @@ class SafeMarkupTest extends UnitTestCase {
* @param string $message
* The message to provide as output for the test.
*/
function testHtmlEscapedText($text, $expected, $message) {
public function testHtmlEscapedText($text, $expected, $message) {
$result = new HtmlEscapedText($text);
$this->assertEquals($expected, $result, $message);
}
@ -87,17 +87,17 @@ class SafeMarkupTest extends UnitTestCase {
*
* @see testCheckPlain()
*/
function providerCheckPlain() {
public function providerCheckPlain() {
// Checks that invalid multi-byte sequences are escaped.
$tests[] = array("Foo\xC0barbaz", 'Foo<6F>barbaz', 'Escapes invalid sequence "Foo\xC0barbaz"');
$tests[] = array("\xc2\"", '<27>&quot;', 'Escapes invalid sequence "\xc2\""');
$tests[] = array("Fooÿñ", "Fooÿñ", 'Does not escape valid sequence "Fooÿñ"');
$tests[] = ["Foo\xC0barbaz", 'Foo<6F>barbaz', 'Escapes invalid sequence "Foo\xC0barbaz"'];
$tests[] = ["\xc2\"", '<27>&quot;', 'Escapes invalid sequence "\xc2\""'];
$tests[] = ["Fooÿñ", "Fooÿñ", 'Does not escape valid sequence "Fooÿñ"'];
// Checks that special characters are escaped.
$tests[] = array(SafeMarkupTestMarkup::create("<script>"), '&lt;script&gt;', 'Escapes &lt;script&gt; even inside an object that implements MarkupInterface.');
$tests[] = array("<script>", '&lt;script&gt;', 'Escapes &lt;script&gt;');
$tests[] = array('<>&"\'', '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters.');
$tests[] = array(SafeMarkupTestMarkup::create('<>&"\''), '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters even inside an object that implements MarkupInterface.');
$tests[] = [SafeMarkupTestMarkup::create("<script>"), '&lt;script&gt;', 'Escapes &lt;script&gt; even inside an object that implements MarkupInterface.'];
$tests[] = ["<script>", '&lt;script&gt;', 'Escapes &lt;script&gt;'];
$tests[] = ['<>&"\'', '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters.'];
$tests[] = [SafeMarkupTestMarkup::create('<>&"\''), '&lt;&gt;&amp;&quot;&#039;', 'Escapes reserved HTML characters even inside an object that implements MarkupInterface.'];
return $tests;
}
@ -136,12 +136,12 @@ class SafeMarkupTest extends UnitTestCase {
*
* @see testFormat()
*/
function providerFormat() {
$tests[] = array('Simple text', array(), 'Simple text', 'SafeMarkup::format leaves simple text alone.', TRUE);
$tests[] = array('Escaped text: @value', array('@value' => '<script>'), 'Escaped text: &lt;script&gt;', 'SafeMarkup::format replaces and escapes string.', TRUE);
$tests[] = array('Escaped text: @value', array('@value' => SafeMarkupTestMarkup::create('<span>Safe HTML</span>')), 'Escaped text: <span>Safe HTML</span>', 'SafeMarkup::format does not escape an already safe string.', TRUE);
$tests[] = array('Placeholder text: %value', array('%value' => '<script>'), 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', 'SafeMarkup::format replaces, escapes and themes string.', TRUE);
$tests[] = array('Placeholder text: %value', array('%value' => SafeMarkupTestMarkup::create('<span>Safe HTML</span>')), 'Placeholder text: <em class="placeholder"><span>Safe HTML</span></em>', 'SafeMarkup::format does not escape an already safe string themed as a placeholder.', TRUE);
public function providerFormat() {
$tests[] = ['Simple text', [], 'Simple text', 'SafeMarkup::format leaves simple text alone.', TRUE];
$tests[] = ['Escaped text: @value', ['@value' => '<script>'], 'Escaped text: &lt;script&gt;', 'SafeMarkup::format replaces and escapes string.', TRUE];
$tests[] = ['Escaped text: @value', ['@value' => SafeMarkupTestMarkup::create('<span>Safe HTML</span>')], 'Escaped text: <span>Safe HTML</span>', 'SafeMarkup::format does not escape an already safe string.', TRUE];
$tests[] = ['Placeholder text: %value', ['%value' => '<script>'], 'Placeholder text: <em class="placeholder">&lt;script&gt;</em>', 'SafeMarkup::format replaces, escapes and themes string.', TRUE];
$tests[] = ['Placeholder text: %value', ['%value' => SafeMarkupTestMarkup::create('<span>Safe HTML</span>')], 'Placeholder text: <em class="placeholder"><span>Safe HTML</span></em>', 'SafeMarkup::format does not escape an already safe string themed as a placeholder.', TRUE];
$tests['javascript-protocol-url'] = ['Simple text <a href=":url">giraffe</a>', [':url' => 'javascript://example.com?foo&bar'], 'Simple text <a href="//example.com?foo&amp;bar">giraffe</a>', 'Support for filtering bad protocols', TRUE];
$tests['external-url'] = ['Simple text <a href=":url">giraffe</a>', [':url' => 'http://example.com?foo&bar'], 'Simple text <a href="http://example.com?foo&amp;bar">giraffe</a>', 'Support for filtering bad protocols', TRUE];

View file

@ -43,49 +43,49 @@ class SortArrayTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\SortArrayTest::testSortByWeightElement()
*/
public function providerSortByWeightElement() {
$tests = array();
$tests = [];
// Weights set and equal.
$tests[] = array(
array('weight' => 1),
array('weight' => 1),
$tests[] = [
['weight' => 1],
['weight' => 1],
0
);
];
// Weights set and $a is less (lighter) than $b.
$tests[] = array(
array('weight' => 1),
array('weight' => 2),
$tests[] = [
['weight' => 1],
['weight' => 2],
-1
);
];
// Weights set and $a is greater (heavier) than $b.
$tests[] = array(
array('weight' => 2),
array('weight' => 1),
$tests[] = [
['weight' => 2],
['weight' => 1],
1
);
];
// Weights not set.
$tests[] = array(
array(),
array(),
$tests[] = [
[],
[],
0
);
];
// Weights for $b not set.
$tests[] = array(
array('weight' => 1),
array(),
$tests[] = [
['weight' => 1],
[],
1
);
];
// Weights for $a not set.
$tests[] = array(
array(),
array('weight' => 1),
$tests[] = [
[],
['weight' => 1],
-1
);
];
return $tests;
}
@ -119,49 +119,49 @@ class SortArrayTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\SortArrayTest::testSortByWeightProperty()
*/
public function providerSortByWeightProperty() {
$tests = array();
$tests = [];
// Weights set and equal.
$tests[] = array(
array('#weight' => 1),
array('#weight' => 1),
$tests[] = [
['#weight' => 1],
['#weight' => 1],
0
);
];
// Weights set and $a is less (lighter) than $b.
$tests[] = array(
array('#weight' => 1),
array('#weight' => 2),
$tests[] = [
['#weight' => 1],
['#weight' => 2],
-1
);
];
// Weights set and $a is greater (heavier) than $b.
$tests[] = array(
array('#weight' => 2),
array('#weight' => 1),
$tests[] = [
['#weight' => 2],
['#weight' => 1],
1
);
];
// Weights not set.
$tests[] = array(
array(),
array(),
$tests[] = [
[],
[],
0
);
];
// Weights for $b not set.
$tests[] = array(
array('#weight' => 1),
array(),
$tests[] = [
['#weight' => 1],
[],
1
);
];
// Weights for $a not set.
$tests[] = array(
array(),
array('#weight' => 1),
$tests[] = [
[],
['#weight' => 1],
-1
);
];
return $tests;
}
@ -195,42 +195,42 @@ class SortArrayTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\SortArrayTest::testSortByTitleElement()
*/
public function providerSortByTitleElement() {
$tests = array();
$tests = [];
// Titles set and equal.
$tests[] = array(
array('title' => 'test'),
array('title' => 'test'),
$tests[] = [
['title' => 'test'],
['title' => 'test'],
0
);
];
// Title $a not set.
$tests[] = array(
array(),
array('title' => 'test'),
$tests[] = [
[],
['title' => 'test'],
-4
);
];
// Title $b not set.
$tests[] = array(
array('title' => 'test'),
array(),
$tests[] = [
['title' => 'test'],
[],
4
);
];
// Titles set but not equal.
$tests[] = array(
array('title' => 'test'),
array('title' => 'testing'),
$tests[] = [
['title' => 'test'],
['title' => 'testing'],
-1
);
];
// Titles set but not equal.
$tests[] = array(
array('title' => 'testing'),
array('title' => 'test'),
$tests[] = [
['title' => 'testing'],
['title' => 'test'],
1
);
];
return $tests;
}
@ -264,42 +264,42 @@ class SortArrayTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\SortArrayTest::testSortByTitleProperty()
*/
public function providerSortByTitleProperty() {
$tests = array();
$tests = [];
// Titles set and equal.
$tests[] = array(
array('#title' => 'test'),
array('#title' => 'test'),
$tests[] = [
['#title' => 'test'],
['#title' => 'test'],
0
);
];
// Title $a not set.
$tests[] = array(
array(),
array('#title' => 'test'),
$tests[] = [
[],
['#title' => 'test'],
-4
);
];
// Title $b not set.
$tests[] = array(
array('#title' => 'test'),
array(),
$tests[] = [
['#title' => 'test'],
[],
4
);
];
// Titles set but not equal.
$tests[] = array(
array('#title' => 'test'),
array('#title' => 'testing'),
$tests[] = [
['#title' => 'test'],
['#title' => 'testing'],
-1
);
];
// Titles set but not equal.
$tests[] = array(
array('#title' => 'testing'),
array('#title' => 'test'),
$tests[] = [
['#title' => 'testing'],
['#title' => 'test'],
1
);
];
return $tests;
}

View file

@ -51,15 +51,15 @@ class UnicodeTest extends UnitTestCase {
* - (optional) Boolean indicating invalid status. Defaults to FALSE.
*/
public function providerTestStatus() {
return array(
array(Unicode::STATUS_SINGLEBYTE, Unicode::STATUS_SINGLEBYTE),
array(rand(10, 100), Unicode::STATUS_SINGLEBYTE, TRUE),
array(rand(10, 100), Unicode::STATUS_SINGLEBYTE, TRUE),
array(Unicode::STATUS_MULTIBYTE, Unicode::STATUS_MULTIBYTE),
array(rand(10, 100), Unicode::STATUS_MULTIBYTE, TRUE),
array(Unicode::STATUS_ERROR, Unicode::STATUS_ERROR),
array(Unicode::STATUS_MULTIBYTE, Unicode::STATUS_MULTIBYTE),
);
return [
[Unicode::STATUS_SINGLEBYTE, Unicode::STATUS_SINGLEBYTE],
[rand(10, 100), Unicode::STATUS_SINGLEBYTE, TRUE],
[rand(10, 100), Unicode::STATUS_SINGLEBYTE, TRUE],
[Unicode::STATUS_MULTIBYTE, Unicode::STATUS_MULTIBYTE],
[rand(10, 100), Unicode::STATUS_MULTIBYTE, TRUE],
[Unicode::STATUS_ERROR, Unicode::STATUS_ERROR],
[Unicode::STATUS_MULTIBYTE, Unicode::STATUS_MULTIBYTE],
];
}
/**
@ -83,11 +83,11 @@ class UnicodeTest extends UnitTestCase {
* An array containing a string and its encoded value.
*/
public function providerTestMimeHeader() {
return array(
array('tést.txt', '=?UTF-8?B?dMOpc3QudHh0?='),
return [
['tést.txt', '=?UTF-8?B?dMOpc3QudHh0?='],
// Simple ASCII characters.
array('ASCII', 'ASCII'),
);
['ASCII', 'ASCII'],
];
}
/**
@ -113,17 +113,17 @@ class UnicodeTest extends UnitTestCase {
* be processed as multibyte.
*/
public function providerStrtolower() {
$cases = array(
array('tHe QUIcK bRoWn', 'the quick brown'),
array('FrançAIS is ÜBER-åwesome', 'français is über-åwesome'),
);
$cases = [
['tHe QUIcK bRoWn', 'the quick brown'],
['FrançAIS is ÜBER-åwesome', 'français is über-åwesome'],
];
foreach ($cases as $case) {
// Test the same string both in multibyte and singlebyte conditions.
array_push($case, TRUE);
$cases[] = $case;
}
// Add a multibyte string.
$cases[] = array('ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', 'αβγδεζηθικλμνξοσὠ', TRUE);
$cases[] = ['ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', 'αβγδεζηθικλμνξοσὠ', TRUE];
return $cases;
}
@ -150,17 +150,17 @@ class UnicodeTest extends UnitTestCase {
* be processed as multibyte.
*/
public function providerStrtoupper() {
$cases = array(
array('tHe QUIcK bRoWn', 'THE QUICK BROWN'),
array('FrançAIS is ÜBER-åwesome', 'FRANÇAIS IS ÜBER-ÅWESOME'),
);
$cases = [
['tHe QUIcK bRoWn', 'THE QUICK BROWN'],
['FrançAIS is ÜBER-åwesome', 'FRANÇAIS IS ÜBER-ÅWESOME'],
];
foreach ($cases as $case) {
// Test the same string both in multibyte and singlebyte conditions.
array_push($case, TRUE);
$cases[] = $case;
}
// Add a multibyte string.
$cases[] = array('αβγδεζηθικλμνξοσὠ', 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', TRUE);
$cases[] = ['αβγδεζηθικλμνξοσὠ', 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', TRUE];
return $cases;
}
@ -183,14 +183,14 @@ class UnicodeTest extends UnitTestCase {
* An array containing a string and its uppercase first version.
*/
public function providerUcfirst() {
return array(
array('tHe QUIcK bRoWn', 'THe QUIcK bRoWn'),
array('françAIS', 'FrançAIS'),
array('über', 'Über'),
array('åwesome', 'Åwesome'),
return [
['tHe QUIcK bRoWn', 'THe QUIcK bRoWn'],
['françAIS', 'FrançAIS'],
['über', 'Über'],
['åwesome', 'Åwesome'],
// A multibyte string.
array('σion', 'Σion'),
);
['σion', 'Σion'],
];
}
/**
@ -215,14 +215,14 @@ class UnicodeTest extends UnitTestCase {
* be processed as multibyte.
*/
public function providerLcfirst() {
return array(
array('tHe QUIcK bRoWn', 'tHe QUIcK bRoWn'),
array('FrançAIS is ÜBER-åwesome', 'françAIS is ÜBER-åwesome'),
array('Über', 'über'),
array('Åwesome', 'åwesome'),
return [
['tHe QUIcK bRoWn', 'tHe QUIcK bRoWn'],
['FrançAIS is ÜBER-åwesome', 'françAIS is ÜBER-åwesome'],
['Über', 'über'],
['Åwesome', 'åwesome'],
// Add a multibyte string.
array('ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', 'αΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', TRUE),
);
['ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', 'αΒΓΔΕΖΗΘΙΚΛΜΝΞΟΣὨ', TRUE],
];
}
/**
@ -247,16 +247,16 @@ class UnicodeTest extends UnitTestCase {
* be processed as multibyte.
*/
public function providerUcwords() {
return array(
array('tHe QUIcK bRoWn', 'THe QUIcK BRoWn'),
array('françAIS', 'FrançAIS'),
array('über', 'Über'),
array('åwesome', 'Åwesome'),
return [
['tHe QUIcK bRoWn', 'THe QUIcK BRoWn'],
['françAIS', 'FrançAIS'],
['über', 'Über'],
['åwesome', 'Åwesome'],
// Make sure we don't mangle extra spaces.
array('frànçAIS is über-åwesome', 'FrànçAIS Is Über-Åwesome'),
['frànçAIS is über-åwesome', 'FrànçAIS Is Über-Åwesome'],
// Add a multibyte string.
array('σion', 'Σion', TRUE),
);
['σion', 'Σion', TRUE],
];
}
/**
@ -283,11 +283,11 @@ class UnicodeTest extends UnitTestCase {
* An array containing a string and its length.
*/
public function providerStrlen() {
return array(
array('tHe QUIcK bRoWn', 15),
array('ÜBER-åwesome', 12),
array('以呂波耳・ほへとち。リヌルヲ。', 15),
);
return [
['tHe QUIcK bRoWn', 15],
['ÜBER-åwesome', 12],
['以呂波耳・ほへとち。リヌルヲ。', 15],
];
}
/**
@ -318,33 +318,33 @@ class UnicodeTest extends UnitTestCase {
* - The expected string result.
*/
public function providerSubstr() {
return array(
array('frànçAIS is über-åwesome', 0, NULL, 'frànçAIS is über-åwesome'),
array('frànçAIS is über-åwesome', 0, 0, ''),
array('frànçAIS is über-åwesome', 0, 1, 'f'),
array('frànçAIS is über-åwesome', 0, 8, 'frànçAIS'),
array('frànçAIS is über-åwesome', 0, 23, 'frànçAIS is über-åwesom'),
array('frànçAIS is über-åwesome', 0, 24, 'frànçAIS is über-åwesome'),
array('frànçAIS is über-åwesome', 0, 25, 'frànçAIS is über-åwesome'),
array('frànçAIS is über-åwesome', 0, 100, 'frànçAIS is über-åwesome'),
array('frànçAIS is über-åwesome', 4, 4, 'çAIS'),
array('frànçAIS is über-åwesome', 1, 0, ''),
array('frànçAIS is über-åwesome', 100, 0, ''),
array('frànçAIS is über-åwesome', -4, 2, 'so'),
array('frànçAIS is über-åwesome', -4, 3, 'som'),
array('frànçAIS is über-åwesome', -4, 4, 'some'),
array('frànçAIS is über-åwesome', -4, 5, 'some'),
array('frànçAIS is über-åwesome', -7, 10, 'åwesome'),
array('frànçAIS is über-åwesome', 5, -10, 'AIS is üb'),
array('frànçAIS is über-åwesome', 0, -10, 'frànçAIS is üb'),
array('frànçAIS is über-åwesome', 0, -1, 'frànçAIS is über-åwesom'),
array('frànçAIS is über-åwesome', -7, -2, 'åweso'),
array('frànçAIS is über-åwesome', -7, -6, 'å'),
array('frànçAIS is über-åwesome', -7, -7, ''),
array('frànçAIS is über-åwesome', -7, -8, ''),
array('...', 0, 2, '..'),
array('以呂波耳・ほへとち。リヌルヲ。', 1, 3, '呂波耳'),
);
return [
['frànçAIS is über-åwesome', 0, NULL, 'frànçAIS is über-åwesome'],
['frànçAIS is über-åwesome', 0, 0, ''],
['frànçAIS is über-åwesome', 0, 1, 'f'],
['frànçAIS is über-åwesome', 0, 8, 'frànçAIS'],
['frànçAIS is über-åwesome', 0, 23, 'frànçAIS is über-åwesom'],
['frànçAIS is über-åwesome', 0, 24, 'frànçAIS is über-åwesome'],
['frànçAIS is über-åwesome', 0, 25, 'frànçAIS is über-åwesome'],
['frànçAIS is über-åwesome', 0, 100, 'frànçAIS is über-åwesome'],
['frànçAIS is über-åwesome', 4, 4, 'çAIS'],
['frànçAIS is über-åwesome', 1, 0, ''],
['frànçAIS is über-åwesome', 100, 0, ''],
['frànçAIS is über-åwesome', -4, 2, 'so'],
['frànçAIS is über-åwesome', -4, 3, 'som'],
['frànçAIS is über-åwesome', -4, 4, 'some'],
['frànçAIS is über-åwesome', -4, 5, 'some'],
['frànçAIS is über-åwesome', -7, 10, 'åwesome'],
['frànçAIS is über-åwesome', 5, -10, 'AIS is üb'],
['frànçAIS is über-åwesome', 0, -10, 'frànçAIS is üb'],
['frànçAIS is über-åwesome', 0, -1, 'frànçAIS is über-åwesom'],
['frànçAIS is über-åwesome', -7, -2, 'åweso'],
['frànçAIS is über-åwesome', -7, -6, 'å'],
['frànçAIS is über-åwesome', -7, -7, ''],
['frànçAIS is über-åwesome', -7, -8, ''],
['...', 0, 2, '..'],
['以呂波耳・ほへとち。リヌルヲ。', 1, 3, '呂波耳'],
];
}
/**
@ -371,52 +371,52 @@ class UnicodeTest extends UnitTestCase {
* - (optional) Boolean for the $add_ellipsis flag. Defaults to FALSE.
*/
public function providerTruncate() {
return array(
array('frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome'),
array('frànçAIS is über-åwesome', 23, 'frànçAIS is über-åwesom'),
array('frànçAIS is über-åwesome', 17, 'frànçAIS is über-'),
array('以呂波耳・ほへとち。リヌルヲ。', 6, '以呂波耳・ほ'),
array('frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome', FALSE, TRUE),
array('frànçAIS is über-åwesome', 23, 'frànçAIS is über-åweso…', FALSE, TRUE),
array('frànçAIS is über-åwesome', 17, 'frànçAIS is über…', FALSE, TRUE),
array('123', 1, '…', TRUE, TRUE),
array('123', 2, '1…', TRUE, TRUE),
array('123', 3, '123', TRUE, TRUE),
array('1234', 3, '12…', TRUE, TRUE),
array('1234567890', 10, '1234567890', TRUE, TRUE),
array('12345678901', 10, '123456789…', TRUE, TRUE),
array('12345678901', 11, '12345678901', TRUE, TRUE),
array('123456789012', 11, '1234567890…', TRUE, TRUE),
array('12345 7890', 10, '12345 7890', TRUE, TRUE),
array('12345 7890', 9, '12345…', TRUE, TRUE),
array('123 567 90', 10, '123 567 90', TRUE, TRUE),
array('123 567 901', 10, '123 567…', TRUE, TRUE),
array('Stop. Hammertime.', 17, 'Stop. Hammertime.', TRUE, TRUE),
array('Stop. Hammertime.', 16, 'Stop…', TRUE, TRUE),
array('frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome', TRUE, TRUE),
array('frànçAIS is über-åwesome', 23, 'frànçAIS is über…', TRUE, TRUE),
array('frànçAIS is über-åwesome', 17, 'frànçAIS is über…', TRUE, TRUE),
array('¿Dónde está el niño?', 20, '¿Dónde está el niño?', TRUE, TRUE),
array('¿Dónde está el niño?', 19, '¿Dónde está el…', TRUE, TRUE),
array('¿Dónde está el niño?', 13, '¿Dónde está…', TRUE, TRUE),
array('¿Dónde está el niño?', 10, '¿Dónde…', TRUE, TRUE),
array('Help! Help! Help!', 17, 'Help! Help! Help!', TRUE, TRUE),
array('Help! Help! Help!', 16, 'Help! Help!…', TRUE, TRUE),
array('Help! Help! Help!', 15, 'Help! Help!…', TRUE, TRUE),
array('Help! Help! Help!', 14, 'Help! Help!…', TRUE, TRUE),
array('Help! Help! Help!', 13, 'Help! Help!…', TRUE, TRUE),
array('Help! Help! Help!', 12, 'Help! Help!…', TRUE, TRUE),
array('Help! Help! Help!', 11, 'Help! Help…', TRUE, TRUE),
array('Help! Help! Help!', 10, 'Help!…', TRUE, TRUE),
array('Help! Help! Help!', 9, 'Help!…', TRUE, TRUE),
array('Help! Help! Help!', 8, 'Help!…', TRUE, TRUE),
array('Help! Help! Help!', 7, 'Help!…', TRUE, TRUE),
array('Help! Help! Help!', 6, 'Help!…', TRUE, TRUE),
array('Help! Help! Help!', 5, 'Help…', TRUE, TRUE),
array('Help! Help! Help!', 4, 'Hel…', TRUE, TRUE),
array('Help! Help! Help!', 3, 'He…', TRUE, TRUE),
array('Help! Help! Help!', 2, 'H…', TRUE, TRUE),
);
return [
['frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome'],
['frànçAIS is über-åwesome', 23, 'frànçAIS is über-åwesom'],
['frànçAIS is über-åwesome', 17, 'frànçAIS is über-'],
['以呂波耳・ほへとち。リヌルヲ。', 6, '以呂波耳・ほ'],
['frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome', FALSE, TRUE],
['frànçAIS is über-åwesome', 23, 'frànçAIS is über-åweso…', FALSE, TRUE],
['frànçAIS is über-åwesome', 17, 'frànçAIS is über…', FALSE, TRUE],
['123', 1, '…', TRUE, TRUE],
['123', 2, '1…', TRUE, TRUE],
['123', 3, '123', TRUE, TRUE],
['1234', 3, '12…', TRUE, TRUE],
['1234567890', 10, '1234567890', TRUE, TRUE],
['12345678901', 10, '123456789…', TRUE, TRUE],
['12345678901', 11, '12345678901', TRUE, TRUE],
['123456789012', 11, '1234567890…', TRUE, TRUE],
['12345 7890', 10, '12345 7890', TRUE, TRUE],
['12345 7890', 9, '12345…', TRUE, TRUE],
['123 567 90', 10, '123 567 90', TRUE, TRUE],
['123 567 901', 10, '123 567…', TRUE, TRUE],
['Stop. Hammertime.', 17, 'Stop. Hammertime.', TRUE, TRUE],
['Stop. Hammertime.', 16, 'Stop…', TRUE, TRUE],
['frànçAIS is über-åwesome', 24, 'frànçAIS is über-åwesome', TRUE, TRUE],
['frànçAIS is über-åwesome', 23, 'frànçAIS is über…', TRUE, TRUE],
['frànçAIS is über-åwesome', 17, 'frànçAIS is über…', TRUE, TRUE],
['¿Dónde está el niño?', 20, '¿Dónde está el niño?', TRUE, TRUE],
['¿Dónde está el niño?', 19, '¿Dónde está el…', TRUE, TRUE],
['¿Dónde está el niño?', 13, '¿Dónde está…', TRUE, TRUE],
['¿Dónde está el niño?', 10, '¿Dónde…', TRUE, TRUE],
['Help! Help! Help!', 17, 'Help! Help! Help!', TRUE, TRUE],
['Help! Help! Help!', 16, 'Help! Help!…', TRUE, TRUE],
['Help! Help! Help!', 15, 'Help! Help!…', TRUE, TRUE],
['Help! Help! Help!', 14, 'Help! Help!…', TRUE, TRUE],
['Help! Help! Help!', 13, 'Help! Help!…', TRUE, TRUE],
['Help! Help! Help!', 12, 'Help! Help!…', TRUE, TRUE],
['Help! Help! Help!', 11, 'Help! Help…', TRUE, TRUE],
['Help! Help! Help!', 10, 'Help!…', TRUE, TRUE],
['Help! Help! Help!', 9, 'Help!…', TRUE, TRUE],
['Help! Help! Help!', 8, 'Help!…', TRUE, TRUE],
['Help! Help! Help!', 7, 'Help!…', TRUE, TRUE],
['Help! Help! Help!', 6, 'Help!…', TRUE, TRUE],
['Help! Help! Help!', 5, 'Help…', TRUE, TRUE],
['Help! Help! Help!', 4, 'Hel…', TRUE, TRUE],
['Help! Help! Help!', 3, 'He…', TRUE, TRUE],
['Help! Help! Help!', 2, 'H…', TRUE, TRUE],
];
}
/**
@ -444,14 +444,14 @@ class UnicodeTest extends UnitTestCase {
* self::testTruncateBytes().
*/
public function providerTestTruncateBytes() {
return array(
return [
// String shorter than max length.
array('Short string', 42, 'Short string'),
['Short string', 42, 'Short string'],
// Simple string longer than max length.
array('Longer string than previous.', 10, 'Longer str'),
['Longer string than previous.', 10, 'Longer str'],
// Unicode.
array('以呂波耳・ほへとち。リヌルヲ。', 10, '以呂波'),
);
['以呂波耳・ほへとち。リヌルヲ。', 10, '以呂波'],
];
}
/**
@ -481,16 +481,16 @@ class UnicodeTest extends UnitTestCase {
* self::testValidateUtf8().
*/
public function providerTestValidateUtf8() {
return array(
return [
// Empty string.
array('', TRUE, 'An empty string did not validate.'),
['', TRUE, 'An empty string did not validate.'],
// Simple text string.
array('Simple text.', TRUE, 'A simple ASCII text string did not validate.'),
['Simple text.', TRUE, 'A simple ASCII text string did not validate.'],
// Invalid UTF-8, overlong 5 byte encoding.
array(chr(0xF8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80), FALSE, 'Invalid UTF-8 was validated.'),
[chr(0xF8) . chr(0x80) . chr(0x80) . chr(0x80) . chr(0x80), FALSE, 'Invalid UTF-8 was validated.'],
// High code-point without trailing characters.
array(chr(0xD0) . chr(0x01), FALSE, 'Invalid UTF-8 was validated.'),
);
[chr(0xD0) . chr(0x01), FALSE, 'Invalid UTF-8 was validated.'],
];
}
/**
@ -518,11 +518,11 @@ class UnicodeTest extends UnitTestCase {
* self::testConvertUtf8(). }
*/
public function providerTestConvertToUtf8() {
return array(
array(chr(0x97), 'Windows-1252', '—'),
array(chr(0x99), 'Windows-1252', '™'),
array(chr(0x80), 'Windows-1252', '€'),
);
return [
[chr(0x97), 'Windows-1252', '—'],
[chr(0x99), 'Windows-1252', '™'],
[chr(0x80), 'Windows-1252', '€'],
];
}
/**
@ -553,18 +553,18 @@ class UnicodeTest extends UnitTestCase {
* - The expected integer/FALSE result.
*/
public function providerStrpos() {
return array(
array('frànçAIS is über-åwesome', 'frànçAIS is über-åwesome', 0, 0),
array('frànçAIS is über-åwesome', 'rànçAIS is über-åwesome', 0, 1),
array('frànçAIS is über-åwesome', 'not in string', 0, FALSE),
array('frànçAIS is über-åwesome', 'r', 0, 1),
array('frànçAIS is über-åwesome', 'nçAIS', 0, 3),
array('frànçAIS is über-åwesome', 'nçAIS', 2, 3),
array('frànçAIS is über-åwesome', 'nçAIS', 3, 3),
array('以呂波耳・ほへとち。リヌルヲ。', '波耳', 0, 2),
array('以呂波耳・ほへとち。リヌルヲ。', '波耳', 1, 2),
array('以呂波耳・ほへとち。リヌルヲ。', '波耳', 2, 2),
);
return [
['frànçAIS is über-åwesome', 'frànçAIS is über-åwesome', 0, 0],
['frànçAIS is über-åwesome', 'rànçAIS is über-åwesome', 0, 1],
['frànçAIS is über-åwesome', 'not in string', 0, FALSE],
['frànçAIS is über-åwesome', 'r', 0, 1],
['frànçAIS is über-åwesome', 'nçAIS', 0, 3],
['frànçAIS is über-åwesome', 'nçAIS', 2, 3],
['frànçAIS is über-åwesome', 'nçAIS', 3, 3],
['以呂波耳・ほへとち。リヌルヲ。', '波耳', 0, 2],
['以呂波耳・ほへとち。リヌルヲ。', '波耳', 1, 2],
['以呂波耳・ほへとち。リヌルヲ。', '波耳', 2, 2],
];
}
}

View file

@ -18,13 +18,13 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public function providerTestBuildQuery() {
return array(
array(array('a' => ' &#//+%20@۞'), 'a=%20%26%23//%2B%2520%40%DB%9E', 'Value was properly encoded.'),
array(array(' &#//+%20@۞' => 'a'), '%20%26%23%2F%2F%2B%2520%40%DB%9E=a', 'Key was properly encoded.'),
array(array('a' => '1', 'b' => '2', 'c' => '3'), 'a=1&b=2&c=3', 'Multiple values were properly concatenated.'),
array(array('a' => array('b' => '2', 'c' => '3'), 'd' => 'foo'), 'a[b]=2&a[c]=3&d=foo', 'Nested array was properly encoded.'),
array(array('foo' => NULL), 'foo', 'Simple parameters are properly added.'),
);
return [
[['a' => ' &#//+%20@۞'], 'a=%20%26%23//%2B%2520%40%DB%9E', 'Value was properly encoded.'],
[[' &#//+%20@۞' => 'a'], '%20%26%23%2F%2F%2B%2520%40%DB%9E=a', 'Key was properly encoded.'],
[['a' => '1', 'b' => '2', 'c' => '3'], 'a=1&b=2&c=3', 'Multiple values were properly concatenated.'],
[['a' => ['b' => '2', 'c' => '3'], 'd' => 'foo'], 'a[b]=2&a[c]=3&d=foo', 'Nested array was properly encoded.'],
[['foo' => NULL], 'foo', 'Simple parameters are properly added.'],
];
}
/**
@ -50,7 +50,7 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public function providerTestValidAbsoluteData() {
$urls = array(
$urls = [
'example.com',
'www.example.com',
'ex-ample.com',
@ -69,7 +69,7 @@ class UrlHelperTest extends UnitTestCase {
'example.org/~,$\'*;',
'caf%C3%A9.example.org',
'[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html',
);
];
return $this->dataEnhanceWithScheme($urls);
}
@ -97,11 +97,11 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public function providerTestInvalidAbsolute() {
$data = array(
$data = [
'',
'ex!ample.com',
'ex%ample.com',
);
];
return $this->dataEnhanceWithScheme($data);
}
@ -128,13 +128,13 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public function providerTestValidRelativeData() {
$data = array(
$data = [
'paren(the)sis',
'index.html#pagetop',
'index.php/node',
'index.php/node?param=false',
'login.php?do=login&style=%23#pagetop',
);
];
return $this->dataEnhanceWithPrefix($data);
}
@ -162,11 +162,11 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public function providerTestInvalidRelativeData() {
$data = array(
$data = [
'ex^mple',
'example<>',
'ex%ample',
);
];
return $this->dataEnhanceWithPrefix($data);
}
@ -212,20 +212,20 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestFilterQueryParameters() {
return array(
return [
// Test without an exclude filter.
array(
'query' => array('a' => array('b' => 'c')),
'exclude' => array(),
'expected' => array('a' => array('b' => 'c')),
),
[
'query' => ['a' => ['b' => 'c']],
'exclude' => [],
'expected' => ['a' => ['b' => 'c']],
],
// Exclude the 'b' element.
array(
'query' => array('a' => array('b' => 'c', 'd' => 'e')),
'exclude' => array('a[b]'),
'expected' => array('a' => array('d' => 'e')),
),
);
[
'query' => ['a' => ['b' => 'c', 'd' => 'e']],
'exclude' => ['a[b]'],
'expected' => ['a' => ['d' => 'e']],
],
];
}
/**
@ -250,52 +250,52 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestParse() {
return array(
array(
return [
[
'http://www.example.com/my/path',
array(
[
'path' => 'http://www.example.com/my/path',
'query' => array(),
'query' => [],
'fragment' => '',
),
),
array(
],
],
[
'http://www.example.com/my/path?destination=home#footer',
array(
[
'path' => 'http://www.example.com/my/path',
'query' => array(
'query' => [
'destination' => 'home',
),
],
'fragment' => 'footer',
),
),
array(
],
],
[
'http://',
array(
[
'path' => '',
'query' => array(),
'query' => [],
'fragment' => '',
),
),
array(
],
],
[
'https://',
array(
[
'path' => '',
'query' => array(),
'query' => [],
'fragment' => '',
),
),
array(
],
],
[
'/my/path?destination=home#footer',
array(
[
'path' => '/my/path',
'query' => array(
'query' => [
'destination' => 'home',
),
],
'fragment' => 'footer',
),
),
);
],
],
];
}
/**
@ -320,10 +320,10 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestEncodePath() {
return array(
array('unencoded path with spaces', 'unencoded%20path%20with%20spaces'),
array('slashes/should/be/preserved', 'slashes/should/be/preserved'),
);
return [
['unencoded path with spaces', 'unencoded%20path%20with%20spaces'],
['slashes/should/be/preserved', 'slashes/should/be/preserved'],
];
}
/**
@ -348,39 +348,39 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestIsExternal() {
return array(
array('/internal/path', FALSE),
array('https://example.com/external/path', TRUE),
array('javascript://fake-external-path', FALSE),
return [
['/internal/path', FALSE],
['https://example.com/external/path', TRUE],
['javascript://fake-external-path', FALSE],
// External URL without an explicit protocol.
array('//www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo', TRUE),
['//www.drupal.org/foo/bar?foo=bar&bar=baz&baz#foo', TRUE],
// Internal URL starting with a slash.
array('/www.drupal.org', FALSE),
['/www.drupal.org', FALSE],
// Simple external URLs.
array('http://example.com', TRUE),
array('https://example.com', TRUE),
array('http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo', TRUE),
array('//drupal.org', TRUE),
['http://example.com', TRUE],
['https://example.com', TRUE],
['http://drupal.org/foo/bar?foo=bar&bar=baz&baz#foo', TRUE],
['//drupal.org', TRUE],
// Some browsers ignore or strip leading control characters.
array("\x00//www.example.com", TRUE),
array("\x08//www.example.com", TRUE),
array("\x1F//www.example.com", TRUE),
array("\n//www.example.com", TRUE),
["\x00//www.example.com", TRUE],
["\x08//www.example.com", TRUE],
["\x1F//www.example.com", TRUE],
["\n//www.example.com", TRUE],
// JSON supports decoding directly from UTF-8 code points.
array(json_decode('"\u00AD"') . "//www.example.com", TRUE),
array(json_decode('"\u200E"') . "//www.example.com", TRUE),
array(json_decode('"\uE0020"') . "//www.example.com", TRUE),
array(json_decode('"\uE000"') . "//www.example.com", TRUE),
[json_decode('"\u00AD"') . "//www.example.com", TRUE],
[json_decode('"\u200E"') . "//www.example.com", TRUE],
[json_decode('"\uE0020"') . "//www.example.com", TRUE],
[json_decode('"\uE000"') . "//www.example.com", TRUE],
// Backslashes should be normalized to forward.
array('\\\\example.com', TRUE),
['\\\\example.com', TRUE],
// Local URLs.
array('node', FALSE),
array('/system/ajax', FALSE),
array('?q=foo:bar', FALSE),
array('node/edit:me', FALSE),
array('/drupal.org', FALSE),
array('<front>', FALSE),
);
['node', FALSE],
['/system/ajax', FALSE],
['?q=foo:bar', FALSE],
['node/edit:me', FALSE],
['/drupal.org', FALSE],
['<front>', FALSE],
];
}
/**
@ -411,15 +411,15 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestFilterBadProtocol() {
return array(
array('javascript://example.com?foo&bar', '//example.com?foo&amp;bar', array('http', 'https')),
return [
['javascript://example.com?foo&bar', '//example.com?foo&amp;bar', ['http', 'https']],
// Test custom protocols.
array('http://example.com?foo&bar', '//example.com?foo&amp;bar', array('https')),
['http://example.com?foo&bar', '//example.com?foo&amp;bar', ['https']],
// Valid protocol.
array('http://example.com?foo&bar', 'http://example.com?foo&amp;bar', array('https', 'http')),
['http://example.com?foo&bar', 'http://example.com?foo&amp;bar', ['https', 'http']],
// Colon not part of the URL scheme.
array('/test:8888?foo&bar', '/test:8888?foo&amp;bar', array('http')),
);
['/test:8888?foo&bar', '/test:8888?foo&amp;bar', ['http']],
];
}
/**
@ -448,15 +448,15 @@ class UrlHelperTest extends UnitTestCase {
* @return array
*/
public static function providerTestStripDangerousProtocols() {
return array(
array('javascript://example.com', '//example.com', array('http', 'https')),
return [
['javascript://example.com', '//example.com', ['http', 'https']],
// Test custom protocols.
array('http://example.com', '//example.com', array('https')),
['http://example.com', '//example.com', ['https']],
// Valid protocol.
array('http://example.com', 'http://example.com', array('https', 'http')),
['http://example.com', 'http://example.com', ['https', 'http']],
// Colon not part of the URL scheme.
array('/test:8888', '/test:8888', array('http')),
);
['/test:8888', '/test:8888', ['http']],
];
}
/**
@ -469,11 +469,11 @@ class UrlHelperTest extends UnitTestCase {
* A list of provider data with schemes.
*/
protected function dataEnhanceWithScheme(array $urls) {
$url_schemes = array('http', 'https', 'ftp');
$data = array();
$url_schemes = ['http', 'https', 'ftp'];
$data = [];
foreach ($url_schemes as $scheme) {
foreach ($urls as $url) {
$data[] = array($url, $scheme);
$data[] = [$url, $scheme];
}
}
return $data;
@ -489,11 +489,11 @@ class UrlHelperTest extends UnitTestCase {
* A list of provider data with prefixes.
*/
protected function dataEnhanceWithPrefix(array $urls) {
$prefixes = array('', '/');
$data = array();
$prefixes = ['', '/'];
$data = [];
foreach ($prefixes as $prefix) {
foreach ($urls as $url) {
$data[] = array($url, $prefix);
$data[] = [$url, $prefix];
}
}
return $data;
@ -523,31 +523,31 @@ class UrlHelperTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\UrlHelperTest::testExternalIsLocal()
*/
public function providerTestExternalIsLocal() {
return array(
return [
// Different mixes of trailing slash.
array('http://example.com', 'http://example.com', TRUE),
array('http://example.com/', 'http://example.com', TRUE),
array('http://example.com', 'http://example.com/', TRUE),
array('http://example.com/', 'http://example.com/', TRUE),
['http://example.com', 'http://example.com', TRUE],
['http://example.com/', 'http://example.com', TRUE],
['http://example.com', 'http://example.com/', TRUE],
['http://example.com/', 'http://example.com/', TRUE],
// Sub directory of site.
array('http://example.com/foo', 'http://example.com/', TRUE),
array('http://example.com/foo/bar', 'http://example.com/foo', TRUE),
array('http://example.com/foo/bar', 'http://example.com/foo/', TRUE),
['http://example.com/foo', 'http://example.com/', TRUE],
['http://example.com/foo/bar', 'http://example.com/foo', TRUE],
['http://example.com/foo/bar', 'http://example.com/foo/', TRUE],
// Different sub-domain.
array('http://example.com', 'http://www.example.com/', FALSE),
array('http://example.com/', 'http://www.example.com/', FALSE),
array('http://example.com/foo', 'http://www.example.com/', FALSE),
['http://example.com', 'http://www.example.com/', FALSE],
['http://example.com/', 'http://www.example.com/', FALSE],
['http://example.com/foo', 'http://www.example.com/', FALSE],
// Different TLD.
array('http://example.com', 'http://example.ca', FALSE),
array('http://example.com', 'http://example.ca/', FALSE),
array('http://example.com/', 'http://example.ca/', FALSE),
array('http://example.com/foo', 'http://example.ca', FALSE),
array('http://example.com/foo', 'http://example.ca/', FALSE),
['http://example.com', 'http://example.ca', FALSE],
['http://example.com', 'http://example.ca/', FALSE],
['http://example.com/', 'http://example.ca/', FALSE],
['http://example.com/foo', 'http://example.ca', FALSE],
['http://example.com/foo', 'http://example.ca/', FALSE],
// Different site path.
array('http://example.com/foo', 'http://example.com/bar', FALSE),
array('http://example.com', 'http://example.com/bar', FALSE),
array('http://example.com/bar', 'http://example.com/bar/', FALSE),
);
['http://example.com/foo', 'http://example.com/bar', FALSE],
['http://example.com', 'http://example.com/bar', FALSE],
['http://example.com/bar', 'http://example.com/bar/', FALSE],
];
}
/**
@ -560,9 +560,9 @@ class UrlHelperTest extends UnitTestCase {
*
* @covers ::externalIsLocal
* @dataProvider providerTestExternalIsLocalInvalid
* @expectedException \InvalidArgumentException
*/
public function testExternalIsLocalInvalid($url, $base_url) {
$this->setExpectedException(\InvalidArgumentException::class);
UrlHelper::externalIsLocal($url, $base_url);
}
@ -572,17 +572,17 @@ class UrlHelperTest extends UnitTestCase {
* @see \Drupal\Tests\Component\Utility\UrlHelperTest::testExternalIsLocalInvalid()
*/
public function providerTestExternalIsLocalInvalid() {
return array(
array('http://example.com/foo', ''),
array('http://example.com/foo', 'bar'),
array('http://example.com/foo', 'http://'),
return [
['http://example.com/foo', ''],
['http://example.com/foo', 'bar'],
['http://example.com/foo', 'http://'],
// Invalid destination urls.
array('', 'http://example.com/foo'),
array('bar', 'http://example.com/foo'),
array('/bar', 'http://example.com/foo'),
array('bar/', 'http://example.com/foo'),
array('http://', 'http://example.com/foo'),
);
['', 'http://example.com/foo'],
['bar', 'http://example.com/foo'],
['/bar', 'http://example.com/foo'],
['bar/', 'http://example.com/foo'],
['http://', 'http://example.com/foo'],
];
}
}

View file

@ -21,7 +21,7 @@ class UserAgentTest extends UnitTestCase {
* Language codes, ordered by priority.
*/
protected function getLanguages() {
return array(
return [
// In our test case, 'en' has priority over 'en-US'.
'en',
'en-US',
@ -39,7 +39,7 @@ class UserAgentTest extends UnitTestCase {
'zh-hans',
'zh-hant',
'zh-hant-tw',
);
];
}
/**
@ -49,7 +49,7 @@ class UserAgentTest extends UnitTestCase {
* Language mappings.
*/
protected function getMappings() {
return array(
return [
'no' => 'nb',
'pt' => 'pt-pt',
'zh' => 'zh-hans',
@ -60,7 +60,7 @@ class UserAgentTest extends UnitTestCase {
'zh-cn' => 'zh-hans',
'zh-sg' => 'zh-hans',
'zh-chs' => 'zh-hans',
);
];
}
/**
@ -82,86 +82,86 @@ class UserAgentTest extends UnitTestCase {
* - Expected best matching language code.
*/
public function providerTestGetBestMatchingLangcode() {
return array(
return [
// Equal qvalue for each language, choose the site preferred one.
array('en,en-US,fr-CA,fr,es-MX', 'en'),
array('en-US,en,fr-CA,fr,es-MX', 'en'),
array('fr,en', 'en'),
array('en,fr', 'en'),
array('en-US,fr', 'en-US'),
array('fr,en-US', 'en-US'),
array('fr,fr-CA', 'fr-CA'),
array('fr-CA,fr', 'fr-CA'),
array('fr', 'fr-CA'),
array('fr;q=1', 'fr-CA'),
array('fr,es-MX', 'fr-CA'),
array('fr,es', 'fr-CA'),
array('es,fr', 'fr-CA'),
array('es-MX,de', 'es-MX'),
array('de,es-MX', 'es-MX'),
['en,en-US,fr-CA,fr,es-MX', 'en'],
['en-US,en,fr-CA,fr,es-MX', 'en'],
['fr,en', 'en'],
['en,fr', 'en'],
['en-US,fr', 'en-US'],
['fr,en-US', 'en-US'],
['fr,fr-CA', 'fr-CA'],
['fr-CA,fr', 'fr-CA'],
['fr', 'fr-CA'],
['fr;q=1', 'fr-CA'],
['fr,es-MX', 'fr-CA'],
['fr,es', 'fr-CA'],
['es,fr', 'fr-CA'],
['es-MX,de', 'es-MX'],
['de,es-MX', 'es-MX'],
// Different cases and whitespace.
array('en', 'en'),
array('En', 'en'),
array('EN', 'en'),
array(' en', 'en'),
array('en ', 'en'),
array('en, fr', 'en'),
['en', 'en'],
['En', 'en'],
['EN', 'en'],
[' en', 'en'],
['en ', 'en'],
['en, fr', 'en'],
// A less specific language from the browser matches a more specific one
// from the website, and the other way around for compatibility with
// some versions of Internet Explorer.
array('es', 'es-MX'),
array('es-MX', 'es-MX'),
array('pt', 'pt'),
array('pt-PT', 'pt'),
array('pt-PT;q=0.5,pt-BR;q=1,en;q=0.7', 'en'),
array('pt-PT;q=1,pt-BR;q=0.5,en;q=0.7', 'en'),
array('pt-PT;q=0.4,pt-BR;q=0.1,en;q=0.7', 'en'),
array('pt-PT;q=0.1,pt-BR;q=0.4,en;q=0.7', 'en'),
['es', 'es-MX'],
['es-MX', 'es-MX'],
['pt', 'pt'],
['pt-PT', 'pt'],
['pt-PT;q=0.5,pt-BR;q=1,en;q=0.7', 'en'],
['pt-PT;q=1,pt-BR;q=0.5,en;q=0.7', 'en'],
['pt-PT;q=0.4,pt-BR;q=0.1,en;q=0.7', 'en'],
['pt-PT;q=0.1,pt-BR;q=0.4,en;q=0.7', 'en'],
// Language code with several dashes are valid. The less specific language
// from the browser matches the more specific one from the website.
array('eh-oh-laa-laa', 'eh-oh-laa-laa'),
array('eh-oh-laa', 'eh-oh-laa-laa'),
array('eh-oh', 'eh-oh-laa-laa'),
array('eh', 'eh-oh-laa-laa'),
['eh-oh-laa-laa', 'eh-oh-laa-laa'],
['eh-oh-laa', 'eh-oh-laa-laa'],
['eh-oh', 'eh-oh-laa-laa'],
['eh', 'eh-oh-laa-laa'],
// Different qvalues.
array('fr,en;q=0.5', 'fr-CA'),
array('fr,en;q=0.5,fr-CA;q=0.25', 'fr'),
['fr,en;q=0.5', 'fr-CA'],
['fr,en;q=0.5,fr-CA;q=0.25', 'fr'],
// Silly wildcards are also valid.
array('*,fr-CA;q=0.5', 'en'),
array('*,en;q=0.25', 'fr-CA'),
array('en,en-US;q=0.5,fr;q=0.25', 'en'),
array('en-US,en;q=0.5,fr;q=0.25', 'en-US'),
['*,fr-CA;q=0.5', 'en'],
['*,en;q=0.25', 'fr-CA'],
['en,en-US;q=0.5,fr;q=0.25', 'en'],
['en-US,en;q=0.5,fr;q=0.25', 'en-US'],
// Unresolvable cases.
array('', FALSE),
array('de,pl', FALSE),
array('iecRswK4eh', FALSE),
array($this->randomMachineName(10), FALSE),
['', FALSE],
['de,pl', FALSE],
['iecRswK4eh', FALSE],
[$this->randomMachineName(10), FALSE],
// Chinese langcodes.
array('zh-cn, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hans'),
array('zh-tw, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'),
array('zh-hant, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'),
array('zh-hans, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hans'),
['zh-cn, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hans'],
['zh-tw, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'],
['zh-hant, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'],
['zh-hans, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hans'],
// @todo: This is copied from RFC4647 but our regex skips the numbers so
// they where removed. Our code should be updated so private1-private2 is
// valid. http://tools.ietf.org/html/rfc4647#section-3.4
array('zh-hant-CN-x-private-private, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'),
array('zh-cn', 'zh-hans'),
array('zh-sg', 'zh-hans'),
array('zh-tw', 'zh-hant'),
array('zh-hk', 'zh-hant'),
array('zh-mo', 'zh-hant'),
array('zh-hans', 'zh-hans'),
array('zh-hant', 'zh-hant'),
array('zh-chs', 'zh-hans'),
array('zh-cht', 'zh-hant'),
);
['zh-hant-CN-x-private-private, en-us;q=0.90, en;q=0.80, zh;q=0.70', 'zh-hant'],
['zh-cn', 'zh-hans'],
['zh-sg', 'zh-hans'],
['zh-tw', 'zh-hant'],
['zh-hk', 'zh-hant'],
['zh-mo', 'zh-hant'],
['zh-hans', 'zh-hans'],
['zh-hant', 'zh-hant'],
['zh-chs', 'zh-hans'],
['zh-cht', 'zh-hant'],
];
}
}

View file

@ -29,72 +29,72 @@ class VariableTest extends UnitTestCase {
* - The variable to export.
*/
public function providerTestExport() {
return array(
return [
// Array.
array(
[
'array()',
array(),
),
array(
[],
],
[
// non-associative.
"array(\n 1,\n 2,\n 3,\n 4,\n)",
array(1, 2, 3, 4),
),
array(
[1, 2, 3, 4],
],
[
// associative.
"array(\n 'a' => 1,\n)",
array('a' => 1),
),
['a' => 1],
],
// Bool.
array(
[
'TRUE',
TRUE,
),
array(
],
[
'FALSE',
FALSE,
),
],
// Strings.
array(
[
"'string'",
'string',
),
array(
],
[
'"\n\r\t"',
"\n\r\t",
),
array(
],
[
// 2 backslashes. \\
"'\\'",
'\\',
),
array(
],
[
// Double-quote "
"'\"'",
"\"",
),
array(
],
[
// Single-quote '
'"\'"',
"'",
),
array(
],
[
// Quotes with $ symbols.
'"\$settings[\'foo\']"',
'$settings[\'foo\']',
),
],
// Object.
array(
[
// A stdClass object.
'(object) array()',
new \stdClass(),
),
array(
],
[
// A not-stdClass object.
"Drupal\Tests\Component\Utility\StubVariableTestClass::__set_state(array(\n))",
new StubVariableTestClass(),
),
);
],
];
}
/**

View file

@ -28,7 +28,7 @@ class XssTest extends UnitTestCase {
protected function setUp() {
parent::setUp();
$allowed_protocols = array(
$allowed_protocols = [
'http',
'https',
'ftp',
@ -41,7 +41,7 @@ class XssTest extends UnitTestCase {
'sftp',
'webcal',
'rtsp',
);
];
UrlHelper::setAllowedProtocols($allowed_protocols);
}
@ -86,30 +86,30 @@ class XssTest extends UnitTestCase {
* \Drupal\Component\Utility\Xss::filter().
*/
public function providerTestFilterXssNormalized() {
return array(
array(
return [
[
"Who&#039;s Online",
"who's online",
'HTML filter -- html entity number',
),
array(
],
[
"Who&amp;#039;s Online",
"who&#039;s online",
'HTML filter -- encoded html entity number',
),
array(
],
[
"Who&amp;amp;#039; Online",
"who&amp;#039; online",
'HTML filter -- double encoded html entity number',
),
],
// Custom elements with dashes in the tag name.
array(
[
"<test-element></test-element>",
"<test-element></test-element>",
'Custom element with dashes in tag name.',
array('test-element'),
),
);
['test-element'],
],
];
}
/**
@ -153,289 +153,289 @@ class XssTest extends UnitTestCase {
* \Drupal\Component\Utility\Xss::filter().
*/
public function providerTestFilterXssNotNormalized() {
$cases = array(
$cases = [
// Tag stripping, different ways to work around removal of HTML tags.
array(
[
'<script>alert(0)</script>',
'script',
'HTML tag stripping -- simple script without special characters.',
),
array(
],
[
'<script src="http://www.example.com" />',
'script',
'HTML tag stripping -- empty script with source.',
),
array(
],
[
'<ScRipt sRc=http://www.example.com/>',
'script',
'HTML tag stripping evasion -- varying case.',
),
array(
],
[
"<script\nsrc\n=\nhttp://www.example.com/\n>",
'script',
'HTML tag stripping evasion -- multiline tag.',
),
array(
],
[
'<script/a src=http://www.example.com/a.js></script>',
'script',
'HTML tag stripping evasion -- non whitespace character after tag name.',
),
array(
],
[
'<script/src=http://www.example.com/a.js></script>',
'script',
'HTML tag stripping evasion -- no space between tag and attribute.',
),
],
// Null between < and tag name works at least with IE6.
array(
[
"<\0scr\0ipt>alert(0)</script>",
'ipt',
'HTML tag stripping evasion -- breaking HTML with nulls.',
),
array(
],
[
"<scrscriptipt src=http://www.example.com/a.js>",
'script',
'HTML tag stripping evasion -- filter just removing "script".',
),
array(
],
[
'<<script>alert(0);//<</script>',
'script',
'HTML tag stripping evasion -- double opening brackets.',
),
array(
],
[
'<script src=http://www.example.com/a.js?<b>',
'script',
'HTML tag stripping evasion -- no closing tag.',
),
],
// DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
// work consistently.
array(
[
'<script>>',
'script',
'HTML tag stripping evasion -- double closing tag.',
),
array(
],
[
'<script src=//www.example.com/.a>',
'script',
'HTML tag stripping evasion -- no scheme or ending slash.',
),
array(
],
[
'<script src=http://www.example.com/.a',
'script',
'HTML tag stripping evasion -- no closing bracket.',
),
array(
],
[
'<script src=http://www.example.com/ <',
'script',
'HTML tag stripping evasion -- opening instead of closing bracket.',
),
array(
],
[
'<nosuchtag attribute="newScriptInjectionVector">',
'nosuchtag',
'HTML tag stripping evasion -- unknown tag.',
),
array(
],
[
'<t:set attributeName="innerHTML" to="&lt;script defer&gt;alert(0)&lt;/script&gt;">',
't:set',
'HTML tag stripping evasion -- colon in the tag name (namespaces\' tricks).',
),
array(
],
[
'<img """><script>alert(0)</script>',
'script',
'HTML tag stripping evasion -- a malformed image tag.',
array('img'),
),
array(
['img'],
],
[
'<blockquote><script>alert(0)</script></blockquote>',
'script',
'HTML tag stripping evasion -- script in a blockqoute.',
array('blockquote'),
),
array(
['blockquote'],
],
[
"<!--[if true]><script>alert(0)</script><![endif]-->",
'script',
'HTML tag stripping evasion -- script within a comment.',
),
],
// Dangerous attributes removal.
array(
[
'<p onmouseover="http://www.example.com/">',
'onmouseover',
'HTML filter attributes removal -- events, no evasion.',
array('p'),
),
array(
['p'],
],
[
'<li style="list-style-image: url(javascript:alert(0))">',
'style',
'HTML filter attributes removal -- style, no evasion.',
array('li'),
),
array(
['li'],
],
[
'<img onerror =alert(0)>',
'onerror',
'HTML filter attributes removal evasion -- spaces before equals sign.',
array('img'),
),
array(
['img'],
],
[
'<img onabort!#$%&()*~+-_.,:;?@[/|\]^`=alert(0)>',
'onabort',
'HTML filter attributes removal evasion -- non alphanumeric characters before equals sign.',
array('img'),
),
array(
['img'],
],
[
'<img oNmediAError=alert(0)>',
'onmediaerror',
'HTML filter attributes removal evasion -- varying case.',
array('img'),
),
['img'],
],
// Works at least with IE6.
array(
[
"<img o\0nfocus\0=alert(0)>",
'focus',
'HTML filter attributes removal evasion -- breaking with nulls.',
array('img'),
),
['img'],
],
// Only whitelisted scheme names allowed in attributes.
array(
[
'<img src="javascript:alert(0)">',
'javascript',
'HTML scheme clearing -- no evasion.',
array('img'),
),
array(
['img'],
],
[
'<img src=javascript:alert(0)>',
'javascript',
'HTML scheme clearing evasion -- no quotes.',
array('img'),
),
['img'],
],
// A bit like CVE-2006-0070.
array(
[
'<img src="javascript:confirm(0)">',
'javascript',
'HTML scheme clearing evasion -- no alert ;)',
array('img'),
),
array(
['img'],
],
[
'<img src=`javascript:alert(0)`>',
'javascript',
'HTML scheme clearing evasion -- grave accents.',
array('img'),
),
array(
['img'],
],
[
'<img dynsrc="javascript:alert(0)">',
'javascript',
'HTML scheme clearing -- rare attribute.',
array('img'),
),
array(
['img'],
],
[
'<table background="javascript:alert(0)">',
'javascript',
'HTML scheme clearing -- another tag.',
array('table'),
),
array(
['table'],
],
[
'<base href="javascript:alert(0);//">',
'javascript',
'HTML scheme clearing -- one more attribute and tag.',
array('base'),
),
array(
['base'],
],
[
'<img src="jaVaSCriPt:alert(0)">',
'javascript',
'HTML scheme clearing evasion -- varying case.',
array('img'),
),
array(
['img'],
],
[
'<img src=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#48;&#41;>',
'javascript',
'HTML scheme clearing evasion -- UTF-8 decimal encoding.',
array('img'),
),
array(
['img'],
],
[
'<img src=&#00000106&#0000097&#00000118&#0000097&#00000115&#0000099&#00000114&#00000105&#00000112&#00000116&#0000058&#0000097&#00000108&#00000101&#00000114&#00000116&#0000040&#0000048&#0000041>',
'javascript',
'HTML scheme clearing evasion -- long UTF-8 encoding.',
array('img'),
),
array(
['img'],
],
[
'<img src=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x30&#x29>',
'javascript',
'HTML scheme clearing evasion -- UTF-8 hex encoding.',
array('img'),
),
array(
['img'],
],
[
"<img src=\"jav\tascript:alert(0)\">",
'script',
'HTML scheme clearing evasion -- an embedded tab.',
array('img'),
),
array(
['img'],
],
[
'<img src="jav&#x09;ascript:alert(0)">',
'script',
'HTML scheme clearing evasion -- an encoded, embedded tab.',
array('img'),
),
array(
['img'],
],
[
'<img src="jav&#x000000A;ascript:alert(0)">',
'script',
'HTML scheme clearing evasion -- an encoded, embedded newline.',
array('img'),
),
['img'],
],
// With &#xD; this test would fail, but the entity gets turned into
// &amp;#xD;, so it's OK.
array(
[
'<img src="jav&#x0D;ascript:alert(0)">',
'script',
'HTML scheme clearing evasion -- an encoded, embedded carriage return.',
array('img'),
),
array(
['img'],
],
[
"<img src=\"\n\n\nj\na\nva\ns\ncript:alert(0)\">",
'cript',
'HTML scheme clearing evasion -- broken into many lines.',
array('img'),
),
array(
['img'],
],
[
"<img src=\"jav\0a\0\0cript:alert(0)\">",
'cript',
'HTML scheme clearing evasion -- embedded nulls.',
array('img'),
),
array(
['img'],
],
[
'<img src="vbscript:msgbox(0)">',
'vbscript',
'HTML scheme clearing evasion -- another scheme.',
array('img'),
),
array(
['img'],
],
[
'<img src="nosuchscheme:notice(0)">',
'nosuchscheme',
'HTML scheme clearing evasion -- unknown scheme.',
array('img'),
),
['img'],
],
// Netscape 4.x javascript entities.
array(
[
'<br size="&{alert(0)}">',
'alert',
'Netscape 4.x javascript entities.',
array('br'),
),
['br'],
],
// DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
// Internet Explorer 6.
array(
[
"<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>",
'style',
'HTML filter -- invalid UTF-8.',
array('p'),
),
);
['p'],
],
];
// @fixme This dataset currently fails under 5.4 because of
// https://www.drupal.org/node/1210798. Restore after its fixed.
if (version_compare(PHP_VERSION, '5.4.0', '<')) {
$cases[] = array(
$cases[] = [
'<img src=" &#14; javascript:alert(0)">',
'javascript',
'HTML scheme clearing evasion -- spaces and metacharacters before scheme.',
array('img'),
);
['img'],
];
}
return $cases;
}
@ -468,11 +468,11 @@ class XssTest extends UnitTestCase {
* - The assertion message.
*/
public function providerTestInvalidMultiByte() {
return array(
array("Foo\xC0barbaz", '', 'Xss::filter() accepted invalid sequence "Foo\xC0barbaz"'),
array("Fooÿñ", "Fooÿñ", 'Xss::filter() rejects valid sequence Fooÿñ"'),
array("\xc0aaa", '', 'HTML filter -- overlong UTF-8 sequences.'),
);
return [
["Foo\xC0barbaz", '', 'Xss::filter() accepted invalid sequence "Foo\xC0barbaz"'],
["Fooÿñ", "Fooÿñ", 'Xss::filter() rejects valid sequence Fooÿñ"'],
["\xc0aaa", '', 'HTML filter -- overlong UTF-8 sequences.'],
];
}
/**
@ -498,38 +498,38 @@ class XssTest extends UnitTestCase {
* Data provider for testFilterXssAdminNotNormalized().
*/
public function providerTestAttributes() {
return array(
array(
return [
[
'<img src="http://example.com/foo.jpg" title="Example: title" alt="Example: alt">',
'<img src="http://example.com/foo.jpg" title="Example: title" alt="Example: alt">',
'Image tag with alt and title attribute',
array('img')
),
array(
['img']
],
[
'<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(
['a']
],
[
'<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(
['span']
],
[
'<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.">',
'Image tag with data attribute',
array('img')
),
array(
['img']
],
[
'<a data-a2a-url="foo"></a>',
'<a data-a2a-url="foo"></a>',
'Link tag with numeric data attribute',
array('a')
),
);
['a']
],
];
}
/**
@ -568,11 +568,11 @@ class XssTest extends UnitTestCase {
* - The assertion message.
*/
public function providerTestFilterXssAdminNotNormalized() {
return array(
return [
// DRUPAL-SA-2008-044
array('<object />', 'object', 'Admin HTML filter -- should not allow object tag.'),
array('<script />', 'script', 'Admin HTML filter -- should not allow script tag.'),
);
['<object />', 'object', 'Admin HTML filter -- should not allow object tag.'],
['<script />', 'script', 'Admin HTML filter -- should not allow script tag.'],
];
}
/**

View file

@ -41,7 +41,7 @@ class UuidTest extends UnitTestCase {
*/
public function providerUuidInstances() {
$instances = array();
$instances = [];
$instances[][] = new Php();
// If valid PECL extensions exists add to list.
@ -83,15 +83,15 @@ class UuidTest extends UnitTestCase {
* - Failure message.
*/
public function providerTestValidation() {
return array(
return [
// These valid UUIDs.
array('6ba7b810-9dad-11d1-80b4-00c04fd430c8', TRUE, 'Basic FQDN UUID did not validate'),
array('00000000-0000-0000-0000-000000000000', TRUE, 'Minimum UUID did not validate'),
array('ffffffff-ffff-ffff-ffff-ffffffffffff', TRUE, 'Maximum UUID did not validate'),
['6ba7b810-9dad-11d1-80b4-00c04fd430c8', TRUE, 'Basic FQDN UUID did not validate'],
['00000000-0000-0000-0000-000000000000', TRUE, 'Minimum UUID did not validate'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', TRUE, 'Maximum UUID did not validate'],
// These are invalid UUIDs.
array('0ab26e6b-f074-4e44-9da-601205fa0e976', FALSE, 'Invalid format was validated'),
array('0ab26e6b-f074-4e44-9daf-1205fa0e9761f', FALSE, 'Invalid length was validated'),
);
['0ab26e6b-f074-4e44-9da-601205fa0e976', FALSE, 'Invalid format was validated'],
['0ab26e6b-f074-4e44-9daf-1205fa0e9761f', FALSE, 'Invalid length was validated'],
];
}
}

View file

@ -8,6 +8,7 @@
namespace Drupal\Tests\Core\Access;
use Drupal\Core\Access\AccessCheckInterface;
use Drupal\Core\Access\AccessException;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Access\CheckProvider;
use Drupal\Core\Cache\Context\CacheContextsManager;
@ -100,25 +101,25 @@ class AccessManagerTest extends UnitTestCase {
$this->routeCollection = new RouteCollection();
$this->routeCollection->add('test_route_1', new Route('/test-route-1'));
$this->routeCollection->add('test_route_2', new Route('/test-route-2', array(), array('_access' => 'TRUE')));
$this->routeCollection->add('test_route_3', new Route('/test-route-3', array(), array('_access' => 'FALSE')));
$this->routeCollection->add('test_route_4', new Route('/test-route-4/{value}', array(), array('_access' => 'TRUE')));
$this->routeCollection->add('test_route_2', new Route('/test-route-2', [], ['_access' => 'TRUE']));
$this->routeCollection->add('test_route_3', new Route('/test-route-3', [], ['_access' => 'FALSE']));
$this->routeCollection->add('test_route_4', new Route('/test-route-4/{value}', [], ['_access' => 'TRUE']));
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$map = array();
$map = [];
foreach ($this->routeCollection->all() as $name => $route) {
$map[] = array($name, array(), $route);
$map[] = [$name, [], $route];
}
$map[] = array('test_route_4', array('value' => 'example'), $this->routeCollection->get('test_route_4'));
$map[] = ['test_route_4', ['value' => 'example'], $this->routeCollection->get('test_route_4')];
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->will($this->returnValueMap($map));
$map = array();
$map[] = array('test_route_1', array(), '/test-route-1');
$map[] = array('test_route_2', array(), '/test-route-2');
$map[] = array('test_route_3', array(), '/test-route-3');
$map[] = array('test_route_4', array('value' => 'example'), '/test-route-4/example');
$map = [];
$map[] = ['test_route_1', [], '/test-route-1'];
$map[] = ['test_route_2', [], '/test-route-2'];
$map[] = ['test_route_3', [], '/test-route-3'];
$map[] = ['test_route_4', ['value' => 'example'], '/test-route-4/example'];
$this->paramConverter = $this->getMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
@ -147,8 +148,8 @@ class AccessManagerTest extends UnitTestCase {
$this->checkProvider->setChecks($this->routeCollection);
$this->assertEquals($this->routeCollection->get('test_route_1')->getOption('_access_checks'), NULL);
$this->assertEquals($this->routeCollection->get('test_route_2')->getOption('_access_checks'), array('test_access_default'));
$this->assertEquals($this->routeCollection->get('test_route_3')->getOption('_access_checks'), array('test_access_default'));
$this->assertEquals($this->routeCollection->get('test_route_2')->getOption('_access_checks'), ['test_access_default']);
$this->assertEquals($this->routeCollection->get('test_route_3')->getOption('_access_checks'), ['test_access_default']);
}
/**
@ -163,8 +164,8 @@ class AccessManagerTest extends UnitTestCase {
$this->container->set('test_access', $access_check);
$this->checkProvider->addCheckService('test_access', 'access');
$route = new Route('/test-path', array(), array('_foo' => '1', '_bar' => '1'));
$route2 = new Route('/test-path', array(), array('_foo' => '1', '_bar' => '2'));
$route = new Route('/test-path', [], ['_foo' => '1', '_bar' => '1']);
$route2 = new Route('/test-path', [], ['_foo' => '1', '_bar' => '2']);
$collection = new RouteCollection();
$collection->add('test_route', $route);
$collection->add('test_route2', $route2);
@ -178,7 +179,7 @@ class AccessManagerTest extends UnitTestCase {
$this->checkProvider->setChecks($collection);
$this->assertEmpty($route->getOption('_access_checks'));
$this->assertEquals(array('test_access'), $route2->getOption('_access_checks'));
$this->assertEquals(['test_access'], $route2->getOption('_access_checks'));
}
/**
@ -254,43 +255,43 @@ class AccessManagerTest extends UnitTestCase {
$access_deny = AccessResult::neutral();
$access_kill = AccessResult::forbidden();
$access_configurations = array();
$access_configurations[] = array(
$access_configurations = [];
$access_configurations[] = [
'name' => 'test_route_4',
'condition_one' => 'TRUE',
'condition_two' => 'FALSE',
'expected' => $access_kill,
);
$access_configurations[] = array(
];
$access_configurations[] = [
'name' => 'test_route_5',
'condition_one' => 'TRUE',
'condition_two' => 'NULL',
'expected' => $access_deny,
);
$access_configurations[] = array(
];
$access_configurations[] = [
'name' => 'test_route_6',
'condition_one' => 'FALSE',
'condition_two' => 'NULL',
'expected' => $access_kill,
);
$access_configurations[] = array(
];
$access_configurations[] = [
'name' => 'test_route_7',
'condition_one' => 'TRUE',
'condition_two' => 'TRUE',
'expected' => $access_allow,
);
$access_configurations[] = array(
];
$access_configurations[] = [
'name' => 'test_route_8',
'condition_one' => 'FALSE',
'condition_two' => 'FALSE',
'expected' => $access_kill,
);
$access_configurations[] = array(
];
$access_configurations[] = [
'name' => 'test_route_9',
'condition_one' => 'NULL',
'condition_two' => 'NULL',
'expected' => $access_deny,
);
];
return $access_configurations;
}
@ -304,21 +305,21 @@ class AccessManagerTest extends UnitTestCase {
$this->setupAccessChecker();
$access_check = new DefinedTestAccessCheck();
$this->container->register('test_access_defined', $access_check);
$this->checkProvider->addCheckService('test_access_defined', 'access', array('_test_access'));
$this->checkProvider->addCheckService('test_access_defined', 'access', ['_test_access']);
$route_collection = new RouteCollection();
// Setup a test route for each access configuration.
$requirements = array(
$requirements = [
'_access' => $condition_one,
'_test_access' => $condition_two,
);
$route = new Route($name, array(), $requirements);
];
$route = new Route($name, [], $requirements);
$route_collection->add($name, $route);
$this->checkProvider->setChecks($route_collection);
$this->setupAccessArgumentsResolverFactory();
$route_match = new RouteMatch($name, $route, array(), array());
$route_match = new RouteMatch($name, $route, [], []);
$this->assertEquals($expected_access->isAllowed(), $this->accessManager->check($route_match, $this->account));
$this->assertEquals($expected_access, $this->accessManager->check($route_match, $this->account, NULL, TRUE));
}
@ -335,27 +336,27 @@ class AccessManagerTest extends UnitTestCase {
$this->paramConverter->expects($this->at(0))
->method('convert')
->with(array(RouteObjectInterface::ROUTE_NAME => 'test_route_2', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_2')))
->will($this->returnValue(array()));
->with([RouteObjectInterface::ROUTE_NAME => 'test_route_2', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_2')])
->will($this->returnValue([]));
$this->paramConverter->expects($this->at(1))
->method('convert')
->with(array(RouteObjectInterface::ROUTE_NAME => 'test_route_2', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_2')))
->will($this->returnValue(array()));
->with([RouteObjectInterface::ROUTE_NAME => 'test_route_2', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_2')])
->will($this->returnValue([]));
$this->paramConverter->expects($this->at(2))
->method('convert')
->with(array('value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_4', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_4')))
->will($this->returnValue(array('value' => 'example')));
->with(['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_4', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_4')])
->will($this->returnValue(['value' => 'example']));
$this->paramConverter->expects($this->at(3))
->method('convert')
->with(array('value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_4', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_4')))
->will($this->returnValue(array('value' => 'example')));
->with(['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_4', RouteObjectInterface::ROUTE_OBJECT => $this->routeCollection->get('test_route_4')])
->will($this->returnValue(['value' => 'example']));
// Tests the access with routes with parameters without given request.
$this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_2', array(), $this->account));
$this->assertEquals(AccessResult::allowed(), $this->accessManager->checkNamedRoute('test_route_2', array(), $this->account, TRUE));
$this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_4', array('value' => 'example'), $this->account));
$this->assertEquals(AccessResult::allowed(), $this->accessManager->checkNamedRoute('test_route_4', array('value' => 'example'), $this->account, TRUE));
$this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_2', [], $this->account));
$this->assertEquals(AccessResult::allowed(), $this->accessManager->checkNamedRoute('test_route_2', [], $this->account, TRUE));
$this->assertEquals(TRUE, $this->accessManager->checkNamedRoute('test_route_4', ['value' => 'example'], $this->account));
$this->assertEquals(AccessResult::allowed(), $this->accessManager->checkNamedRoute('test_route_4', ['value' => 'example'], $this->account, TRUE));
}
/**
@ -365,23 +366,23 @@ class AccessManagerTest extends UnitTestCase {
*/
public function testCheckNamedRouteWithUpcastedValues() {
$this->routeCollection = new RouteCollection();
$route = new Route('/test-route-1/{value}', array(), array('_test_access' => 'TRUE'));
$route = new Route('/test-route-1/{value}', [], ['_test_access' => 'TRUE']);
$this->routeCollection->add('test_route_1', $route);
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->with('test_route_1', array('value' => 'example'))
->with('test_route_1', ['value' => 'example'])
->will($this->returnValue($route));
$map = array();
$map[] = array('test_route_1', array('value' => 'example'), '/test-route-1/example');
$map = [];
$map[] = ['test_route_1', ['value' => 'example'], '/test-route-1/example'];
$this->paramConverter = $this->getMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
$this->paramConverter->expects($this->atLeastOnce())
->method('convert')
->with(array('value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_1', RouteObjectInterface::ROUTE_OBJECT => $route))
->will($this->returnValue(array('value' => 'upcasted_value')));
->with(['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_1', RouteObjectInterface::ROUTE_OBJECT => $route])
->will($this->returnValue(['value' => 'upcasted_value']));
$this->setupAccessArgumentsResolverFactory($this->exactly(2))
->with($this->callback(function ($route_match) {
@ -403,8 +404,8 @@ class AccessManagerTest extends UnitTestCase {
$this->checkProvider->addCheckService('test_access', 'access');
$this->checkProvider->setChecks($this->routeCollection);
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', array('value' => 'example'), $this->account));
$this->assertEquals(AccessResult::forbidden(), $this->accessManager->checkNamedRoute('test_route_1', array('value' => 'example'), $this->account, TRUE));
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', ['value' => 'example'], $this->account));
$this->assertEquals(AccessResult::forbidden(), $this->accessManager->checkNamedRoute('test_route_1', ['value' => 'example'], $this->account, TRUE));
}
/**
@ -414,23 +415,23 @@ class AccessManagerTest extends UnitTestCase {
*/
public function testCheckNamedRouteWithDefaultValue() {
$this->routeCollection = new RouteCollection();
$route = new Route('/test-route-1/{value}', array('value' => 'example'), array('_test_access' => 'TRUE'));
$route = new Route('/test-route-1/{value}', ['value' => 'example'], ['_test_access' => 'TRUE']);
$this->routeCollection->add('test_route_1', $route);
$this->routeProvider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
$this->routeProvider->expects($this->any())
->method('getRouteByName')
->with('test_route_1', array())
->with('test_route_1', [])
->will($this->returnValue($route));
$map = array();
$map[] = array('test_route_1', array('value' => 'example'), '/test-route-1/example');
$map = [];
$map[] = ['test_route_1', ['value' => 'example'], '/test-route-1/example'];
$this->paramConverter = $this->getMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
$this->paramConverter->expects($this->atLeastOnce())
->method('convert')
->with(array('value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_1', RouteObjectInterface::ROUTE_OBJECT => $route))
->will($this->returnValue(array('value' => 'upcasted_value')));
->with(['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_1', RouteObjectInterface::ROUTE_OBJECT => $route])
->will($this->returnValue(['value' => 'upcasted_value']));
$this->setupAccessArgumentsResolverFactory($this->exactly(2))
->with($this->callback(function ($route_match) {
@ -452,8 +453,8 @@ class AccessManagerTest extends UnitTestCase {
$this->checkProvider->addCheckService('test_access', 'access');
$this->checkProvider->setChecks($this->routeCollection);
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', array(), $this->account));
$this->assertEquals(AccessResult::forbidden(), $this->accessManager->checkNamedRoute('test_route_1', array(), $this->account, TRUE));
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', [], $this->account));
$this->assertEquals(AccessResult::forbidden(), $this->accessManager->checkNamedRoute('test_route_1', [], $this->account, TRUE));
}
/**
@ -466,30 +467,28 @@ class AccessManagerTest extends UnitTestCase {
$this->setupAccessChecker();
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', array(), $this->account), 'A non existing route lead to access.');
$this->assertEquals(AccessResult::forbidden()->addCacheTags(['config:core.extension']), $this->accessManager->checkNamedRoute('test_route_1', array(), $this->account, TRUE), 'A non existing route lead to access.');
$this->assertEquals(FALSE, $this->accessManager->checkNamedRoute('test_route_1', [], $this->account), 'A non existing route lead to access.');
$this->assertEquals(AccessResult::forbidden()->addCacheTags(['config:core.extension']), $this->accessManager->checkNamedRoute('test_route_1', [], $this->account, TRUE), 'A non existing route lead to access.');
}
/**
* Tests that an access checker throws an exception for not allowed values.
*
* @dataProvider providerCheckException
*
* @expectedException \Drupal\Core\Access\AccessException
*/
public function testCheckException($return_value) {
$route_provider = $this->getMock('Drupal\Core\Routing\RouteProviderInterface');
// Setup a test route for each access configuration.
$requirements = array(
$requirements = [
'_test_incorrect_value' => 'TRUE',
);
$options = array(
'_access_checks' => array(
];
$options = [
'_access_checks' => [
'test_incorrect_value',
),
);
$route = new Route('', array(), $requirements, $options);
],
];
$route = new Route('', [], $requirements, $options);
$route_provider->expects($this->any())
->method('getRouteByName')
@ -498,7 +497,7 @@ class AccessManagerTest extends UnitTestCase {
$this->paramConverter = $this->getMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
$this->paramConverter->expects($this->any())
->method('convert')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$this->setupAccessArgumentsResolverFactory();
@ -515,7 +514,8 @@ class AccessManagerTest extends UnitTestCase {
$this->checkProvider->setContainer($container);
$this->checkProvider->addCheckService('test_incorrect_value', 'access');
$access_manager->checkNamedRoute('test_incorrect_value', array(), $this->account);
$this->setExpectedException(AccessException::class);
$access_manager->checkNamedRoute('test_incorrect_value', [], $this->account);
}
/**
@ -524,12 +524,12 @@ class AccessManagerTest extends UnitTestCase {
* @return array
*/
public function providerCheckException() {
return array(
array(array(1)),
array('string'),
array(0),
array(1),
);
return [
[[1]],
['string'],
[0],
[1],
];
}
/**
@ -538,7 +538,7 @@ class AccessManagerTest extends UnitTestCase {
protected function setupAccessChecker() {
$access_check = new DefaultAccessCheck();
$this->container->register('test_access_default', $access_check);
$this->checkProvider->addCheckService('test_access_default', 'access', array('_access'));
$this->checkProvider->addCheckService('test_access_default', 'access', ['_access']);
}
/**
@ -555,7 +555,7 @@ class AccessManagerTest extends UnitTestCase {
$resolver->expects($this->any())
->method('getArguments')
->will($this->returnCallback(function ($callable) use ($route_match) {
return array($route_match->getRouteObject());
return [$route_match->getRouteObject()];
}));
return $resolver;
}));

View file

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

View file

@ -174,9 +174,9 @@ class AccessResultTest extends UnitTestCase {
* @covers ::andIf
*/
public function testAndIf() {
$neutral = AccessResult::neutral();
$neutral = AccessResult::neutral('neutral message');
$allowed = AccessResult::allowed();
$forbidden = AccessResult::forbidden();
$forbidden = AccessResult::forbidden('forbidden message');
$unused_access_result_due_to_lazy_evaluation = $this->getMock('\Drupal\Core\Access\AccessResultInterface');
$unused_access_result_due_to_lazy_evaluation->expects($this->never())
->method($this->anything());
@ -193,6 +193,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertFalse($access->isForbidden());
$this->assertTrue($access->isNeutral());
$this->assertEquals('neutral message', $access->getReason());
$this->assertDefaultCacheability($access);
// ALLOWED && FORBIDDEN === FORBIDDEN.
@ -200,6 +201,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// NEUTRAL && ALLOW == NEUTRAL
@ -207,6 +209,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertFalse($access->isForbidden());
$this->assertTrue($access->isNeutral());
$this->assertEquals('neutral message', $access->getReason());
$this->assertDefaultCacheability($access);
// NEUTRAL && NEUTRAL === NEUTRAL.
@ -214,6 +217,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertFalse($access->isForbidden());
$this->assertTrue($access->isNeutral());
$this->assertEquals('neutral message', $access->getReason());
$this->assertDefaultCacheability($access);
// NEUTRAL && FORBIDDEN === FORBIDDEN.
@ -221,6 +225,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN && ALLOWED = FORBIDDEN
@ -228,6 +233,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN && NEUTRAL = FORBIDDEN
@ -235,6 +241,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN && FORBIDDEN = FORBIDDEN
@ -242,6 +249,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN && * === FORBIDDEN: lazy evaluation verification.
@ -249,6 +257,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
}
@ -256,9 +265,9 @@ class AccessResultTest extends UnitTestCase {
* @covers ::orIf
*/
public function testOrIf() {
$neutral = AccessResult::neutral();
$neutral = AccessResult::neutral('neutral message');
$allowed = AccessResult::allowed();
$forbidden = AccessResult::forbidden();
$forbidden = AccessResult::forbidden('forbidden message');
$unused_access_result_due_to_lazy_evaluation = $this->getMock('\Drupal\Core\Access\AccessResultInterface');
$unused_access_result_due_to_lazy_evaluation->expects($this->never())
->method($this->anything());
@ -282,6 +291,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// NEUTRAL || NEUTRAL === NEUTRAL.
@ -289,6 +299,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertFalse($access->isForbidden());
$this->assertTrue($access->isNeutral());
$this->assertEquals('neutral message', $access->getReason());
$this->assertDefaultCacheability($access);
// NEUTRAL || ALLOWED === ALLOWED.
@ -303,6 +314,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN || ALLOWED === FORBIDDEN.
@ -310,6 +322,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN || NEUTRAL === FORBIDDEN.
@ -317,6 +330,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN || FORBIDDEN === FORBIDDEN.
@ -324,6 +338,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
// FORBIDDEN || * === FORBIDDEN.
@ -331,6 +346,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertFalse($access->isAllowed());
$this->assertTrue($access->isForbidden());
$this->assertFalse($access->isNeutral());
$this->assertEquals('forbidden message', $access->getReason());
$this->assertDefaultCacheability($access);
}
@ -381,7 +397,7 @@ class AccessResultTest extends UnitTestCase {
$verify($access, ['bar', 'foo']);
// ::cachePerPermissions() convenience method.
$contexts = array('user.permissions');
$contexts = ['user.permissions'];
$a = AccessResult::neutral()->addCacheContexts($contexts);
$verify($a, $contexts);
$b = AccessResult::neutral()->cachePerPermissions();
@ -389,7 +405,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertEquals($a, $b);
// ::cachePerUser() convenience method.
$contexts = array('user');
$contexts = ['user'];
$a = AccessResult::neutral()->addCacheContexts($contexts);
$verify($a, $contexts);
$b = AccessResult::neutral()->cachePerUser();
@ -397,7 +413,7 @@ class AccessResultTest extends UnitTestCase {
$this->assertEquals($a, $b);
// Both.
$contexts = array('user', 'user.permissions');
$contexts = ['user', 'user.permissions'];
$a = AccessResult::neutral()->addCacheContexts($contexts);
$verify($a, $contexts);
$b = AccessResult::neutral()->cachePerPermissions()->cachePerUser();
@ -413,7 +429,7 @@ class AccessResultTest extends UnitTestCase {
->method('hasPermission')
->with('may herd llamas')
->will($this->returnValue(FALSE));
$contexts = array('user.permissions');
$contexts = ['user.permissions'];
// Verify the object when using the ::allowedIfHasPermission() convenience
// static method.
@ -464,14 +480,14 @@ class AccessResultTest extends UnitTestCase {
$node = $this->getMock('\Drupal\node\NodeInterface');
$node->expects($this->any())
->method('getCacheTags')
->will($this->returnValue(array('node:20011988')));
->will($this->returnValue(['node:20011988']));
$node->expects($this->any())
->method('getCacheMaxAge')
->willReturn(600);
$node->expects($this->any())
->method('getCacheContexts')
->willReturn(['user']);
$tags = array('node:20011988');
$tags = ['node:20011988'];
$a = AccessResult::neutral()->addCacheTags($tags);
$verify($a, $tags);
$b = AccessResult::neutral()->addCacheableDependency($node);
@ -901,18 +917,31 @@ class AccessResultTest extends UnitTestCase {
* @return array
*/
public function providerTestAllowedIfHasPermissions() {
return [
[[], 'AND', AccessResult::allowedIf(FALSE)],
[[], 'OR', AccessResult::allowedIf(FALSE)],
[['allowed'], 'OR', AccessResult::allowedIf(TRUE)],
[['allowed'], 'AND', AccessResult::allowedIf(TRUE)],
[['denied'], 'OR', AccessResult::allowedIf(FALSE)],
[['denied'], 'AND', AccessResult::allowedIf(FALSE)],
[['allowed', 'denied'], 'OR', AccessResult::allowedIf(TRUE)],
[['denied', 'allowed'], 'OR', AccessResult::allowedIf(TRUE)],
[['allowed', 'denied', 'other'], 'OR', AccessResult::allowedIf(TRUE)],
[['allowed', 'denied'], 'AND', AccessResult::allowedIf(FALSE)],
];
$access_result = AccessResult::allowedIf(FALSE);
$data[] = [[], 'AND', $access_result];
$data[] = [[], 'OR', $access_result];
$access_result = AccessResult::allowedIf(TRUE);
$data[] = [['allowed'], 'OR', $access_result];
$data[] = [['allowed'], 'AND', $access_result];
$access_result = AccessResult::allowedIf(FALSE);
$access_result->setReason("The 'denied' permission is required.");
$data[] = [['denied'], 'OR', $access_result];
$data[] = [['denied'], 'AND', $access_result];
$access_result = AccessResult::allowedIf(TRUE);
$data[] = [['allowed', 'denied'], 'OR', $access_result];
$data[] = [['denied', 'allowed'], 'OR', $access_result];
$access_result = AccessResult::allowedIf(TRUE);
$data[] = [['allowed', 'denied', 'other'], 'OR', $access_result];
$access_result = AccessResult::allowedIf(FALSE);
$access_result->setReason("The following permissions are required: 'allowed' AND 'denied'.");
$data[] = [['allowed', 'denied'], 'AND', $access_result];
return $data;
}
}

View file

@ -56,18 +56,18 @@ class CsrfAccessCheckTest extends UnitTestCase {
$this->routeMatch->expects($this->once())
->method('getRawParameters')
->will($this->returnValue(array('node' => 42)));
->will($this->returnValue(['node' => 42]));
$route = new Route('/test-path/{node}', array(), array('_csrf_token' => 'TRUE'));
$route = new Route('/test-path/{node}', [], ['_csrf_token' => 'TRUE']);
$request = Request::create('/test-path/42?token=test_query');
$this->assertEquals(AccessResult::allowed()->setCacheMaxAge(0), $this->accessCheck->access($route, $request, $this->routeMatch));
}
/**
* Tests the access() method with an invalid token.
* @covers ::access
*/
public function testAccessTokenFail() {
public function testCsrfTokenInvalid() {
$this->csrfToken->expects($this->once())
->method('validate')
->with('test_query', 'test-path')
@ -75,12 +75,30 @@ class CsrfAccessCheckTest extends UnitTestCase {
$this->routeMatch->expects($this->once())
->method('getRawParameters')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$route = new Route('/test-path', array(), array('_csrf_token' => 'TRUE'));
$route = new Route('/test-path', [], ['_csrf_token' => 'TRUE']);
$request = Request::create('/test-path?token=test_query');
$this->assertEquals(AccessResult::forbidden()->setCacheMaxAge(0), $this->accessCheck->access($route, $request, $this->routeMatch));
$this->assertEquals(AccessResult::forbidden("'csrf_token' URL query argument is invalid.")->setCacheMaxAge(0), $this->accessCheck->access($route, $request, $this->routeMatch));
}
/**
* @covers ::access
*/
public function testCsrfTokenMissing() {
$this->csrfToken->expects($this->once())
->method('validate')
->with('', 'test-path')
->will($this->returnValue(FALSE));
$this->routeMatch->expects($this->once())
->method('getRawParameters')
->will($this->returnValue([]));
$route = new Route('/test-path', [], ['_csrf_token' => 'TRUE']);
$request = Request::create('/test-path');
$this->assertEquals(AccessResult::forbidden("'csrf_token' URL query argument is missing.")->setCacheMaxAge(0), $this->accessCheck->access($route, $request, $this->routeMatch));
}
}

View file

@ -44,16 +44,16 @@ class CsrfTokenGeneratorTest extends UnitTestCase {
$this->privateKey = $this->getMockBuilder('Drupal\Core\PrivateKey')
->disableOriginalConstructor()
->setMethods(array('get'))
->setMethods(['get'])
->getMock();
$this->sessionMetadata = $this->getMockBuilder('Drupal\Core\Session\MetadataBag')
->disableOriginalConstructor()
->getMock();
$settings = array(
$settings = [
'hash_salt' => $this->randomMachineName(),
);
];
new Settings($settings);
@ -154,11 +154,11 @@ class CsrfTokenGeneratorTest extends UnitTestCase {
* An array of data used by the test.
*/
public function providerTestValidateParameterTypes() {
return array(
array(array(), ''),
array(TRUE, 'foo'),
array(0, 'foo'),
);
return [
[[], ''],
[TRUE, 'foo'],
[0, 'foo'],
];
}
/**
@ -171,11 +171,11 @@ class CsrfTokenGeneratorTest extends UnitTestCase {
*
* @covers ::validate
* @dataProvider providerTestInvalidParameterTypes
* @expectedException InvalidArgumentException
*/
public function testInvalidParameterTypes($token, $value = '') {
$this->setupDefaultExpectations();
$this->setExpectedException(\InvalidArgumentException::class);
$this->generator->validate($token, $value);
}
@ -186,24 +186,24 @@ class CsrfTokenGeneratorTest extends UnitTestCase {
* An array of data used by the test.
*/
public function providerTestInvalidParameterTypes() {
return array(
array(NULL, new \stdClass()),
array(0, array()),
array('', array()),
array(array(), array()),
);
return [
[NULL, new \stdClass()],
[0, []],
['', []],
[[], []],
];
}
/**
* Tests the exception thrown when no 'hash_salt' is provided in settings.
*
* @covers ::get
* @expectedException \RuntimeException
*/
public function testGetWithNoHashSalt() {
// Update settings with no hash salt.
new Settings(array());
new Settings([]);
$generator = new CsrfTokenGenerator($this->privateKey, $this->sessionMetadata);
$this->setExpectedException(\RuntimeException::class);
$generator->get();
}

View file

@ -59,12 +59,12 @@ class CustomAccessCheckTest extends UnitTestCase {
$this->controllerResolver->expects($this->at(0))
->method('getControllerFromDefinition')
->with('\Drupal\Tests\Core\Access\TestController::accessDeny')
->will($this->returnValue(array(new TestController(), 'accessDeny')));
->will($this->returnValue([new TestController(), 'accessDeny']));
$resolver0 = $this->getMock('Drupal\Component\Utility\ArgumentsResolverInterface');
$resolver0->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$this->argumentsResolverFactory->expects($this->at(0))
->method('getArgumentsResolver')
->will($this->returnValue($resolver0));
@ -72,12 +72,12 @@ class CustomAccessCheckTest extends UnitTestCase {
$this->controllerResolver->expects($this->at(1))
->method('getControllerFromDefinition')
->with('\Drupal\Tests\Core\Access\TestController::accessAllow')
->will($this->returnValue(array(new TestController(), 'accessAllow')));
->will($this->returnValue([new TestController(), 'accessAllow']));
$resolver1 = $this->getMock('Drupal\Component\Utility\ArgumentsResolverInterface');
$resolver1->expects($this->once())
->method('getArguments')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$this->argumentsResolverFactory->expects($this->at(1))
->method('getArgumentsResolver')
->will($this->returnValue($resolver1));
@ -85,24 +85,24 @@ class CustomAccessCheckTest extends UnitTestCase {
$this->controllerResolver->expects($this->at(2))
->method('getControllerFromDefinition')
->with('\Drupal\Tests\Core\Access\TestController::accessParameter')
->will($this->returnValue(array(new TestController(), 'accessParameter')));
->will($this->returnValue([new TestController(), 'accessParameter']));
$resolver2 = $this->getMock('Drupal\Component\Utility\ArgumentsResolverInterface');
$resolver2->expects($this->once())
->method('getArguments')
->will($this->returnValue(array('parameter' => 'TRUE')));
->will($this->returnValue(['parameter' => 'TRUE']));
$this->argumentsResolverFactory->expects($this->at(2))
->method('getArgumentsResolver')
->will($this->returnValue($resolver2));
$route = new Route('/test-route', array(), array('_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessDeny'));
$route = new Route('/test-route', [], ['_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessDeny']);
$account = $this->getMock('Drupal\Core\Session\AccountInterface');
$this->assertEquals(AccessResult::neutral(), $this->accessChecker->access($route, $route_match, $account));
$route = new Route('/test-route', array(), array('_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessAllow'));
$route = new Route('/test-route', [], ['_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessAllow']);
$this->assertEquals(AccessResult::allowed(), $this->accessChecker->access($route, $route_match, $account));
$route = new Route('/test-route', array('parameter' => 'TRUE'), array('_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessParameter'));
$route = new Route('/test-route', ['parameter' => 'TRUE'], ['_custom_access' => '\Drupal\Tests\Core\Access\TestController::accessParameter']);
$this->assertEquals(AccessResult::allowed(), $this->accessChecker->access($route, $route_match, $account));
}

View file

@ -42,15 +42,15 @@ class DefaultAccessCheckTest extends UnitTestCase {
* Test the access method.
*/
public function testAccess() {
$request = new Request(array());
$request = new Request([]);
$route = new Route('/test-route', array(), array('_access' => 'NULL'));
$route = new Route('/test-route', [], ['_access' => 'NULL']);
$this->assertEquals(AccessResult::neutral(), $this->accessChecker->access($route, $request, $this->account));
$route = new Route('/test-route', array(), array('_access' => 'FALSE'));
$route = new Route('/test-route', [], ['_access' => 'FALSE']);
$this->assertEquals(AccessResult::forbidden(), $this->accessChecker->access($route, $request, $this->account));
$route = new Route('/test-route', array(), array('_access' => 'TRUE'));
$route = new Route('/test-route', [], ['_access' => 'TRUE']);
$this->assertEquals(AccessResult::allowed(), $this->accessChecker->access($route, $request, $this->account));
}

View file

@ -2,6 +2,7 @@
namespace Drupal\Tests\Core\Access;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Render\BubbleableMetadata;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Access\RouteProcessorCsrf;
@ -43,7 +44,7 @@ class RouteProcessorCsrfTest extends UnitTestCase {
->method('get');
$route = new Route('/test-path');
$parameters = array();
$parameters = [];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
@ -58,8 +59,8 @@ class RouteProcessorCsrfTest extends UnitTestCase {
* Tests the processOutbound() method with a _csrf_token route requirement.
*/
public function testProcessOutbound() {
$route = new Route('/test-path', array(), array('_csrf_token' => 'TRUE'));
$parameters = array();
$route = new Route('/test-path', [], ['_csrf_token' => 'TRUE']);
$parameters = [];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
@ -68,7 +69,7 @@ class RouteProcessorCsrfTest extends UnitTestCase {
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = 'test-path';
$placeholder = hash('sha1', $path);
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];
@ -80,15 +81,15 @@ class RouteProcessorCsrfTest extends UnitTestCase {
* Tests the processOutbound() method with a dynamic path and one replacement.
*/
public function testProcessOutboundDynamicOne() {
$route = new Route('/test-path/{slug}', array(), array('_csrf_token' => 'TRUE'));
$parameters = array('slug' => 100);
$route = new Route('/test-path/{slug}', [], ['_csrf_token' => 'TRUE']);
$parameters = ['slug' => 100];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = 'test-path/100';
$placeholder = hash('sha1', $path);
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];
@ -99,15 +100,15 @@ class RouteProcessorCsrfTest extends UnitTestCase {
* Tests the processOutbound() method with two parameter replacements.
*/
public function testProcessOutboundDynamicTwo() {
$route = new Route('{slug_1}/test-path/{slug_2}', array(), array('_csrf_token' => 'TRUE'));
$parameters = array('slug_1' => 100, 'slug_2' => 'test');
$route = new Route('{slug_1}/test-path/{slug_2}', [], ['_csrf_token' => 'TRUE']);
$parameters = ['slug_1' => 100, 'slug_2' => 'test'];
$bubbleable_metadata = new BubbleableMetadata();
$this->processor->processOutbound('test', $route, $parameters, $bubbleable_metadata);
// Bubbleable metadata of routes with a _csrf_token route requirement is a
// placeholder.
$path = '100/test-path/test';
$placeholder = hash('sha1', $path);
$placeholder = Crypt::hashBase64($path);
$placeholder_render_array = [
'#lazy_builder' => ['route_processor_csrf:renderPlaceholderCsrfToken', [$path]],
];

View file

@ -38,10 +38,10 @@ class AjaxCommandsTest extends UnitTestCase {
public function testAddCssCommand() {
$command = new AddCssCommand('p{ text-decoration:blink; }');
$expected = array(
$expected = [
'command' => 'add_css',
'data' => 'p{ text-decoration:blink; }',
);
];
$this->assertEquals($expected, $command->render());
}
@ -50,15 +50,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\AfterCommand
*/
public function testAfterCommand() {
$command = new AfterCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new AfterCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'after',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -68,10 +68,10 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testAlertCommand() {
$command = new AlertCommand('Set condition 1 throughout the ship!');
$expected = array(
$expected = [
'command' => 'alert',
'text' => 'Set condition 1 throughout the ship!',
);
];
$this->assertEquals($expected, $command->render());
}
@ -80,15 +80,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\AppendCommand
*/
public function testAppendCommand() {
$command = new AppendCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new AppendCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'append',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -97,15 +97,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\BeforeCommand
*/
public function testBeforeCommand() {
$command = new BeforeCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new BeforeCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'before',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -116,11 +116,11 @@ class AjaxCommandsTest extends UnitTestCase {
public function testChangedCommand() {
$command = new ChangedCommand('#page-title', '#page-title-changed');
$expected = array(
$expected = [
'command' => 'changed',
'selector' => '#page-title',
'asterisk' => '#page-title-changed',
);
];
$this->assertEquals($expected, $command->render());
}
@ -129,18 +129,18 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\CssCommand
*/
public function testCssCommand() {
$command = new CssCommand('#page-title', array('text-decoration' => 'blink'));
$command = new CssCommand('#page-title', ['text-decoration' => 'blink']);
$command->setProperty('font-size', '40px')->setProperty('font-weight', 'bold');
$expected = array(
$expected = [
'command' => 'css',
'selector' => '#page-title',
'argument' => array(
'argument' => [
'text-decoration' => 'blink',
'font-size' => '40px',
'font-weight' => 'bold',
),
);
],
];
$this->assertEquals($expected, $command->render());
}
@ -149,14 +149,14 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\DataCommand
*/
public function testDataCommand() {
$command = new DataCommand('#page-title', 'my-data', array('key' => 'value'));
$command = new DataCommand('#page-title', 'my-data', ['key' => 'value']);
$expected = array(
$expected = [
'command' => 'data',
'selector' => '#page-title',
'name' => 'my-data',
'value' => array('key' => 'value'),
);
'value' => ['key' => 'value'],
];
$this->assertEquals($expected, $command->render());
}
@ -165,15 +165,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\HtmlCommand
*/
public function testHtmlCommand() {
$command = new HtmlCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new HtmlCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'html',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -182,15 +182,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\InsertCommand
*/
public function testInsertCommand() {
$command = new InsertCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new InsertCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => NULL,
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -199,14 +199,14 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\InvokeCommand
*/
public function testInvokeCommand() {
$command = new InvokeCommand('#page-title', 'myMethod', array('var1', 'var2'));
$command = new InvokeCommand('#page-title', 'myMethod', ['var1', 'var2']);
$expected = array(
$expected = [
'command' => 'invoke',
'selector' => '#page-title',
'method' => 'myMethod',
'args' => array('var1', 'var2'),
);
'args' => ['var1', 'var2'],
];
$this->assertEquals($expected, $command->render());
}
@ -215,15 +215,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\PrependCommand
*/
public function testPrependCommand() {
$command = new PrependCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new PrependCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'prepend',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -234,10 +234,10 @@ class AjaxCommandsTest extends UnitTestCase {
public function testRemoveCommand() {
$command = new RemoveCommand('#page-title');
$expected = array(
$expected = [
'command' => 'remove',
'selector' => '#page-title',
);
];
$this->assertEquals($expected, $command->render());
}
@ -246,15 +246,15 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\ReplaceCommand
*/
public function testReplaceCommand() {
$command = new ReplaceCommand('#page-title', '<p>New Text!</p>', array('my-setting' => 'setting'));
$command = new ReplaceCommand('#page-title', '<p>New Text!</p>', ['my-setting' => 'setting']);
$expected = array(
$expected = [
'command' => 'insert',
'method' => 'replaceWith',
'selector' => '#page-title',
'data' => '<p>New Text!</p>',
'settings' => array('my-setting' => 'setting'),
);
'settings' => ['my-setting' => 'setting'],
];
$this->assertEquals($expected, $command->render());
}
@ -265,10 +265,10 @@ class AjaxCommandsTest extends UnitTestCase {
public function testRestripeCommand() {
$command = new RestripeCommand('#page-title');
$expected = array(
$expected = [
'command' => 'restripe',
'selector' => '#page-title',
);
];
$this->assertEquals($expected, $command->render());
}
@ -277,13 +277,13 @@ class AjaxCommandsTest extends UnitTestCase {
* @covers \Drupal\Core\Ajax\SettingsCommand
*/
public function testSettingsCommand() {
$command = new SettingsCommand(array('key' => 'value'), TRUE);
$command = new SettingsCommand(['key' => 'value'], TRUE);
$expected = array(
$expected = [
'command' => 'settings',
'settings' => array('key' => 'value'),
'settings' => ['key' => 'value'],
'merge' => TRUE,
);
];
$this->assertEquals($expected, $command->render());
}
@ -293,13 +293,13 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testOpenDialogCommand() {
$command = $this->getMockBuilder('Drupal\Core\Ajax\OpenDialogCommand')
->setConstructorArgs(array(
'#some-dialog', 'Title', '<p>Text!</p>', array(
->setConstructorArgs([
'#some-dialog', 'Title', '<p>Text!</p>', [
'url' => FALSE,
'width' => 500,
),
))
->setMethods(array('getRenderedContent'))
],
])
->setMethods(['getRenderedContent'])
->getMock();
// This method calls the render service, which isn't available. We want it
@ -308,18 +308,18 @@ class AjaxCommandsTest extends UnitTestCase {
->method('getRenderedContent')
->willReturn('rendered content');
$expected = array(
$expected = [
'command' => 'openDialog',
'selector' => '#some-dialog',
'settings' => NULL,
'data' => 'rendered content',
'dialogOptions' => array(
'dialogOptions' => [
'url' => FALSE,
'width' => 500,
'title' => 'Title',
'modal' => FALSE,
),
);
],
];
$this->assertEquals($expected, $command->render());
}
@ -328,13 +328,13 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testOpenModalDialogCommand() {
$command = $this->getMockBuilder('Drupal\Core\Ajax\OpenModalDialogCommand')
->setConstructorArgs(array(
'Title', '<p>Text!</p>', array(
->setConstructorArgs([
'Title', '<p>Text!</p>', [
'url' => 'example',
'width' => 500,
),
))
->setMethods(array('getRenderedContent'))
],
])
->setMethods(['getRenderedContent'])
->getMock();
// This method calls the render service, which isn't available. We want it
@ -343,18 +343,18 @@ class AjaxCommandsTest extends UnitTestCase {
->method('getRenderedContent')
->willReturn('rendered content');
$expected = array(
$expected = [
'command' => 'openDialog',
'selector' => '#drupal-modal',
'settings' => NULL,
'data' => 'rendered content',
'dialogOptions' => array(
'dialogOptions' => [
'url' => 'example',
'width' => 500,
'title' => 'Title',
'modal' => TRUE,
),
);
],
];
$this->assertEquals($expected, $command->render());
}
@ -363,11 +363,11 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testCloseModalDialogCommand() {
$command = new CloseModalDialogCommand();
$expected = array(
$expected = [
'command' => 'closeDialog',
'selector' => '#drupal-modal',
'persist' => FALSE,
);
];
$this->assertEquals($expected, $command->render());
}
@ -377,11 +377,11 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testCloseDialogCommand() {
$command = new CloseDialogCommand('#some-dialog', TRUE);
$expected = array(
$expected = [
'command' => 'closeDialog',
'selector' => '#some-dialog',
'persist' => TRUE,
);
];
$this->assertEquals($expected, $command->render());
}
@ -391,12 +391,12 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testSetDialogOptionCommand() {
$command = new SetDialogOptionCommand('#some-dialog', 'width', '500');
$expected = array(
$expected = [
'command' => 'setDialogOption',
'selector' => '#some-dialog',
'optionName' => 'width',
'optionValue' => '500',
);
];
$this->assertEquals($expected, $command->render());
}
@ -406,12 +406,12 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testSetDialogTitleCommand() {
$command = new SetDialogTitleCommand('#some-dialog', 'Example');
$expected = array(
$expected = [
'command' => 'setDialogOption',
'selector' => '#some-dialog',
'optionName' => 'title',
'optionValue' => 'Example',
);
];
$this->assertEquals($expected, $command->render());
}
@ -421,10 +421,10 @@ class AjaxCommandsTest extends UnitTestCase {
*/
public function testRedirectCommand() {
$command = new RedirectCommand('http://example.com');
$expected = array(
$expected = [
'command' => 'redirect',
'url' => 'http://example.com',
);
];
$this->assertEquals($expected, $command->render());
}

View file

@ -36,15 +36,15 @@ class AjaxResponseTest extends UnitTestCase {
$command_one = $this->getMock('Drupal\Core\Ajax\CommandInterface');
$command_one->expects($this->once())
->method('render')
->will($this->returnValue(array('command' => 'one')));
->will($this->returnValue(['command' => 'one']));
$command_two = $this->getMock('Drupal\Core\Ajax\CommandInterface');
$command_two->expects($this->once())
->method('render')
->will($this->returnValue(array('command' => 'two')));
->will($this->returnValue(['command' => 'two']));
$command_three = $this->getMock('Drupal\Core\Ajax\CommandInterface');
$command_three->expects($this->once())
->method('render')
->will($this->returnValue(array('command' => 'three')));
->will($this->returnValue(['command' => 'three']));
$this->ajaxResponse->addCommand($command_one);
$this->ajaxResponse->addCommand($command_two);
@ -52,9 +52,9 @@ class AjaxResponseTest extends UnitTestCase {
// Ensure that the added commands are in the right order.
$commands =& $this->ajaxResponse->getCommands();
$this->assertSame($commands[1], array('command' => 'one'));
$this->assertSame($commands[2], array('command' => 'two'));
$this->assertSame($commands[0], array('command' => 'three'));
$this->assertSame($commands[1], ['command' => 'one']);
$this->assertSame($commands[2], ['command' => 'two']);
$this->assertSame($commands[0], ['command' => 'three']);
// Remove one and change one element from commands and ensure the reference
// worked as expected.
@ -62,9 +62,9 @@ class AjaxResponseTest extends UnitTestCase {
$commands[0]['class'] = 'test-class';
$commands = $this->ajaxResponse->getCommands();
$this->assertSame($commands[1], array('command' => 'one'));
$this->assertSame($commands[1], ['command' => 'one']);
$this->assertFalse(isset($commands[2]));
$this->assertSame($commands[0], array('command' => 'three', 'class' => 'test-class'));
$this->assertSame($commands[0], ['command' => 'three', 'class' => 'test-class']);
}
/**

View file

@ -36,10 +36,10 @@ class TranslationTest extends UnitTestCase {
$container->set('string_translation', $this->translationManager);
\Drupal::setContainer($container);
$arguments = isset($values['arguments']) ? $values['arguments'] : array();
$options = isset($values['context']) ? array(
$arguments = isset($values['arguments']) ? $values['arguments'] : [];
$options = isset($values['context']) ? [
'context' => $values['context'],
) : array();
] : [];
$annotation = new Translation($values);
@ -50,27 +50,27 @@ class TranslationTest extends UnitTestCase {
* Provides data to self::testGet().
*/
public function providerTestGet() {
$data = array();
$data[] = array(
array(
$data = [];
$data[] = [
[
'value' => 'Foo',
),
],
'Foo'
);
];
$random = $this->randomMachineName();
$random_html_entity = '&' . $random;
$data[] = array(
array(
$data[] = [
[
'value' => 'Foo @bar @baz %qux',
'arguments' => array(
'arguments' => [
'@bar' => $random,
'@baz' => $random_html_entity,
'%qux' => $random_html_entity,
),
],
'context' => $this->randomMachineName(),
),
],
'Foo ' . $random . ' &amp;' . $random . ' <em class="placeholder">&amp;' . $random . '</em>',
);
];
return $data;
}

View file

@ -153,6 +153,17 @@ class AssertLegacyTraitTest extends UnitTestCase {
$this->assertOptionSelected('myselect', 'two');
}
/**
* @covers ::assertNoPattern
*/
public function testAssertNoPattern() {
$this->webAssert
->responseNotMatches('/.*foo$/')
->shouldBeCalled();
$this->assertNoPattern('/.*foo$/');
}
/**
* Returns a mocked behat session object.
*

View file

@ -106,7 +106,7 @@ class AssetResolverTest extends UnitTestCase {
$this->languageManager->expects($this->any())
->method('getCurrentLanguage')
->will($this->onConsecutiveCalls($english, $english, $japanese, $japanese));
$this->cache = new TestMemoryBackend('llama');
$this->cache = new TestMemoryBackend();
$this->assetResolver = new AssetResolver($this->libraryDiscovery, $this->libraryDependencyResolver, $this->moduleHandler, $this->themeManager, $this->languageManager, $this->cache);
}

View file

@ -28,79 +28,79 @@ class CssCollectionGrouperUnitTest extends UnitTestCase {
/**
* Tests \Drupal\Core\Asset\CssCollectionGrouper.
*/
function testGrouper() {
$css_assets = array(
'system.base.css' => array(
public function testGrouper() {
$css_assets = [
'system.base.css' => [
'group' => -100,
'type' => 'file',
'weight' => 0.012,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'core/modules/system/system.base.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'system.base.css',
),
'js.module.css' => array(
],
'js.module.css' => [
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'core/modules/system/js.module.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'js.module.css',
),
'jquery.ui.core.css' => array(
],
'jquery.ui.core.css' => [
'group' => -100,
'type' => 'file',
'weight' => 0.004,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'core/misc/ui/themes/base/jquery.ui.core.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'jquery.ui.core.css',
),
'field.css' => array(
],
'field.css' => [
'group' => 0,
'type' => 'file',
'weight' => 0.011,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'core/modules/field/theme/field.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'field.css',
),
'external.css' => array(
],
'external.css' => [
'group' => 0,
'type' => 'external',
'weight' => 0.009,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'http://example.com/external.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'external.css',
),
'elements.css' => array(
],
'elements.css' => [
'group' => 100,
'media' => 'all',
'type' => 'file',
'weight' => 0.001,
'preprocess' => TRUE,
'data' => 'core/themes/bartik/css/base/elements.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'elements.css',
),
'print.css' => array(
],
'print.css' => [
'group' => 100,
'media' => 'print',
'type' => 'file',
'weight' => 0.003,
'preprocess' => TRUE,
'data' => 'core/themes/bartik/css/print.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'print.css',
),
);
],
];
$groups = $this->grouper->group($css_assets);

View file

@ -39,35 +39,35 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
$this->state = $this->getMock('Drupal\Core\State\StateInterface');
$this->renderer = new CssCollectionRenderer($this->state);
$this->fileCssGroup = array(
$this->fileCssGroup = [
'group' => -100,
'type' => 'file',
'media' => 'all',
'preprocess' => TRUE,
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'items' => array(
0 => array(
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'items' => [
0 => [
'group' => -100,
'type' => 'file',
'weight' => 0.012,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'tests/Drupal/Tests/Core/Asset/foo.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'foo.css',
),
1 => array(
],
1 => [
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => 'tests/Drupal/Tests/Core/Asset/bar.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'bar.css',
),
),
);
],
],
];
}
/**
@ -75,60 +75,60 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
*
* @see testRender
*/
function providerTestRender() {
$create_link_element = function($href, $media = 'all', $browsers = array()) {
return array(
public function providerTestRender() {
$create_link_element = function($href, $media = 'all', $browsers = []) {
return [
'#type' => 'html_tag',
'#tag' => 'link',
'#attributes' => array(
'#attributes' => [
'rel' => 'stylesheet',
'href' => $href,
'media' => $media,
),
],
'#browsers' => $browsers,
);
];
};
$create_style_element = function($value, $media, $browsers = array()) {
$style_element = array(
$create_style_element = function($value, $media, $browsers = []) {
$style_element = [
'#type' => 'html_tag',
'#tag' => 'style',
'#value' => $value,
'#attributes' => array(
'#attributes' => [
'media' => $media
),
],
'#browsers' => $browsers,
);
];
return $style_element;
};
$create_file_css_asset = function($data, $media = 'all', $preprocess = TRUE) {
return array('group' => 0, 'type' => 'file', 'media' => $media, 'preprocess' => $preprocess, 'data' => $data, 'browsers' => array());
return ['group' => 0, 'type' => 'file', 'media' => $media, 'preprocess' => $preprocess, 'data' => $data, 'browsers' => []];
};
return array(
return [
// Single external CSS asset.
0 => array(
0 => [
// CSS assets.
array(
0 => array('group' => 0, 'type' => 'external', 'media' => 'all', 'preprocess' => TRUE, 'data' => 'http://example.com/popular.js', 'browsers' => array()),
),
[
0 => ['group' => 0, 'type' => 'external', 'media' => 'all', 'preprocess' => TRUE, 'data' => 'http://example.com/popular.js', 'browsers' => []],
],
// Render elements.
array(
[
0 => $create_link_element('http://example.com/popular.js', 'all'),
),
),
],
],
// Single file CSS asset.
2 => array(
array(
0 => array('group' => 0, 'type' => 'file', 'media' => 'all', 'preprocess' => TRUE, 'data' => 'public://css/file-all', 'browsers' => array()),
),
array(
2 => [
[
0 => ['group' => 0, 'type' => 'file', 'media' => 'all', 'preprocess' => TRUE, 'data' => 'public://css/file-all', 'browsers' => []],
],
[
0 => $create_link_element(file_url_transform_relative(file_create_url('public://css/file-all')) . '?0', 'all'),
),
),
],
],
// 31 file CSS assets: expect 31 link elements.
3 => array(
array(
3 => [
[
0 => $create_file_css_asset('public://css/1.css'),
1 => $create_file_css_asset('public://css/2.css'),
2 => $create_file_css_asset('public://css/3.css'),
@ -160,8 +160,8 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
28 => $create_file_css_asset('public://css/29.css'),
29 => $create_file_css_asset('public://css/30.css'),
30 => $create_file_css_asset('public://css/31.css'),
),
array(
],
[
0 => $create_link_element(file_url_transform_relative(file_create_url('public://css/1.css')) . '?0'),
1 => $create_link_element(file_url_transform_relative(file_create_url('public://css/2.css')) . '?0'),
2 => $create_link_element(file_url_transform_relative(file_create_url('public://css/3.css')) . '?0'),
@ -193,11 +193,11 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
28 => $create_link_element(file_url_transform_relative(file_create_url('public://css/29.css')) . '?0'),
29 => $create_link_element(file_url_transform_relative(file_create_url('public://css/30.css')) . '?0'),
30 => $create_link_element(file_url_transform_relative(file_create_url('public://css/31.css')) . '?0'),
),
),
],
],
// 32 file CSS assets with the same properties: expect 2 style elements.
4 => array(
array(
4 => [
[
0 => $create_file_css_asset('public://css/1.css'),
1 => $create_file_css_asset('public://css/2.css'),
2 => $create_file_css_asset('public://css/3.css'),
@ -230,8 +230,8 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
29 => $create_file_css_asset('public://css/30.css'),
30 => $create_file_css_asset('public://css/31.css'),
31 => $create_file_css_asset('public://css/32.css'),
),
array(
],
[
0 => $create_style_element('
@import url("' . file_url_transform_relative(file_create_url('public://css/1.css')) . '?0");
@import url("' . file_url_transform_relative(file_create_url('public://css/2.css')) . '?0");
@ -268,13 +268,13 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
1 => $create_style_element('
@import url("' . file_url_transform_relative(file_create_url('public://css/32.css')) . '?0");
', 'all'),
),
),
],
],
// 32 file CSS assets with the same properties, except for the 10th and
// 20th files, they have different 'media' properties. Expect 5 style
// elements.
5 => array(
array(
5 => [
[
0 => $create_file_css_asset('public://css/1.css'),
1 => $create_file_css_asset('public://css/2.css'),
2 => $create_file_css_asset('public://css/3.css'),
@ -307,8 +307,8 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
29 => $create_file_css_asset('public://css/30.css'),
30 => $create_file_css_asset('public://css/31.css'),
31 => $create_file_css_asset('public://css/32.css'),
),
array(
],
[
0 => $create_style_element('
@import url("' . file_url_transform_relative(file_create_url('public://css/1.css')) . '?0");
@import url("' . file_url_transform_relative(file_create_url('public://css/2.css')) . '?0");
@ -351,12 +351,12 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
@import url("' . file_url_transform_relative(file_create_url('public://css/31.css')) . '?0");
@import url("' . file_url_transform_relative(file_create_url('public://css/32.css')) . '?0");
', 'all'),
),
),
],
],
// 32 file CSS assets with the same properties, except for the 15th, which
// has 'preprocess' = FALSE. Expect 1 link element and 2 style elements.
6 => array(
array(
6 => [
[
0 => $create_file_css_asset('public://css/1.css'),
1 => $create_file_css_asset('public://css/2.css'),
2 => $create_file_css_asset('public://css/3.css'),
@ -389,8 +389,8 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
29 => $create_file_css_asset('public://css/30.css'),
30 => $create_file_css_asset('public://css/31.css'),
31 => $create_file_css_asset('public://css/32.css'),
),
array(
],
[
0 => $create_style_element('
@import url("' . file_url_transform_relative(file_create_url('public://css/1.css')) . '?0");
@import url("' . file_url_transform_relative(file_create_url('public://css/2.css')) . '?0");
@ -427,9 +427,9 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
@import url("' . file_url_transform_relative(file_create_url('public://css/31.css')) . '?0");
@import url("' . file_url_transform_relative(file_create_url('public://css/32.css')) . '?0");
', 'all'),
),
),
);
],
],
];
}
/**
@ -437,7 +437,7 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
*
* @dataProvider providerTestRender
*/
function testRender(array $css_assets, array $render_elements) {
public function testRender(array $css_assets, array $render_elements) {
$this->state->expects($this->once())
->method('get')
->with('system.css_js_query_string')
@ -448,21 +448,21 @@ class CssCollectionRendererUnitTest extends UnitTestCase {
/**
* Tests a CSS asset group with the invalid 'type' => 'internal'.
*/
function testRenderInvalidType() {
public function testRenderInvalidType() {
$this->state->expects($this->once())
->method('get')
->with('system.css_js_query_string')
->will($this->returnValue(NULL));
$this->setExpectedException('Exception', 'Invalid CSS asset type.');
$css_group = array(
$css_group = [
'group' => 0,
'type' => 'internal',
'media' => 'all',
'preprocess' => TRUE,
'browsers' => array(),
'browsers' => [],
'data' => 'http://example.com/popular.js'
);
];
$this->renderer->render($css_group);
}

View file

@ -33,27 +33,27 @@ class CssOptimizerUnitTest extends UnitTestCase {
/**
* Provides data for the CSS asset optimizing test.
*/
function providerTestOptimize() {
public function providerTestOptimize() {
$path = 'core/tests/Drupal/Tests/Core/Asset/css_test_files/';
$absolute_path = dirname(__FILE__) . '/css_test_files/';
return array(
return [
// File. Tests:
// - Stripped comments and white-space.
// - Retain white-space in selectors. (https://www.drupal.org/node/472820)
// - Retain pseudo-selectors. (https://www.drupal.org/node/460448)
array(
array(
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.012,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_without_import.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_without_import.css',
),
],
file_get_contents($absolute_path . 'css_input_without_import.css.optimized.css'),
),
],
// File. Tests:
// - Proper URLs in imported files. (https://www.drupal.org/node/265719)
// - A background image with relative paths, which must be rewritten.
@ -61,133 +61,146 @@ class CssOptimizerUnitTest extends UnitTestCase {
// file_create_url(). (https://www.drupal.org/node/1961340)
// - Imported files that are external (protocol-relative URL or not)
// should not be expanded. (https://www.drupal.org/node/2014851)
array(
array(
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_with_import.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_import.css',
),
],
str_replace('url(images/icon.png)', 'url(' . file_url_transform_relative(file_create_url($path . 'images/icon.png')) . ')', file_get_contents($absolute_path . 'css_input_with_import.css.optimized.css')),
),
],
// File. Tests:
// - Retain comment hacks.
array(
array(
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'comment_hacks.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'comment_hacks.css',
),
],
file_get_contents($absolute_path . 'comment_hacks.css.optimized.css'),
),
],
// File in subfolder. Tests:
// - CSS import path is properly interpreted.
// (https://www.drupal.org/node/1198904)
// - Don't adjust data URIs (https://www.drupal.org/node/2142441)
array(
array(
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_subfolder/css_input_with_import.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_import.css',
),
],
str_replace('url(../images/icon.png)', 'url(' . file_url_transform_relative(file_create_url($path . 'images/icon.png')) . ')', file_get_contents($absolute_path . 'css_subfolder/css_input_with_import.css.optimized.css')),
),
],
// File. Tests:
// - Any @charaset declaration at the beginning of a file should be
// removed without breaking subsequent CSS.
array(
array(
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'charset_sameline.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'charset_sameline.css',
),
],
file_get_contents($absolute_path . 'charset.css.optimized.css'),
),
array(
array(
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'charset_newline.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'charset_newline.css',
),
],
file_get_contents($absolute_path . 'charset.css.optimized.css'),
),
array(
array(
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_with_bom.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_bom.css',
),
],
'.byte-order-mark-test{content:"☃";}' . "\n",
),
array(
array(
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_with_charset.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_charset.css',
),
],
'.charset-test{content:"€";}' . "\n",
),
array(
array(
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_with_bom_and_charset.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_bom_and_charset.css',
),
],
'.byte-order-mark-charset-test{content:"☃";}' . "\n",
),
array(
array(
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'css_input_with_utf16_bom.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'css_input_with_utf16_bom.css',
),
],
'.utf16-byte-order-mark-test{content:"☃";}' . "\n",
),
);
],
[
[
'group' => -100,
'type' => 'file',
'weight' => 0.013,
'media' => 'all',
'preprocess' => TRUE,
'data' => $path . 'quotes.css',
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'quotes.css',
],
file_get_contents($absolute_path . 'quotes.css.optimized.css'),
],
];
}
/**
@ -195,7 +208,7 @@ class CssOptimizerUnitTest extends UnitTestCase {
*
* @dataProvider providerTestOptimize
*/
function testOptimize($css_asset, $expected) {
public function testOptimize($css_asset, $expected) {
global $base_path;
$original_base_path = $base_path;
$base_path = '/';
@ -213,10 +226,10 @@ class CssOptimizerUnitTest extends UnitTestCase {
/**
* Tests a file CSS asset with preprocessing disabled.
*/
function testTypeFilePreprocessingDisabled() {
public function testTypeFilePreprocessingDisabled() {
$this->setExpectedException('Exception', 'Only file CSS assets with preprocessing enabled can be optimized.');
$css_asset = array(
$css_asset = [
'group' => -100,
'type' => 'file',
'weight' => 0.012,
@ -224,19 +237,19 @@ class CssOptimizerUnitTest extends UnitTestCase {
// Preprocessing disabled.
'preprocess' => FALSE,
'data' => 'tests/Drupal/Tests/Core/Asset/foo.css',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
'basename' => 'foo.css',
);
];
$this->optimizer->optimize($css_asset);
}
/**
* Tests a CSS asset with 'type' => 'external'.
*/
function testTypeExternal() {
public function testTypeExternal() {
$this->setExpectedException('Exception', 'Only file CSS assets can be optimized.');
$css_asset = array(
$css_asset = [
'group' => -100,
// Type external.
'type' => 'external',
@ -244,8 +257,8 @@ class CssOptimizerUnitTest extends UnitTestCase {
'media' => 'all',
'preprocess' => TRUE,
'data' => 'http://example.com/foo.js',
'browsers' => array('IE' => TRUE, '!IE' => TRUE),
);
'browsers' => ['IE' => TRUE, '!IE' => TRUE],
];
$this->optimizer->optimize($css_asset);
}

View file

@ -36,34 +36,34 @@ class JsOptimizerUnitTest extends UnitTestCase {
* @returns array
* An array of test data.
*/
function providerTestClean() {
public function providerTestClean() {
$path = dirname(__FILE__) . '/js_test_files/';
return array(
return [
// File. Tests:
// - Stripped sourceMappingURL with comment # syntax.
0 => array(
0 => [
file_get_contents($path . 'source_mapping_url.min.js'),
file_get_contents($path . 'source_mapping_url.min.js.optimized.js'),
),
],
// File. Tests:
// - Stripped sourceMappingURL with comment @ syntax.
1 => array(
1 => [
file_get_contents($path . 'source_mapping_url_old.min.js'),
file_get_contents($path . 'source_mapping_url_old.min.js.optimized.js'),
),
],
// File. Tests:
// - Stripped sourceURL with comment # syntax.
2 => array(
2 => [
file_get_contents($path . 'source_url.min.js'),
file_get_contents($path . 'source_url.min.js.optimized.js'),
),
],
// File. Tests:
// - Stripped sourceURL with comment @ syntax.
3 => array(
3 => [
file_get_contents($path . 'source_url_old.min.js'),
file_get_contents($path . 'source_url_old.min.js.optimized.js'),
),
);
],
];
}
/**
@ -71,7 +71,7 @@ class JsOptimizerUnitTest extends UnitTestCase {
*
* @dataProvider providerTestClean
*/
function testClean($js_asset, $expected) {
public function testClean($js_asset, $expected) {
$this->assertEquals($expected, $this->optimizer->clean($js_asset));
}
@ -83,35 +83,35 @@ class JsOptimizerUnitTest extends UnitTestCase {
* @returns array
* An array of test data.
*/
function providerTestOptimize() {
public function providerTestOptimize() {
$path = dirname(__FILE__) . '/js_test_files/';
return array(
0 => array(
array(
return [
0 => [
[
'type' => 'file',
'preprocess' => TRUE,
'data' => $path . 'utf8_bom.js',
),
],
file_get_contents($path . 'utf8_bom.js.optimized.js'),
),
1 => array(
array(
],
1 => [
[
'type' => 'file',
'preprocess' => TRUE,
'data' => $path . 'utf16_bom.js',
),
],
file_get_contents($path . 'utf16_bom.js.optimized.js'),
),
2 => array(
array(
],
2 => [
[
'type' => 'file',
'preprocess' => TRUE,
'data' => $path . 'latin_9.js',
'attributes' => array('charset' => 'ISO-8859-15'),
),
'attributes' => ['charset' => 'ISO-8859-15'],
],
file_get_contents($path . 'latin_9.js.optimized.js'),
),
);
],
];
}
/**
@ -119,7 +119,7 @@ class JsOptimizerUnitTest extends UnitTestCase {
*
* @dataProvider providerTestOptimize
*/
function testOptimize($js_asset, $expected) {
public function testOptimize($js_asset, $expected) {
$this->assertEquals($expected, $this->optimizer->optimize($js_asset));
}

View file

@ -37,7 +37,7 @@ class LibraryDependencyResolverTest extends UnitTestCase {
*
* @var array
*/
protected $libraryData = array(
protected $libraryData = [
'no_deps_a' => ['js' => [], 'css' => []],
'no_deps_b' => ['js' => [], 'css' => []],
'no_deps_c' => ['js' => [], 'css' => []],
@ -47,7 +47,7 @@ class LibraryDependencyResolverTest extends UnitTestCase {
'nested_deps_a' => ['js' => [], 'css' => [], 'dependencies' => ['test/deps_a']],
'nested_deps_b' => ['js' => [], 'css' => [], 'dependencies' => ['test/nested_deps_a']],
'nested_deps_c' => ['js' => [], 'css' => [], 'dependencies' => ['test/nested_deps_b']],
);
];
/**
* {@inheritdoc}

View file

@ -52,16 +52,16 @@ class LibraryDiscoveryCollectorTest extends UnitTestCase {
*
* @var array
*/
protected $libraryData = array(
'test_1' => array(
'js' => array(),
'css' => array(),
),
'test_2' => array(
'js' => array(),
'css' => array(),
),
);
protected $libraryData = [
'test_1' => [
'js' => [],
'css' => [],
],
'test_2' => [
'js' => [],
'css' => [],
],
];
protected $activeTheme;
@ -140,7 +140,7 @@ class LibraryDiscoveryCollectorTest extends UnitTestCase {
->willReturn(FALSE);
$this->cache->expects($this->once())
->method('set')
->with('library_info:kitten_theme', array('test' => $this->libraryData), Cache::PERMANENT, ['library_info']);
->with('library_info:kitten_theme', ['test' => $this->libraryData], Cache::PERMANENT, ['library_info']);
$this->lock->expects($this->once())
->method('release')
->with($lock_key);

View file

@ -7,6 +7,9 @@
namespace Drupal\Tests\Core\Asset;
use Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException;
use Drupal\Core\Asset\Exception\InvalidLibraryFileException;
use Drupal\Core\Asset\Exception\LibraryDefinitionMissingLicenseException;
use Drupal\Core\Asset\LibraryDiscoveryParser;
use Drupal\Tests\UnitTestCase;
@ -137,14 +140,12 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'example_module', $path);
$this->assertSame($this->libraryDiscoveryParser->buildByExtension('example_module'), array());
$this->assertSame($this->libraryDiscoveryParser->buildByExtension('example_module'), []);
}
/**
* Tests that an exception is thrown when a libraries file couldn't be parsed.
*
* @expectedException \Drupal\Core\Asset\Exception\InvalidLibraryFileException
*
* @covers ::buildByExtension
*/
public function testInvalidLibrariesFile() {
@ -157,15 +158,13 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'invalid_file', $path);
$this->setExpectedException(InvalidLibraryFileException::class);
$this->libraryDiscoveryParser->buildByExtension('invalid_file');
}
/**
* Tests that an exception is thrown when no CSS/JS/setting is specified.
*
* @expectedException \Drupal\Core\Asset\Exception\IncompleteLibraryDefinitionException
* @expectedExceptionMessage Incomplete library definition for definition 'example' in extension 'example_module_missing_information'
*
* @covers ::buildByExtension
*/
public function testBuildByExtensionWithMissingInformation() {
@ -178,6 +177,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'example_module_missing_information', $path);
$this->setExpectedException(IncompleteLibraryDefinitionException::class, "Incomplete library definition for definition 'example' in extension 'example_module_missing_information'");
$this->libraryDiscoveryParser->buildByExtension('example_module_missing_information');
}
@ -276,8 +276,6 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
/**
* Ensures that you cannot provide positive weights for JavaScript libraries.
*
* @expectedException \UnexpectedValueException
*
* @covers ::buildByExtension
*/
public function testJsWithPositiveWeight() {
@ -290,6 +288,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'js_positive_weight', $path);
$this->setExpectedException(\UnexpectedValueException::class);
$this->libraryDiscoveryParser->buildByExtension('js_positive_weight');
}
@ -320,7 +319,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$this->assertEquals('file', $library['css'][0]['type']);
$this->assertEquals($path . '/css/base.css', $library['css'][0]['data']);
$this->assertEquals(array('key' => 'value'), $library['drupalSettings']);
$this->assertEquals(['key' => 'value'], $library['drupalSettings']);
}
/**
@ -403,9 +402,6 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
/**
* Tests that an exception is thrown when license is missing when 3rd party.
*
* @expectedException \Drupal\Core\Asset\Exception\LibraryDefinitionMissingLicenseException
* @expectedExceptionMessage Missing license information in library definition for definition 'no-license-info-but-remote' extension 'licenses_missing_information': it has a remote, but no license.
*
* @covers ::buildByExtension
*/
public function testLibraryThirdPartyWithMissingLicense() {
@ -418,6 +414,7 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$path = substr($path, strlen($this->root) + 1);
$this->libraryDiscoveryParser->setPaths('module', 'licenses_missing_information', $path);
$this->setExpectedException(LibraryDefinitionMissingLicenseException::class, "Missing license information in library definition for definition 'no-license-info-but-remote' extension 'licenses_missing_information': it has a remote, but no license.");
$this->libraryDiscoveryParser->buildByExtension('licenses_missing_information');
}
@ -443,65 +440,65 @@ class LibraryDiscoveryParserTest extends UnitTestCase {
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$this->assertTrue(isset($library['license']));
$default_license = array(
$default_license = [
'name' => 'GNU-GPL-2.0-or-later',
'url' => 'https://www.drupal.org/licensing/faq',
'gpl-compatible' => TRUE,
);
];
$this->assertEquals($library['license'], $default_license);
// GPL2-licensed libraries.
$library = $libraries['gpl2'];
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$expected_license = array(
$expected_license = [
'name' => 'gpl2',
'url' => 'https://url-to-gpl2-license',
'gpl-compatible' => TRUE,
);
];
$this->assertEquals($library['license'], $expected_license);
// MIT-licensed libraries.
$library = $libraries['mit'];
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$expected_license = array(
$expected_license = [
'name' => 'MIT',
'url' => 'https://url-to-mit-license',
'gpl-compatible' => TRUE,
);
];
$this->assertEquals($library['license'], $expected_license);
// Libraries in the Public Domain.
$library = $libraries['public-domain'];
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$expected_license = array(
$expected_license = [
'name' => 'Public Domain',
'url' => 'https://url-to-public-domain-license',
'gpl-compatible' => TRUE,
);
];
$this->assertEquals($library['license'], $expected_license);
// Apache-licensed libraries.
$library = $libraries['apache'];
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$expected_license = array(
$expected_license = [
'name' => 'apache',
'url' => 'https://url-to-apache-license',
'gpl-compatible' => FALSE,
);
];
$this->assertEquals($library['license'], $expected_license);
// Copyrighted libraries.
$library = $libraries['copyright'];
$this->assertCount(1, $library['css']);
$this->assertCount(1, $library['js']);
$expected_license = array(
$expected_license = [
'name' => '© Some company',
'gpl-compatible' => FALSE,
);
];
$this->assertEquals($library['license'], $expected_license);
}

View file

@ -0,0 +1,31 @@
/* Example from https://www.w3.org/TR/CSS2/syndata.html#rule-sets */
q[example="public class foo\
{\
private int x;\
\
foo(int x) {\
this.x = x;\
}\
\
}"] { color: red }
/* A pseudo selector with essential whitespace wrapped in quotes. */
q[style*="quotes: none"] {
quotes: none;
}
q[style*='quotes: none'] {
quotes: none;
}
q:after {
content: ": colon & escaped double \" quotes \".";
}
q:after {
content: ' (brackets & escaped single \' quotes \') ';
}
q:after {
content: "I'm Quote";
}

View file

@ -0,0 +1,9 @@
q[example="public class foo\
{\
private int x;\
\
foo(int x) {\
this.x = x;\
}\
\
}"]{color:red}q[style*="quotes: none"]{quotes:none;}q[style*='quotes: none']{quotes:none;}q:after{content:": colon & escaped double \" quotes \".";}q:after{content:' (brackets & escaped single \' quotes \') ';}q:after{content:"I'm Quote";}

View file

@ -13,7 +13,7 @@ use Drupal\Tests\UnitTestCase;
* in all cases.
*/
class PercentagesTest extends UnitTestCase {
protected $testCases = array();
protected $testCases = [];
/**
* @dataProvider providerTestPercentages
@ -31,39 +31,39 @@ class PercentagesTest extends UnitTestCase {
*/
public function providerTestPercentages() {
// Set up an array of test cases.
return array(
return [
// array(total, current, expected).
// 1/2 is 50%.
array(2, 1, '50'),
[2, 1, '50'],
// Though we should never encounter a case where the current set is set
// 0, if we did, we should get 0%.
array(3, 0, '0'),
[3, 0, '0'],
// 1/3 is closer to 33% than to 34%.
array(3, 1, '33'),
[3, 1, '33'],
// 2/3 is closer to 67% than to 66%.
array(3, 2, '67'),
[3, 2, '67'],
// 1/199 should round up to 1%.
array(199, 1, '1'),
[199, 1, '1'],
// 198/199 should round down to 99%.
array(199, 198, '99'),
[199, 198, '99'],
// 199/200 would have rounded up to 100%, which would give the false
// impression of being finished, so we add another digit and should get
// 99.5%.
array(200, 199, '99.5'),
[200, 199, '99.5'],
// The same logic holds for 1/200: we should get 0.5%.
array(200, 1, '0.5'),
[200, 1, '0.5'],
// Numbers that come out evenly, such as 50/200, should be forced to have
// extra digits for consistency.
array(200, 50, '25.0'),
[200, 50, '25.0'],
// Regardless of number of digits we're using, 100% should always just be
// 100%.
array(200, 200, '100'),
[200, 200, '100'],
// 1998/1999 should similarly round down to 99.9%.
array(1999, 1998, '99.9'),
[1999, 1998, '99.9'],
// 1999/2000 should add another digit and go to 99.95%.
array(2000, 1999, '99.95'),
[2000, 1999, '99.95'],
// 19999/20000 should add yet another digit and go to 99.995%.
array(20000, 19999, '99.995'),
[20000, 19999, '99.995'],
// The next five test cases simulate a batch with a single operation
// ('total' equals 1) that takes several steps to complete. Within the
// operation, we imagine that there are 501 items to process, and 100 are
@ -72,12 +72,12 @@ class PercentagesTest extends UnitTestCase {
// but for the last pass through, when 500 out of 501 items have been
// processed, we do not want to round up to 100%, since that would
// erroneously indicate that the processing is complete.
array('total' => 1, 'current' => 100 / 501, '20'),
array('total' => 1, 'current' => 200 / 501, '40'),
array('total' => 1, 'current' => 300 / 501, '60'),
array('total' => 1, 'current' => 400 / 501, '80'),
array('total' => 1, 'current' => 500 / 501, '99.8'),
);
['total' => 1, 'current' => 100 / 501, '20'],
['total' => 1, 'current' => 200 / 501, '40'],
['total' => 1, 'current' => 300 / 501, '60'],
['total' => 1, 'current' => 400 / 501, '80'],
['total' => 1, 'current' => 500 / 501, '99.8'],
];
}
}

View file

@ -19,24 +19,24 @@ class BlockBaseTest extends UnitTestCase {
public function testGetMachineNameSuggestion() {
$module_handler = $this->getMock('Drupal\Core\Extension\ModuleHandlerInterface');
$transliteration = $this->getMockBuilder('Drupal\Core\Transliteration\PhpTransliteration')
->setConstructorArgs(array(NULL, $module_handler))
->setMethods(array('readLanguageOverrides'))
->setConstructorArgs([NULL, $module_handler])
->setMethods(['readLanguageOverrides'])
->getMock();
$config = array();
$definition = array(
$config = [];
$definition = [
'admin_label' => 'Admin label',
'provider' => 'block_test',
);
];
$block_base = new TestBlockInstantiation($config, 'test_block_instantiation', $definition);
$block_base->setTransliteration($transliteration);
$this->assertEquals('adminlabel', $block_base->getMachineNameSuggestion());
// Test with more unicodes.
$definition = array(
$definition = [
'admin_label' => 'über åwesome',
'provider' => 'block_test',
);
];
$block_base = new TestBlockInstantiation($config, 'test_block_instantiation', $definition);
$block_base->setTransliteration($transliteration);
$this->assertEquals('uberawesome', $block_base->getMachineNameSuggestion());

View file

@ -80,7 +80,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
*/
public function testBuildWithSingleBuilder() {
$builder = $this->getMock('Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface');
$links = array('<a href="/example">Test</a>');
$links = ['<a href="/example">Test</a>'];
$this->breadcrumb->setLinks($links);
$this->breadcrumb->addCacheContexts(['foo'])->addCacheTags(['bar']);
@ -95,7 +95,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
$route_match = $this->getMock('Drupal\Core\Routing\RouteMatchInterface');
$this->moduleHandler->expects($this->once())
->method('alter')
->with('system_breadcrumb', $this->breadcrumb, $route_match, array('builder' => $builder));
->with('system_breadcrumb', $this->breadcrumb, $route_match, ['builder' => $builder]);
$this->breadcrumbManager->addBuilder($builder, 0);
@ -117,7 +117,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
->method('build');
$builder2 = $this->getMock('Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface');
$links2 = array('<a href="/example2">Test2</a>');
$links2 = ['<a href="/example2">Test2</a>'];
$this->breadcrumb->setLinks($links2);
$this->breadcrumb->addCacheContexts(['baz'])->addCacheTags(['qux']);
$builder2->expects($this->once())
@ -131,7 +131,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
$this->moduleHandler->expects($this->once())
->method('alter')
->with('system_breadcrumb', $this->breadcrumb, $route_match, array('builder' => $builder2));
->with('system_breadcrumb', $this->breadcrumb, $route_match, ['builder' => $builder2]);
$this->breadcrumbManager->addBuilder($builder1, 0);
$this->breadcrumbManager->addBuilder($builder2, 10);
@ -169,7 +169,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
$this->moduleHandler->expects($this->once())
->method('alter')
->with('system_breadcrumb', $this->breadcrumb, $route_match, array('builder' => $builder2));
->with('system_breadcrumb', $this->breadcrumb, $route_match, ['builder' => $builder2]);
$this->breadcrumbManager->addBuilder($builder1, 10);
$this->breadcrumbManager->addBuilder($builder2, 0);
@ -183,8 +183,6 @@ class BreadcrumbManagerTest extends UnitTestCase {
/**
* Tests a breadcrumb builder with a bad return value.
*
* @expectedException \UnexpectedValueException
*/
public function testBuildWithInvalidBreadcrumbResult() {
$builder = $this->getMock('Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface');
@ -196,6 +194,7 @@ class BreadcrumbManagerTest extends UnitTestCase {
->will($this->returnValue('invalid_result'));
$this->breadcrumbManager->addBuilder($builder, 0);
$this->setExpectedException(\UnexpectedValueException::class);
$this->breadcrumbManager->build($this->getMock('Drupal\Core\Routing\RouteMatchInterface'));
}

View file

@ -15,12 +15,11 @@ class BreadcrumbTest extends UnitTestCase {
/**
* @covers ::setLinks
* @expectedException \LogicException
* @expectedExceptionMessage Once breadcrumb links are set, only additional breadcrumb links can be added.
*/
public function testSetLinks() {
$breadcrumb = new Breadcrumb();
$breadcrumb->setLinks([new Link('Home', Url::fromRoute('<front>'))]);
$this->setExpectedException(\LogicException::class, 'Once breadcrumb links are set, only additional breadcrumb links can be added.');
$breadcrumb->setLinks([new Link('None', Url::fromRoute('<none>'))]);
}

View file

@ -46,9 +46,9 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
parent::setUp();
// Set up three memory backends to be used in the chain.
$this->firstBackend = new MemoryBackend('foo');
$this->secondBackend = new MemoryBackend('bar');
$this->thirdBackend = new MemoryBackend('baz');
$this->firstBackend = new MemoryBackend();
$this->secondBackend = new MemoryBackend();
$this->thirdBackend = new MemoryBackend();
// Set an initial fixed dataset for all testing. The next three data
// collections will test two edge cases (last backend has the data, and
@ -100,7 +100,7 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
* Test the get multiple feature.
*/
public function testGetMultiple() {
$cids = array('t123', 't23', 't3', 't4');
$cids = ['t123', 't23', 't3', 't4'];
$ret = $this->chain->getMultiple($cids);
$this->assertSame($ret['t123']->data, 1231, 'Got key 123 and value is from the first backend');
@ -175,7 +175,7 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
* Ensure get multiple values propagation to previous backends.
*/
public function testGetMultipleHasPropagated() {
$cids = array('t3', 't23');
$cids = ['t3', 't23'];
$this->chain->getMultiple($cids);
$cached = $this->firstBackend->get('t3');
@ -213,8 +213,8 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
*/
public function testDeleteTagsPropagation() {
// Create two cache entries with the same tag and tag value.
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, array('test_tag:2'));
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, array('test_tag:2'));
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, ['test_tag:2']);
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, ['test_tag:2']);
$this->assertNotSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->secondBackend->get('test_cid_clear1')
@ -224,7 +224,7 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
'Two cache items were created in all backends.');
// Invalidate test_tag of value 1. This should invalidate both entries.
$this->chain->invalidateTags(array('test_tag:2'));
$this->chain->invalidateTags(['test_tag:2']);
$this->assertSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->secondBackend->get('test_cid_clear1')
@ -234,8 +234,8 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
'Two caches removed from all backends after clearing a cache tag.');
// Create two cache entries with the same tag and an array tag value.
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, array('test_tag:1'));
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, array('test_tag:1'));
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, ['test_tag:1']);
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, ['test_tag:1']);
$this->assertNotSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->secondBackend->get('test_cid_clear1')
@ -245,7 +245,7 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
'Two cache items were created in all backends.');
// Invalidate test_tag of value 1. This should invalidate both entries.
$this->chain->invalidateTags(array('test_tag:1'));
$this->chain->invalidateTags(['test_tag:1']);
$this->assertSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->secondBackend->get('test_cid_clear1')
@ -255,9 +255,9 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
'Two caches removed from all backends after clearing a cache tag.');
// Create three cache entries with a mix of tags and tag values.
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, array('test_tag:1'));
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, array('test_tag:2'));
$this->chain->set('test_cid_clear3', 'foo', Cache::PERMANENT, array('test_tag_foo:3'));
$this->chain->set('test_cid_clear1', 'foo', Cache::PERMANENT, ['test_tag:1']);
$this->chain->set('test_cid_clear2', 'foo', Cache::PERMANENT, ['test_tag:2']);
$this->chain->set('test_cid_clear3', 'foo', Cache::PERMANENT, ['test_tag_foo:3']);
$this->assertNotSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->firstBackend->get('test_cid_clear3')
@ -269,7 +269,7 @@ class BackendChainImplementationUnitTest extends UnitTestCase {
&& $this->thirdBackend->get('test_cid_clear3'),
'Three cached items were created in all backends.');
$this->chain->invalidateTags(array('test_tag_foo:3'));
$this->chain->invalidateTags(['test_tag_foo:3']);
$this->assertNotSame(FALSE, $this->firstBackend->get('test_cid_clear1')
&& $this->firstBackend->get('test_cid_clear2')
&& $this->secondBackend->get('test_cid_clear1')

View file

@ -13,7 +13,7 @@ class CacheCollectorHelper extends CacheCollector {
* Contains data to return on a cache miss.
* @var array
*/
protected $cacheMissData = array();
protected $cacheMissData = [];
/**
* Number of calls to \Drupal\Core\Cache\CacheCollector::resolveCacheMiss().

View file

@ -114,10 +114,10 @@ class CacheCollectorTest extends UnitTestCase {
$key = $this->randomMachineName();
$value = $this->randomMachineName();
$cache = (object) array(
'data' => array($key => $value),
$cache = (object) [
'data' => [$key => $value],
'created' => (int) $_SERVER['REQUEST_TIME'],
);
];
$this->cacheBackend->expects($this->once())
->method('get')
->with($this->cid)
@ -183,7 +183,7 @@ class CacheCollectorTest extends UnitTestCase {
->with($this->cid, FALSE);
$this->cacheBackend->expects($this->once())
->method('set')
->with($this->cid, array($key => $value), Cache::PERMANENT, array());
->with($this->cid, [$key => $value], Cache::PERMANENT, []);
$this->lock->expects($this->once())
->method('release')
->with($this->cid . ':Drupal\Core\Cache\CacheCollector');
@ -222,10 +222,10 @@ class CacheCollectorTest extends UnitTestCase {
$key = $this->randomMachineName();
$value = $this->randomMachineName();
$cache = (object) array(
'data' => array($key => $value),
$cache = (object) [
'data' => [$key => $value],
'created' => (int) $_SERVER['REQUEST_TIME'],
);
];
$this->cacheBackend->expects($this->at(0))
->method('get')
->with($this->cid)
@ -243,10 +243,10 @@ class CacheCollectorTest extends UnitTestCase {
->method('acquire')
->with($this->cid . ':Drupal\Core\Cache\CacheCollector')
->will($this->returnValue(TRUE));
$cache = (object) array(
'data' => array($key => $value),
$cache = (object) [
'data' => [$key => $value],
'created' => (int) $_SERVER['REQUEST_TIME'] + 1,
);
];
$this->cacheBackend->expects($this->at(0))
->method('get')
->with($this->cid)
@ -279,17 +279,17 @@ class CacheCollectorTest extends UnitTestCase {
->method('acquire')
->with($this->cid . ':Drupal\Core\Cache\CacheCollector')
->will($this->returnValue(TRUE));
$cache = (object) array(
'data' => array('other key' => 'other value'),
$cache = (object) [
'data' => ['other key' => 'other value'],
'created' => (int) $_SERVER['REQUEST_TIME'] + 1,
);
];
$this->cacheBackend->expects($this->at(0))
->method('get')
->with($this->cid)
->will($this->returnValue($cache));
$this->cacheBackend->expects($this->once())
->method('set')
->with($this->cid, array('other key' => 'other value', $key => $value), Cache::PERMANENT, array());
->with($this->cid, ['other key' => 'other value', $key => $value], Cache::PERMANENT, []);
$this->lock->expects($this->once())
->method('release')
->with($this->cid . ':Drupal\Core\Cache\CacheCollector');
@ -305,10 +305,10 @@ class CacheCollectorTest extends UnitTestCase {
$key = $this->randomMachineName();
$value = $this->randomMachineName();
$cache = (object) array(
'data' => array($key => $value),
$cache = (object) [
'data' => [$key => $value],
'created' => (int) $_SERVER['REQUEST_TIME'],
);
];
$this->cacheBackend->expects($this->at(0))
->method('get')
->with($this->cid)
@ -330,7 +330,7 @@ class CacheCollectorTest extends UnitTestCase {
->with($this->cid, TRUE);
$this->cacheBackend->expects($this->once())
->method('set')
->with($this->cid, array(), Cache::PERMANENT, array());
->with($this->cid, [], Cache::PERMANENT, []);
$this->lock->expects($this->once())
->method('release')
->with($this->cid . ':Drupal\Core\Cache\CacheCollector');
@ -392,7 +392,7 @@ class CacheCollectorTest extends UnitTestCase {
public function testUpdateCacheClearTags() {
$key = $this->randomMachineName();
$value = $this->randomMachineName();
$tags = array($this->randomMachineName());
$tags = [$this->randomMachineName()];
$this->collector = new CacheCollectorHelper($this->cid, $this->cacheBackend, $this->lock, $tags);
// Set the data and request it.

View file

@ -20,7 +20,7 @@ class CacheFactoryTest extends UnitTestCase {
* @covers ::get
*/
public function testCacheFactoryWithDefaultSettings() {
$settings = new Settings(array());
$settings = new Settings([]);
$cache_factory = new CacheFactory($settings);
$container = new ContainerBuilder();
@ -46,11 +46,11 @@ class CacheFactoryTest extends UnitTestCase {
* @covers ::get
*/
public function testCacheFactoryWithCustomizedDefaultBackend() {
$settings = new Settings(array(
'cache' => array(
$settings = new Settings([
'cache' => [
'default' => 'cache.backend.custom',
),
));
],
]);
$cache_factory = new CacheFactory($settings);
$container = new ContainerBuilder();
@ -77,11 +77,11 @@ class CacheFactoryTest extends UnitTestCase {
*/
public function testCacheFactoryWithDefaultBinBackend() {
// Ensure the default bin backends are used before the configured default.
$settings = new Settings(array(
'cache' => array(
$settings = new Settings([
'cache' => [
'default' => 'cache.backend.unused',
),
));
],
]);
$default_bin_backends = [
'render' => 'cache.backend.custom',
@ -114,14 +114,14 @@ class CacheFactoryTest extends UnitTestCase {
public function testCacheFactoryWithSpecifiedPerBinBackend() {
// Ensure the per-bin configuration is used before the configured default
// and per-bin defaults.
$settings = new Settings(array(
'cache' => array(
$settings = new Settings([
'cache' => [
'default' => 'cache.backend.unused',
'bins' => array(
'bins' => [
'render' => 'cache.backend.custom',
),
),
));
],
],
]);
$default_bin_backends = [
'render' => 'cache.backend.unused',

View file

@ -14,11 +14,10 @@ class CacheTagsInvalidatorTest extends UnitTestCase {
/**
* @covers ::invalidateTags
*
* @expectedException \AssertionError
*/
public function testInvalidateTagsWithInvalidTags() {
$cache_tags_invalidator = new CacheTagsInvalidator();
$this->setExpectedException(\AssertionError::class);
$cache_tags_invalidator->invalidateTags(['node' => [2, 3, 5, 8, 13]]);
}
@ -35,7 +34,7 @@ class CacheTagsInvalidatorTest extends UnitTestCase {
$invalidator_cache_bin = $this->getMock('\Drupal\Core\Cache\CacheTagsInvalidator');
$invalidator_cache_bin->expects($this->once())
->method('invalidateTags')
->with(array('node:1'));
->with(['node:1']);
// We do not have to define that invalidateTags() is never called as the
// interface does not define that method, trying to call it would result in
@ -45,17 +44,17 @@ class CacheTagsInvalidatorTest extends UnitTestCase {
$container = new Container();
$container->set('cache.invalidator_cache_bin', $invalidator_cache_bin);
$container->set('cache.non_invalidator_cache_bin', $non_invalidator_cache_bin);
$container->setParameter('cache_bins', array('cache.invalidator_cache_bin' => 'invalidator_cache_bin', 'cache.non_invalidator_cache_bin' => 'non_invalidator_cache_bin'));
$container->setParameter('cache_bins', ['cache.invalidator_cache_bin' => 'invalidator_cache_bin', 'cache.non_invalidator_cache_bin' => 'non_invalidator_cache_bin']);
$cache_tags_invalidator->setContainer($container);
$invalidator = $this->getMock('\Drupal\Core\Cache\CacheTagsInvalidator');
$invalidator->expects($this->once())
->method('invalidateTags')
->with(array('node:1'));
->with(['node:1']);
$cache_tags_invalidator->addInvalidator($invalidator);
$cache_tags_invalidator->invalidateTags(array('node:1'));
$cache_tags_invalidator->invalidateTags(['node:1']);
}
}

View file

@ -40,14 +40,14 @@ class ChainedFastBackendTest extends UnitTestCase {
$consistent_cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$timestamp_cid = ChainedFastBackend::LAST_WRITE_TIMESTAMP_PREFIX . 'cache_foo';
// Use the request time because that is what we will be comparing against.
$timestamp_item = (object) array('cid' => $timestamp_cid, 'data' => (int) $_SERVER['REQUEST_TIME'] - 60);
$timestamp_item = (object) ['cid' => $timestamp_cid, 'data' => (int) $_SERVER['REQUEST_TIME'] - 60];
$consistent_cache->expects($this->once())
->method('get')->with($timestamp_cid)
->will($this->returnValue($timestamp_item));
$consistent_cache->expects($this->never())
->method('getMultiple');
$fast_cache = new MemoryBackend('foo');
$fast_cache = new MemoryBackend();
$fast_cache->set('foo', 'baz');
$chained_fast_backend = new ChainedFastBackend(
@ -62,17 +62,17 @@ class ChainedFastBackendTest extends UnitTestCase {
* Tests a fast cache miss gets data from the consistent cache backend.
*/
public function testFallThroughToConsistentCache() {
$timestamp_item = (object) array(
$timestamp_item = (object) [
'cid' => ChainedFastBackend::LAST_WRITE_TIMESTAMP_PREFIX . 'cache_foo',
'data' => time() + 60, // Time travel is easy.
);
$cache_item = (object) array(
];
$cache_item = (object) [
'cid' => 'foo',
'data' => 'baz',
'created' => time(),
'expire' => time() + 3600,
'tags' => ['tag'],
);
];
$consistent_cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
$fast_cache = $this->getMock('Drupal\Core\Cache\CacheBackendInterface');
@ -86,14 +86,14 @@ class ChainedFastBackendTest extends UnitTestCase {
// We should get a call for the cache item on the consistent backend.
$consistent_cache->expects($this->once())
->method('getMultiple')
->with(array($cache_item->cid))
->will($this->returnValue(array($cache_item->cid => $cache_item)));
->with([$cache_item->cid])
->will($this->returnValue([$cache_item->cid => $cache_item]));
// We should get a call for the cache item on the fast backend.
$fast_cache->expects($this->once())
->method('getMultiple')
->with(array($cache_item->cid))
->will($this->returnValue(array($cache_item->cid => $cache_item)));
->with([$cache_item->cid])
->will($this->returnValue([$cache_item->cid => $cache_item]));
// We should get a call to set the cache item on the fast backend.
$fast_cache->expects($this->once())

View file

@ -105,27 +105,25 @@ class CacheContextsManagerTest extends UnitTestCase {
/**
* @covers ::convertTokensToKeys
*
* @expectedException \AssertionError
*/
public function testInvalidContext() {
$container = $this->getMockContainer();
$cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture());
$this->setExpectedException(\AssertionError::class);
$cache_contexts_manager->convertTokensToKeys(["non-cache-context"]);
}
/**
* @covers ::convertTokensToKeys
*
* @expectedException \Exception
*
* @dataProvider providerTestInvalidCalculatedContext
*/
public function testInvalidCalculatedContext($context_token) {
$container = $this->getMockContainer();
$cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture());
$this->setExpectedException(\Exception::class);
$cache_contexts_manager->convertTokensToKeys([$context_token]);
}
@ -142,19 +140,19 @@ class CacheContextsManagerTest extends UnitTestCase {
public function testAvailableContextStrings() {
$cache_contexts_manager = new CacheContextsManager($this->getMockContainer(), $this->getContextsFixture());
$contexts = $cache_contexts_manager->getAll();
$this->assertEquals(array("foo", "baz"), $contexts);
$this->assertEquals(["foo", "baz"], $contexts);
}
public function testAvailableContextLabels() {
$container = $this->getMockContainer();
$cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture());
$labels = $cache_contexts_manager->getLabels();
$expected = array("foo" => "Foo");
$expected = ["foo" => "Foo"];
$this->assertEquals($expected, $labels);
}
protected function getContextsFixture() {
return array('foo', 'baz');
return ['foo', 'baz'];
}
protected function getMockContainer() {

View file

@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\Core\Cache\Context;
use Drupal\Core\Cache\Context\IsFrontPathCacheContext;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Tests\UnitTestCase;
/**
* @coversDefaultClass \Drupal\Core\Cache\Context\IsFrontPathCacheContext
* @group Cache
*/
class IsFrontPathCacheContextTest extends UnitTestCase {
/**
* @covers ::getContext
*/
public function testGetContextFront() {
$cache_context = new IsFrontPathCacheContext($this->createPathMatcher(TRUE)->reveal());
$this->assertSame('is_front.1', $cache_context->getContext());
}
/**
* @covers ::getContext
*/
public function testGetContextNotFront() {
$cache_context = new IsFrontPathCacheContext($this->createPathMatcher(FALSE)->reveal());
$this->assertSame('is_front.0', $cache_context->getContext());
}
/**
* Creates a PathMatcherInterface prophecy.
*
* @param bool $is_front
*
* @return \Prophecy\Prophecy\ObjectProphecy
*/
protected function createPathMatcher($is_front) {
$path_matcher = $this->prophesize(PathMatcherInterface::class);
$path_matcher->isFrontPage()
->willReturn($is_front);
return $path_matcher;
}
}

View file

@ -15,7 +15,7 @@ class NullBackendTest extends UnitTestCase {
/**
* Tests that the NullBackend does not actually store variables.
*/
function testNullBackend() {
public function testNullBackend() {
$null_cache = new NullBackend('test');
$key = $this->randomMachineName();

View file

@ -18,31 +18,31 @@ class AttributesTest extends UnitTestCase {
* @return array
*/
public function providerTestAttributeData() {
return array(
return [
// Verify that special characters are HTML encoded.
array(array('&"\'<>' => 'value'), ' &amp;&quot;&#039;&lt;&gt;="value"', 'HTML encode attribute names.'),
array(array('title' => '&"\'<>'), ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.'),
[['&"\'<>' => 'value'], ' &amp;&quot;&#039;&lt;&gt;="value"', 'HTML encode attribute names.'],
[['title' => '&"\'<>'], ' title="&amp;&quot;&#039;&lt;&gt;"', 'HTML encode attribute values.'],
// Verify multi-value attributes are concatenated with spaces.
array(array('class' => array('first', 'last')), ' class="first last"', 'Concatenate multi-value attributes.'),
[['class' => ['first', 'last']], ' class="first last"', 'Concatenate multi-value attributes.'],
// Verify boolean attribute values are rendered correctly.
array(array('disabled' => TRUE), ' disabled', 'Boolean attribute is rendered.'),
array(array('disabled' => FALSE), '', 'Boolean attribute is not rendered.'),
[['disabled' => TRUE], ' disabled', 'Boolean attribute is rendered.'],
[['disabled' => FALSE], '', 'Boolean attribute is not rendered.'],
// Verify empty attribute values are rendered.
array(array('alt' => ''), ' alt=""', 'Empty attribute value #1.'),
array(array('alt' => NULL), '', 'Null attribute value #2.'),
[['alt' => ''], ' alt=""', 'Empty attribute value #1.'],
[['alt' => NULL], '', 'Null attribute value #2.'],
// Verify multiple attributes are rendered.
array(
array(
[
[
'id' => 'id-test',
'class' => array('first', 'last'),
'class' => ['first', 'last'],
'alt' => 'Alternate',
),
],
' id="id-test" class="first last" alt="Alternate"',
'Multiple attributes.'
),
],
// Verify empty attributes array is rendered.
array(array(), '', 'Empty attributes array.'),
);
[[], '', 'Empty attributes array.'],
];
}
/**
@ -52,7 +52,7 @@ class AttributesTest extends UnitTestCase {
*
* @dataProvider providerTestAttributeData
*/
function testDrupalAttributes($attributes, $expected, $message) {
public function testDrupalAttributes($attributes, $expected, $message) {
$this->assertSame($expected, (string) new Attribute($attributes), $message);
}
@ -60,7 +60,7 @@ class AttributesTest extends UnitTestCase {
* Test attribute iteration
*/
public function testAttributeIteration() {
$attribute = new Attribute(array('key1' => 'value1'));
$attribute = new Attribute(['key1' => 'value1']);
foreach ($attribute as $value) {
$this->assertSame((string) $value, 'value1', 'Iterate over attribute.');
}

View file

@ -29,42 +29,42 @@ class DiffArrayTest extends UnitTestCase {
protected function setUp() {
parent::setUp();
$this->array1 = array(
$this->array1 = [
'same' => 'yes',
'different' => 'no',
'array_empty_diff' => array(),
'array_empty_diff' => [],
'null' => NULL,
'int_diff' => 1,
'array_diff' => array('same' => 'same', 'array' => array('same' => 'same')),
'array_compared_to_string' => array('value'),
'array_diff' => ['same' => 'same', 'array' => ['same' => 'same']],
'array_compared_to_string' => ['value'],
'string_compared_to_array' => 'value',
'new' => 'new',
);
$this->array2 = array(
];
$this->array2 = [
'same' => 'yes',
'different' => 'yes',
'array_empty_diff' => array(),
'array_empty_diff' => [],
'null' => NULL,
'int_diff' => '1',
'array_diff' => array('same' => 'different', 'array' => array('same' => 'same')),
'array_diff' => ['same' => 'different', 'array' => ['same' => 'same']],
'array_compared_to_string' => 'value',
'string_compared_to_array' => array('value'),
);
'string_compared_to_array' => ['value'],
];
}
/**
* Tests DiffArray::diffAssocRecursive().
*/
public function testDiffAssocRecursive() {
$expected = array(
$expected = [
'different' => 'no',
'int_diff' => 1,
// The 'array' key should not be returned, as it's the same.
'array_diff' => array('same' => 'same'),
'array_compared_to_string' => array('value'),
'array_diff' => ['same' => 'same'],
'array_compared_to_string' => ['value'],
'string_compared_to_array' => 'value',
'new' => 'new',
);
];
$this->assertSame(DiffArray::diffAssocRecursive($this->array1, $this->array2), $expected);
}

View file

@ -12,12 +12,12 @@ use Drupal\Tests\UnitTestCase;
*/
class TagsTest extends UnitTestCase {
protected $validTags = array(
protected $validTags = [
'Drupal' => 'Drupal',
'Drupal with some spaces' => 'Drupal with some spaces',
'"Legendary Drupal mascot of doom: ""Druplicon"""' => 'Legendary Drupal mascot of doom: "Druplicon"',
'"Drupal, although it rhymes with sloopal, is as awesome as a troopal!"' => 'Drupal, although it rhymes with sloopal, is as awesome as a troopal!',
);
];
/**
* Explodes a series of tags.

View file

@ -29,7 +29,7 @@ class ConditionAccessResolverTraitTest extends UnitTestCase {
}
public function providerTestResolveConditions() {
$data = array();
$data = [];
$condition_true = $this->getMock('Drupal\Core\Condition\ConditionInterface');
$condition_true->expects($this->any())
@ -54,49 +54,49 @@ class ConditionAccessResolverTraitTest extends UnitTestCase {
->method('isNegated')
->will($this->returnValue(TRUE));
$conditions = array();
$data[] = array($conditions, 'and', TRUE);
$data[] = array($conditions, 'or', FALSE);
$conditions = [];
$data[] = [$conditions, 'and', TRUE];
$data[] = [$conditions, 'or', FALSE];
$conditions = array($condition_false);
$data[] = array($conditions, 'or', FALSE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_false];
$data[] = [$conditions, 'or', FALSE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_true);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', TRUE);
$conditions = [$condition_true];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', TRUE];
$conditions = array($condition_true, $condition_false);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_true, $condition_false];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_exception);
$data[] = array($conditions, 'or', FALSE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_exception];
$data[] = [$conditions, 'or', FALSE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_true, $condition_exception);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_true, $condition_exception];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_exception, $condition_true);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_exception, $condition_true];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_false, $condition_exception);
$data[] = array($conditions, 'or', FALSE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_false, $condition_exception];
$data[] = [$conditions, 'or', FALSE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_exception, $condition_false);
$data[] = array($conditions, 'or', FALSE);
$data[] = array($conditions, 'and', FALSE);
$conditions = [$condition_exception, $condition_false];
$data[] = [$conditions, 'or', FALSE];
$data[] = [$conditions, 'and', FALSE];
$conditions = array($condition_negated);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', TRUE);
$conditions = [$condition_negated];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', TRUE];
$conditions = array($condition_negated, $condition_negated);
$data[] = array($conditions, 'or', TRUE);
$data[] = array($conditions, 'and', TRUE);
$conditions = [$condition_negated, $condition_negated];
$data[] = [$conditions, 'or', TRUE];
$data[] = [$conditions, 'and', TRUE];
return $data;
}

View file

@ -25,7 +25,7 @@ class CachedStorageTest extends UnitTestCase {
$prefix = __FUNCTION__;
$storage = $this->getMock('Drupal\Core\Config\StorageInterface');
$response = array("$prefix." . $this->randomMachineName(), "$prefix." . $this->randomMachineName());
$response = ["$prefix." . $this->randomMachineName(), "$prefix." . $this->randomMachineName()];
$storage->expects($this->once())
->method('listAll')
->with($prefix)

View file

@ -6,6 +6,7 @@ use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Render\Markup;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ConfigValueException;
/**
* Tests the Config.
@ -87,16 +88,16 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testSetName()
*/
public function setNameProvider() {
return array(
return [
// Valid name with dot.
array(
[
'test.name',
),
],
// Maximum length.
array(
[
'test.' . str_repeat('a', Config::MAX_NAME_LENGTH - 5),
),
);
],
];
}
/**
@ -230,21 +231,21 @@ class ConfigTest extends UnitTestCase {
/**
* @covers ::set
* @expectedException \Drupal\Core\Config\ConfigValueException
*/
public function testSetValidation() {
$this->config->set('testData', array('dot.key' => 1));
$this->setExpectedException(ConfigValueException::class);
$this->config->set('testData', ['dot.key' => 1]);
}
/**
* @covers ::set
* @expectedException PHPUnit_Framework_Error_Warning
*/
public function testSetIllegalOffsetValue() {
// Set a single value.
$this->config->set('testData', 1);
// Attempt to treat the single value as a nested item.
$this->setExpectedException(\PHPUnit_Framework_Error_Warning::class);
$this->config->set('testData.illegalOffset', 1);
}
@ -369,21 +370,20 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testMerge()
*/
public function mergeDataProvider() {
return array(
array(
return [
[
// Data.
array('a' => 1, 'b' => 2, 'c' => array('d' => 3)),
['a' => 1, 'b' => 2, 'c' => ['d' => 3]],
// Data to merge.
array('a' => 2, 'e' => 4, 'c' => array('f' => 5)),
['a' => 2, 'e' => 4, 'c' => ['f' => 5]],
// Data merged.
array('a' => 2, 'b' => 2, 'c' => array('d' => 3, 'f' => 5), 'e' => 4),
),
);
['a' => 2, 'b' => 2, 'c' => ['d' => 3, 'f' => 5], 'e' => 4],
],
];
}
/**
* @covers ::validateName
* @expectedException \Drupal\Core\Config\ConfigNameException
* @dataProvider validateNameProvider
*/
public function testValidateNameException($name, $exception_message) {
@ -404,25 +404,25 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testValidateNameException()
*/
public function validateNameProvider() {
$return = array(
$return = [
// Name missing namespace (dot).
array(
[
'MissingNamespace',
'Missing namespace in Config object name MissingNamespace.',
),
],
// Exceeds length (max length plus an extra dot).
array(
[
str_repeat('a', Config::MAX_NAME_LENGTH) . ".",
'Config object name ' . str_repeat('a', Config::MAX_NAME_LENGTH) . '. exceeds maximum allowed length of ' . Config::MAX_NAME_LENGTH . ' characters.',
),
);
],
];
// Name must not contain : ? * < > " ' / \
foreach (array(':', '?', '*', '<', '>', '"', "'", '/', '\\') as $char) {
foreach ([':', '?', '*', '<', '>', '"', "'", '/', '\\'] as $char) {
$name = 'name.' . $char;
$return[] = array(
$return[] = [
$name,
"Invalid character in Config object name $name.",
);
];
}
return $return;
}
@ -434,22 +434,22 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testDelete()
*/
public function overrideDataProvider() {
return array(
array(
return [
[
// Original data.
array(
[
'a' => 'originalValue',
),
],
// Module overrides.
array(
[
'a' => 'moduleValue',
),
],
// Setting overrides.
array(
[
'a' => 'settingValue',
),
),
);
],
],
];
}
/**
@ -458,15 +458,15 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testClear()
*/
public function simpleDataProvider() {
return array(
array(
array(
return [
[
[
'a' => '1',
'b' => '2',
'c' => '3',
),
),
);
],
],
];
}
/**
@ -479,21 +479,21 @@ class ConfigTest extends UnitTestCase {
* @see \Drupal\Tests\Core\Config\ConfigTest::testNestedClear()
*/
public function nestedDataProvider() {
return array(
array(
array(
'a' => array(
return [
[
[
'a' => [
'd' => 1,
),
'b' => array(
],
'b' => [
'e' => 2,
),
'c' => array(
],
'c' => [
'f' => 3,
),
),
),
);
],
],
],
];
}
/**

View file

@ -19,11 +19,11 @@ class ConfigDependencyManagerTest extends UnitTestCase {
public function testNoConfigEntities() {
$dep_manger = new ConfigDependencyManager();
$dep_manger->setData(array(
'simple.config' => array(
$dep_manger->setData([
'simple.config' => [
'key' => 'value',
),
));
],
]);
$this->assertEmpty($dep_manger->getDependentEntities('config', 'config_test.dynamic.entity_id:745b0ce0-aece-42dd-a800-ade5b8455e84'));
// Configuration is always dependent on its provider.

View file

@ -8,6 +8,7 @@
namespace Drupal\Tests\Core\Config\Entity;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Config\Schema\SchemaIncompleteException;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\Language\Language;
use Drupal\Core\Plugin\DefaultLazyPluginCollection;
@ -96,11 +97,11 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
*/
protected function setUp() {
$this->id = $this->randomMachineName();
$values = array(
$values = [
'id' => $this->id,
'langcode' => 'en',
'uuid' => '3bb9ee60-bea5-4622-b89b-a63319d10b3a',
);
];
$this->entityTypeId = $this->randomMachineName();
$this->provider = $this->randomMachineName();
$this->entityType = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityTypeInterface');
@ -123,7 +124,7 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
$this->languageManager->expects($this->any())
->method('getLanguage')
->with('en')
->will($this->returnValue(new Language(array('id' => 'en'))));
->will($this->returnValue(new Language(['id' => 'en'])));
$this->cacheTagsInvalidator = $this->getMock('Drupal\Core\Cache\CacheTagsInvalidatorInterface');
@ -137,7 +138,7 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
$container->set('config.typed', $this->typedConfigManager);
\Drupal::setContainer($container);
$this->entity = $this->getMockForAbstractClass('\Drupal\Core\Config\Entity\ConfigEntityBase', array($values, $this->entityTypeId));
$this->entity = $this->getMockForAbstractClass('\Drupal\Core\Config\Entity\ConfigEntityBase', [$values, $this->entityTypeId]);
}
/**
@ -146,12 +147,12 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
*/
public function testCalculateDependencies() {
// Calculating dependencies will reset the dependencies array.
$this->entity->set('dependencies', array('module' => array('node')));
$this->entity->set('dependencies', ['module' => ['node']]);
$this->assertEmpty($this->entity->calculateDependencies()->getDependencies());
// Calculating dependencies will reset the dependencies array using enforced
// dependencies.
$this->entity->set('dependencies', array('module' => array('node'), 'enforced' => array('module' => 'views')));
$this->entity->set('dependencies', ['module' => ['node'], 'enforced' => ['module' => 'views']]);
$dependencies = $this->entity->calculateDependencies()->getDependencies();
$this->assertContains('views', $dependencies['module']);
$this->assertNotContains('node', $dependencies['module']);
@ -166,7 +167,7 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
$query->expects($this->any())
->method('execute')
->will($this->returnValue(array()));
->will($this->returnValue([]));
$query->expects($this->any())
->method('condition')
->will($this->returnValue($query));
@ -179,12 +180,12 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
// Saving an entity will not reset the dependencies array during config
// synchronization.
$this->entity->set('dependencies', array('module' => array('node')));
$this->entity->set('dependencies', ['module' => ['node']]);
$this->entity->preSave($storage);
$this->assertEmpty($this->entity->getDependencies());
$this->entity->setSyncing(TRUE);
$this->entity->set('dependencies', array('module' => array('node')));
$this->entity->set('dependencies', ['module' => ['node']]);
$this->entity->preSave($storage);
$dependencies = $this->entity->getDependencies();
$this->assertContains('node', $dependencies['module']);
@ -207,12 +208,12 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
// Test sorting of dependencies.
$method->invoke($this->entity, 'module', 'action');
$dependencies = $this->entity->getDependencies();
$this->assertEquals(array('action', 'node'), $dependencies['module']);
$this->assertEquals(['action', 'node'], $dependencies['module']);
// Test sorting of dependency types.
$method->invoke($this->entity, 'entity', 'system.action.id');
$dependencies = $this->entity->getDependencies();
$this->assertEquals(array('entity', 'module'), array_keys($dependencies));
$this->assertEquals(['entity', 'module'], array_keys($dependencies));
}
/**
@ -222,20 +223,20 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
* @dataProvider providerCalculateDependenciesWithPluginCollections
*/
public function testCalculateDependenciesWithPluginCollections($definition, $expected_dependencies) {
$values = array();
$values = [];
$this->entity = $this->getMockBuilder('\Drupal\Tests\Core\Config\Entity\Fixtures\ConfigEntityBaseWithPluginCollections')
->setConstructorArgs(array($values, $this->entityTypeId))
->setMethods(array('getPluginCollections'))
->setConstructorArgs([$values, $this->entityTypeId])
->setMethods(['getPluginCollections'])
->getMock();
// Create a configurable plugin that would add a dependency.
$instance_id = $this->randomMachineName();
$instance = new TestConfigurablePlugin(array(), $instance_id, $definition);
$instance = new TestConfigurablePlugin([], $instance_id, $definition);
// Create a plugin collection to contain the instance.
$pluginCollection = $this->getMockBuilder('\Drupal\Core\Plugin\DefaultLazyPluginCollection')
->disableOriginalConstructor()
->setMethods(array('get'))
->setMethods(['get'])
->getMock();
$pluginCollection->expects($this->atLeastOnce())
->method('get')
@ -246,7 +247,7 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
// Return the mocked plugin collection.
$this->entity->expects($this->once())
->method('getPluginCollections')
->will($this->returnValue(array($pluginCollection)));
->will($this->returnValue([$pluginCollection]));
$this->assertEquals($expected_dependencies, $this->entity->calculateDependencies()->getDependencies());
}
@ -261,34 +262,34 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
$instance_dependency_1 = 'a' . $this->randomMachineName(10);
$instance_dependency_2 = 'a' . $this->randomMachineName(11);
return array(
return [
// Tests that the plugin provider is a module dependency.
array(
array('provider' => 'test'),
array('module' => array('test')),
),
[
['provider' => 'test'],
['module' => ['test']],
],
// Tests that a plugin that is provided by the same module as the config
// entity is not added to the dependencies array.
array(
array('provider' => $this->provider),
array('module' => array(NULL)),
),
[
['provider' => $this->provider],
['module' => [NULL]],
],
// Tests that a config entity that has a plugin which provides config
// dependencies in its definition has them.
array(
array(
[
[
'provider' => 'test',
'config_dependencies' => array(
'config' => array($instance_dependency_1),
'module' => array($instance_dependency_2),
)
),
array(
'config' => array($instance_dependency_1),
'module' => array($instance_dependency_2, 'test')
)
)
);
'config_dependencies' => [
'config' => [$instance_dependency_1],
'module' => [$instance_dependency_2],
]
],
[
'config' => [$instance_dependency_1],
'module' => [$instance_dependency_2, 'test']
]
]
];
}
/**
@ -297,17 +298,17 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
* @covers ::onDependencyRemoval
*/
public function testCalculateDependenciesWithThirdPartySettings() {
$this->entity = $this->getMockForAbstractClass('\Drupal\Core\Config\Entity\ConfigEntityBase', array(array(), $this->entityTypeId));
$this->entity = $this->getMockForAbstractClass('\Drupal\Core\Config\Entity\ConfigEntityBase', [[], $this->entityTypeId]);
$this->entity->setThirdPartySetting('test_provider', 'test', 'test');
$this->entity->setThirdPartySetting('test_provider2', 'test', 'test');
$this->entity->setThirdPartySetting($this->provider, 'test', 'test');
$this->assertEquals(array('test_provider', 'test_provider2'), $this->entity->calculateDependencies()->getDependencies()['module']);
$this->assertEquals(['test_provider', 'test_provider2'], $this->entity->calculateDependencies()->getDependencies()['module']);
$changed = $this->entity->onDependencyRemoval(['module' => ['test_provider2']]);
$this->assertTrue($changed, 'Calling onDependencyRemoval with an existing third party dependency provider returns TRUE.');
$changed = $this->entity->onDependencyRemoval(['module' => ['test_provider3']]);
$this->assertFalse($changed, 'Calling onDependencyRemoval with a non-existing third party dependency provider returns FALSE.');
$this->assertEquals(array('test_provider'), $this->entity->calculateDependencies()->getDependencies()['module']);
$this->assertEquals(['test_provider'], $this->entity->calculateDependencies()->getDependencies()['module']);
}
/**
@ -470,11 +471,11 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
$this->entityManager->expects($this->any())
->method('getDefinition')
->with($this->entityTypeId)
->will($this->returnValue(array(
'entity_keys' => array(
->will($this->returnValue([
'entity_keys' => [
'label' => 'label',
),
)));
],
]));
$entity_a = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityInterface');
$entity_a->expects($this->atLeastOnce())
@ -486,12 +487,12 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
->willReturn('bar');
// Test sorting by label.
$list = array($entity_a, $entity_b);
$list = [$entity_a, $entity_b];
// Suppress errors because of https://bugs.php.net/bug.php?id=50688.
@usort($list, '\Drupal\Core\Config\Entity\ConfigEntityBase::sort');
$this->assertSame($entity_b, $list[0]);
$list = array($entity_b, $entity_a);
$list = [$entity_b, $entity_a];
// Suppress errors because of https://bugs.php.net/bug.php?id=50688.
@usort($list, '\Drupal\Core\Config\Entity\ConfigEntityBase::sort');
$this->assertSame($entity_b, $list[0]);
@ -499,12 +500,12 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
// Test sorting by weight.
$entity_a->weight = 0;
$entity_b->weight = 1;
$list = array($entity_b, $entity_a);
$list = [$entity_b, $entity_a];
// Suppress errors because of https://bugs.php.net/bug.php?id=50688.
@usort($list, '\Drupal\Core\Config\Entity\ConfigEntityBase::sort');
$this->assertSame($entity_a, $list[0]);
$list = array($entity_a, $entity_b);
$list = [$entity_a, $entity_b];
// Suppress errors because of https://bugs.php.net/bug.php?id=50688.
@usort($list, '\Drupal\Core\Config\Entity\ConfigEntityBase::sort');
$this->assertSame($entity_a, $list[0]);
@ -521,7 +522,7 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
->willReturn(['id' => 'configId', 'dependencies' => 'dependencies']);
$properties = $this->entity->toArray();
$this->assertInternalType('array', $properties);
$this->assertEquals(array('configId' => $this->entity->id(), 'dependencies' => array()), $properties);
$this->assertEquals(['configId' => $this->entity->id(), 'dependencies' => []], $properties);
}
/**
@ -556,24 +557,23 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
public function testToArraySchemaFallback() {
$this->typedConfigManager->expects($this->once())
->method('getDefinition')
->will($this->returnValue(array('mapping' => array('id' => '', 'dependencies' => ''))));
->will($this->returnValue(['mapping' => ['id' => '', 'dependencies' => '']]));
$this->entityType->expects($this->any())
->method('getPropertiesToExport')
->willReturn([]);
$properties = $this->entity->toArray();
$this->assertInternalType('array', $properties);
$this->assertEquals(array('id' => $this->entity->id(), 'dependencies' => array()), $properties);
$this->assertEquals(['id' => $this->entity->id(), 'dependencies' => []], $properties);
}
/**
* @covers ::toArray
*
* @expectedException \Drupal\Core\Config\Schema\SchemaIncompleteException
*/
public function testToArrayFallback() {
$this->entityType->expects($this->any())
->method('getPropertiesToExport')
->willReturn([]);
$this->setExpectedException(SchemaIncompleteException::class);
$this->entity->toArray();
}
@ -600,15 +600,15 @@ class ConfigEntityBaseUnitTest extends UnitTestCase {
// Test getThirdPartySettings().
$this->entity->setThirdPartySetting($third_party, 'test2', 'value2');
$this->assertEquals(array($key => $value, 'test2' => 'value2'), $this->entity->getThirdPartySettings($third_party));
$this->assertEquals([$key => $value, 'test2' => 'value2'], $this->entity->getThirdPartySettings($third_party));
// Test getThirdPartyProviders().
$this->entity->setThirdPartySetting('test_provider2', $key, $value);
$this->assertEquals(array($third_party, 'test_provider2'), $this->entity->getThirdPartyProviders());
$this->assertEquals([$third_party, 'test_provider2'], $this->entity->getThirdPartyProviders());
// Test unsetThirdPartyProviders().
$this->entity->unsetThirdPartySetting('test_provider2', $key);
$this->assertEquals(array($third_party), $this->entity->getThirdPartyProviders());
$this->assertEquals([$third_party], $this->entity->getThirdPartyProviders());
}
}

View file

@ -13,34 +13,34 @@ use Drupal\Core\Config\Entity\ConfigEntityDependency;
class ConfigEntityDependencyTest extends UnitTestCase {
public function testEmptyDependencies() {
$dep = new ConfigEntityDependency('config_test.dynamic.entity_id', array());
$dep = new ConfigEntityDependency('config_test.dynamic.entity_id', []);
$this->assertEquals('config_test.dynamic.entity_id', $dep->getConfigDependencyName());
$this->assertEquals(array(), $dep->getDependencies('theme'));
$this->assertEquals(array(), $dep->getDependencies('config'));
$this->assertEquals(array('config_test'), $dep->getDependencies('module'));
$this->assertEquals([], $dep->getDependencies('theme'));
$this->assertEquals([], $dep->getDependencies('config'));
$this->assertEquals(['config_test'], $dep->getDependencies('module'));
$this->assertTrue($dep->hasDependency('module', 'config_test'));
$this->assertFalse($dep->hasDependency('module', 'views'));
}
public function testWithDependencies() {
$values = array(
$values = [
'uuid' => '60db47f4-54fb-4c86-a439-5769fbda4bd1',
'dependencies' => array(
'module' => array(
'dependencies' => [
'module' => [
'node',
'views'
),
'config' => array(
],
'config' => [
'config_test.dynamic.entity_id:745b0ce0-aece-42dd-a800-ade5b8455e84',
),
),
);
],
],
];
$dep = new ConfigEntityDependency('config_test.dynamic.entity_id', $values);
$this->assertEquals(array(), $dep->getDependencies('theme'));
$this->assertEquals(array('config_test.dynamic.entity_id:745b0ce0-aece-42dd-a800-ade5b8455e84'), $dep->getDependencies('config'));
$this->assertEquals(array('node', 'views', 'config_test'), $dep->getDependencies('module'));
$this->assertEquals([], $dep->getDependencies('theme'));
$this->assertEquals(['config_test.dynamic.entity_id:745b0ce0-aece-42dd-a800-ade5b8455e84'], $dep->getDependencies('config'));
$this->assertEquals(['node', 'views', 'config_test'], $dep->getDependencies('module'));
$this->assertTrue($dep->hasDependency('module', 'config_test'));
$this->assertTrue($dep->hasDependency('module', 'views'));
$this->assertTrue($dep->hasDependency('module', 'node'));

View file

@ -6,6 +6,7 @@ use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheTagsInvalidatorInterface;
use Drupal\Core\Config\Config;
use Drupal\Core\Config\ConfigDuplicateUUIDException;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\ConfigManagerInterface;
use Drupal\Core\Config\Entity\ConfigEntityBase;
@ -15,7 +16,9 @@ use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Config\ImmutableConfig;
use Drupal\Core\Config\TypedConfigManagerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityMalformedException;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Entity\Query\QueryFactoryInterface;
use Drupal\Core\Entity\Query\QueryInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
@ -177,7 +180,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->uuidService->generate()->shouldNotBeCalled();
$entity = $this->entityStorage->create(array('id' => 'foo', 'uuid' => 'baz'));
$entity = $this->entityStorage->create(['id' => 'foo', 'uuid' => 'baz']);
$this->assertInstanceOf(EntityInterface::class, $entity);
$this->assertSame('foo', $entity->id());
$this->assertSame('baz', $entity->uuid());
@ -206,7 +209,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->uuidService->generate()->willReturn('bar');
$entity = $this->entityStorage->create(array('id' => 'foo'));
$entity = $this->entityStorage->create(['id' => 'foo']);
$this->assertInstanceOf(EntityInterface::class, $entity);
$this->assertSame('foo', $entity->id());
$this->assertSame('bar', $entity->uuid());
@ -220,7 +223,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
public function testCreateWithCurrentLanguage() {
$this->languageManager->getLanguage('hu')->willReturn(new Language(['id' => 'hu']));
$entity = $this->entityStorage->create(array('id' => 'foo'));
$entity = $this->entityStorage->create(['id' => 'foo']);
$this->assertSame('hu', $entity->language()->getId());
}
@ -231,7 +234,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
public function testCreateWithExplicitLanguage() {
$this->languageManager->getLanguage('en')->willReturn(new Language(['id' => 'en']));
$entity = $this->entityStorage->create(array('id' => 'foo', 'langcode' => 'en'));
$entity = $this->entityStorage->create(['id' => 'foo', 'langcode' => 'en']);
$this->assertSame('en', $entity->language()->getId());
}
@ -376,23 +379,19 @@ class ConfigEntityStorageTest extends UnitTestCase {
/**
* @covers ::save
*
* @expectedException \Drupal\Core\Entity\EntityMalformedException
* @expectedExceptionMessage The entity does not have an ID.
*/
public function testSaveInvalid() {
$this->cacheTagsInvalidator->invalidateTags(Argument::cetera())
->shouldNotBeCalled();
$entity = $this->getMockEntity();
$this->setExpectedException(EntityMalformedException::class, 'The entity does not have an ID.');
$this->entityStorage->save($entity);
}
/**
* @covers ::save
* @covers ::doSave
*
* @expectedException \Drupal\Core\Entity\EntityStorageException
*/
public function testSaveDuplicate() {
$config_object = $this->prophesize(ImmutableConfig::class);
@ -404,18 +403,16 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->configFactory->get('the_provider.the_config_prefix.foo')
->willReturn($config_object->reveal());
$entity = $this->getMockEntity(array('id' => 'foo'));
$entity = $this->getMockEntity(['id' => 'foo']);
$entity->enforceIsNew();
$this->setExpectedException(EntityStorageException::class);
$this->entityStorage->save($entity);
}
/**
* @covers ::save
* @covers ::doSave
*
* @expectedException \Drupal\Core\Config\ConfigDuplicateUUIDException
* @expectedExceptionMessage when this UUID is already used for
*/
public function testSaveMismatch() {
$config_object = $this->prophesize(ImmutableConfig::class);
@ -430,7 +427,8 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->entityQuery->condition('uuid', NULL)->willReturn($this->entityQuery);
$this->entityQuery->execute()->willReturn(['baz']);
$entity = $this->getMockEntity(array('id' => 'foo'));
$entity = $this->getMockEntity(['id' => 'foo']);
$this->setExpectedException(ConfigDuplicateUUIDException::class, 'when this UUID is already used for');
$this->entityStorage->save($entity);
}
@ -463,7 +461,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->entityQuery->condition('uuid', NULL)->willReturn($this->entityQuery);
$this->entityQuery->execute()->willReturn(['baz']);
$entity = $this->getMockEntity(array('id' => 'foo'));
$entity = $this->getMockEntity(['id' => 'foo']);
$entity->setOriginalId('baz');
$entity->enforceIsNew();
$this->entityStorage->save($entity);
@ -472,9 +470,6 @@ class ConfigEntityStorageTest extends UnitTestCase {
/**
* @covers ::save
* @covers ::doSave
*
* @expectedException \Drupal\Core\Config\ConfigDuplicateUUIDException
* @expectedExceptionMessage when this entity already exists with UUID
*/
public function testSaveChangedUuid() {
$config_object = $this->prophesize(ImmutableConfig::class);
@ -501,9 +496,10 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->entityQuery->condition('uuid', 'baz')->willReturn($this->entityQuery);
$this->entityQuery->execute()->willReturn(['foo']);
$entity = $this->getMockEntity(array('id' => 'foo'));
$entity = $this->getMockEntity(['id' => 'foo']);
$entity->set('uuid', 'baz');
$this->setExpectedException(ConfigDuplicateUUIDException::class, 'when this entity already exists with UUID');
$this->entityStorage->save($entity);
}
@ -595,7 +591,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->moduleHandler->getImplementations('entity_load')->willReturn([]);
$this->moduleHandler->getImplementations('test_entity_type_load')->willReturn([]);
$entities = $this->entityStorage->loadMultiple(array('foo'));
$entities = $this->entityStorage->loadMultiple(['foo']);
$this->assertContainsOnlyInstancesOf(EntityInterface::class, $entities);
foreach ($entities as $id => $entity) {
$this->assertSame($id, $entity->id());
@ -633,9 +629,9 @@ class ConfigEntityStorageTest extends UnitTestCase {
->getConfigEntitiesToChangeOnDependencyRemoval('config', ['the_provider.the_config_prefix.bar'], FALSE)
->willReturn(['update' => [], 'delete' => [], 'unchanged' => []]);
$entities = array();
foreach (array('foo', 'bar') as $id) {
$entity = $this->getMockEntity(array('id' => $id));
$entities = [];
foreach (['foo', 'bar'] as $id) {
$entity = $this->getMockEntity(['id' => $id]);
$entities[] = $entity;
$config_object = $this->prophesize(Config::class);
@ -674,7 +670,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
$this->cacheTagsInvalidator->invalidateTags(Argument::cetera())->shouldNotBeCalled();
$this->entityStorage->delete(array());
$this->entityStorage->delete([]);
}
/**
@ -687,7 +683,7 @@ class ConfigEntityStorageTest extends UnitTestCase {
*
* @return \Drupal\Core\Entity\EntityInterface|\PHPUnit_Framework_MockObject_MockObject
*/
public function getMockEntity(array $values = array(), $methods = array()) {
public function getMockEntity(array $values = [], $methods = []) {
return $this->getMockForAbstractClass(ConfigEntityBase::class, [$values, 'test_entity_type'], '', TRUE, TRUE, TRUE, $methods);
}

View file

@ -4,6 +4,7 @@ namespace Drupal\Tests\Core\Config\Entity;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\Config\Entity\ConfigEntityType;
use Drupal\Core\Config\Entity\Exception\ConfigEntityStorageClassException;
/**
* @coversDefaultClass \Drupal\Core\Config\Entity\ConfigEntityType
@ -21,9 +22,9 @@ class ConfigEntityTypeTest extends UnitTestCase {
*/
protected function setUpConfigEntityType($definition) {
if (!isset($definition['id'])) {
$definition += array(
$definition += [
'id' => 'example_config_entity_type',
);
];
}
return new ConfigEntityType($definition);
}
@ -37,10 +38,10 @@ class ConfigEntityTypeTest extends UnitTestCase {
public function testConfigPrefixLengthExceeds() {
// A provider length of 24 and config_prefix length of 59 (+1 for the .)
// results in a config length of 84, which is too long.
$definition = array(
$definition = [
'provider' => $this->randomMachineName(24),
'config_prefix' => $this->randomMachineName(59),
);
];
$config_entity = $this->setUpConfigEntityType($definition);
$this->setExpectedException(
'\Drupal\Core\Config\ConfigPrefixLengthException',
@ -58,10 +59,10 @@ class ConfigEntityTypeTest extends UnitTestCase {
public function testConfigPrefixLengthValid() {
// A provider length of 24 and config_prefix length of 58 (+1 for the .)
// results in a config length of 83, which is right at the limit.
$definition = array(
$definition = [
'provider' => $this->randomMachineName(24),
'config_prefix' => $this->randomMachineName(58),
);
];
$config_entity = $this->setUpConfigEntityType($definition);
$expected_prefix = $definition['provider'] . '.' . $definition['config_prefix'];
$this->assertEquals($expected_prefix, $config_entity->getConfigPrefix());
@ -79,11 +80,9 @@ class ConfigEntityTypeTest extends UnitTestCase {
/**
* @covers ::__construct
*
* @expectedException \Drupal\Core\Config\Entity\Exception\ConfigEntityStorageClassException
* @expectedExceptionMessage \Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage is not \Drupal\Core\Config\Entity\ConfigEntityStorage or it does not extend it
*/
public function testConstructBadStorage() {
$this->setExpectedException(ConfigEntityStorageClassException::class, '\Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage is not \Drupal\Core\Config\Entity\ConfigEntityStorage or it does not extend it');
new ConfigEntityType([
'id' => 'example_config_entity_type',
'handlers' => ['storage' => '\Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage']
@ -92,12 +91,10 @@ class ConfigEntityTypeTest extends UnitTestCase {
/**
* @covers ::setStorageClass
*
* @expectedException \Drupal\Core\Config\Entity\Exception\ConfigEntityStorageClassException
* @expectedExceptionMessage \Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage is not \Drupal\Core\Config\Entity\ConfigEntityStorage or it does not extend it
*/
public function testSetStorageClass() {
$config_entity = $this->setUpConfigEntityType([]);
$this->setExpectedException(ConfigEntityStorageClassException::class, '\Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage is not \Drupal\Core\Config\Entity\ConfigEntityStorage or it does not extend it');
$config_entity->setStorageClass('\Drupal\Core\Entity\KeyValueStore\KeyValueEntityStorage');
}
@ -117,10 +114,10 @@ class ConfigEntityTypeTest extends UnitTestCase {
* Provides test data.
*/
public function providerTestGetConfigPrefix() {
return array(
array(array('provider' => 'node', 'id' => 'node_type', 'config_prefix' => 'type'), 'node.type'),
array(array('provider' => 'views', 'id' => 'view'), 'views.view'),
);
return [
[['provider' => 'node', 'id' => 'node_type', 'config_prefix' => 'type'], 'node.type'],
[['provider' => 'views', 'id' => 'view'], 'views.view'],
];
}
/**

View file

@ -77,7 +77,7 @@ class EntityDisplayModeBaseUnitTest extends UnitTestCase {
$target_entity_type->expects($this->any())
->method('getProvider')
->will($this->returnValue('test_module'));
$values = array('targetEntityType' => $target_entity_type_id);
$values = ['targetEntityType' => $target_entity_type_id];
$this->entityManager->expects($this->at(0))
->method('getDefinition')
@ -89,8 +89,8 @@ class EntityDisplayModeBaseUnitTest extends UnitTestCase {
->will($this->returnValue($this->entityInfo));
$this->entity = $this->getMockBuilder('\Drupal\Core\Entity\EntityDisplayModeBase')
->setConstructorArgs(array($values, $this->entityType))
->setMethods(array('getFilterFormat'))
->setConstructorArgs([$values, $this->entityType])
->setMethods(['getFilterFormat'])
->getMock();
$dependencies = $this->entity->calculateDependencies()->getDependencies();
@ -105,7 +105,7 @@ class EntityDisplayModeBaseUnitTest extends UnitTestCase {
$mock = $this->getMock(
'Drupal\Core\Entity\EntityDisplayModeBase',
NULL,
array(array('something' => 'nothing'), 'test_type')
[['something' => 'nothing'], 'test_type']
);
// Some test values.
@ -134,7 +134,7 @@ class EntityDisplayModeBaseUnitTest extends UnitTestCase {
$mock = $this->getMock(
'Drupal\Core\Entity\EntityDisplayModeBase',
NULL,
array(array('something' => 'nothing'), 'test_type')
[['something' => 'nothing'], 'test_type']
);
// A test value.

View file

@ -96,8 +96,8 @@ class QueryFactoryTest extends UnitTestCase {
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage test_config_entity_type lookup key test.* ends with a wildcard this can not be used as a lookup
* @covers ::getKeys
* @covers ::getValues
*/
public function testGetKeysWildCardEnd() {
$config_factory = $this->getMock('Drupal\Core\Config\ConfigFactoryInterface');
@ -111,6 +111,7 @@ class QueryFactoryTest extends UnitTestCase {
$method = new \ReflectionMethod($query_factory, 'getKeys');
$method->setAccessible(TRUE);
$this->setExpectedException(\LogicException::class, 'test_config_entity_type lookup key test.* ends with a wildcard this can not be used as a lookup');
$method->invoke($query_factory, $this->getConfigObject('test'), 'test.*', 'get', $config_entity_type);
}

Some files were not shown because too many files have changed in this diff Show more