updated core and modules

This commit is contained in:
Bachir Soussi Chiadmi
2017-09-09 16:27:51 +02:00
parent 027aa99b32
commit 41863f872c
7810 changed files with 318922 additions and 83631 deletions
+1 -1
View File
@@ -50,7 +50,7 @@ function hook_test_group_finished() {
* $results The results of the test as gathered by
* \Drupal\simpletest\WebTestBase.
*
* @see \Drupal\simpletest\WebTestBase->results()
* @see \Drupal\simpletest\WebTestBase::results()
*/
function hook_test_finished($results) {
}
+3 -3
View File
@@ -6,8 +6,8 @@ package: Core
# core: 8.x
configure: simpletest.settings
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233792
datestamp: 1502903957
+60 -50
View File
@@ -16,27 +16,37 @@ const SIMPLETEST_MINIMUM_PHP_MEMORY_LIMIT = '128M';
* Implements hook_requirements().
*/
function simpletest_requirements($phase) {
$requirements = array();
$requirements = [];
$has_phpunit = class_exists('\PHPUnit_Framework_TestCase');
$has_curl = function_exists('curl_init');
$open_basedir = ini_get('open_basedir');
$requirements['curl'] = array(
$requirements['phpunit'] = [
'title' => t('PHPUnit dependency'),
'value' => $has_phpunit ? t('Found') : t('Not found'),
];
if (!$has_phpunit) {
$requirements['phpunit']['severity'] = REQUIREMENT_ERROR;
$requirements['phpunit']['description'] = t("The testing framework requires the PHPUnit package. Please run 'composer install --dev' to ensure it is present.");
}
$requirements['curl'] = [
'title' => t('cURL'),
'value' => $has_curl ? t('Enabled') : t('Not found'),
);
];
if (!$has_curl) {
$requirements['curl']['severity'] = REQUIREMENT_ERROR;
$requirements['curl']['description'] = t('The testing framework could not be installed because the PHP <a href="http://php.net/manual/curl.setup.php">cURL</a> library is not available.');
$requirements['curl']['description'] = t('The testing framework requires the <a href="https://secure.php.net/manual/en/curl.setup.php">PHP cURL library</a>. For more information, see the <a href="https://www.drupal.org/requirements/php/curl">online information on installing the PHP cURL extension</a>.');
}
// SimpleTest currently needs 2 cURL options which are incompatible with
// having PHP's open_basedir restriction set.
// See https://www.drupal.org/node/674304.
$requirements['php_open_basedir'] = array(
$requirements['php_open_basedir'] = [
'title' => t('PHP open_basedir restriction'),
'value' => $open_basedir ? t('Enabled') : t('Disabled'),
);
];
if ($open_basedir) {
$requirements['php_open_basedir']['severity'] = REQUIREMENT_ERROR;
$requirements['php_open_basedir']['description'] = t('The testing framework requires the PHP <a href="http://php.net/manual/ini.core.php#ini.open-basedir">open_basedir</a> restriction to be disabled. Check your webserver configuration or contact your web host.');
@@ -47,29 +57,29 @@ function simpletest_requirements($phase) {
$memory_limit = ini_get('memory_limit');
if (!Environment::checkMemoryLimit(SIMPLETEST_MINIMUM_PHP_MEMORY_LIMIT, $memory_limit)) {
$requirements['php_memory_limit']['severity'] = REQUIREMENT_WARNING;
$requirements['php_memory_limit']['description'] = t('The testing framework requires the PHP memory limit to be at least %memory_minimum_limit. The current value is %memory_limit. <a href=":url">Follow these steps to continue</a>.', array('%memory_limit' => $memory_limit, '%memory_minimum_limit' => SIMPLETEST_MINIMUM_PHP_MEMORY_LIMIT, ':url' => 'https://www.drupal.org/node/207036'));
$requirements['php_memory_limit']['description'] = t('The testing framework requires the PHP memory limit to be at least %memory_minimum_limit. The current value is %memory_limit. <a href=":url">Follow these steps to continue</a>.', ['%memory_limit' => $memory_limit, '%memory_minimum_limit' => SIMPLETEST_MINIMUM_PHP_MEMORY_LIMIT, ':url' => 'https://www.drupal.org/node/207036']);
}
$site_directory = 'sites/simpletest';
if (!drupal_verify_install_file(\Drupal::root() . '/' . $site_directory, FILE_EXIST | FILE_READABLE | FILE_WRITABLE | FILE_EXECUTABLE, 'dir')) {
$requirements['simpletest_site_directory'] = array(
$requirements['simpletest_site_directory'] = [
'title' => t('Simpletest site directory'),
'value' => is_dir(\Drupal::root() . '/' . $site_directory) ? t('Not writable') : t('Missing'),
'severity' => REQUIREMENT_ERROR,
'description' => t('The testing framework requires the %sites-simpletest directory to exist and be writable in order to run tests.', array(
'description' => t('The testing framework requires the %sites-simpletest directory to exist and be writable in order to run tests.', [
'%sites-simpletest' => $site_directory,
)),
);
]),
];
}
elseif (!file_save_htaccess(\Drupal::root() . '/' . $site_directory, FALSE)) {
$requirements['simpletest_site_directory'] = array(
$requirements['simpletest_site_directory'] = [
'title' => t('Simpletest site directory'),
'value' => t('Not protected'),
'severity' => REQUIREMENT_ERROR,
'description' => t('The file %file does not exist and could not be created automatically, which poses a security risk. Ensure that the directory is writable.', array(
'description' => t('The file %file does not exist and could not be created automatically, which poses a security risk. Ensure that the directory is writable.', [
'%file' => $site_directory . '/.htaccess',
)),
);
]),
];
}
return $requirements;
@@ -79,91 +89,91 @@ function simpletest_requirements($phase) {
* Implements hook_schema().
*/
function simpletest_schema() {
$schema['simpletest'] = array(
$schema['simpletest'] = [
'description' => 'Stores simpletest messages',
'fields' => array(
'message_id' => array(
'fields' => [
'message_id' => [
'type' => 'serial',
'not null' => TRUE,
'description' => 'Primary Key: Unique simpletest message ID.',
),
'test_id' => array(
],
'test_id' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Test ID, messages belonging to the same ID are reported together',
),
'test_class' => array(
],
'test_class' => [
'type' => 'varchar_ascii',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'The name of the class that created this message.',
),
'status' => array(
],
'status' => [
'type' => 'varchar',
'length' => 9,
'not null' => TRUE,
'default' => '',
'description' => 'Message status. Core understands pass, fail, exception.',
),
'message' => array(
],
'message' => [
'type' => 'text',
'not null' => TRUE,
'description' => 'The message itself.',
),
'message_group' => array(
],
'message_group' => [
'type' => 'varchar_ascii',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'The message group this message belongs to. For example: warning, browser, user.',
),
'function' => array(
],
'function' => [
'type' => 'varchar_ascii',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'Name of the assertion function or method that created this message.',
),
'line' => array(
],
'line' => [
'type' => 'int',
'not null' => TRUE,
'default' => 0,
'description' => 'Line number on which the function is called.',
),
'file' => array(
],
'file' => [
'type' => 'varchar',
'length' => 255,
'not null' => TRUE,
'default' => '',
'description' => 'Name of the file where the function is called.',
),
),
'primary key' => array('message_id'),
'indexes' => array(
'reporter' => array('test_class', 'message_id'),
),
);
$schema['simpletest_test_id'] = array(
],
],
'primary key' => ['message_id'],
'indexes' => [
'reporter' => ['test_class', 'message_id'],
],
];
$schema['simpletest_test_id'] = [
'description' => 'Stores simpletest test IDs, used to auto-increment the test ID so that a fresh test ID is used.',
'fields' => array(
'test_id' => array(
'fields' => [
'test_id' => [
'type' => 'serial',
'not null' => TRUE,
'description' => 'Primary Key: Unique simpletest ID used to group test results together. Each time a set of tests
are run a new test ID is used.',
),
'last_prefix' => array(
],
'last_prefix' => [
'type' => 'varchar',
'length' => 60,
'not null' => FALSE,
'default' => '',
'description' => 'The last database prefix used during testing.',
),
),
'primary key' => array('test_id'),
);
],
],
'primary key' => ['test_id'],
];
return $schema;
}
+85 -70
View File
@@ -12,7 +12,9 @@ use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\simpletest\TestBase;
use Drupal\Core\Test\TestDatabase;
use Drupal\simpletest\TestDiscovery;
use Drupal\Tests\Listeners\SimpletestUiPrinter;
use Symfony\Component\Process\PhpExecutableFinder;
use Drupal\Core\Test\TestStatus;
/**
* Implements hook_help().
@@ -22,11 +24,11 @@ function simpletest_help($route_name, RouteMatchInterface $route_match) {
case 'help.page.simpletest':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The Testing module provides a framework for running automated tests. It can be used to verify a working state of Drupal before and after any code changes, or as a means for developers to write and execute tests for their modules. For more information, see the <a href=":simpletest">online documentation for the Testing module</a>.', array(':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest')) . '</p>';
$output .= '<p>' . t('The Testing module provides a framework for running automated tests. It can be used to verify a working state of Drupal before and after any code changes, or as a means for developers to write and execute tests for their modules. For more information, see the <a href=":simpletest">online documentation for the Testing module</a>.', [':simpletest' => 'https://www.drupal.org/documentation/modules/simpletest']) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Running tests') . '</dt>';
$output .= '<dd><p>' . t('Visit the <a href=":admin-simpletest">Testing page</a> to display a list of available tests. For comprehensive testing, select <em>all</em> tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete.', array(':admin-simpletest' => \Drupal::url('simpletest.test_form'))) . '</p>';
$output .= '<dd><p>' . t('Visit the <a href=":admin-simpletest">Testing page</a> to display a list of available tests. For comprehensive testing, select <em>all</em> tests, or individually select tests for more targeted testing. Note that it might take several minutes for all tests to complete.', [':admin-simpletest' => \Drupal::url('simpletest.test_form')]) . '</p>';
$output .= '<p>' . t('After the tests run, a message will be displayed next to each test group indicating whether tests within it passed, failed, or had exceptions. A pass means that the test returned the expected results, while fail means that it did not. An exception normally indicates an error outside of the test, such as a PHP warning or notice. If there were failures or exceptions, the results will be expanded to show details, and the tests that had failures or exceptions will be indicated in red or pink rows. You can then use these results to refine your code and tests, until all tests pass.') . '</p></dd>';
$output .= '</dl>';
return $output;
@@ -41,11 +43,11 @@ function simpletest_help($route_name, RouteMatchInterface $route_match) {
* Implements hook_theme().
*/
function simpletest_theme() {
return array(
'simpletest_result_summary' => array(
'variables' => array('label' => NULL, 'items' => array(), 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0),
),
);
return [
'simpletest_result_summary' => [
'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
],
];
}
/**
@@ -136,7 +138,7 @@ function simpletest_run_tests($test_list) {
}
$test_id = db_insert('simpletest_test_id')
->useDefaults(array('test_id'))
->useDefaults(['test_id'])
->execute();
// Clear out the previous verbose files.
@@ -146,16 +148,16 @@ function simpletest_run_tests($test_list) {
$first_test = reset($test_list);
$info = TestDiscovery::getTestInfo($first_test);
$batch = array(
$batch = [
'title' => t('Running tests'),
'operations' => array(
array('_simpletest_batch_operation', array($test_list, $test_id)),
),
'operations' => [
['_simpletest_batch_operation', [$test_list, $test_id]],
],
'finished' => '_simpletest_batch_finished',
'progress_message' => '',
'library' => array('simpletest/drupal.simpletest'),
'init_message' => t('Processing test @num of @max - %test.', array('%test' => $info['name'], '@num' => '1', '@max' => count($test_list))),
);
'library' => ['simpletest/drupal.simpletest'],
'init_message' => t('Processing test @num of @max - %test.', ['%test' => $info['name'], '@num' => '1', '@max' => count($test_list)]),
];
batch_set($batch);
\Drupal::moduleHandler()->invokeAll('test_group_started');
@@ -181,19 +183,18 @@ function simpletest_run_tests($test_list) {
*/
function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) {
$phpunit_file = simpletest_phpunit_xml_filepath($test_id);
simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file, $status);
simpletest_phpunit_run_command($unescaped_test_classnames, $phpunit_file, $status, $output);
$rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
// A $status of 0 = passed test, 1 = failed test, > 1 indicates segfault
// timeout, or other type of failure.
if ($status > 1) {
// Something broke during the execution of phpunit.
// Return an error record of all failed classes.
$rows = [];
if ($status == TestStatus::PASS) {
$rows = simpletest_phpunit_xml_to_rows($test_id, $phpunit_file);
}
else {
$rows[] = [
'test_id' => $test_id,
'test_class' => implode(",", $unescaped_test_classnames),
'status' => 'fail',
'message' => 'PHPunit Test failed to complete',
'status' => TestStatus::label($status),
'message' => 'PHPunit Test failed to complete; Error: ' . implode("\n", $output),
'message_group' => 'Other',
'function' => implode(",", $unescaped_test_classnames),
'line' => '0',
@@ -236,12 +237,12 @@ function simpletest_summarize_phpunit_result($results) {
$summaries = [];
foreach ($results as $result) {
if (!isset($summaries[$result['test_class']])) {
$summaries[$result['test_class']] = array(
$summaries[$result['test_class']] = [
'#pass' => 0,
'#fail' => 0,
'#exception' => 0,
'#debug' => 0,
);
];
}
switch ($result['status']) {
@@ -299,11 +300,13 @@ function simpletest_phpunit_configuration_filepath() {
* @param int $status
* (optional) The exit status code of the PHPUnit process will be assigned to
* this variable.
* @param string $output
* (optional) The output by running the phpunit command.
*
* @return string
* The results as returned by exec().
*/
function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL) {
function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
global $base_url;
// Setup an environment variable containing the database connection so that
// functional tests can connect to the database.
@@ -315,14 +318,17 @@ function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpun
// this variable.
if ($base_url) {
putenv('SIMPLETEST_BASE_URL=' . $base_url);
putenv('BROWSERTEST_OUTPUT_DIRECTORY=' . \Drupal::service('file_system')->realpath('public://simpletest'));
}
$phpunit_bin = simpletest_phpunit_command();
$command = array(
$command = [
$phpunit_bin,
'--log-junit',
escapeshellarg($phpunit_file),
);
'--printer',
escapeshellarg(SimpletestUiPrinter::class),
];
// Optimized for running a single test.
if (count($unescaped_test_classnames) == 1) {
@@ -336,10 +342,10 @@ function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpun
}, $unescaped_test_classnames);
$filter_string = implode("|", $escaped_test_classnames);
$command = array_merge($command, array(
$command = array_merge($command, [
'--filter',
escapeshellarg($filter_string),
));
]);
}
// Need to change directories before running the command so that we can use
@@ -355,6 +361,7 @@ function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpun
putenv('SIMPLETEST_DB=');
if ($base_url) {
putenv('SIMPLETEST_BASE_URL=');
putenv('BROWSERTEST_OUTPUT_DIRECTORY=');
}
return $ret;
}
@@ -372,17 +379,16 @@ function simpletest_phpunit_command() {
$reflector = new ReflectionClass($autoloader);
$vendor_dir = dirname(dirname($reflector->getFileName()));
// Don't use the committed version in composer's bin dir if running on
// windows.
// The file in Composer's bin dir is a *nix link, which does not work when
// extracted from a tarball and generally not on Windows.
$command = $vendor_dir . '/phpunit/phpunit/phpunit';
if (substr(PHP_OS, 0, 3) == 'WIN') {
// On Windows it is necessary to run the script using the PHP executable.
$php_executable_finder = new PhpExecutableFinder();
$php = $php_executable_finder->find();
$phpunit_bin = escapeshellarg($php) . ' -f ' . escapeshellarg($vendor_dir . '/phpunit/phpunit/composer/bin/phpunit') . ' --';
$command = $php . ' -f ' . escapeshellarg($command) . ' --';
}
else {
$phpunit_bin = $vendor_dir . '/phpunit/phpunit/phpunit';
}
return $phpunit_bin;
return $command;
}
/**
@@ -395,7 +401,7 @@ function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
// First iteration: initialize working values.
$test_list = $test_list_init;
$context['sandbox']['max'] = count($test_list);
$test_results = array('#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0);
$test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0];
}
else {
// Nth iteration: get the current values where we last stored them.
@@ -414,7 +420,7 @@ function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
else {
$test = new $test_class($test_id);
$test->run();
\Drupal::moduleHandler()->invokeAll('test_finished', array($test->results));
\Drupal::moduleHandler()->invokeAll('test_finished', [$test->results]);
$test_results[$test_class] = $test->results;
}
$size = count($test_list);
@@ -425,25 +431,25 @@ function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
$test_results[$key] += $value;
}
$test_results[$test_class]['#name'] = $info['name'];
$items = array();
$items = [];
foreach (Element::children($test_results) as $class) {
$class_test_result = $test_results[$class] + array(
$class_test_result = $test_results[$class] + [
'#theme' => 'simpletest_result_summary',
'#label' => t($test_results[$class]['#name'] . ':'),
);
];
array_unshift($items, drupal_render($class_test_result));
}
$context['message'] = t('Processed test @num of @max - %test.', array('%test' => $info['name'], '@num' => $max - $size, '@max' => $max));
$overall_results = $test_results + array(
$context['message'] = t('Processed test @num of @max - %test.', ['%test' => $info['name'], '@num' => $max - $size, '@max' => $max]);
$overall_results = $test_results + [
'#theme' => 'simpletest_result_summary',
'#label' => t('Overall results:'),
);
];
$context['message'] .= drupal_render($overall_results);
$item_list = array(
$item_list = [
'#theme' => 'item_list',
'#items' => $items,
);
];
$context['message'] .= drupal_render($item_list);
// Save working values for the next iteration.
@@ -461,7 +467,7 @@ function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
*/
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
if ($success) {
drupal_set_message(t('The test run finished in @elapsed.', array('@elapsed' => $elapsed)));
drupal_set_message(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
}
else {
// Use the test_id passed as a parameter to _simpletest_batch_operation().
@@ -490,16 +496,16 @@ function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
*/
function simpletest_last_test_get($test_id) {
$last_prefix = TestDatabase::getConnection()
->queryRange('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, array(
->queryRange('SELECT last_prefix FROM {simpletest_test_id} WHERE test_id = :test_id', 0, 1, [
':test_id' => $test_id,
))
])
->fetchField();
$last_test_class = TestDatabase::getConnection()
->queryRange('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, array(
->queryRange('SELECT test_class FROM {simpletest} WHERE test_id = :test_id ORDER BY message_id DESC', 0, 1, [
':test_id' => $test_id,
))
])
->fetchField();
return array($last_prefix, $last_test_class);
return [$last_prefix, $last_test_class];
}
/**
@@ -519,17 +525,18 @@ function simpletest_last_test_get($test_id) {
* Whether any fatal errors were found.
*/
function simpletest_log_read($test_id, $database_prefix, $test_class) {
$log = DRUPAL_ROOT . '/sites/simpletest/' . substr($database_prefix, 10) . '/error.log';
$test_db = new TestDatabase($database_prefix);
$log = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/error.log';
$found = FALSE;
if (file_exists($log)) {
foreach (file($log) as $line) {
if (preg_match('/\[.*?\] (.*?): (.*?) in (.*) on line (\d+)/', $line, $match)) {
// Parse PHP fatal errors for example: PHP Fatal error: Call to
// undefined function break_me() in /path/to/file.php on line 17
$caller = array(
$caller = [
'line' => $match[4],
'file' => $match[3],
);
];
TestBase::insertAssert($test_id, $test_class, FALSE, $match[2], $match[1], $caller);
}
else {
@@ -566,13 +573,20 @@ function simpletest_log_read($test_id, $database_prefix, $test_class) {
* ),
* );
* @endcode
*
* @deprecated in Drupal 8.3.x, for removal before 9.0.0 release. Use
* \Drupal::service('test_discovery')->getTestClasses($extension, $types)
* instead.
*/
function simpletest_test_get_all($extension = NULL, array $types = []) {
return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
}
/**
* Registers namespaces for disabled modules.
* Registers test namespaces of all extensions and core test classes.
*
* @deprecated in Drupal 8.3.x for removal before 9.0.0 release. Use
* \Drupal::service('test_discovery')->registerTestNamespaces() instead.
*/
function simpletest_classloader_register() {
\Drupal::service('test_discovery')->registerTestNamespaces();
@@ -649,13 +663,12 @@ function simpletest_clean_environment() {
* Removes prefixed tables from the database from crashed tests.
*/
function simpletest_clean_database() {
$tables = db_find_tables(Database::getConnection()->prefixTables('{simpletest}') . '%');
$schema = drupal_get_module_schema('simpletest');
$tables = db_find_tables('test%');
$count = 0;
foreach (array_diff_key($tables, $schema) as $table) {
// Strip the prefix and skip tables without digits following "simpletest",
// e.g. {simpletest_test_id}.
if (preg_match('/simpletest\d+.*/', $table, $matches)) {
foreach ($tables as $table) {
// Only drop tables which begin wih 'test' followed by digits, for example,
// {test12345678node__body}.
if (preg_match('/^test\d+.*/', $table, $matches)) {
db_drop_table($matches[0]);
$count++;
}
@@ -679,7 +692,9 @@ function simpletest_clean_temporary_directories() {
foreach ($files as $file) {
if ($file[0] != '.') {
$path = DRUPAL_ROOT . '/sites/simpletest/' . $file;
file_unmanaged_delete_recursive($path, array('Drupal\simpletest\TestBase', 'filePreDeleteCallback'));
file_unmanaged_delete_recursive($path, function ($any_path) {
@chmod($any_path, 0700);
});
$count++;
}
}
@@ -706,7 +721,7 @@ function simpletest_clean_results_table($test_id = NULL) {
if (\Drupal::config('simpletest.settings')->get('clear_results')) {
$connection = TestDatabase::getConnection();
if ($test_id) {
$count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', array(':test_id' => $test_id))->fetchField();
$count = $connection->query('SELECT COUNT(test_id) FROM {simpletest_test_id} WHERE test_id = :test_id', [':test_id' => $test_id])->fetchField();
$connection->delete('simpletest')
->condition('test_id', $test_id)
@@ -758,7 +773,7 @@ function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
if (!$contents) {
return;
}
$records = array();
$records = [];
$testcases = simpletest_phpunit_find_testcases(new SimpleXMLElement($contents));
foreach ($testcases as $testcase) {
$records[] = simpletest_phpunit_testcase_to_row($test_id, $testcase);
@@ -778,7 +793,7 @@ function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
* A list of all test cases.
*/
function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
$testcases = array();
$testcases = [];
if (!isset($parent)) {
$parent = $element;
@@ -832,7 +847,7 @@ function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcas
$attributes = $testcase->attributes();
$record = array(
$record = [
'test_id' => $test_id,
'test_class' => (string) $attributes->class,
'status' => $pass ? 'pass' : 'fail',
@@ -842,6 +857,6 @@ function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $testcas
'function' => $attributes->class . '->' . $attributes->name . '()',
'line' => $attributes->line ?: 0,
'file' => $attributes->file,
);
];
return $record;
}
@@ -61,7 +61,7 @@ trait AssertContentTrait {
$this->content = $content;
$this->plainTextContent = NULL;
$this->elements = NULL;
$this->drupalSettings = array();
$this->drupalSettings = [];
if (preg_match('@<script type="application/json" data-drupal-selector="drupal-settings-json">([^<]*)</script>@', $content, $matches)) {
$this->drupalSettings = Json::decode($matches[1]);
}
@@ -75,7 +75,7 @@ trait AssertContentTrait {
$raw_content = $this->getRawContent();
// Strip everything between the HEAD tags.
$raw_content = preg_replace('@<head>(.+?)</head>@si', '', $raw_content);
$this->plainTextContent = Xss::filter($raw_content, array());
$this->plainTextContent = Xss::filter($raw_content, []);
}
return $this->plainTextContent;
}
@@ -117,7 +117,7 @@ trait AssertContentTrait {
/**
* Parse content returned from curlExec using DOM and SimpleXML.
*
* @return \SimpleXMLElement|FALSE
* @return \SimpleXMLElement|false
* A SimpleXMLElement or FALSE on failure.
*/
protected function parse() {
@@ -127,7 +127,7 @@ trait AssertContentTrait {
$html_dom = new \DOMDocument();
@$html_dom->loadHTML('<?xml encoding="UTF-8">' . $this->getRawContent());
if ($html_dom) {
$this->pass(SafeMarkup::format('Valid HTML found on "@path"', array('@path' => $this->getUrl())), 'Browser');
$this->pass(SafeMarkup::format('Valid HTML found on "@path"', ['@path' => $this->getUrl()]), 'Browser');
// It's much easier to work with simplexml than DOM, luckily enough
// we can just simply import our DOM tree.
$this->elements = simplexml_import_dom($html_dom);
@@ -170,7 +170,7 @@ trait AssertContentTrait {
* @return string
* An XPath query with arguments replaced.
*/
protected function buildXPathQuery($xpath, array $args = array()) {
protected function buildXPathQuery($xpath, array $args = []) {
// Replace placeholders.
foreach ($args as $placeholder => $value) {
// Cast MarkupInterface objects to string.
@@ -260,7 +260,7 @@ trait AssertContentTrait {
* Option elements in select.
*/
protected function getAllOptions(\SimpleXMLElement $element) {
$options = array();
$options = [];
// Add all options items.
foreach ($element->option as $option) {
$options[] = $option;
@@ -300,8 +300,8 @@ trait AssertContentTrait {
protected function assertLink($label, $index = 0, $message = '', $group = 'Other') {
// Cast MarkupInterface objects to string.
$label = (string) $label;
$links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
$message = ($message ? $message : strtr('Link with label %label found.', array('%label' => $label)));
$links = $this->xpath('//a[normalize-space(text())=:label]', [':label' => $label]);
$message = ($message ? $message : strtr('Link with label %label found.', ['%label' => $label]));
return $this->assert(isset($links[$index]), $message, $group);
}
@@ -327,8 +327,8 @@ trait AssertContentTrait {
protected function assertNoLink($label, $message = '', $group = 'Other') {
// Cast MarkupInterface objects to string.
$label = (string) $label;
$links = $this->xpath('//a[normalize-space(text())=:label]', array(':label' => $label));
$message = ($message ? $message : SafeMarkup::format('Link with label %label not found.', array('%label' => $label)));
$links = $this->xpath('//a[normalize-space(text())=:label]', [':label' => $label]);
$message = ($message ? $message : SafeMarkup::format('Link with label %label not found.', ['%label' => $label]));
return $this->assert(empty($links), $message, $group);
}
@@ -354,8 +354,8 @@ trait AssertContentTrait {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertLinkByHref($href, $index = 0, $message = '', $group = 'Other') {
$links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
$message = ($message ? $message : SafeMarkup::format('Link containing href %href found.', array('%href' => $href)));
$links = $this->xpath('//a[contains(@href, :href)]', [':href' => $href]);
$message = ($message ? $message : SafeMarkup::format('Link containing href %href found.', ['%href' => $href]));
return $this->assert(isset($links[$index]), $message, $group);
}
@@ -379,8 +379,8 @@ trait AssertContentTrait {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertNoLinkByHref($href, $message = '', $group = 'Other') {
$links = $this->xpath('//a[contains(@href, :href)]', array(':href' => $href));
$message = ($message ? $message : SafeMarkup::format('No link containing href %href found.', array('%href' => $href)));
$links = $this->xpath('//a[contains(@href, :href)]', [':href' => $href]);
$message = ($message ? $message : SafeMarkup::format('No link containing href %href found.', ['%href' => $href]));
return $this->assert(empty($links), $message, $group);
}
@@ -404,8 +404,8 @@ trait AssertContentTrait {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertNoLinkByHrefInMainRegion($href, $message = '', $group = 'Other') {
$links = $this->xpath('//main//a[contains(@href, :href)]', array(':href' => $href));
$message = ($message ? $message : SafeMarkup::format('No link containing href %href found.', array('%href' => $href)));
$links = $this->xpath('//main//a[contains(@href, :href)]', [':href' => $href]);
$message = ($message ? $message : SafeMarkup::format('No link containing href %href found.', ['%href' => $href]));
return $this->assert(empty($links), $message, $group);
}
@@ -604,7 +604,7 @@ trait AssertContentTrait {
*/
protected function assertTextHelper($text, $message = '', $group = 'Other', $not_exists = TRUE) {
if (!$message) {
$message = !$not_exists ? SafeMarkup::format('"@text" found', array('@text' => $text)) : SafeMarkup::format('"@text" not found', array('@text' => $text));
$message = !$not_exists ? SafeMarkup::format('"@text" found', ['@text' => $text]) : SafeMarkup::format('"@text" not found', ['@text' => $text]);
}
return $this->assert($not_exists == (strpos($this->getTextContent(), (string) $text) === FALSE), $message, $group);
}
@@ -723,7 +723,7 @@ trait AssertContentTrait {
*/
protected function assertPattern($pattern, $message = '', $group = 'Other') {
if (!$message) {
$message = SafeMarkup::format('Pattern "@pattern" found', array('@pattern' => $pattern));
$message = SafeMarkup::format('Pattern "@pattern" found', ['@pattern' => $pattern]);
}
return $this->assert((bool) preg_match($pattern, $this->getRawContent()), $message, $group);
}
@@ -749,7 +749,7 @@ trait AssertContentTrait {
*/
protected function assertNoPattern($pattern, $message = '', $group = 'Other') {
if (!$message) {
$message = SafeMarkup::format('Pattern "@pattern" not found', array('@pattern' => $pattern));
$message = SafeMarkup::format('Pattern "@pattern" not found', ['@pattern' => $pattern]);
}
return $this->assert(!preg_match($pattern, $this->getRawContent()), $message, $group);
}
@@ -772,7 +772,7 @@ trait AssertContentTrait {
*/
protected function assertTextPattern($pattern, $message = NULL, $group = 'Other') {
if (!isset($message)) {
$message = SafeMarkup::format('Pattern "@pattern" found', array('@pattern' => $pattern));
$message = SafeMarkup::format('Pattern "@pattern" found', ['@pattern' => $pattern]);
}
return $this->assert((bool) preg_match($pattern, $this->getTextContent()), $message, $group);
}
@@ -804,10 +804,10 @@ trait AssertContentTrait {
$actual = $this->castSafeStrings($actual);
$title = $this->castSafeStrings($title);
if (!$message) {
$message = SafeMarkup::format('Page title @actual is equal to @expected.', array(
$message = SafeMarkup::format('Page title @actual is equal to @expected.', [
'@actual' => var_export($actual, TRUE),
'@expected' => var_export($title, TRUE),
));
]);
}
return $this->assertEqual($actual, $title, $message, $group);
}
@@ -836,10 +836,10 @@ trait AssertContentTrait {
protected function assertNoTitle($title, $message = '', $group = 'Other') {
$actual = (string) current($this->xpath('//title'));
if (!$message) {
$message = SafeMarkup::format('Page title @actual is not equal to @unexpected.', array(
$message = SafeMarkup::format('Page title @actual is not equal to @unexpected.', [
'@actual' => var_export($actual, TRUE),
'@unexpected' => var_export($title, TRUE),
));
]);
}
return $this->assertNotEqual($actual, $title, $message, $group);
}
@@ -867,7 +867,7 @@ trait AssertContentTrait {
* @return bool
* TRUE on pass, FALSE on fail.
*/
protected function assertThemeOutput($callback, array $variables = array(), $expected = '', $message = '', $group = 'Other') {
protected function assertThemeOutput($callback, array $variables = [], $expected = '', $message = '', $group = 'Other') {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = \Drupal::service('renderer');
@@ -885,7 +885,7 @@ trait AssertContentTrait {
if (!$message) {
$message = '%callback rendered correctly.';
}
$message = format_string($message, array('%callback' => 'theme_' . $callback . '()'));
$message = format_string($message, ['%callback' => 'theme_' . $callback . '()']);
return $this->assertIdentical($output, $expected, $message, $group);
}
@@ -1064,15 +1064,15 @@ trait AssertContentTrait {
protected function assertFieldByName($name, $value = NULL, $message = NULL, $group = 'Browser') {
if (!isset($message)) {
if (!isset($value)) {
$message = SafeMarkup::format('Found field with name @name', array(
$message = SafeMarkup::format('Found field with name @name', [
'@name' => var_export($name, TRUE),
));
]);
}
else {
$message = SafeMarkup::format('Found field with name @name and value @value', array(
$message = SafeMarkup::format('Found field with name @name and value @value', [
'@name' => var_export($name, TRUE),
'@value' => var_export($value, TRUE),
));
]);
}
}
return $this->assertFieldByXPath($this->constructFieldXpath('name', $name), $value, $message, $group);
@@ -1103,7 +1103,7 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertNoFieldByName($name, $value = '', $message = '', $group = 'Browser') {
return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : SafeMarkup::format('Did not find field by name @name', array('@name' => $name)), $group);
return $this->assertNoFieldByXPath($this->constructFieldXpath('name', $name), $value, $message ? $message : SafeMarkup::format('Did not find field by name @name', ['@name' => $name]), $group);
}
/**
@@ -1136,7 +1136,7 @@ trait AssertContentTrait {
$value = (string) $value;
}
$message = (string) $message;
return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : SafeMarkup::format('Found field by id @id', array('@id' => $id)), $group);
return $this->assertFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : SafeMarkup::format('Found field by id @id', ['@id' => $id]), $group);
}
/**
@@ -1164,7 +1164,7 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertNoFieldById($id, $value = '', $message = '', $group = 'Browser') {
return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : SafeMarkup::format('Did not find field by id @id', array('@id' => $id)), $group);
return $this->assertNoFieldByXPath($this->constructFieldXpath('id', $id), $value, $message ? $message : SafeMarkup::format('Did not find field by id @id', ['@id' => $id]), $group);
}
/**
@@ -1187,8 +1187,8 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertFieldChecked($id, $message = '', $group = 'Browser') {
$elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : SafeMarkup::format('Checkbox field @id is checked.', array('@id' => $id)), $group);
$elements = $this->xpath('//input[@id=:id]', [':id' => $id]);
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['checked']), $message ? $message : SafeMarkup::format('Checkbox field @id is checked.', ['@id' => $id]), $group);
}
/**
@@ -1211,8 +1211,8 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertNoFieldChecked($id, $message = '', $group = 'Browser') {
$elements = $this->xpath('//input[@id=:id]', array(':id' => $id));
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : SafeMarkup::format('Checkbox field @id is not checked.', array('@id' => $id)), $group);
$elements = $this->xpath('//input[@id=:id]', [':id' => $id]);
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['checked']), $message ? $message : SafeMarkup::format('Checkbox field @id is not checked.', ['@id' => $id]), $group);
}
/**
@@ -1237,8 +1237,8 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertOption($id, $option, $message = '', $group = 'Browser') {
$options = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @id exists.', array('@option' => $option, '@id' => $id)), $group);
$options = $this->xpath('//select[@id=:id]//option[@value=:option]', [':id' => $id, ':option' => $option]);
return $this->assertTrue(isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @id exists.', ['@option' => $option, '@id' => $id]), $group);
}
/**
@@ -1281,8 +1281,8 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertOptionWithDrupalSelector($drupal_selector, $option, $message = '', $group = 'Browser') {
$options = $this->xpath('//select[@data-drupal-selector=:data_drupal_selector]//option[@value=:option]', array(':data_drupal_selector' => $drupal_selector, ':option' => $option));
return $this->assertTrue(isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @data_drupal_selector exists.', array('@option' => $option, '@data_drupal_selector' => $drupal_selector)), $group);
$options = $this->xpath('//select[@data-drupal-selector=:data_drupal_selector]//option[@value=:option]', [':data_drupal_selector' => $drupal_selector, ':option' => $option]);
return $this->assertTrue(isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @data_drupal_selector exists.', ['@option' => $option, '@data_drupal_selector' => $drupal_selector]), $group);
}
/**
@@ -1307,9 +1307,9 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertNoOption($id, $option, $message = '', $group = 'Browser') {
$selects = $this->xpath('//select[@id=:id]', array(':id' => $id));
$options = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($selects[0]) && !isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @id does not exist.', array('@option' => $option, '@id' => $id)), $group);
$selects = $this->xpath('//select[@id=:id]', [':id' => $id]);
$options = $this->xpath('//select[@id=:id]//option[@value=:option]', [':id' => $id, ':option' => $option]);
return $this->assertTrue(isset($selects[0]) && !isset($options[0]), $message ? $message : SafeMarkup::format('Option @option for field @id does not exist.', ['@option' => $option, '@id' => $id]), $group);
}
/**
@@ -1336,8 +1336,8 @@ trait AssertContentTrait {
* @todo $id is unusable. Replace with $name.
*/
protected function assertOptionSelected($id, $option, $message = '', $group = 'Browser') {
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @id is selected.', array('@option' => $option, '@id' => $id)), $group);
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', [':id' => $id, ':option' => $option]);
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @id is selected.', ['@option' => $option, '@id' => $id]), $group);
}
/**
@@ -1364,8 +1364,8 @@ trait AssertContentTrait {
* @todo $id is unusable. Replace with $name.
*/
protected function assertOptionSelectedWithDrupalSelector($drupal_selector, $option, $message = '', $group = 'Browser') {
$elements = $this->xpath('//select[@data-drupal-selector=:data_drupal_selector]//option[@value=:option]', array(':data_drupal_selector' => $drupal_selector, ':option' => $option));
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @data_drupal_selector is selected.', array('@option' => $option, '@data_drupal_selector' => $drupal_selector)), $group);
$elements = $this->xpath('//select[@data-drupal-selector=:data_drupal_selector]//option[@value=:option]', [':data_drupal_selector' => $drupal_selector, ':option' => $option]);
return $this->assertTrue(isset($elements[0]) && !empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @data_drupal_selector is selected.', ['@option' => $option, '@data_drupal_selector' => $drupal_selector]), $group);
}
/**
@@ -1390,8 +1390,8 @@ trait AssertContentTrait {
* TRUE on pass, FALSE on fail.
*/
protected function assertNoOptionSelected($id, $option, $message = '', $group = 'Browser') {
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', array(':id' => $id, ':option' => $option));
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @id is not selected.', array('@option' => $option, '@id' => $id)), $group);
$elements = $this->xpath('//select[@id=:id]//option[@value=:option]', [':id' => $id, ':option' => $option]);
return $this->assertTrue(isset($elements[0]) && empty($elements[0]['selected']), $message ? $message : SafeMarkup::format('Option @option for field @id is not selected.', ['@option' => $option, '@id' => $id]), $group);
}
/**
@@ -1464,12 +1464,12 @@ trait AssertContentTrait {
* @return bool
* TRUE on pass, FALSE on fail.
*/
protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = array()) {
protected function assertNoDuplicateIds($message = '', $group = 'Other', $ids_to_skip = []) {
$status = TRUE;
foreach ($this->xpath('//*[@id]') as $element) {
$id = (string) $element['id'];
if (isset($seen_ids[$id]) && !in_array($id, $ids_to_skip)) {
$this->fail(SafeMarkup::format('The HTML ID %id is unique.', array('%id' => $id)), $group);
$this->fail(SafeMarkup::format('The HTML ID %id is unique.', ['%id' => $id]), $group);
$status = FALSE;
}
$seen_ids[$id] = TRUE;
@@ -1490,7 +1490,7 @@ trait AssertContentTrait {
*/
protected function constructFieldXpath($attribute, $value) {
$xpath = '//textarea[@' . $attribute . '=:value]|//input[@' . $attribute . '=:value]|//select[@' . $attribute . '=:value]';
return $this->buildXPathQuery($xpath, array(':value' => $value));
return $this->buildXPathQuery($xpath, [':value' => $value]);
}
}
@@ -38,19 +38,19 @@ trait BlockCreationTrait {
* @todo
* Add support for creating custom block instances.
*/
protected function placeBlock($plugin_id, array $settings = array()) {
protected function placeBlock($plugin_id, array $settings = []) {
$config = \Drupal::configFactory();
$settings += array(
$settings += [
'plugin' => $plugin_id,
'region' => 'sidebar_first',
'id' => strtolower($this->randomMachineName(8)),
'theme' => $config->get('system.theme')->get('default'),
'label' => $this->randomMachineName(8),
'visibility' => array(),
'visibility' => [],
'weight' => 0,
);
];
$values = [];
foreach (array('region', 'id', 'theme', 'plugin', 'weight', 'visibility') as $key) {
foreach (['region', 'id', 'theme', 'plugin', 'weight', 'visibility'] as $key) {
$values[$key] = $settings[$key];
// Remove extra values that do not belong in the settings array.
unset($settings[$key]);
@@ -22,7 +22,7 @@ trait ContentTypeCreationTrait {
* @return \Drupal\node\Entity\NodeType
* Created content type.
*/
protected function createContentType(array $values = array()) {
protected function createContentType(array $values = []) {
// Find a non-existent random type name.
if (!isset($values['type'])) {
do {
@@ -32,19 +32,19 @@ trait ContentTypeCreationTrait {
else {
$id = $values['type'];
}
$values += array(
$values += [
'type' => $id,
'name' => $id,
);
];
$type = NodeType::create($values);
$status = $type->save();
node_add_body_field($type);
if ($this instanceof \PHPUnit_Framework_TestCase) {
$this->assertSame($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', array('%type' => $type->id())))->__toString());
$this->assertSame($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', ['%type' => $type->id()]))->__toString());
}
else {
$this->assertEqual($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', array('%type' => $type->id())))->__toString());
$this->assertEqual($status, SAVED_NEW, (new FormattableMarkup('Created content type %type.', ['%type' => $type->id()]))->__toString());
}
return $type;
@@ -59,40 +59,40 @@ class SimpletestResultsForm extends FormBase {
* Builds the status image map.
*/
protected static function buildStatusImageMap() {
$image_pass = array(
$image_pass = [
'#theme' => 'image',
'#uri' => 'core/misc/icons/73b355/check.svg',
'#width' => 18,
'#height' => 18,
'#alt' => 'Pass',
);
$image_fail = array(
];
$image_fail = [
'#theme' => 'image',
'#uri' => 'core/misc/icons/e32700/error.svg',
'#width' => 18,
'#height' => 18,
'#alt' => 'Fail',
);
$image_exception = array(
];
$image_exception = [
'#theme' => 'image',
'#uri' => 'core/misc/icons/e29700/warning.svg',
'#width' => 18,
'#height' => 18,
'#alt' => 'Exception',
);
$image_debug = array(
];
$image_debug = [
'#theme' => 'image',
'#uri' => 'core/misc/icons/e29700/warning.svg',
'#width' => 18,
'#height' => 18,
'#alt' => 'Debug',
);
return array(
];
return [
'pass' => $image_pass,
'fail' => $image_fail,
'exception' => $image_exception,
'debug' => $image_debug,
);
];
}
/**
@@ -108,10 +108,10 @@ class SimpletestResultsForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state, $test_id = NULL) {
// Make sure there are test results to display and a re-run is not being
// performed.
$results = array();
$results = [];
if (is_numeric($test_id) && !$results = $this->getResults($test_id)) {
drupal_set_message($this->t('No test results to display.'), 'error');
return new RedirectResponse($this->url('simpletest.test_form', array(), array('absolute' => TRUE)));
return new RedirectResponse($this->url('simpletest.test_form', [], ['absolute' => TRUE]));
}
// Load all classes and include CSS.
@@ -120,45 +120,45 @@ class SimpletestResultsForm extends FormBase {
$filter = static::addResultForm($form, $results, $this->getStringTranslation());
// Actions.
$form['#action'] = $this->url('simpletest.result_form', array('test_id' => 're-run'));
$form['action'] = array(
$form['#action'] = $this->url('simpletest.result_form', ['test_id' => 're-run']);
$form['action'] = [
'#type' => 'fieldset',
'#title' => $this->t('Actions'),
'#attributes' => array('class' => array('container-inline')),
'#attributes' => ['class' => ['container-inline']],
'#weight' => -11,
);
];
$form['action']['filter'] = array(
$form['action']['filter'] = [
'#type' => 'select',
'#title' => 'Filter',
'#options' => array(
'all' => $this->t('All (@count)', array('@count' => count($filter['pass']) + count($filter['fail']))),
'pass' => $this->t('Pass (@count)', array('@count' => count($filter['pass']))),
'fail' => $this->t('Fail (@count)', array('@count' => count($filter['fail']))),
),
);
'#options' => [
'all' => $this->t('All (@count)', ['@count' => count($filter['pass']) + count($filter['fail'])]),
'pass' => $this->t('Pass (@count)', ['@count' => count($filter['pass'])]),
'fail' => $this->t('Fail (@count)', ['@count' => count($filter['fail'])]),
],
];
$form['action']['filter']['#default_value'] = ($filter['fail'] ? 'fail' : 'all');
// Categorized test classes for to be used with selected filter value.
$form['action']['filter_pass'] = array(
$form['action']['filter_pass'] = [
'#type' => 'hidden',
'#default_value' => implode(',', $filter['pass']),
);
$form['action']['filter_fail'] = array(
];
$form['action']['filter_fail'] = [
'#type' => 'hidden',
'#default_value' => implode(',', $filter['fail']),
);
];
$form['action']['op'] = array(
$form['action']['op'] = [
'#type' => 'submit',
'#value' => $this->t('Run tests'),
);
];
$form['action']['return'] = array(
$form['action']['return'] = [
'#type' => 'link',
'#title' => $this->t('Return to list'),
'#url' => Url::fromRoute('simpletest.test_form'),
);
];
if (is_numeric($test_id)) {
simpletest_clean_results_table($test_id);
@@ -171,8 +171,8 @@ class SimpletestResultsForm extends FormBase {
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$pass = $form_state->getValue('filter_pass') ? explode(',', $form_state->getValue('filter_pass')) : array();
$fail = $form_state->getValue('filter_fail') ? explode(',', $form_state->getValue('filter_fail')) : array();
$pass = $form_state->getValue('filter_pass') ? explode(',', $form_state->getValue('filter_pass')) : [];
$fail = $form_state->getValue('filter_fail') ? explode(',', $form_state->getValue('filter_fail')) : [];
if ($form_state->getValue('filter') == 'all') {
$classes = array_merge($pass, $fail);
@@ -189,7 +189,7 @@ class SimpletestResultsForm extends FormBase {
return;
}
$form_execute = array();
$form_execute = [];
$form_state_execute = new FormState();
foreach ($classes as $class) {
$form_state_execute->setValue(['tests', $class], $class);
@@ -247,10 +247,10 @@ class SimpletestResultsForm extends FormBase {
*/
public static function addResultForm(array &$form, array $results) {
// Transform the test results to be grouped by test class.
$test_results = array();
$test_results = [];
foreach ($results as $result) {
if (!isset($test_results[$result->test_class])) {
$test_results[$result->test_class] = array();
$test_results[$result->test_class] = [];
}
$test_results[$result->test_class][] = $result;
}
@@ -258,55 +258,55 @@ class SimpletestResultsForm extends FormBase {
$image_status_map = static::buildStatusImageMap();
// Keep track of which test cases passed or failed.
$filter = array(
'pass' => array(),
'fail' => array(),
);
$filter = [
'pass' => [],
'fail' => [],
];
// Summary result widget.
$form['result'] = array(
$form['result'] = [
'#type' => 'fieldset',
'#title' => 'Results',
// Because this is used in a theme-less situation need to provide a
// default.
'#attributes' => array(),
);
$form['result']['summary'] = $summary = array(
'#attributes' => [],
];
$form['result']['summary'] = $summary = [
'#theme' => 'simpletest_result_summary',
'#pass' => 0,
'#fail' => 0,
'#exception' => 0,
'#debug' => 0,
);
];
\Drupal::service('test_discovery')->registerTestNamespaces();
// Cycle through each test group.
$header = array(
$header = [
'Message',
'Group',
'Filename',
'Line',
'Function',
array('colspan' => 2, 'data' => 'Status')
);
$form['result']['results'] = array();
['colspan' => 2, 'data' => 'Status']
];
$form['result']['results'] = [];
foreach ($test_results as $group => $assertions) {
// Create group details with summary information.
$info = TestDiscovery::getTestInfo($group);
$form['result']['results'][$group] = array(
$form['result']['results'][$group] = [
'#type' => 'details',
'#title' => $info['name'],
'#open' => TRUE,
'#description' => $info['description'],
);
];
$form['result']['results'][$group]['summary'] = $summary;
$group_summary =& $form['result']['results'][$group]['summary'];
// Create table of assertions for the group.
$rows = array();
$rows = [];
foreach ($assertions as $assertion) {
$row = array();
$row = [];
$row[] = ['data' => ['#markup' => $assertion->message]];
$row[] = $assertion->message_group;
$row[] = \Drupal::service('file_system')->basename(($assertion->file));
@@ -318,16 +318,16 @@ class SimpletestResultsForm extends FormBase {
if ($assertion->message_group == 'Debug') {
$class = 'simpletest-debug';
}
$rows[] = array('data' => $row, 'class' => array($class));
$rows[] = ['data' => $row, 'class' => [$class]];
$group_summary['#' . $assertion->status]++;
$form['result']['summary']['#' . $assertion->status]++;
}
$form['result']['results'][$group]['table'] = array(
$form['result']['results'][$group]['table'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
);
];
// Set summary information.
$group_summary['#ok'] = $group_summary['#fail'] + $group_summary['#exception'] == 0;
@@ -29,56 +29,56 @@ class SimpletestSettingsForm extends ConfigFormBase {
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('simpletest.settings');
$form['general'] = array(
$form['general'] = [
'#type' => 'details',
'#title' => $this->t('General'),
'#open' => TRUE,
);
$form['general']['simpletest_clear_results'] = array(
];
$form['general']['simpletest_clear_results'] = [
'#type' => 'checkbox',
'#title' => $this->t('Clear results after each complete test suite run'),
'#description' => $this->t('By default SimpleTest will clear the results after they have been viewed on the results page, but in some cases it may be useful to leave the results in the database. The results can then be viewed at <em>admin/config/development/testing/results/[test_id]</em>. The test ID can be found in the database, simpletest table, or kept track of when viewing the results the first time. Additionally, some modules may provide more analysis or features that require this setting to be disabled.'),
'#default_value' => $config->get('clear_results'),
);
$form['general']['simpletest_verbose'] = array(
];
$form['general']['simpletest_verbose'] = [
'#type' => 'checkbox',
'#title' => $this->t('Provide verbose information when running tests'),
'#description' => $this->t('The verbose data will be printed along with the standard assertions and is useful for debugging. The verbose data will be erased between each test suite run. The verbose data output is very detailed and should only be used when debugging.'),
'#default_value' => $config->get('verbose'),
);
];
$form['httpauth'] = array(
$form['httpauth'] = [
'#type' => 'details',
'#title' => $this->t('HTTP authentication'),
'#description' => $this->t('HTTP auth settings to be used by the SimpleTest browser during testing. Useful when the site requires basic HTTP authentication.'),
);
$form['httpauth']['simpletest_httpauth_method'] = array(
];
$form['httpauth']['simpletest_httpauth_method'] = [
'#type' => 'select',
'#title' => $this->t('Method'),
'#options' => array(
'#options' => [
CURLAUTH_BASIC => $this->t('Basic'),
CURLAUTH_DIGEST => $this->t('Digest'),
CURLAUTH_GSSNEGOTIATE => $this->t('GSS negotiate'),
CURLAUTH_NTLM => $this->t('NTLM'),
CURLAUTH_ANY => $this->t('Any'),
CURLAUTH_ANYSAFE => $this->t('Any safe'),
),
],
'#default_value' => $config->get('httpauth.method'),
);
];
$username = $config->get('httpauth.username');
$password = $config->get('httpauth.password');
$form['httpauth']['simpletest_httpauth_username'] = array(
$form['httpauth']['simpletest_httpauth_username'] = [
'#type' => 'textfield',
'#title' => $this->t('Username'),
'#default_value' => $username,
);
];
if (!empty($username) && !empty($password)) {
$form['httpauth']['simpletest_httpauth_username']['#description'] = $this->t('Leave this blank to delete both the existing username and password.');
}
$form['httpauth']['simpletest_httpauth_password'] = array(
$form['httpauth']['simpletest_httpauth_password'] = [
'#type' => 'password',
'#title' => $this->t('Password'),
);
];
if ($password) {
$form['httpauth']['simpletest_httpauth_password']['#description'] = $this->t('To change the password, enter the new password here.');
}
@@ -5,6 +5,7 @@ namespace Drupal\simpletest\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\RendererInterface;
use Drupal\simpletest\TestDiscovery;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
@@ -19,12 +20,20 @@ class SimpletestTestForm extends FormBase {
*/
protected $renderer;
/**
* The test discovery service.
*
* @var \Drupal\simpletest\TestDiscovery
*/
protected $testDiscovery;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('renderer')
$container->get('renderer'),
$container->get('test_discovery')
);
}
@@ -33,9 +42,12 @@ class SimpletestTestForm extends FormBase {
*
* @param \Drupal\Core\Render\RendererInterface $renderer
* The renderer.
* @param \Drupal\simpletest\TestDiscovery $test_discovery
* The test discovery service.
*/
public function __construct(RendererInterface $renderer) {
public function __construct(RendererInterface $renderer, TestDiscovery $test_discovery) {
$this->renderer = $renderer;
$this->testDiscovery = $test_discovery;
}
/**
@@ -49,24 +61,24 @@ class SimpletestTestForm extends FormBase {
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['actions'] = array('#type' => 'actions');
$form['actions']['submit'] = array(
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Run tests'),
'#tableselect' => TRUE,
'#button_type' => 'primary',
);
$form['clean'] = array(
];
$form['clean'] = [
'#type' => 'fieldset',
'#title' => $this->t('Clean test environment'),
'#description' => $this->t('Remove tables with the prefix "simpletest" and temporary directories that are left over from tests that crashed. This is intended for developers when creating tests.'),
'#weight' => 200,
);
$form['clean']['op'] = array(
];
$form['clean']['op'] = [
'#type' => 'submit',
'#value' => $this->t('Clean environment'),
'#submit' => array('simpletest_clean_environment'),
);
'#submit' => ['simpletest_clean_environment'],
];
// Do not needlessly re-execute a full test discovery if the user input
// already contains an explicit list of test classes to run.
@@ -76,43 +88,43 @@ class SimpletestTestForm extends FormBase {
}
// JavaScript-only table filters.
$form['filters'] = array(
$form['filters'] = [
'#type' => 'container',
'#attributes' => array(
'class' => array('table-filter', 'js-show'),
),
);
$form['filters']['text'] = array(
'#attributes' => [
'class' => ['table-filter', 'js-show'],
],
];
$form['filters']['text'] = [
'#type' => 'search',
'#title' => $this->t('Search'),
'#size' => 30,
'#placeholder' => $this->t('Enter test name…'),
'#attributes' => array(
'class' => array('table-filter-text'),
'#attributes' => [
'class' => ['table-filter-text'],
'data-table' => '#simpletest-test-form',
'autocomplete' => 'off',
'title' => $this->t('Enter at least 3 characters of the test name or description to filter by.'),
),
);
],
];
$form['tests'] = array(
$form['tests'] = [
'#type' => 'table',
'#id' => 'simpletest-form-table',
'#tableselect' => TRUE,
'#header' => array(
array('data' => $this->t('Test'), 'class' => array('simpletest-test-label')),
array('data' => $this->t('Description'), 'class' => array('simpletest-test-description')),
),
'#header' => [
['data' => $this->t('Test'), 'class' => ['simpletest-test-label']],
['data' => $this->t('Description'), 'class' => ['simpletest-test-description']],
],
'#empty' => $this->t('No tests to display.'),
'#attached' => array(
'library' => array(
'#attached' => [
'library' => [
'simpletest/drupal.simpletest',
),
),
);
],
],
];
// Define the images used to expand/collapse the test groups.
$image_collapsed = array(
$image_collapsed = [
'#theme' => 'image',
'#uri' => 'core/misc/menu-collapsed.png',
'#width' => '7',
@@ -120,8 +132,8 @@ class SimpletestTestForm extends FormBase {
'#alt' => $this->t('Expand'),
'#title' => $this->t('Expand'),
'#suffix' => '<a href="#" class="simpletest-collapse">(' . $this->t('Expand') . ')</a>',
);
$image_extended = array(
];
$image_extended = [
'#theme' => 'image',
'#uri' => 'core/misc/menu-expanded.png',
'#width' => '7',
@@ -129,18 +141,18 @@ class SimpletestTestForm extends FormBase {
'#alt' => $this->t('Collapse'),
'#title' => $this->t('Collapse'),
'#suffix' => '<a href="#" class="simpletest-collapse">(' . $this->t('Collapse') . ')</a>',
);
];
$form['tests']['#attached']['drupalSettings']['simpleTest']['images'] = [
(string) $this->renderer->renderPlain($image_collapsed),
(string) $this->renderer->renderPlain($image_extended),
];
// Generate the list of tests arranged by group.
$groups = simpletest_test_get_all();
$groups = $this->testDiscovery->getTestClasses();
foreach ($groups as $group => $tests) {
$form['tests'][$group] = array(
'#attributes' => array('class' => array('simpletest-group')),
);
$form['tests'][$group] = [
'#attributes' => ['class' => ['simpletest-group']],
];
// Make the class name safe for output on the page by replacing all
// non-word/decimal characters with a dash (-).
@@ -148,47 +160,47 @@ class SimpletestTestForm extends FormBase {
// Override tableselect column with custom selector for this group.
// This group-select-all checkbox is injected via JavaScript.
$form['tests'][$group]['select'] = array(
'#wrapper_attributes' => array(
$form['tests'][$group]['select'] = [
'#wrapper_attributes' => [
'id' => $group_class,
'class' => array('simpletest-group-select-all'),
),
);
$form['tests'][$group]['title'] = array(
'class' => ['simpletest-group-select-all'],
],
];
$form['tests'][$group]['title'] = [
// Expand/collapse image.
'#prefix' => '<div class="simpletest-image" id="simpletest-test-group-' . $group_class . '"></div>',
'#markup' => '<label for="' . $group_class . '-group-select-all">' . $group . '</label>',
'#wrapper_attributes' => array(
'class' => array('simpletest-group-label'),
),
);
$form['tests'][$group]['description'] = array(
'#wrapper_attributes' => [
'class' => ['simpletest-group-label'],
],
];
$form['tests'][$group]['description'] = [
'#markup' => '&nbsp;',
'#wrapper_attributes' => array(
'class' => array('simpletest-group-description'),
),
);
'#wrapper_attributes' => [
'class' => ['simpletest-group-description'],
],
];
// Cycle through each test within the current group.
foreach ($tests as $class => $info) {
$form['tests'][$class] = array(
'#attributes' => array('class' => array($group_class . '-test', 'js-hide')),
);
$form['tests'][$class]['title'] = array(
$form['tests'][$class] = [
'#attributes' => ['class' => [$group_class . '-test', 'js-hide']],
];
$form['tests'][$class]['title'] = [
'#type' => 'label',
'#title' => '\\' . $info['name'],
'#wrapper_attributes' => array(
'class' => array('simpletest-test-label', 'table-filter-text-source'),
),
);
$form['tests'][$class]['description'] = array(
'#wrapper_attributes' => [
'class' => ['simpletest-test-label', 'table-filter-text-source'],
],
];
$form['tests'][$class]['description'] = [
'#prefix' => '<div class="description">',
'#plain_text' => $info['description'],
'#suffix' => '</div>',
'#wrapper_attributes' => array(
'class' => array('simpletest-test-description', 'table-filter-text-source'),
),
);
'#wrapper_attributes' => [
'class' => ['simpletest-test-description', 'table-filter-text-source'],
],
];
}
}
@@ -200,7 +212,7 @@ class SimpletestTestForm extends FormBase {
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Test discovery does not run upon form submission.
simpletest_classloader_register();
$this->testDiscovery->registerTestNamespaces();
// This form accepts arbitrary user input for 'tests'.
// An invalid value will cause the $class_name lookup below to die with a
@@ -221,7 +233,7 @@ class SimpletestTestForm extends FormBase {
$test_id = simpletest_run_tests($tests_list, 'drupal');
$form_state->setRedirect(
'simpletest.result_form',
array('test_id' => $test_id)
['test_id' => $test_id]
);
}
}
@@ -23,7 +23,7 @@ abstract class InstallerTestBase extends WebTestBase {
* An array of settings to write out, in the format expected by
* drupal_rewrite_settings().
*/
protected $settings = array();
protected $settings = [];
/**
* The language code in which to install Drupal.
@@ -46,7 +46,7 @@ abstract class InstallerTestBase extends WebTestBase {
*
* @var array
*/
protected $parameters = array();
protected $parameters = [];
/**
* A string translation map used for translated installer screens.
@@ -55,9 +55,9 @@ abstract class InstallerTestBase extends WebTestBase {
*
* @var array
*/
protected $translations = array(
protected $translations = [
'Save and continue' => 'Save and continue',
);
];
/**
* Whether the installer has completed.
@@ -73,12 +73,12 @@ abstract class InstallerTestBase extends WebTestBase {
$this->isInstalled = FALSE;
// Define information about the user 1 account.
$this->rootUser = new UserSession(array(
$this->rootUser = new UserSession([
'uid' => 1,
'name' => 'admin',
'mail' => 'admin@example.com',
'pass_raw' => $this->randomMachineName(),
));
]);
// If any $settings are defined for this test, copy and prepare an actual
// settings.php, so as to resemble a regular installation.
@@ -171,9 +171,9 @@ abstract class InstallerTestBase extends WebTestBase {
* Installer step: Select language.
*/
protected function setUpLanguage() {
$edit = array(
$edit = [
'langcode' => $this->langcode,
);
];
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
}
@@ -181,9 +181,9 @@ abstract class InstallerTestBase extends WebTestBase {
* Installer step: Select installation profile.
*/
protected function setUpProfile() {
$edit = array(
$edit = [
'profile' => $this->profile,
);
];
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
}
+28 -27
View File
@@ -5,6 +5,7 @@ namespace Drupal\simpletest;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Component\Utility\Variable;
use Drupal\Core\Config\Development\ConfigSchemaChecker;
use Drupal\Core\Database\Database;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DrupalKernel;
@@ -29,7 +30,7 @@ use Symfony\Component\HttpFoundation\Request;
* Additional modules needed in a test may be loaded and added to the fixed
* module list.
*
* @deprecated in Drupal 8.0.x, will be removed before Drupal 8.2.x. Use
* @deprecated in Drupal 8.0.x, will be removed before Drupal 9.0.0. Use
* \Drupal\KernelTests\KernelTestBase instead.
*
* @see \Drupal\simpletest\KernelTestBase::$modules
@@ -60,7 +61,7 @@ abstract class KernelTestBase extends TestBase {
*
* @var array
*/
public static $modules = array();
public static $modules = [];
private $moduleFiles;
private $themeFiles;
@@ -70,7 +71,7 @@ abstract class KernelTestBase extends TestBase {
*
* @var array
*/
protected $configDirectories = array();
protected $configDirectories = [];
/**
* A KeyValueMemoryFactory instance to use when building the container.
@@ -84,12 +85,12 @@ abstract class KernelTestBase extends TestBase {
*
* @var array
*/
protected $streamWrappers = array();
protected $streamWrappers = [];
/**
* {@inheritdoc}
*/
function __construct($test_id = NULL) {
public function __construct($test_id = NULL) {
parent::__construct($test_id);
$this->skipClasses[__CLASS__] = TRUE;
}
@@ -100,8 +101,8 @@ abstract class KernelTestBase extends TestBase {
protected function beforePrepareEnvironment() {
// Copy/prime extension file lists once to avoid filesystem scans.
if (!isset($this->moduleFiles)) {
$this->moduleFiles = \Drupal::state()->get('system.module.files') ?: array();
$this->themeFiles = \Drupal::state()->get('system.theme.files') ?: array();
$this->moduleFiles = \Drupal::state()->get('system.module.files') ?: [];
$this->themeFiles = \Drupal::state()->get('system.theme.files') ?: [];
}
}
@@ -114,7 +115,7 @@ abstract class KernelTestBase extends TestBase {
* Thrown when CONFIG_SYNC_DIRECTORY cannot be created or made writable.
*/
protected function prepareConfigDirectories() {
$this->configDirectories = array();
$this->configDirectories = [];
include_once DRUPAL_ROOT . '/core/includes/install.inc';
// Assign the relative path to the global variable.
$path = $this->siteDirectory . '/config_' . CONFIG_SYNC_DIRECTORY;
@@ -231,11 +232,11 @@ EOD;
// \Drupal\Core\Config\ConfigInstaller::installDefaultConfig() to work.
// Write directly to active storage to avoid early instantiation of
// the event dispatcher which can prevent modules from registering events.
\Drupal::service('config.storage')->write('core.extension', array('module' => array(), 'theme' => array()));
\Drupal::service('config.storage')->write('core.extension', ['module' => [], 'theme' => [], 'profile' => '']);
// Collect and set a fixed module list.
$class = get_class($this);
$modules = array();
$modules = [];
while ($class) {
if (property_exists($class, 'modules')) {
// Only add the modules, if the $modules property was not inherited.
@@ -261,7 +262,7 @@ EOD;
// @see https://www.drupal.org/node/2028109
file_prepare_directory($this->publicFilesDirectory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS);
$this->settingsSet('file_public_path', $this->publicFilesDirectory);
$this->streamWrappers = array();
$this->streamWrappers = [];
$this->registerStreamWrapper('public', 'Drupal\Core\StreamWrapper\PublicStream');
// The temporary stream wrapper is able to operate both with and without
// configuration.
@@ -321,13 +322,13 @@ EOD;
if ($this->strictConfigSchema) {
$container
->register('simpletest.config_schema_checker', 'Drupal\Core\Config\Testing\ConfigSchemaChecker')
->register('simpletest.config_schema_checker', ConfigSchemaChecker::class)
->addArgument(new Reference('config.typed'))
->addArgument($this->getConfigSchemaExclusions())
->addTag('event_subscriber');
}
$keyvalue_options = $container->getParameter('factory.keyvalue') ?: array();
$keyvalue_options = $container->getParameter('factory.keyvalue') ?: [];
$keyvalue_options['default'] = 'keyvalue.memory';
$container->setParameter('factory.keyvalue', $keyvalue_options);
$container->set('keyvalue.memory', $this->keyValueFactory);
@@ -365,14 +366,14 @@ EOD;
}
if ($container->hasDefinition('password')) {
$container->getDefinition('password')->setArguments(array(1));
$container->getDefinition('password')->setArguments([1]);
}
// Register the stream wrapper manager.
$container
->register('stream_wrapper_manager', 'Drupal\Core\StreamWrapper\StreamWrapperManager')
->addArgument(new Reference('module_handler'))
->addMethodCall('setContainer', array(new Reference('service_container')));
->addMethodCall('setContainer', [new Reference('service_container')]);
$request = Request::create('/');
$container->get('request_stack')->push($request);
@@ -404,9 +405,9 @@ EOD;
}
\Drupal::service('config.installer')->installDefaultConfig('module', $module);
}
$this->pass(format_string('Installed default config: %modules.', array(
$this->pass(format_string('Installed default config: %modules.', [
'%modules' => implode(', ', $modules),
)));
]));
}
/**
@@ -446,10 +447,10 @@ EOD;
}
$this->container->get('database')->schema()->createTable($table, $schema);
}
$this->pass(format_string('Installed %module tables: %tables.', array(
$this->pass(format_string('Installed %module tables: %tables.', [
'%tables' => '{' . implode('}, {', $tables) . '}',
'%module' => $module,
)));
]));
}
@@ -475,18 +476,18 @@ EOD;
$all_tables_exist = TRUE;
foreach ($tables as $table) {
if (!$db_schema->tableExists($table)) {
$this->fail(SafeMarkup::format('Installed entity type table for the %entity_type entity type: %table', array(
$this->fail(SafeMarkup::format('Installed entity type table for the %entity_type entity type: %table', [
'%entity_type' => $entity_type_id,
'%table' => $table,
)));
]));
$all_tables_exist = FALSE;
}
}
if ($all_tables_exist) {
$this->pass(SafeMarkup::format('Installed entity type tables for the %entity_type entity type: %tables', array(
$this->pass(SafeMarkup::format('Installed entity type tables for the %entity_type entity type: %tables', [
'%entity_type' => $entity_type_id,
'%tables' => '{' . implode('}, {', $tables) . '}',
)));
]));
}
}
}
@@ -538,9 +539,9 @@ EOD;
// Note that the kernel has rebuilt the container; this $module_handler is
// no longer the $module_handler instance from above.
$this->container->get('module_handler')->reload();
$this->pass(format_string('Enabled modules: %modules.', array(
$this->pass(format_string('Enabled modules: %modules.', [
'%modules' => implode(', ', $modules),
)));
]));
}
/**
@@ -573,9 +574,9 @@ EOD;
// no longer the $module_handler instance from above.
$module_handler = $this->container->get('module_handler');
$module_handler->reload();
$this->pass(format_string('Disabled modules: %modules.', array(
$this->pass(format_string('Disabled modules: %modules.', [
'%modules' => implode(', ', $modules),
)));
]));
}
/**
@@ -22,7 +22,7 @@ trait NodeCreationTrait {
* @return \Drupal\node\NodeInterface
* A node entity matching $title.
*/
function getNodeByTitle($title, $reset = FALSE) {
public function getNodeByTitle($title, $reset = FALSE) {
if ($reset) {
\Drupal::entityTypeManager()->getStorage('node')->resetCache();
}
@@ -64,17 +64,17 @@ trait NodeCreationTrait {
* @return \Drupal\node\NodeInterface
* The created node entity.
*/
protected function createNode(array $settings = array()) {
protected function createNode(array $settings = []) {
// Populate defaults array.
$settings += array(
'body' => array(array(
$settings += [
'body' => [[
'value' => $this->randomMachineName(32),
'format' => filter_default_format(),
)),
]],
'title' => $this->randomMachineName(8),
'type' => 'page',
'uid' => \Drupal::currentUser()->id(),
);
];
$node = Node::create($settings);
$node->save();
+61 -302
View File
@@ -7,15 +7,15 @@ use Drupal\Component\Render\MarkupInterface;
use Drupal\Component\Utility\Crypt;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\Core\Database\Database;
use Drupal\Core\Config\ConfigImporter;
use Drupal\Core\Config\StorageComparer;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\PublicStream;
use Drupal\Core\Test\TestDatabase;
use Drupal\Core\Test\TestSetupTrait;
use Drupal\Core\Utility\Error;
use Drupal\Tests\ConfigTestTrait;
use Drupal\Tests\RandomGeneratorTrait;
use Drupal\Tests\SessionTestTrait;
use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
/**
* Base class for Drupal tests.
@@ -24,23 +24,16 @@ use Drupal\Tests\SessionTestTrait;
*/
abstract class TestBase {
use TestSetupTrait;
use SessionTestTrait;
use RandomGeneratorTrait;
use AssertHelperTrait;
/**
* The test run ID.
*
* @var string
*/
protected $testId;
/**
* The site directory of this test run.
*
* @var string
*/
protected $siteDirectory = NULL;
use GeneratePermutationsTrait;
// For backwards compatibility switch the visbility of the methods to public.
use ConfigTestTrait {
configImporter as public;
copyConfig as public;
}
/**
* The database prefix of this test run.
@@ -59,19 +52,19 @@ abstract class TestBase {
*
* @var Array
*/
public $results = array(
public $results = [
'#pass' => 0,
'#fail' => 0,
'#exception' => 0,
'#debug' => 0,
);
];
/**
* Assertions thrown in that test case.
*
* @var Array
*/
protected $assertions = array();
protected $assertions = [];
/**
* This class is skipped when looking for the source of an assertion.
@@ -81,7 +74,7 @@ abstract class TestBase {
* that called it. So we need to skip the classes defining these helper
* methods.
*/
protected $skipClasses = array(__CLASS__ => TRUE);
protected $skipClasses = [__CLASS__ => TRUE];
/**
* TRUE if verbose debugging is enabled.
@@ -174,13 +167,6 @@ abstract class TestBase {
*/
protected $originalPrefix;
/**
* The original installation profile.
*
* @var string
*/
protected $originalProfile;
/**
* The name of the session cookie of the test-runner.
*
@@ -202,13 +188,6 @@ abstract class TestBase {
*/
protected $originalShutdownCallbacks;
/**
* The site directory of the original parent site.
*
* @var string
*/
protected $originalSite;
/**
* The original user, before testing began.
*
@@ -216,33 +195,6 @@ abstract class TestBase {
*/
protected $originalUser;
/**
* The public file directory for the test environment.
*
* This is set in TestBase::prepareEnvironment().
*
* @var string
*/
protected $publicFilesDirectory;
/**
* The private file directory for the test environment.
*
* This is set in TestBase::prepareEnvironment().
*
* @var string
*/
protected $privateFilesDirectory;
/**
* The temporary file directory for the test environment.
*
* This is set in TestBase::prepareEnvironment().
*
* @var string
*/
protected $tempFilesDirectory;
/**
* The translation file directory for the test environment.
*
@@ -261,20 +213,6 @@ abstract class TestBase {
*/
public $dieOnFail = FALSE;
/**
* 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 used in a test.
*
@@ -282,31 +220,6 @@ abstract class TestBase {
*/
protected $configImporter;
/**
* Set to TRUE to strict check all configuration saved.
*
* @see \Drupal\Core\Config\Testing\ConfigSchemaChecker
*
* @var bool
*/
protected $strictConfigSchema = TRUE;
/**
* 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',
);
/**
* HTTP authentication method (specified as a CURLAUTH_* constant).
*
@@ -344,7 +257,7 @@ abstract class TestBase {
* Array of errors containing a list of unmet requirements.
*/
protected function checkRequirements() {
return array();
return [];
}
/**
@@ -408,7 +321,7 @@ abstract class TestBase {
}
// Creation assertion array that can be displayed while tests are running.
$assertion = array(
$assertion = [
'test_id' => $this->testId,
'test_class' => get_class($this),
'status' => $status,
@@ -417,7 +330,7 @@ abstract class TestBase {
'function' => $caller['function'],
'line' => $caller['line'],
'file' => $caller['file'],
);
];
// Store assertion for display after the test has completed.
$message_id = $this->storeAssertion($assertion);
@@ -453,19 +366,19 @@ abstract class TestBase {
* @see \Drupal\simpletest\TestBase::assert()
* @see \Drupal\simpletest\TestBase::deleteAssert()
*/
public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = array()) {
public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
// Convert boolean status to string status.
if (is_bool($status)) {
$status = $status ? 'pass' : 'fail';
}
$caller += array(
$caller += [
'function' => 'Unknown',
'line' => 0,
'file' => 'Unknown',
);
];
$assertion = array(
$assertion = [
'test_id' => $test_id,
'test_class' => $test_class,
'status' => $status,
@@ -474,7 +387,7 @@ abstract class TestBase {
'function' => $caller['function'],
'line' => $caller['line'],
'file' => $caller['file'],
);
];
// We can't use storeAssertion() because this method is static.
return self::getDatabaseConnection()
@@ -502,16 +415,6 @@ abstract class TestBase {
->execute();
}
/**
* 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();
}
/**
* Cycles through backtrace until the first non-assertion method is found.
*
@@ -524,7 +427,7 @@ abstract class TestBase {
// The first element is the call. The second element is the caller.
// We skip calls that occurred in one of the methods of our base classes
// or in an assertion function.
while (($caller = $backtrace[1]) &&
while (($caller = $backtrace[1]) &&
((isset($caller['class']) && isset($this->skipClasses[$caller['class']])) ||
substr($caller['function'], 0, 6) == 'assert')) {
// We remove that call.
@@ -556,7 +459,7 @@ abstract class TestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertTrue($value, $message = '', $group = 'Other') {
return $this->assert((bool) $value, $message ? $message : SafeMarkup::format('Value @value is TRUE.', array('@value' => var_export($value, TRUE))), $group);
return $this->assert((bool) $value, $message ? $message : SafeMarkup::format('Value @value is TRUE.', ['@value' => var_export($value, TRUE)]), $group);
}
/**
@@ -581,7 +484,7 @@ abstract class TestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertFalse($value, $message = '', $group = 'Other') {
return $this->assert(!$value, $message ? $message : SafeMarkup::format('Value @value is FALSE.', array('@value' => var_export($value, TRUE))), $group);
return $this->assert(!$value, $message ? $message : SafeMarkup::format('Value @value is FALSE.', ['@value' => var_export($value, TRUE)]), $group);
}
/**
@@ -604,7 +507,7 @@ abstract class TestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertNull($value, $message = '', $group = 'Other') {
return $this->assert(!isset($value), $message ? $message : SafeMarkup::format('Value @value is NULL.', array('@value' => var_export($value, TRUE))), $group);
return $this->assert(!isset($value), $message ? $message : SafeMarkup::format('Value @value is NULL.', ['@value' => var_export($value, TRUE)]), $group);
}
/**
@@ -627,7 +530,7 @@ abstract class TestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertNotNull($value, $message = '', $group = 'Other') {
return $this->assert(isset($value), $message ? $message : SafeMarkup::format('Value @value is not NULL.', array('@value' => var_export($value, TRUE))), $group);
return $this->assert(isset($value), $message ? $message : SafeMarkup::format('Value @value is not NULL.', ['@value' => var_export($value, TRUE)]), $group);
}
/**
@@ -659,7 +562,7 @@ abstract class TestBase {
$second = $this->castSafeStrings($second);
$is_equal = $first == $second;
if (!$is_equal || !$message) {
$default_message = SafeMarkup::format('Value @first is equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)));
$default_message = SafeMarkup::format('Value @first is equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
$message = $message ? $message . PHP_EOL . $default_message : $default_message;
}
return $this->assert($is_equal, $message, $group);
@@ -694,7 +597,7 @@ abstract class TestBase {
$second = $this->castSafeStrings($second);
$not_equal = $first != $second;
if (!$not_equal || !$message) {
$default_message = SafeMarkup::format('Value @first is not equal to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)));
$default_message = SafeMarkup::format('Value @first is not equal to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
$message = $message ? $message . PHP_EOL . $default_message : $default_message;
}
return $this->assert($not_equal, $message, $group);
@@ -724,7 +627,7 @@ abstract class TestBase {
protected function assertIdentical($first, $second, $message = '', $group = 'Other') {
$is_identical = $first === $second;
if (!$is_identical || !$message) {
$default_message = SafeMarkup::format('Value @first is identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)));
$default_message = SafeMarkup::format('Value @first is identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
$message = $message ? $message . PHP_EOL . $default_message : $default_message;
}
return $this->assert($is_identical, $message, $group);
@@ -754,7 +657,7 @@ abstract class TestBase {
protected function assertNotIdentical($first, $second, $message = '', $group = 'Other') {
$not_identical = $first !== $second;
if (!$not_identical || !$message) {
$default_message = SafeMarkup::format('Value @first is not identical to value @second.', array('@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)));
$default_message = SafeMarkup::format('Value @first is not identical to value @second.', ['@first' => var_export($first, TRUE), '@second' => var_export($second, TRUE)]);
$message = $message ? $message . PHP_EOL . $default_message : $default_message;
}
return $this->assert($not_identical, $message, $group);
@@ -782,10 +685,10 @@ abstract class TestBase {
* TRUE if the assertion succeeded, FALSE otherwise.
*/
protected function assertIdenticalObject($object1, $object2, $message = '', $group = 'Other') {
$message = $message ?: SafeMarkup::format('@object1 is identical to @object2', array(
$message = $message ?: SafeMarkup::format('@object1 is identical to @object2', [
'@object1' => var_export($object1, TRUE),
'@object2' => var_export($object2, TRUE),
));
]);
$identical = TRUE;
foreach ($object1 as $key => $value) {
$identical = $identical && isset($object2->$key) && $object2->$key === $value;
@@ -957,14 +860,14 @@ abstract class TestBase {
* taken into account, but it can be useful to only run a few selected test
* methods during debugging.
*/
public function run(array $methods = array()) {
public function run(array $methods = []) {
$class = get_class($this);
if ($missing_requirements = $this->checkRequirements()) {
$object_info = new \ReflectionObject($this);
$caller = array(
$caller = [
'file' => $object_info->getFileName(),
);
];
foreach ($missing_requirements as $missing_requirement) {
TestBase::insertAssert($this->testId, $class, FALSE, $missing_requirement, 'Requirements check', $caller);
}
@@ -1002,7 +905,7 @@ abstract class TestBase {
// compatibility.
Handle::register();
set_error_handler(array($this, 'errorHandler'));
set_error_handler([$this, 'errorHandler']);
// Iterate through all the methods in this class, unless a specific list of
// methods to run was passed.
$test_methods = array_filter(get_class_methods($class), function ($method) {
@@ -1011,7 +914,7 @@ abstract class TestBase {
if (empty($test_methods)) {
// Call $this->assert() here because we need to pass along custom caller
// information, lest the wrong originating code file/line be identified.
$this->assert(FALSE, 'No test methods found.', 'Requirements', array('function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__));
$this->assert(FALSE, 'No test methods found.', 'Requirements', ['function' => __METHOD__ . '()', 'file' => __FILE__, 'line' => __LINE__]);
}
if ($methods) {
$test_methods = array_intersect($test_methods, $methods);
@@ -1020,11 +923,11 @@ abstract class TestBase {
// Insert a fail record. This will be deleted on completion to ensure
// that testing completed.
$method_info = new \ReflectionMethod($class, $method);
$caller = array(
$caller = [
'file' => $method_info->getFileName(),
'line' => $method_info->getStartLine(),
'function' => $class . '->' . $method . '()',
);
];
$test_completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
try {
@@ -1105,20 +1008,15 @@ abstract class TestBase {
* @see drupal_valid_test_ua()
*/
private function prepareDatabasePrefix() {
// Ensure that the generated test site directory does not exist already,
// which may happen with a large amount of concurrent threads and
// long-running tests.
do {
$suffix = mt_rand(100000, 999999);
$this->siteDirectory = 'sites/simpletest/' . $suffix;
$this->databasePrefix = 'simpletest' . $suffix;
} while (is_dir(DRUPAL_ROOT . '/' . $this->siteDirectory));
$test_db = new TestDatabase();
$this->siteDirectory = $test_db->getTestSitePath();
$this->databasePrefix = $test_db->getDatabasePrefix();
// As soon as the database prefix is set, the test might start to execute.
// All assertions as well as the SimpleTest batch operations are associated
// with the testId, so the database prefix has to be associated with it.
$affected_rows = self::getDatabaseConnection()->update('simpletest_test_id')
->fields(array('last_prefix' => $this->databasePrefix))
->fields(['last_prefix' => $this->databasePrefix])
->condition('test_id', $this->testId)
->execute();
if (!$affected_rows) {
@@ -1126,36 +1024,6 @@ abstract class TestBase {
}
}
/**
* Changes the database connection to the prefixed one.
*
* @see TestBase::prepareEnvironment()
*/
private function changeDatabasePrefix() {
if (empty($this->databasePrefix)) {
$this->prepareDatabasePrefix();
}
// If the backup already exists, something went terribly wrong.
// This case is possible, because database connection info is a static
// global state construct on the Database class, which at least persists
// for all test methods executed in one PHP process.
if (Database::getConnectionInfo('simpletest_original_default')) {
throw new \RuntimeException("Bad Database connection state: 'simpletest_original_default' connection key already exists. Broken test?");
}
// Clone the current connection and replace the current prefix.
$connection_info = Database::getConnectionInfo('default');
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']);
}
/**
* Act on global state information before the environment is altered for a test.
*
@@ -1237,7 +1105,7 @@ abstract class TestBase {
// handlers defined by the original one.
$callbacks = &drupal_register_shutdown_function();
$this->originalShutdownCallbacks = $callbacks;
$callbacks = array();
$callbacks = [];
// Create test directory ahead of installation so fatal errors and debug
// information can be logged during installation process.
@@ -1287,11 +1155,11 @@ abstract class TestBase {
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,
'container_yamls' => [],
));
]);
drupal_set_time_limit($this->timeLimit);
}
@@ -1315,7 +1183,7 @@ abstract class TestBase {
*/
private function restoreEnvironment() {
// Destroy the session if one was started during the test-run.
$_SESSION = array();
$_SESSION = [];
if (PHP_SAPI !== 'cli' && session_status() === PHP_SESSION_ACTIVE) {
session_destroy();
$params = session_get_cookie_params();
@@ -1331,7 +1199,7 @@ abstract class TestBase {
drupal_static_reset();
if ($this->container && $this->container->has('state') && $state = $this->container->get('state')) {
$captured_emails = $state->get('system.test_mail_collector') ?: array();
$captured_emails = $state->get('system.test_mail_collector') ?: [];
$emailCount = count($captured_emails);
if ($emailCount) {
$message = $emailCount == 1 ? '1 email was sent during this test.' : $emailCount . ' emails were sent during this test.';
@@ -1366,7 +1234,7 @@ abstract class TestBase {
\Drupal::setContainer($this->originalContainer);
// Delete test site directory.
file_unmanaged_delete_recursive($this->siteDirectory, array($this, 'filePreDeleteCallback'));
file_unmanaged_delete_recursive($this->siteDirectory, [$this, 'filePreDeleteCallback']);
// Restore original database connection.
Database::removeConnection('default');
@@ -1412,7 +1280,7 @@ abstract class TestBase {
*/
public function errorHandler($severity, $message, $file = NULL, $line = NULL) {
if ($severity & error_reporting()) {
$error_map = array(
$error_map = [
E_STRICT => 'Run-time notice',
E_WARNING => 'Warning',
E_NOTICE => 'Notice',
@@ -1424,7 +1292,7 @@ abstract class TestBase {
E_RECOVERABLE_ERROR => 'Recoverable error',
E_DEPRECATED => 'Deprecated',
E_USER_DEPRECATED => 'User deprecated',
);
];
$backtrace = debug_backtrace();
@@ -1449,15 +1317,15 @@ abstract class TestBase {
$backtrace = $exception->getTrace();
$verbose_backtrace = $backtrace;
// Push on top of the backtrace the call that generated the exception.
array_unshift($backtrace, array(
array_unshift($backtrace, [
'line' => $exception->getLine(),
'file' => $exception->getFile(),
));
]);
$decoded_exception = Error::decodeException($exception);
unset($decoded_exception['backtrace']);
$message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + array(
$message = SafeMarkup::format('%type: @message in %function (line %line of %file). <pre class="backtrace">@backtrace</pre>', $decoded_exception + [
'@backtrace' => Error::formatBacktrace($verbose_backtrace),
));
]);
$this->error($message, 'Uncaught exception', Error::getLastCaller($backtrace));
}
@@ -1477,55 +1345,6 @@ abstract class TestBase {
new Settings($settings);
}
/**
* Converts a list of possible parameters into a stack of permutations.
*
* Takes a list of parameters containing possible values, and converts all of
* them into a list of items containing every possible permutation.
*
* Example:
* @code
* $parameters = array(
* 'one' => array(0, 1),
* 'two' => array(2, 3),
* );
* $permutations = TestBase::generatePermutations($parameters);
* // Result:
* $permutations == array(
* array('one' => 0, 'two' => 2),
* array('one' => 1, 'two' => 2),
* array('one' => 0, 'two' => 3),
* array('one' => 1, 'two' => 3),
* )
* @endcode
*
* @param $parameters
* An associative array of parameters, keyed by parameter name, and whose
* values are arrays of parameter values.
*
* @return
* A list of permutations, which is an array of arrays. Each inner array
* contains the full list of parameters that have been passed, but with a
* single value only.
*/
public static function generatePermutations($parameters) {
$all_permutations = array(array());
foreach ($parameters as $parameter => $values) {
$new_permutations = array();
// Iterate over all values of the parameter.
foreach ($values as $value) {
// Iterate over all existing permutations.
foreach ($all_permutations as $permutation) {
// Add the new parameter value to existing permutations.
$new_permutations[] = $permutation + array($parameter => $value);
}
}
// Replace the old permutations with the new permutations.
$all_permutations = $new_permutations;
}
return $all_permutations;
}
/**
* Ensures test files are deletable within file_unmanaged_delete_recursive().
*
@@ -1534,52 +1353,11 @@ abstract class TestBase {
* need to get deleted too.
*/
public static function filePreDeleteCallback($path) {
chmod($path, 0700);
}
/**
* Returns a ConfigImporter object to import test importing of configuration.
*
* @return \Drupal\Core\Config\ConfigImporter
* The ConfigImporter object.
*/
public function configImporter() {
if (!$this->configImporter) {
// Set up the ConfigImporter object for testing.
$storage_comparer = new StorageComparer(
$this->container->get('config.storage.sync'),
$this->container->get('config.storage'),
$this->container->get('config.manager')
);
$this->configImporter = new ConfigImporter(
$storage_comparer,
$this->container->get('event_dispatcher'),
$this->container->get('config.manager'),
$this->container->get('lock'),
$this->container->get('config.typed'),
$this->container->get('module_handler'),
$this->container->get('module_installer'),
$this->container->get('theme_handler'),
$this->container->get('string_translation')
);
}
// Always recalculate the changelist when called.
return $this->configImporter->reset();
}
/**
* Copies configuration objects from source storage to target storage.
*
* @param \Drupal\Core\Config\StorageInterface $source_storage
* The source config storage service.
* @param \Drupal\Core\Config\StorageInterface $target_storage
* The target config storage service.
*/
public function copyConfig(StorageInterface $source_storage, StorageInterface $target_storage) {
$target_storage->deleteAll();
foreach ($source_storage->listAll() as $name) {
$target_storage->write($name, $source_storage->read($name));
}
// When the webserver runs with the same system user as the test runner, we
// can make read-only files writable again. If not, chmod will fail while
// the file deletion still works if file permissions have been configured
// correctly. Thus, we ignore any problems while running chmod.
@chmod($path, 0700);
}
/**
@@ -1615,23 +1393,4 @@ abstract class TestBase {
return $this->tempFilesDirectory;
}
/**
* Gets the config schema exclusions for this test.
*
* @return string[]
* An array of config object names that are excluded from schema checking.
*/
protected function getConfigSchemaExclusions() {
$class = get_class($this);
$exceptions = [];
while ($class) {
if (property_exists($class, 'configSchemaCheckerExclusions')) {
$exceptions = array_merge($exceptions, $class::$configSchemaCheckerExclusions);
}
$class = get_parent_class($class);
}
// Filter out any duplicates.
return array_unique($exceptions);
}
}
+15 -11
View File
@@ -81,7 +81,7 @@ class TestDiscovery {
}
/**
* Registers test namespaces of all available extensions.
* Registers test namespaces of all extensions and core test classes.
*
* @return array
* An associative array whose keys are PSR-4 namespace prefixes and whose
@@ -91,7 +91,7 @@ class TestDiscovery {
if (isset($this->testNamespaces)) {
return $this->testNamespaces;
}
$this->testNamespaces = array();
$this->testNamespaces = [];
$existing = $this->classLoader->getPrefixesPsr4();
@@ -101,7 +101,7 @@ class TestDiscovery {
$this->testNamespaces['Drupal\\FunctionalTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalTests'];
$this->testNamespaces['Drupal\\FunctionalJavascriptTests\\'] = [$this->root . '/core/tests/Drupal/FunctionalJavascriptTests'];
$this->availableExtensions = array();
$this->availableExtensions = [];
foreach ($this->getExtensions() as $name => $extension) {
$this->availableExtensions[$extension->getType()][$name] = $name;
@@ -119,6 +119,10 @@ class TestDiscovery {
$this->testNamespaces["Drupal\\Tests\\$name\\Kernel\\"][] = "$base_path/tests/src/Kernel";
$this->testNamespaces["Drupal\\Tests\\$name\\Functional\\"][] = "$base_path/tests/src/Functional";
$this->testNamespaces["Drupal\\Tests\\$name\\FunctionalJavascript\\"][] = "$base_path/tests/src/FunctionalJavascript";
// Add discovery for traits which are shared between different test
// suites.
$this->testNamespaces["Drupal\\Tests\\$name\\Traits\\"][] = "$base_path/tests/src/Traits";
}
foreach ($this->testNamespaces as $prefix => $paths) {
@@ -160,7 +164,7 @@ class TestDiscovery {
return $cache->data;
}
}
$list = array();
$list = [];
$classmap = $this->findAllClassFiles($extension);
@@ -234,7 +238,7 @@ class TestDiscovery {
* fully-qualified classnames to pathnames.
*/
public function findAllClassFiles($extension = NULL) {
$classmap = array();
$classmap = [];
$namespaces = $this->registerTestNamespaces();
if (isset($extension)) {
// Include tests in the \Drupal\Tests\{$extension} namespace.
@@ -290,7 +294,7 @@ class TestDiscovery {
return $current->isFile() && $current->getExtension() === 'php';
});
$files = new \RecursiveIteratorIterator($filter);
$classes = array();
$classes = [];
foreach ($files as $fileinfo) {
$class = $namespace_prefix;
if ('' !== $subpath = $fileinfo->getSubPath()) {
@@ -328,10 +332,10 @@ class TestDiscovery {
$reflection = new \ReflectionClass($classname);
$doc_comment = $reflection->getDocComment();
}
$info = array(
$info = [
'name' => $classname,
);
$annotations = array();
];
$annotations = [];
// Look for annotations, allow an arbitrary amount of spaces before the
// * but nothing else.
preg_match_all('/^[ ]*\* \@([^\s]*) (.*$)/m', $doc_comment, $matches);
@@ -375,7 +379,7 @@ class TestDiscovery {
/**
* Parses the phpDoc summary line of a test class.
*
* @param string $doc_comment.
* @param string $doc_comment
*
* @return string
* The parsed phpDoc summary line. An empty string is returned if no summary
@@ -475,7 +479,7 @@ class TestDiscovery {
protected function getExtensions() {
$listing = new ExtensionDiscovery($this->root);
// Ensure that tests in all profiles are discovered.
$listing->setProfileDirectories(array());
$listing->setProfileDirectories([]);
$extensions = $listing->scan('module', TRUE);
$extensions += $listing->scan('profile', TRUE);
$extensions += $listing->scan('theme', TRUE);
@@ -17,7 +17,7 @@ class TestServiceProvider implements ServiceProviderInterface, ServiceModifierIn
/**
* {@inheritdoc}
*/
function register(ContainerBuilder $container) {
public function register(ContainerBuilder $container) {
if (static::$currentTest && method_exists(static::$currentTest, 'containerBuild')) {
static::$currentTest->containerBuild($container);
}
@@ -22,7 +22,7 @@ class BrokenSetUpTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('simpletest');
public static $modules = ['simpletest'];
/**
* The path to the shared trigger file.
@@ -39,7 +39,7 @@ class BrokenSetUpTest extends WebTestBase {
$this->sharedTriggerFile = $this->publicFilesDirectory . '/trigger';
// Create and log in user.
$admin_user = $this->drupalCreateUser(array('administer unit tests'));
$admin_user = $this->drupalCreateUser(['administer unit tests']);
$this->drupalLogin($admin_user);
}
// If the test is being run from within simpletest, set up the broken test.
@@ -71,7 +71,7 @@ class BrokenSetUpTest extends WebTestBase {
/**
* Runs this test case from within the simpletest child site.
*/
function testMethod() {
public function testMethod() {
// If the test is being run from the main site, run it again from the web
// interface within the simpletest child site.
if (!$this->isInChildSite()) {
@@ -37,20 +37,20 @@ class BrowserTest extends WebTestBase {
/**
* Test \Drupal\simpletest\WebTestBase::getAbsoluteUrl().
*/
function testGetAbsoluteUrl() {
public function testGetAbsoluteUrl() {
$url = 'user/login';
$this->drupalGet($url);
$absolute = \Drupal::url('user.login', array(), array('absolute' => TRUE));
$absolute = \Drupal::url('user.login', [], ['absolute' => TRUE]);
$this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
$this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
$this->drupalPostForm(NULL, array(), t('Log in'));
$this->drupalPostForm(NULL, [], t('Log in'));
$this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
$this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
$this->clickLink('Create new account');
$absolute = \Drupal::url('user.register', array(), array('absolute' => TRUE));
$absolute = \Drupal::url('user.register', [], ['absolute' => TRUE]);
$this->assertEqual($absolute, $this->url, 'Passed and requested URL are equal.');
$this->assertEqual($this->url, $this->getAbsoluteUrl($this->url), 'Requested and returned absolute URL are equal.');
}
@@ -58,7 +58,7 @@ class BrowserTest extends WebTestBase {
/**
* Tests XPath escaping.
*/
function testXPathEscaping() {
public function testXPathEscaping() {
$testpage = <<< EOF
<html>
<body>
@@ -72,16 +72,16 @@ EOF;
$this->setRawContent($testpage);
// Matches the first link.
$urls = $this->xpath('//a[text()=:text]', array(':text' => 'A "weird" link, just to bother the dumb "XPath 1.0"'));
$urls = $this->xpath('//a[text()=:text]', [':text' => 'A "weird" link, just to bother the dumb "XPath 1.0"']);
$this->assertEqual($urls[0]['href'], 'link1', 'Match with quotes.');
$urls = $this->xpath('//a[text()=:text]', array(':text' => 'A second "even more weird" link, in memory of George O\'Malley'));
$urls = $this->xpath('//a[text()=:text]', [':text' => 'A second "even more weird" link, in memory of George O\'Malley']);
$this->assertEqual($urls[0]['href'], 'link2', 'Match with mixed single and double quotes.');
$urls = $this->xpath('//a[text()=:text]', array(':text' => 'A $third$ link, so weird it\'s worth $1 million'));
$urls = $this->xpath('//a[text()=:text]', [':text' => 'A $third$ link, so weird it\'s worth $1 million']);
$this->assertEqual($urls[0]['href'], 'link3', 'Match with a regular expression back reference symbol (dollar sign).');
$urls = $this->xpath('//a[text()=:text]', array(':text' => 'A fourth link, containing alternative \\1 regex backreferences \\2'));
$urls = $this->xpath('//a[text()=:text]', [':text' => 'A fourth link, containing alternative \\1 regex backreferences \\2']);
$this->assertEqual($urls[0]['href'], 'link4', 'Match with another regular expression back reference symbol (double backslash).');
}
@@ -16,7 +16,7 @@ class InstallationProfileModuleTestsTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('simpletest');
public static $modules = ['simpletest'];
/**
* An administrative user with permission to adminsiter unit tests.
@@ -42,19 +42,19 @@ class InstallationProfileModuleTestsTest extends WebTestBase {
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(array('administer unit tests'));
$this->adminUser = $this->drupalCreateUser(['administer unit tests']);
$this->drupalLogin($this->adminUser);
}
/**
* Tests existence of test case located in an installation profile module.
*/
function testInstallationProfileTests() {
public function testInstallationProfileTests() {
$this->drupalGet('admin/config/development/testing');
$this->assertText('Drupal\drupal_system_listing_compatible_test\Tests\SystemListingCompatibleTest');
$edit = array(
$edit = [
'tests[Drupal\drupal_system_listing_compatible_test\Tests\SystemListingCompatibleTest]' => TRUE,
);
];
$this->drupalPostForm(NULL, $edit, t('Run tests'));
$this->assertText('SystemListingCompatibleTest test executed.');
}
@@ -20,7 +20,7 @@ class KernelTestBaseTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('entity_test');
public static $modules = ['entity_test'];
/**
* {@inheritdoc}
@@ -50,8 +50,8 @@ EOS;
/**
* Tests expected behavior of setUp().
*/
function testSetUp() {
$modules = array('entity_test');
public function testSetUp() {
$modules = ['entity_test'];
$table = 'entity_test';
// Verify that specified $modules have been loaded.
@@ -79,7 +79,7 @@ EOS;
/**
* Tests expected load behavior of enableModules().
*/
function testEnableModulesLoad() {
public function testEnableModulesLoad() {
$module = 'field_test';
// Verify that the module does not exist yet.
@@ -90,7 +90,7 @@ EOS;
$this->assertFalse(in_array($module, $list), "{$module}_entity_display_build_alter() in \Drupal::moduleHandler()->getImplementations() not found.");
// Enable the module.
$this->enableModules(array($module));
$this->enableModules([$module]);
// Verify that the module exists.
$this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
@@ -103,7 +103,7 @@ EOS;
/**
* Tests expected installation behavior of enableModules().
*/
function testEnableModulesInstall() {
public function testEnableModulesInstall() {
$module = 'module_test';
$table = 'module_test';
@@ -117,7 +117,7 @@ EOS;
$this->assertFalse(db_table_exists($table), "'$table' database table not found.");
// Install the module.
\Drupal::service('module_installer')->install(array($module));
\Drupal::service('module_installer')->install([$module]);
// Verify that the enabled module exists.
$this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
@@ -134,11 +134,11 @@ EOS;
/**
* Tests installing modules with DependencyInjection services.
*/
function testEnableModulesInstallContainer() {
public function testEnableModulesInstallContainer() {
// Install Node module.
$this->enableModules(array('user', 'field', 'node'));
$this->enableModules(['user', 'field', 'node']);
$this->installEntitySchema('node', array('node', 'node_field_data'));
$this->installEntitySchema('node', ['node', 'node_field_data']);
// Perform an entity query against node.
$query = \Drupal::entityQuery('node');
// Disable node access checks, since User module is not enabled.
@@ -151,7 +151,7 @@ EOS;
/**
* Tests expected behavior of installSchema().
*/
function testInstallSchema() {
public function testInstallSchema() {
$module = 'entity_test';
$table = 'entity_test_example';
// Verify that we can install a table from the module schema.
@@ -190,7 +190,7 @@ EOS;
$this->assertTrue($schema, "'$table' table schema found.");
// Verify that the same table can be installed after enabling the module.
$this->enableModules(array($module));
$this->enableModules([$module]);
$this->installSchema($module, $table);
$this->assertTrue(db_table_exists($table), "'$table' database table found.");
$schema = drupal_get_module_schema($module, $table);
@@ -200,10 +200,10 @@ EOS;
/**
* Tests expected behavior of installEntitySchema().
*/
function testInstallEntitySchema() {
public function testInstallEntitySchema() {
$entity = 'entity_test';
// The entity_test Entity has a field that depends on the User module.
$this->enableModules(array('user'));
$this->enableModules(['user']);
// Verity that the entity schema is created properly.
$this->installEntitySchema($entity);
$this->assertTrue(db_table_exists($entity), "'$entity' database table found.");
@@ -212,14 +212,14 @@ EOS;
/**
* Tests expected behavior of installConfig().
*/
function testInstallConfig() {
public function testInstallConfig() {
// The user module has configuration that depends on system.
$this->enableModules(array('system'));
$this->enableModules(['system']);
$module = 'user';
// Verify that default config can only be installed for enabled modules.
try {
$this->installConfig(array($module));
$this->installConfig([$module]);
$this->fail('Exception for non-enabled module found.');
}
catch (\Exception $e) {
@@ -228,8 +228,8 @@ EOS;
$this->assertFalse($this->container->get('config.storage')->exists('user.settings'));
// Verify that default config can be installed.
$this->enableModules(array('user'));
$this->installConfig(array('user'));
$this->enableModules(['user']);
$this->installConfig(['user']);
$this->assertTrue($this->container->get('config.storage')->exists('user.settings'));
$this->assertTrue($this->config('user.settings')->get('register'));
}
@@ -237,9 +237,9 @@ EOS;
/**
* Tests that the module list is retained after enabling/installing/disabling.
*/
function testEnableModulesFixedList() {
public function testEnableModulesFixedList() {
// Install system module.
$this->container->get('module_installer')->install(array('system', 'menu_link_content'));
$this->container->get('module_installer')->install(['system', 'menu_link_content']);
$entity_manager = \Drupal::entityManager();
// entity_test is loaded via $modules; its entity type should exist.
@@ -247,17 +247,17 @@ EOS;
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
// Load some additional modules; entity_test should still exist.
$this->enableModules(array('field', 'text', 'entity_test'));
$this->enableModules(['field', 'text', 'entity_test']);
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
// Install some other modules; entity_test should still exist.
$this->container->get('module_installer')->install(array('user', 'field', 'field_test'), FALSE);
$this->container->get('module_installer')->install(['user', 'field', 'field_test'], FALSE);
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
// Uninstall one of those modules; entity_test should still exist.
$this->container->get('module_installer')->uninstall(array('field_test'));
$this->container->get('module_installer')->uninstall(['field_test']);
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
@@ -267,19 +267,19 @@ EOS;
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
// Reactivate the previously uninstalled module.
$this->enableModules(array('field_test'));
$this->enableModules(['field_test']);
// Create a field.
$display = EntityViewDisplay::create(array(
$display = EntityViewDisplay::create([
'targetEntityType' => 'entity_test',
'bundle' => 'entity_test',
'mode' => 'default',
));
$field_storage = FieldStorageConfig::create(array(
]);
$field_storage = FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'entity_test',
'type' => 'test_field'
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@@ -290,52 +290,52 @@ EOS;
/**
* Tests that ThemeManager works right after loading a module.
*/
function testEnableModulesTheme() {
public function testEnableModulesTheme() {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container->get('renderer');
$original_element = $element = array(
$original_element = $element = [
'#type' => 'container',
'#markup' => 'Foo',
'#attributes' => array(),
);
$this->enableModules(array('system'));
'#attributes' => [],
];
$this->enableModules(['system']);
// \Drupal\Core\Theme\ThemeManager::render() throws an exception if modules
// are not loaded yet.
$this->assertTrue($renderer->renderRoot($element));
$element = $original_element;
$this->disableModules(array('entity_test'));
$this->disableModules(['entity_test']);
$this->assertTrue($renderer->renderRoot($element));
}
/**
* Tests that there is no theme by default.
*/
function testNoThemeByDefault() {
public function testNoThemeByDefault() {
$themes = $this->config('core.extension')->get('theme');
$this->assertEqual($themes, array());
$this->assertEqual($themes, []);
$extensions = $this->container->get('config.storage')->read('core.extension');
$this->assertEqual($extensions['theme'], array());
$this->assertEqual($extensions['theme'], []);
$active_theme = $this->container->get('theme.manager')->getActiveTheme();
$this->assertEqual($active_theme->getName(), 'core');
}
/**
* Tests that drupal_get_profile() returns NULL.
* Tests that \Drupal::installProfile() returns NULL.
*
* As the currently active installation profile is used when installing
* configuration, for example, this is essential to ensure test isolation.
*/
public function testDrupalGetProfile() {
$this->assertNull(drupal_get_profile());
$this->assertNull(\Drupal::installProfile());
}
/**
* {@inheritdoc}
*/
public function run(array $methods = array()) {
public function run(array $methods = []) {
parent::run($methods);
// Check that all tables of the test instance have been deleted. At this
@@ -357,11 +357,11 @@ EOS;
':prefix' => $this->databasePrefix
]);
$result = $connection->query("SELECT name FROM " . $this->databasePrefix . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", array(
$result = $connection->query("SELECT name FROM " . $this->databasePrefix . ".sqlite_master WHERE type = :type AND name LIKE :table_name AND name NOT LIKE :pattern", [
':type' => 'table',
':table_name' => '%',
':pattern' => 'sqlite_%',
))->fetchAllKeyed(0, 0);
])->fetchAllKeyed(0, 0);
$this->assertTrue(empty($result), 'All test tables have been removed.');
}
@@ -16,11 +16,11 @@ class MissingCheckedRequirementsTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('simpletest');
public static $modules = ['simpletest'];
protected function setUp() {
parent::setUp();
$admin_user = $this->drupalCreateUser(array('administer unit tests'));
$admin_user = $this->drupalCreateUser(['administer unit tests']);
$this->drupalLogin($admin_user);
}
@@ -29,9 +29,9 @@ class MissingCheckedRequirementsTest extends WebTestBase {
*/
protected function checkRequirements() {
if ($this->isInChildSite()) {
return array(
return [
'Test is not allowed to run.'
);
];
}
return parent::checkRequirements();
}
@@ -4,6 +4,7 @@ namespace Drupal\simpletest\Tests;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\simpletest\Functional\ThroughUITest;
/**
* Tests the Simpletest UI internal browser.
@@ -17,12 +18,12 @@ class SimpleTestBrowserTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('simpletest', 'test_page_test');
public static $modules = ['simpletest', 'test_page_test'];
protected function setUp() {
parent::setUp();
// Create and log in an admin user.
$this->drupalLogin($this->drupalCreateUser(array('administer unit tests')));
$this->drupalLogin($this->drupalCreateUser(['administer unit tests']));
}
/**
@@ -32,9 +33,9 @@ class SimpleTestBrowserTest extends WebTestBase {
// Retrieve the test page and check its title and headers.
$this->drupalGet('test-page');
$this->assertTrue($this->drupalGetHeader('Date'), 'An HTTP header was received.');
$this->assertTitle(t('Test page | @site-name', array(
$this->assertTitle(t('Test page | @site-name', [
'@site-name' => $this->config('system.site')->get('name'),
)));
]));
$this->assertNoTitle('Foo');
$old_user_id = $this->container->get('current_user')->id();
@@ -56,13 +57,13 @@ class SimpleTestBrowserTest extends WebTestBase {
// Test the maximum redirection option.
$this->maximumRedirects = 1;
$edit = array(
$edit = [
'name' => $user->getUsername(),
'pass' => $user->pass_raw
);
$this->drupalPostForm('user/login', $edit, t('Log in'), array(
'query' => array('destination' => 'user/logout'),
));
];
$this->drupalPostForm('user/login', $edit, t('Log in'), [
'query' => ['destination' => 'user/logout'],
]);
$headers = $this->drupalGetHeaders(TRUE);
$this->assertEqual(count($headers), 2, 'Simpletest stopped following redirects after the first one.');
@@ -72,7 +73,7 @@ class SimpleTestBrowserTest extends WebTestBase {
// @see drupal_valid_test_ua()
// Not using File API; a potential error must trigger a PHP warning.
unlink($this->siteDirectory . '/.htkey');
$this->drupalGet(Url::fromUri('base:core/install.php', array('external' => TRUE, 'absolute' => TRUE))->toString());
$this->drupalGet(Url::fromUri('base:core/install.php', ['external' => TRUE, 'absolute' => TRUE])->toString());
$this->assertResponse(403, 'Cannot access install.php.');
}
@@ -89,9 +90,9 @@ class SimpleTestBrowserTest extends WebTestBase {
$HTTP_path = $system_path . '/tests/http.php/user/login';
$https_path = $system_path . '/tests/https.php/user/login';
// Generate a valid simpletest User-Agent to pass validation.
$this->assertTrue(preg_match('/simpletest\d+/', $this->databasePrefix, $matches), 'Database prefix contains simpletest prefix.');
$this->assertTrue(preg_match('/test\d+/', $this->databasePrefix, $matches), 'Database prefix contains test prefix.');
$test_ua = drupal_generate_test_ua($matches[0]);
$this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua);
$this->additionalCurlOptions = [CURLOPT_USERAGENT => $test_ua];
// Test pages only available for testing.
$this->drupalGet($HTTP_path);
@@ -100,7 +101,7 @@ class SimpleTestBrowserTest extends WebTestBase {
$this->assertResponse(200, 'Requesting https.php with a legitimate simpletest User-Agent returns OK.');
// Now slightly modify the HMAC on the header, which should not validate.
$this->additionalCurlOptions = array(CURLOPT_USERAGENT => $test_ua . 'X');
$this->additionalCurlOptions = [CURLOPT_USERAGENT => $test_ua . 'X'];
$this->drupalGet($HTTP_path);
$this->assertResponse(403, 'Requesting http.php with a bad simpletest User-Agent fails.');
$this->drupalGet($https_path);
@@ -108,7 +109,7 @@ class SimpleTestBrowserTest extends WebTestBase {
// Use a real User-Agent and verify that the special files http.php and
// https.php can't be accessed.
$this->additionalCurlOptions = array(CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12');
$this->additionalCurlOptions = [CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12'];
$this->drupalGet($HTTP_path);
$this->assertResponse(403, 'Requesting http.php with a normal User-Agent fails.');
$this->drupalGet($https_path);
@@ -125,20 +126,20 @@ class SimpleTestBrowserTest extends WebTestBase {
// to be created. However this scenario is covered by the testception of
// \Drupal\simpletest\Tests\SimpleTestTest.
$tests = array(
$tests = [
// A KernelTestBase test.
'Drupal\KernelTests\KernelTestBaseTest',
// A PHPUnit unit test.
'Drupal\Tests\action\Unit\Menu\ActionLocalTasksTest',
// A PHPUnit functional test.
'Drupal\Tests\simpletest\Functional\BrowserTestBaseTest',
);
ThroughUITest::class,
];
foreach ($tests as $test) {
$this->drupalGet('admin/config/development/testing');
$edit = array(
$edit = [
"tests[$test]" => TRUE,
);
];
$this->drupalPostForm(NULL, $edit, t('Run tests'));
$this->assertText('0 fails, 0 exceptions');
}
@@ -2,6 +2,7 @@
namespace Drupal\simpletest\Tests;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\simpletest\WebTestBase;
/**
@@ -19,15 +20,15 @@ class SimpleTestInstallBatchTest extends WebTestBase {
*
* @var array
*/
public static $modules = array('simpletest', 'simpletest_test', 'entity_test');
public static $modules = ['simpletest', 'simpletest_test', 'entity_test'];
/**
* Tests loading entities created in a batch in simpletest_test_install().
*/
public function testLoadingEntitiesCreatedInBatch() {
$entity1 = entity_load('entity_test', 1);
$entity1 = EntityTest::load(1);
$this->assertNotNull($entity1, 'Successfully loaded entity 1.');
$entity2 = entity_load('entity_test', 2);
$entity2 = EntityTest::load(2);
$this->assertNotNull($entity2, 'Successfully loaded entity 2.');
}
@@ -3,6 +3,7 @@
namespace Drupal\simpletest\Tests;
use Drupal\Component\Utility\Crypt;
use Drupal\Core\Test\TestDatabase;
use Drupal\simpletest\WebTestBase;
/**
@@ -33,7 +34,7 @@ class SimpleTestTest extends WebTestBase {
*
* Used to ensure they are incrementing.
*/
protected $testIds = array();
protected $testIds = [];
/**
* Translated fail message.
@@ -96,12 +97,12 @@ EOD;
parent::setUp();
$this->assertNotIdentical(\Drupal::getContainer(), $original_container, 'WebTestBase test creates a new container.');
// Create and log in an admin user.
$this->drupalLogin($this->drupalCreateUser(array('administer unit tests')));
$this->drupalLogin($this->drupalCreateUser(['administer unit tests']));
}
else {
// This causes three of the five fails that are asserted in
// confirmStubResults().
self::$modules = array('non_existent_module');
self::$modules = ['non_existent_module'];
parent::setUp();
}
}
@@ -109,7 +110,7 @@ EOD;
/**
* Ensures the tests selected through the web interface are run and displayed.
*/
function testWebTestRunner() {
public function testWebTestRunner() {
$this->passMessage = t('SimpleTest pass.');
$this->failMessage = t('SimpleTest fail.');
$this->validPermission = 'access administration pages';
@@ -126,7 +127,7 @@ EOD;
// Run this test from web interface.
$this->drupalGet('admin/config/development/testing');
$edit = array();
$edit = [];
$edit['tests[Drupal\simpletest\Tests\SimpleTestTest]'] = TRUE;
$this->drupalPostForm(NULL, $edit, t('Run tests'));
@@ -147,14 +148,15 @@ EOD;
* Here we force test results which must match the expected results from
* confirmStubResults().
*/
function stubTest() {
public function stubTest() {
// Ensure the .htkey file exists since this is only created just before a
// request. This allows the stub test to make requests. The event does not
// fire here and drupal_generate_test_ua() can not generate a key for a
// test in a test since the prefix has changed.
// @see \Drupal\Core\Test\HttpClientMiddleware\TestHttpClientMiddleware::onBeforeSendRequest()
// @see drupal_generate_test_ua();
$key_file = DRUPAL_ROOT . '/sites/simpletest/' . substr($this->databasePrefix, 10) . '/.htkey';
$test_db = new TestDatabase($this->databasePrefix);
$key_file = DRUPAL_ROOT . '/' . $test_db->getTestSitePath() . '/.htkey';
$private_key = Crypt::randomBytesBase64(55);
$site_path = $this->container->get('site.path');
file_put_contents($key_file, $private_key);
@@ -190,10 +192,10 @@ EOD;
// This causes the third to fifth of the sixteen passes asserted in
// confirmStubResults().
$user = $this->drupalCreateUser(array($this->validPermission), 'SimpleTestTest');
$user = $this->drupalCreateUser([$this->validPermission], 'SimpleTestTest');
// This causes the fifth of the five fails asserted in confirmStubResults().
$this->drupalCreateUser(array($this->invalidPermission));
$this->drupalCreateUser([$this->invalidPermission]);
// Test logging in as a user.
// This causes the sixth to tenth of the sixteen passes asserted in
@@ -202,7 +204,7 @@ EOD;
// This causes the eleventh of the sixteen passes asserted in
// confirmStubResults().
$this->pass(t('Test ID is @id.', array('@id' => $this->testId)));
$this->pass(t('Test ID is @id.', ['@id' => $this->testId]));
// These cause the twelfth to fifteenth of the sixteen passes asserted in
// confirmStubResults().
@@ -230,21 +232,21 @@ EOD;
/**
* Assert nothing.
*/
function assertNothing() {
public function assertNothing() {
$this->pass("This is nothing.");
}
/**
* Confirm that the stub test produced the desired results.
*/
function confirmStubTestResults() {
$this->assertAssertion(t('Unable to install modules %modules due to missing modules %missing.', array('%modules' => 'non_existent_module', '%missing' => 'non_existent_module')), 'Other', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->setUp()');
public function confirmStubTestResults() {
$this->assertAssertion(t('Unable to install modules %modules due to missing modules %missing.', ['%modules' => 'non_existent_module', '%missing' => 'non_existent_module']), 'Other', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->setUp()');
$this->assertAssertion($this->passMessage, 'Other', 'Pass', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
$this->assertAssertion($this->failMessage, 'Other', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
$this->assertAssertion(t('Created permissions: @perms', array('@perms' => $this->validPermission)), 'Role', 'Pass', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
$this->assertAssertion(t('Invalid permission %permission.', array('%permission' => $this->invalidPermission)), 'Role', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
$this->assertAssertion(t('Created permissions: @perms', ['@perms' => $this->validPermission]), 'Role', 'Pass', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
$this->assertAssertion(t('Invalid permission %permission.', ['%permission' => $this->invalidPermission]), 'Role', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
// Check that the user was logged in successfully.
$this->assertAssertion('User SimpleTestTest successfully logged in.', 'User login', 'Pass', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
@@ -272,7 +274,7 @@ EOD;
/**
* Fetch the test id from the test results.
*/
function getTestIdFromResults() {
public function getTestIdFromResults() {
foreach ($this->childTestResults['assertions'] as $assertion) {
if (preg_match('@^Test ID is ([0-9]*)\.$@', $assertion['message'], $matches)) {
return $matches[1];
@@ -297,7 +299,7 @@ EOD;
*
* @return Assertion result.
*/
function assertAssertion($message, $type, $status, $file, $function) {
public function assertAssertion($message, $type, $status, $file, $function) {
$message = trim(strip_tags($message));
$found = FALSE;
foreach ($this->childTestResults['assertions'] as $assertion) {
@@ -310,24 +312,24 @@ EOD;
break;
}
}
return $this->assertTrue($found, format_string('Found assertion {"@message", "@type", "@status", "@file", "@function"}.', array('@message' => $message, '@type' => $type, '@status' => $status, "@file" => $file, "@function" => $function)));
return $this->assertTrue($found, format_string('Found assertion {"@message", "@type", "@status", "@file", "@function"}.', ['@message' => $message, '@type' => $type, '@status' => $status, "@file" => $file, "@function" => $function]));
}
/**
* Get the results from a test and store them in the class array $results.
*/
function getTestResults() {
$results = array();
public function getTestResults() {
$results = [];
if ($this->parse()) {
if ($details = $this->getResultFieldSet()) {
// Code assumes this is the only test in group.
$results['summary'] = $this->asText($details->div->div[1]);
$results['name'] = $this->asText($details->summary);
$results['assertions'] = array();
$results['assertions'] = [];
$tbody = $details->div->table->tbody;
foreach ($tbody->tr as $row) {
$assertion = array();
$assertion = [];
$assertion['message'] = $this->asText($row->td[0]);
$assertion['type'] = $this->asText($row->td[1]);
$assertion['file'] = $this->asText($row->td[2]);
@@ -345,7 +347,7 @@ EOD;
/**
* Get the details containing the results for group this test is in.
*/
function getResultFieldSet() {
public function getResultFieldSet() {
$all_details = $this->xpath('//details');
foreach ($all_details as $details) {
if ($this->asText($details->summary) == __CLASS__) {
@@ -364,7 +366,7 @@ EOD;
* @return
* Extracted text.
*/
function asText(\SimpleXMLElement $element) {
public function asText(\SimpleXMLElement $element) {
if (!is_object($element)) {
return $this->fail('The element is not an element.');
}
@@ -28,7 +28,7 @@ class TimeZoneTest extends WebTestBase {
/**
* Tests that user accounts have the default time zone set.
*/
function testAccountTimeZones() {
public function testAccountTimeZones() {
$expected = 'Australia/Sydney';
$this->assertEqual($this->rootUser->getTimeZone(), $expected, 'Root user has correct time zone.');
$this->assertEqual($this->adminUser->getTimeZone(), $expected, 'Admin user has correct time zone.');
@@ -0,0 +1,43 @@
<?php
namespace Drupal\simpletest\Tests;
use Drupal\simpletest\WebTestBase;
use Drupal\Tests\simpletest\Functional\SimpletestPhpunitBrowserTest;
/**
* Test PHPUnit output for the Simpletest UI.
*
* @group simpletest
*
* @see \Drupal\Tests\Listeners\SimpletestUiPrinter
*/
class UiPhpUnitOutputTest extends WebTestBase {
/**
* Modules to enable.
*
* @var string[]
*/
public static $modules = ['simpletest'];
/**
* Tests that PHPUnit output in the Simpletest UI looks good.
*/
public function testOutput() {
require_once __DIR__ . '/../../tests/fixtures/simpletest_phpunit_browsertest.php';
$phpunit_junit_file = $this->container->get('file_system')->realpath('public://phpunit_junit.xml');
// Prepare the default browser test output directory in the child site.
$this->container->get('file_system')->mkdir('public://simpletest');
$status = 0;
$output = [];
simpletest_phpunit_run_command([SimpletestPhpunitBrowserTest::class], $phpunit_junit_file, $status, $output);
// Check that there are <br> tags for the HTML output by
// SimpletestUiPrinter.
$this->assertEqual($output[18], 'HTML output was generated<br />');
// Check that URLs are printed as HTML links.
$this->assertIdentical(strpos($output[19], '<a href="http'), 0);
}
}
@@ -0,0 +1,22 @@
<?php
namespace Drupal\simpletest\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the test-specifics customisations done in the installation.
*
* @group simpletest
*/
class WebTestBaseInstallTest extends WebTestBase {
/**
* Tests the Drupal install done in \Drupal\simpletest\WebTestBase::setUp().
*/
public function testInstall() {
$htaccess_filename = $this->getTempFilesDirectory() . '/.htaccess';
$this->assertTrue(file_exists($htaccess_filename), "$htaccess_filename exists");
}
}
@@ -43,7 +43,7 @@ trait UserCreationTrait {
* A fully loaded user object with pass_raw property, or FALSE if account
* creation fails.
*/
protected function createUser(array $permissions = array(), $name = NULL, $admin = FALSE) {
protected function createUser(array $permissions = [], $name = NULL, $admin = FALSE) {
// Create a role with the given permission set, if any.
$rid = FALSE;
if ($permissions) {
@@ -54,13 +54,13 @@ trait UserCreationTrait {
}
// Create a user assigned to that role.
$edit = array();
$edit = [];
$edit['name'] = !empty($name) ? $name : $this->randomMachineName();
$edit['mail'] = $edit['name'] . '@example.com';
$edit['pass'] = user_password();
$edit['status'] = 1;
if ($rid) {
$edit['roles'] = array($rid);
$edit['roles'] = [$rid];
}
if ($admin) {
@@ -70,7 +70,7 @@ trait UserCreationTrait {
$account = User::create($edit);
$account->save();
$this->assertTrue($account->id(), SafeMarkup::format('User created with name %name and pass %pass', array('%name' => $edit['name'], '%pass' => $edit['pass'])), 'User login');
$this->assertTrue($account->id(), SafeMarkup::format('User created with name %name and pass %pass', ['%name' => $edit['name'], '%pass' => $edit['pass']]), 'User login');
if (!$account->id()) {
return FALSE;
}
@@ -141,19 +141,19 @@ trait UserCreationTrait {
}
// Create new role.
$role = Role::create(array(
$role = Role::create([
'id' => $rid,
'label' => $name,
));
]);
if (isset($weight)) {
$role->set('weight', $weight);
}
$result = $role->save();
$this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', array(
$this->assertIdentical($result, SAVED_NEW, SafeMarkup::format('Created role ID @rid with name @name.', [
'@name' => var_export($role->label(), TRUE),
'@rid' => var_export($role->id(), TRUE),
)), 'Role');
]), 'Role');
if ($result === SAVED_NEW) {
// Grant the specified permissions to the role, if any.
@@ -162,10 +162,10 @@ trait UserCreationTrait {
$assigned_permissions = Role::load($role->id())->getPermissions();
$missing_permissions = array_diff($permissions, $assigned_permissions);
if (!$missing_permissions) {
$this->pass(SafeMarkup::format('Created permissions: @perms', array('@perms' => implode(', ', $permissions))), 'Role');
$this->pass(SafeMarkup::format('Created permissions: @perms', ['@perms' => implode(', ', $permissions)]), 'Role');
}
else {
$this->fail(SafeMarkup::format('Failed to create permissions: @perms', array('@perms' => implode(', ', $missing_permissions))), 'Role');
$this->fail(SafeMarkup::format('Failed to create permissions: @perms', ['@perms' => implode(', ', $missing_permissions)]), 'Role');
}
}
return $role->id();
@@ -189,7 +189,7 @@ trait UserCreationTrait {
$valid = TRUE;
foreach ($permissions as $permission) {
if (!in_array($permission, $available)) {
$this->fail(SafeMarkup::format('Invalid permission %permission.', array('%permission' => $permission)), 'Role');
$this->fail(SafeMarkup::format('Invalid permission %permission.', ['%permission' => $permission]), 'Role');
$valid = FALSE;
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* A PHPUnit-based browser test that will be run from Simpletest.
*
* To avoid accidentally running it is not in a normal PSR-4 directory.
*
* @group simpletest
*/
class SimpletestPhpunitBrowserTest extends BrowserTestBase {
/**
* Dummy test that logs the visited front page for HTML output.
*/
public function testOutput() {
$this->drupalGet('<front>');
$this->assertSession()->responseContains('<h2>TEST escaping</h2>');
}
}
@@ -2,22 +2,27 @@
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
/**
* This test crashes PHP.
*
* To avoid accidentally running, it is not in a normal PSR-4 directory, the
* file name does not adhere to PSR-4 and an environment variable also needs to
* be set for the crash to happen.
*
* @see \Drupal\Tests\simpletest\Unit\SimpletestPhpunitRunCommandTest::testSimpletestPhpUnitRunCommand()
*/
class SimpletestPhpunitRunCommandTestWillDie extends UnitTestCase {
class SimpletestPhpunitRunCommandTestWillDie extends \PHPUnit_Framework_TestCase {
/**
* Performs the status specified by SimpletestPhpunitRunCommandTestWillDie.
*/
public function testWillDie() {
if (getenv('SimpletestPhpunitRunCommandTestWillDie') === 'fail') {
exit(2);
$status = (int) getenv('SimpletestPhpunitRunCommandTestWillDie');
if ($status == 0) {
$this->assertTrue(TRUE, 'Assertion to ensure test pass');
return;
}
$this->assertTrue(TRUE, 'Assertion to ensure test pass');
exit($status);
}
}
@@ -5,8 +5,8 @@ package: Testing
# version: VERSION
# core: 8.x
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233792
datestamp: 1502903957
@@ -7,8 +7,8 @@ package: Testing
dependencies:
- entity_test
# Information added by Drupal.org packaging script on 2016-08-03
version: '8.1.8'
# Information added by Drupal.org packaging script on 2017-08-16
version: '8.3.7'
core: '8.x'
project: 'drupal'
datestamp: 1470233792
datestamp: 1502903957
@@ -12,13 +12,13 @@ use Drupal\entity_test\Entity\EntityTest;
*/
function simpletest_test_install() {
$total = 2;
$operations = array();
$operations = [];
for ($i = 1; $i <= $total; $i++) {
$operations[] = array('_simpletest_test_callback', array($i));
$operations[] = ['_simpletest_test_callback', [$i]];
}
$batch = array(
$batch = [
'operations' => $operations,
);
];
batch_set($batch);
$batch =& batch_get();
$batch['progressive'] = FALSE;
@@ -29,6 +29,6 @@ function simpletest_test_install() {
* Callback for batch operations.
*/
function _simpletest_test_callback($id) {
$entity = EntityTest::create(array('id' => $id));
$entity = EntityTest::create(['id' => $id]);
$entity->save();
}
@@ -0,0 +1,27 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* This test will check SimpleTest's treatment of hook_install during setUp.
* Image module is used for test.
*
* @group simpletest
*/
class FolderTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['image'];
public function testFolderSetup() {
$directory = file_default_scheme() . '://styles';
$this->assertTrue(file_prepare_directory($directory, FALSE), 'Directory created.');
}
}
@@ -0,0 +1,82 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
use Drupal\Core\Test\AssertMailTrait;
/**
* Tests the SimpleTest email capturing logic, the assertMail assertion and the
* drupalGetMails function.
*
* @group simpletest
*/
class MailCaptureTest extends BrowserTestBase {
use AssertMailTrait {
getMails as drupalGetMails;
}
/**
* Test to see if the wrapper function is executed correctly.
*/
public function testMailSend() {
// Create an email.
$subject = $this->randomString(64);
$body = $this->randomString(128);
$message = [
'id' => 'drupal_mail_test',
'headers' => ['Content-type' => 'text/html'],
'subject' => $subject,
'to' => 'foobar@example.com',
'body' => $body,
];
// Before we send the email, drupalGetMails should return an empty array.
$captured_emails = $this->drupalGetMails();
$this->assertEqual(count($captured_emails), 0, 'The captured emails queue is empty.', 'Email');
// Send the email.
\Drupal::service('plugin.manager.mail')->getInstance(['module' => 'simpletest', 'key' => 'drupal_mail_test'])->mail($message);
// Ensure that there is one email in the captured emails array.
$captured_emails = $this->drupalGetMails();
$this->assertEqual(count($captured_emails), 1, 'One email was captured.', 'Email');
// Assert that the email was sent by iterating over the message properties
// and ensuring that they are captured intact.
foreach ($message as $field => $value) {
$this->assertMail($field, $value, format_string('The email was sent and the value for property @field is intact.', ['@field' => $field]), 'Email');
}
// Send additional emails so more than one email is captured.
for ($index = 0; $index < 5; $index++) {
$message = [
'id' => 'drupal_mail_test_' . $index,
'headers' => ['Content-type' => 'text/html'],
'subject' => $this->randomString(64),
'to' => $this->randomMachineName(32) . '@example.com',
'body' => $this->randomString(512),
];
\Drupal::service('plugin.manager.mail')->getInstance(['module' => 'drupal_mail_test', 'key' => $index])->mail($message);
}
// There should now be 6 emails captured.
$captured_emails = $this->drupalGetMails();
$this->assertEqual(count($captured_emails), 6, 'All emails were captured.', 'Email');
// Test different ways of getting filtered emails via drupalGetMails().
$captured_emails = $this->drupalGetMails(['id' => 'drupal_mail_test']);
$this->assertEqual(count($captured_emails), 1, 'Only one email is returned when filtering by id.', 'Email');
$captured_emails = $this->drupalGetMails(['id' => 'drupal_mail_test', 'subject' => $subject]);
$this->assertEqual(count($captured_emails), 1, 'Only one email is returned when filtering by id and subject.', 'Email');
$captured_emails = $this->drupalGetMails(['id' => 'drupal_mail_test', 'subject' => $subject, 'from' => 'this_was_not_used@example.com']);
$this->assertEqual(count($captured_emails), 0, 'No emails are returned when querying with an unused from address.', 'Email');
// Send the last email again, so we can confirm that the
// drupalGetMails-filter correctly returns all emails with a given
// property/value.
\Drupal::service('plugin.manager.mail')->getInstance(['module' => 'drupal_mail_test', 'key' => $index])->mail($message);
$captured_emails = $this->drupalGetMails(['id' => 'drupal_mail_test_4']);
$this->assertEqual(count($captured_emails), 2, 'All emails with the same id are returned when filtering by id.', 'Email');
}
}
@@ -0,0 +1,22 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* This test should not load since it requires a module that is not found.
*
* @group simpletest
* @dependencies simpletest_missing_module
*/
class MissingDependentModuleUnitTest extends BrowserTestBase {
/**
* Ensure that this test will not be loaded despite its dependency.
*/
public function testFail() {
$this->fail('Running test with missing required module.');
}
}
@@ -0,0 +1,64 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Verifies that tests in other installation profiles are found.
*
* @group simpletest
* @see SimpleTestInstallationProfileModuleTestsTestCase
*/
class OtherInstallationProfileTestsTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['simpletest'];
/**
* Use the Minimal profile.
*
* The Testing profile contains drupal_system_listing_compatible_test.test,
* which should be found.
*
* The Standard profile contains \Drupal\standard\Tests\StandardTest, which
* should be found.
*
* @see \Drupal\simpletest\Tests\InstallationProfileModuleTestsTest
* @see \Drupal\drupal_system_listing_compatible_test\Tests\SystemListingCompatibleTest
*/
protected $profile = 'minimal';
/**
* An administrative user with permission to administer unit tests.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
$this->adminUser = $this->drupalCreateUser(['administer unit tests']);
$this->drupalLogin($this->adminUser);
}
/**
* Tests that tests located in another installation profile appear.
*/
public function testOtherInstallationProfile() {
// Assert the existence of a test in a different installation profile than
// the current.
$this->drupalGet('admin/config/development/testing');
$this->assertText('Tests Standard installation profile expectations.');
// Assert the existence of a test for a module in a different installation
// profile than the current.
$this->assertText('Drupal\drupal_system_listing_compatible_test\Tests\SystemListingCompatibleTest');
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Fixture test that is executed during Simpletest UI testing.
*
* @see \Drupal\simpletest\Tests::testTestingThroughUI()
*
* @group simpletest
*/
class ThroughUITest extends BrowserTestBase {
/**
* This test method must always pass.
*/
public function testThroughUi() {
$this->pass('Success!');
}
}
@@ -0,0 +1,52 @@
<?php
namespace Drupal\Tests\simpletest\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests User related helper methods of WebTestBase.
*
* @group simpletest
*/
class UserHelpersTest extends BrowserTestBase {
/**
* Tests WebTestBase::drupalUserIsLoggedIn().
*/
public function testDrupalUserIsLoggedIn() {
$first_user = $this->drupalCreateUser();
$second_user = $this->drupalCreateUser();
// After logging in, the first user should be logged in, the second not.
$this->drupalLogin($first_user);
$this->assertTrue($this->drupalUserIsLoggedIn($first_user));
$this->assertFalse($this->drupalUserIsLoggedIn($second_user));
// Verify that logged in state is retained across pages.
$this->drupalGet('');
$this->assertTrue($this->drupalUserIsLoggedIn($first_user));
$this->assertFalse($this->drupalUserIsLoggedIn($second_user));
// After logging out, both users should be logged out.
$this->drupalLogout();
$this->assertFalse($this->drupalUserIsLoggedIn($first_user));
$this->assertFalse($this->drupalUserIsLoggedIn($second_user));
// After logging back in, the second user should still be logged out.
$this->drupalLogin($first_user);
$this->assertTrue($this->drupalUserIsLoggedIn($first_user));
$this->assertFalse($this->drupalUserIsLoggedIn($second_user));
// After logging in the second user, the first one should be logged out.
$this->drupalLogin($second_user);
$this->assertTrue($this->drupalUserIsLoggedIn($second_user));
$this->assertFalse($this->drupalUserIsLoggedIn($first_user));
// After logging out, both should be logged out.
$this->drupalLogout();
$this->assertFalse($this->drupalUserIsLoggedIn($first_user));
$this->assertFalse($this->drupalUserIsLoggedIn($second_user));
}
}
@@ -0,0 +1,46 @@
<?php
namespace Drupal\Tests\simpletest\FunctionalJavascript;
use Drupal\FunctionalJavascriptTests\JavascriptTestBase;
/**
* Tests Drupal settings retrieval in JavascriptTestBase tests.
*
* @group javascript
*/
class JavascriptGetDrupalSettingsTest extends JavascriptTestBase {
/**
* {@inheritdoc}
*/
protected static $modules = ['test_page_test'];
/**
* Tests retrieval of Drupal settings.
*
* @see \Drupal\FunctionalJavascriptTests\JavascriptTestBase::getDrupalSettings()
*/
public function testGetDrupalSettings() {
$this->drupalLogin($this->drupalCreateUser());
$this->drupalGet('test-page');
// Check that we can read the JS settings.
$js_settings = $this->getDrupalSettings();
$this->assertSame('azAZ09();.,\\\/-_{}', $js_settings['test-setting']);
// Dynamically change the setting using Javascript.
$script = <<<EndOfScript
(function () {
drupalSettings['test-setting'] = 'foo';
})();
EndOfScript;
$this->getSession()->evaluateScript($script);
// Check that the setting has been changed.
$js_settings = $this->getDrupalSettings();
$this->assertSame('foo', $js_settings['test-setting']);
}
}
@@ -2,7 +2,7 @@
namespace Drupal\Tests\simpletest\Kernel\Migrate\d6;
use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
/**
@@ -17,7 +17,7 @@ class MigrateSimpletestConfigsTest extends MigrateDrupal6TestBase {
/**
* {@inheritdoc}
*/
public static $modules = array('simpletest');
public static $modules = ['simpletest'];
/**
* {@inheritdoc}
@@ -0,0 +1,32 @@
<?php
namespace Drupal\Tests\simpletest\Traits;
/**
* A nothing trait, but declared in the Drupal\Tests namespace.
*
* We use this trait to test autoloading of traits outside of the normal test
* suite namespaces.
*
* @see \Drupal\Tests\simpletest\Unit\TraitAccessTest
*/
trait TestTrait {
/**
* Random string for a not very interesting trait.
*
* @var string
*/
protected $stuff = 'stuff';
/**
* Return a test string to a trait user.
*
* @return string
* Just a random sort of string.
*/
protected function getStuff() {
return $this->stuff;
}
}
@@ -3,7 +3,7 @@
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Tests\UnitTestCase;
use Drupal\Core\File\FileSystemInterface;
/**
* Tests simpletest_run_phpunit_tests() handles PHPunit fatals correctly.
@@ -11,27 +11,92 @@ use Drupal\Tests\UnitTestCase;
* @group simpletest
*
* @runTestsInSeparateProcesses
* @preserveGlobalState disabled
*/
class SimpletestPhpunitRunCommandTest extends UnitTestCase {
class SimpletestPhpunitRunCommandTest extends \PHPUnit_Framework_TestCase {
function testSimpletestPhpUnitRunCommand() {
include_once __DIR__ . '/../../fixtures/simpletest_phpunit_run_command_test.php';
$app_root = __DIR__ . '/../../../../../..';
include_once "$app_root/core/modules/simpletest/simpletest.module";
/**
* Path to the app root.
*
* @var string
*/
protected static $root;
/**
* {@inheritdoc}
*/
public static function setUpBeforeClass() {
parent::setUpBeforeClass();
// Figure out our app root.
self::$root = dirname(dirname(dirname(dirname(dirname(dirname(__DIR__))))));
// Include the files we need for tests. The stub test we will run is
// SimpletestPhpunitRunCommandTestWillDie which is located in
// simpletest_phpunit_run_command_test.php.
include_once self::$root . '/core/modules/simpletest/tests/fixtures/simpletest_phpunit_run_command_test.php';
// Since we're testing simpletest_run_phpunit_tests(), we need to include
// simpletest.module.
include_once self::$root . '/core/modules/simpletest/simpletest.module';
}
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Organize our mock container.
$container = new ContainerBuilder();
$container->set('app.root', $app_root);
$file_system = $this->prophesize('Drupal\Core\File\FileSystemInterface');
$container->set('app.root', self::$root);
$file_system = $this->prophesize(FileSystemInterface::class);
// The simpletest directory wrapper will always point to /tmp.
$file_system->realpath('public://simpletest')->willReturn(sys_get_temp_dir());
$container->set('file_system', $file_system->reveal());
\Drupal::setContainer($container);
$test_id = basename(tempnam(sys_get_temp_dir(), 'xxx'));
foreach (['pass', 'fail'] as $status) {
putenv('SimpletestPhpunitRunCommandTestWillDie=' . $status);
$ret = simpletest_run_phpunit_tests($test_id, ['Drupal\Tests\simpletest\Unit\SimpletestPhpunitRunCommandTestWillDie']);
$this->assertSame($ret[0]['status'], $status);
}
/**
* Data provider for testSimpletestPhpUnitRunCommand().
*
* @return array
* Arrays of status codes and the label they're expected to have.
*/
public function provideStatusCodes() {
$data = [
[0, 'pass'],
[1, 'fail'],
[2, 'exception'],
];
// All status codes 3 and above should be labeled 'error'.
// @todo: The valid values here would be 3 to 127. But since the test
// touches the file system a lot, we only have 3, 4, and 127 for speed.
foreach ([3, 4, 127] as $status) {
$data[] = [$status, 'error'];
}
return $data;
}
/**
* Test the round trip for PHPUnit execution status codes.
*
* @covers ::simpletest_run_phpunit_tests
*
* @dataProvider provideStatusCodes
*/
public function testSimpletestPhpUnitRunCommand($status, $label) {
$test_id = basename(tempnam(sys_get_temp_dir(), 'xxx'));
putenv('SimpletestPhpunitRunCommandTestWillDie=' . $status);
$ret = simpletest_run_phpunit_tests($test_id, [SimpletestPhpunitRunCommandTestWillDie::class]);
$this->assertSame($ret[0]['status'], $label);
putenv('SimpletestPhpunitRunCommandTestWillDie');
unlink(simpletest_phpunit_xml_filepath($test_id));
}
/**
* {@inheritdoc}
*/
protected function tearDown() {
// We unset the $base_url global, since the test code sets it as a
// side-effect.
unset($GLOBALS['base_url']);
parent::tearDown();
}
}
@@ -25,13 +25,13 @@ class TestBaseTest extends UnitTestCase {
*/
public function getTestBaseForAssertionTests($test_id) {
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
->setConstructorArgs(array($test_id))
->setMethods(array('storeAssertion'))
->getMockForAbstractClass();
->setConstructorArgs([$test_id])
->setMethods(['storeAssertion'])
->getMockForAbstractClass();
// Override storeAssertion() so we don't need a database.
$mock_test_base->expects($this->any())
->method('storeAssertion')
->will($this->returnValue(NULL));
->method('storeAssertion')
->will($this->returnValue(NULL));
return $mock_test_base;
}
@@ -62,16 +62,16 @@ class TestBaseTest extends UnitTestCase {
* - The string to validate.
*/
public function providerRandomStringValidate() {
return array(
array(FALSE, ' curry paste'),
array(FALSE, 'curry paste '),
array(FALSE, 'curry paste'),
array(FALSE, 'curry paste'),
array(TRUE, 'curry paste'),
array(TRUE, 'thai green curry paste'),
array(TRUE, '@startswithat'),
array(TRUE, 'contains@at'),
);
return [
[FALSE, ' curry paste'],
[FALSE, 'curry paste '],
[FALSE, 'curry paste'],
[FALSE, 'curry paste'],
[TRUE, 'curry paste'],
[TRUE, 'thai green curry paste'],
[TRUE, '@startswithat'],
[TRUE, 'contains@at'],
];
}
/**
@@ -136,7 +136,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertInternalType(
'array',
$this->invokeProtectedMethod($test_base, 'checkRequirements', array())
$this->invokeProtectedMethod($test_base, 'checkRequirements', [])
);
}
@@ -153,14 +153,14 @@ class TestBaseTest extends UnitTestCase {
* - Caller, passed to assert().
*/
public function providerAssert() {
return array(
array(TRUE, 'pass', TRUE, 'Yay pass', 'test', array()),
array(FALSE, 'fail', FALSE, 'Boo fail', 'test', array()),
array(TRUE, 'pass', 'pass', 'Yay pass', 'test', array()),
array(FALSE, 'fail', 'fail', 'Boo fail', 'test', array()),
array(FALSE, 'exception', 'exception', 'Boo fail', 'test', array()),
array(FALSE, 'debug', 'debug', 'Boo fail', 'test', array()),
);
return [
[TRUE, 'pass', TRUE, 'Yay pass', 'test', []],
[FALSE, 'fail', FALSE, 'Boo fail', 'test', []],
[TRUE, 'pass', 'pass', 'Yay pass', 'test', []],
[FALSE, 'fail', 'fail', 'Boo fail', 'test', []],
[FALSE, 'exception', 'exception', 'Boo fail', 'test', []],
[FALSE, 'debug', 'debug', 'Boo fail', 'test', []],
];
}
/**
@@ -185,7 +185,7 @@ class TestBaseTest extends UnitTestCase {
$this->assertEquals(
$expected,
$ref_assert->invokeArgs($test_base,
array($status, $message, $group, $caller)
[$status, $message, $group, $caller]
)
);
@@ -211,10 +211,10 @@ class TestBaseTest extends UnitTestCase {
* Data provider for assertTrue().
*/
public function providerAssertTrue() {
return array(
array(TRUE, TRUE),
array(FALSE, FALSE),
);
return [
[TRUE, TRUE],
[FALSE, FALSE],
];
}
/**
@@ -225,7 +225,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertTrue', array($value))
$this->invokeProtectedMethod($test_base, 'assertTrue', [$value])
);
}
@@ -237,7 +237,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected),
$this->invokeProtectedMethod($test_base, 'assertFalse', array($value))
$this->invokeProtectedMethod($test_base, 'assertFalse', [$value])
);
}
@@ -245,10 +245,10 @@ class TestBaseTest extends UnitTestCase {
* Data provider for assertNull().
*/
public function providerAssertNull() {
return array(
array(TRUE, NULL),
array(FALSE, ''),
);
return [
[TRUE, NULL],
[FALSE, ''],
];
}
/**
@@ -259,7 +259,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertNull', array($value))
$this->invokeProtectedMethod($test_base, 'assertNull', [$value])
);
}
@@ -271,7 +271,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected),
$this->invokeProtectedMethod($test_base, 'assertNotNull', array($value))
$this->invokeProtectedMethod($test_base, 'assertNotNull', [$value])
);
}
@@ -325,7 +325,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected_identical,
$this->invokeProtectedMethod($test_base, 'assertIdentical', array($first, $second))
$this->invokeProtectedMethod($test_base, 'assertIdentical', [$first, $second])
);
}
@@ -337,7 +337,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected_identical),
$this->invokeProtectedMethod($test_base, 'assertNotIdentical', array($first, $second))
$this->invokeProtectedMethod($test_base, 'assertNotIdentical', [$first, $second])
);
}
@@ -349,7 +349,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected_equal,
$this->invokeProtectedMethod($test_base, 'assertEqual', array($first, $second))
$this->invokeProtectedMethod($test_base, 'assertEqual', [$first, $second])
);
}
@@ -361,7 +361,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
(!$expected_equal),
$this->invokeProtectedMethod($test_base, 'assertNotEqual', array($first, $second))
$this->invokeProtectedMethod($test_base, 'assertNotEqual', [$first, $second])
);
}
@@ -374,11 +374,11 @@ class TestBaseTest extends UnitTestCase {
$obj2 = $obj1;
$obj3 = clone $obj1;
$obj4 = new \stdClass();
return array(
array(TRUE, $obj1, $obj2),
array(TRUE, $obj1, $obj3),
array(FALSE, $obj1, $obj4),
);
return [
[TRUE, $obj1, $obj2],
[TRUE, $obj1, $obj3],
[FALSE, $obj1, $obj4],
];
}
/**
@@ -389,7 +389,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
$expected,
$this->invokeProtectedMethod($test_base, 'assertIdenticalObject', array($first, $second))
$this->invokeProtectedMethod($test_base, 'assertIdenticalObject', [$first, $second])
);
}
@@ -400,7 +400,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
TRUE,
$this->invokeProtectedMethod($test_base, 'pass', array())
$this->invokeProtectedMethod($test_base, 'pass', [])
);
}
@@ -411,7 +411,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertEquals(
FALSE,
$this->invokeProtectedMethod($test_base, 'fail', array())
$this->invokeProtectedMethod($test_base, 'fail', [])
);
}
@@ -423,10 +423,10 @@ class TestBaseTest extends UnitTestCase {
* - Group for use in assert().
*/
public function providerError() {
return array(
array('debug', 'User notice'),
array('exception', 'Not User notice'),
);
return [
['debug', 'User notice'],
['exception', 'Not User notice'],
];
}
/**
@@ -436,7 +436,7 @@ class TestBaseTest extends UnitTestCase {
public function testError($status, $group) {
// Mock up a TestBase object.
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
->setMethods(array('assert'))
->setMethods(['assert'])
->getMockForAbstractClass();
// Set expectations for assert().
@@ -451,7 +451,7 @@ class TestBaseTest extends UnitTestCase {
// Invoke error().
$this->assertEquals(
"$status:$group",
$this->invokeProtectedMethod($mock_test_base, 'error', array('msg', $group))
$this->invokeProtectedMethod($mock_test_base, 'error', ['msg', $group])
);
}
@@ -462,7 +462,7 @@ class TestBaseTest extends UnitTestCase {
$test_base = $this->getTestBaseForAssertionTests('test_id');
$this->assertInstanceOf(
'Drupal\Component\Utility\Random',
$this->invokeProtectedMethod($test_base, 'getRandomGenerator', array())
$this->invokeProtectedMethod($test_base, 'getRandomGenerator', [])
);
}
@@ -0,0 +1,421 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Composer\Autoload\ClassLoader;
use Drupal\Core\Extension\Extension;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\simpletest\Exception\MissingGroupException;
use Drupal\simpletest\TestDiscovery;
use Drupal\Tests\UnitTestCase;
use org\bovigo\vfs\vfsStream;
/**
* @coversDefaultClass \Drupal\simpletest\TestDiscovery
* @group simpletest
*/
class TestDiscoveryTest extends UnitTestCase {
/**
* @covers ::getTestInfo
* @dataProvider infoParserProvider
*/
public function testTestInfoParser($expected, $classname, $doc_comment = NULL) {
$info = TestDiscovery::getTestInfo($classname, $doc_comment);
$this->assertEquals($expected, $info);
}
public function infoParserProvider() {
// A module provided unit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\Tests\simpletest\Unit\TestDiscoveryTest',
'group' => 'simpletest',
'description' => 'Tests \Drupal\simpletest\TestDiscovery.',
'type' => 'PHPUnit-Unit',
],
// Classname.
'Drupal\Tests\simpletest\Unit\TestDiscoveryTest',
];
// A core unit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\Tests\Core\DrupalTest',
'group' => 'DrupalTest',
'description' => 'Tests \Drupal.',
'type' => 'PHPUnit-Unit',
],
// Classname.
'Drupal\Tests\Core\DrupalTest',
];
// Functional PHPUnit test.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\FunctionalTests\BrowserTestBaseTest',
'group' => 'browsertestbase',
'description' => 'Tests BrowserTestBase functionality.',
'type' => 'PHPUnit-Functional',
],
// Classname.
'Drupal\FunctionalTests\BrowserTestBaseTest',
];
// kernel PHPUnit test.
$tests['phpunit-kernel'] = [
// Expected result.
[
'name' => '\Drupal\Tests\file\Kernel\FileItemValidationTest',
'group' => 'file',
'description' => 'Tests that files referenced in file and image fields are always validated.',
'type' => 'PHPUnit-Kernel',
],
// Classname.
'\Drupal\Tests\file\Kernel\FileItemValidationTest',
];
// Simpletest classes can not be autoloaded in a PHPUnit test, therefore
// provide a docblock.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
",
];
// Test with a different amount of leading spaces.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
*/
",
];
// Make sure that a "* @" inside a string does not get parsed as an
// annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'simpletest',
'description' => 'Tests the Simpletest UI internal browser. * @',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser. * @
*
* @group simpletest
*/
",
];
// Multiple @group annotations.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'group' => 'Test',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @group Test
* @group simpletest
*/
",
];
// @dependencies annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
'requires' => ['module' => ['test']],
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @dependencies test
* @group simpletest
*/
",
];
// Multiple @dependencies annotation.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser.',
'type' => 'Simpletest',
'requires' => ['module' => ['test', 'test1', 'test2']],
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser.
*
* @dependencies test, test1, test2
* @group simpletest
*/
",
];
// Multi-line summary line.
$tests[] = [
// Expected result.
[
'name' => 'Drupal\simpletest\Tests\ExampleSimpleTest',
'description' => 'Tests the Simpletest UI internal browser. And the summary line continues an there is no gap to the annotation.',
'type' => 'Simpletest',
'group' => 'simpletest',
],
// Classname.
'Drupal\simpletest\Tests\ExampleSimpleTest',
// Doc block.
"/**
* Tests the Simpletest UI internal browser. And the summary line continues an
* there is no gap to the annotation.
*
* @group simpletest
*/
",
];
return $tests;
}
/**
* @covers ::getTestInfo
*/
public function testTestInfoParserMissingGroup() {
$classname = 'Drupal\KernelTests\field\BulkDeleteTest';
$doc_comment = <<<EOT
/**
* Bulk delete storages and fields, and clean up afterwards.
*/
EOT;
$this->setExpectedException(MissingGroupException::class, 'Missing @group annotation in Drupal\KernelTests\field\BulkDeleteTest');
TestDiscovery::getTestInfo($classname, $doc_comment);
}
/**
* @covers ::getTestInfo
*/
public function testTestInfoParserMissingSummary() {
$classname = 'Drupal\KernelTests\field\BulkDeleteTest';
$doc_comment = <<<EOT
/**
* @group field
*/
EOT;
$info = TestDiscovery::getTestInfo($classname, $doc_comment);
$this->assertEmpty($info['description']);
}
protected function setupVfsWithTestClasses() {
vfsStream::setup('drupal');
$test_file = <<<EOF
<?php
/**
* Test description
* @group example
*/
class FunctionalExampleTest {}
EOF;
vfsStream::create([
'modules' => [
'test_module' => [
'tests' => [
'src' => [
'Functional' => [
'FunctionalExampleTest.php' => $test_file,
'FunctionalExampleTest2.php' => str_replace(['FunctionalExampleTest', '@group example'], ['FunctionalExampleTest2', '@group example2'], $test_file),
],
'Kernel' => [
'KernelExampleTest3.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleTest3', '@group example2'], $test_file),
],
],
],
],
],
]);
}
/**
* @covers ::getTestClasses
*/
public function testGetTestClasses() {
$this->setupVfsWithTestClasses();
$class_loader = $this->prophesize(ClassLoader::class);
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$test_discovery = new TestTestDiscovery('vfs://drupal', $class_loader->reveal(), $module_handler->reveal());
$extensions = [
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
];
$test_discovery->setExtensions($extensions);
$result = $test_discovery->getTestClasses();
$this->assertCount(2, $result);
$this->assertEquals([
'example' => [
'Drupal\Tests\test_module\Functional\FunctionalExampleTest' => [
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest',
'description' => 'Test description',
'group' => 'example',
'type' => 'PHPUnit-Functional',
],
],
'example2' => [
'Drupal\Tests\test_module\Functional\FunctionalExampleTest2' => [
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest2',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Functional',
],
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Kernel',
],
],
], $result);
}
/**
* @covers ::getTestClasses
*/
public function testGetTestClassesWithSelectedTypes() {
$this->setupVfsWithTestClasses();
$class_loader = $this->prophesize(ClassLoader::class);
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
$test_discovery = new TestTestDiscovery('vfs://drupal', $class_loader->reveal(), $module_handler->reveal());
$extensions = [
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
];
$test_discovery->setExtensions($extensions);
$result = $test_discovery->getTestClasses(NULL, ['PHPUnit-Kernel']);
$this->assertCount(2, $result);
$this->assertEquals([
'example' => [
],
'example2' => [
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
'description' => 'Test description',
'group' => 'example2',
'type' => 'PHPUnit-Kernel',
],
],
], $result);
}
/**
* @covers ::getPhpunitTestSuite
* @dataProvider providerTestGetPhpunitTestSuite
*/
public function testGetPhpunitTestSuite($classname, $expected) {
$this->assertEquals($expected, TestDiscovery::getPhpunitTestSuite($classname));
}
public function providerTestGetPhpunitTestSuite() {
$data = [];
$data['simpletest-webtest'] = ['\Drupal\rest\Tests\NodeTest', FALSE];
$data['simpletest-kerneltest'] = ['\Drupal\hal\Tests\FileNormalizeTest', FALSE];
$data['module-unittest'] = [static::class, 'Unit'];
$data['module-kerneltest'] = ['\Drupal\KernelTests\Core\Theme\TwigMarkupInterfaceTest', 'Kernel'];
$data['module-functionaltest'] = ['\Drupal\FunctionalTests\BrowserTestBaseTest', 'Functional'];
$data['module-functionaljavascripttest'] = ['\Drupal\Tests\toolbar\FunctionalJavascript\ToolbarIntegrationTest', 'FunctionalJavascript'];
$data['core-unittest'] = ['\Drupal\Tests\ComposerIntegrationTest', 'Unit'];
$data['core-unittest2'] = ['Drupal\Tests\Core\DrupalTest', 'Unit'];
$data['core-kerneltest'] = ['\Drupal\KernelTests\KernelTestBaseTest', 'Kernel'];
$data['core-functionaltest'] = ['\Drupal\FunctionalTests\ExampleTest', 'Functional'];
$data['core-functionaljavascripttest'] = ['\Drupal\FunctionalJavascriptTests\ExampleTest', 'FunctionalJavascript'];
return $data;
}
}
class TestTestDiscovery extends TestDiscovery {
/**
* @var \Drupal\Core\Extension\Extension[]
*/
protected $extensions = [];
public function setExtensions(array $extensions) {
$this->extensions = $extensions;
}
/**
* {@inheritdoc}
*/
protected function getExtensions() {
return $this->extensions;
}
}
namespace Drupal\simpletest\Tests;
use Drupal\simpletest\WebTestBase;
/**
* Tests the Simpletest UI internal browser.
*
* @group simpletest
*/
class ExampleSimpleTest extends WebTestBase {
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\Tests\simpletest\Unit;
use Drupal\Tests\UnitTestCase;
use Drupal\Tests\simpletest\Traits\TestTrait;
/**
* Test whether traits are autoloaded during PHPUnit discovery time.
*
* @group simpletest
*/
class TraitAccessTest extends UnitTestCase {
use TestTrait;
/**
* @coversNothing
*/
public function testSimpleStuff() {
$stuff = $this->getStuff();
$this->assertSame($stuff, 'stuff', "Same old stuff");
}
}
@@ -18,12 +18,12 @@ class WebTestBaseTest extends UnitTestCase {
* An array of values passed to the test method.
*/
public function providerAssertFieldByName() {
$data = array();
$data[] = array('select_2nd_selected', 'test', '1', FALSE);
$data[] = array('select_2nd_selected', 'test', '2', TRUE);
$data[] = array('select_none_selected', 'test', '', FALSE);
$data[] = array('select_none_selected', 'test', '1', TRUE);
$data[] = array('select_none_selected', 'test', NULL, TRUE);
$data = [];
$data[] = ['select_2nd_selected', 'test', '1', FALSE];
$data[] = ['select_2nd_selected', 'test', '2', TRUE];
$data[] = ['select_none_selected', 'test', '', FALSE];
$data[] = ['select_none_selected', 'test', '1', TRUE];
$data[] = ['select_none_selected', 'test', NULL, TRUE];
return $data;
}
@@ -50,7 +50,7 @@ class WebTestBaseTest extends UnitTestCase {
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
->disableOriginalConstructor()
->setMethods(array('getRawContent', 'assertTrue', 'pass'))
->setMethods(['getRawContent', 'assertTrue', 'pass'])
->getMock();
$web_test->expects($this->any())
@@ -65,7 +65,7 @@ class WebTestBaseTest extends UnitTestCase {
$test_method = new \ReflectionMethod('Drupal\simpletest\WebTestBase', 'assertFieldByName');
$test_method->setAccessible(TRUE);
$test_method->invokeArgs($web_test, array($name, $value, 'message'));
$test_method->invokeArgs($web_test, [$name, $value, 'message']);
}
/**
@@ -87,32 +87,32 @@ class WebTestBaseTest extends UnitTestCase {
* to mock no link found on the page.
*/
public function providerTestClickLink() {
return array(
return [
// Test for a non-existent label.
array(
[
FALSE,
'does_not_exist',
0,
array(),
),
[],
],
// Test for an existing label.
array(
[
'This Text Returned By drupalGet()',
'exists',
0,
array(0 => array('href' => 'this_is_a_url')),
),
[0 => ['href' => 'this_is_a_url']],
],
// Test for an existing label that isn't the first one.
array(
[
'This Text Returned By drupalGet()',
'exists',
1,
array(
0 => array('href' => 'this_is_a_url'),
1 => array('href' => 'this_is_another_url'),
),
),
);
[
0 => ['href' => 'this_is_a_url'],
1 => ['href' => 'this_is_another_url'],
],
],
];
}
/**
@@ -134,14 +134,14 @@ class WebTestBaseTest extends UnitTestCase {
// Mock a WebTestBase object and some of its methods.
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
->disableOriginalConstructor()
->setMethods(array(
->setMethods([
'pass',
'fail',
'getUrl',
'xpath',
'drupalGet',
'getAbsoluteUrl',
))
])
->getMock();
// Mocked getUrl() is only used for reporting so we just return a string.