first commit
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
clear_results: true
|
||||
httpauth:
|
||||
method: 1
|
||||
password: ''
|
||||
username: ''
|
||||
verbose: true
|
||||
@@ -0,0 +1,25 @@
|
||||
# Schema for the configuration files of the Simpletest module.
|
||||
|
||||
simpletest.settings:
|
||||
type: config_object
|
||||
label: 'Testing'
|
||||
mapping:
|
||||
clear_results:
|
||||
type: boolean
|
||||
label: 'Clear results after each complete test suite run'
|
||||
verbose:
|
||||
type: boolean
|
||||
label: 'Provide verbose information when running tests'
|
||||
httpauth:
|
||||
type: mapping
|
||||
label: 'HTTP authentication'
|
||||
mapping:
|
||||
method:
|
||||
type: integer
|
||||
label: 'Method'
|
||||
username:
|
||||
type: string
|
||||
label: 'Username'
|
||||
password:
|
||||
type: string
|
||||
label: 'Password'
|
||||
@@ -0,0 +1,93 @@
|
||||
|
||||
/* Test Table */
|
||||
#simpletest-form-table th.select-all {
|
||||
width: 1em;
|
||||
}
|
||||
th.simpletest-test-label {
|
||||
width: 40%;
|
||||
}
|
||||
|
||||
.simpletest-image {
|
||||
display: inline-block;
|
||||
width: 1em;
|
||||
cursor: pointer;
|
||||
}
|
||||
.simpletest-group-label label {
|
||||
display: inline;
|
||||
font-weight: bold;
|
||||
}
|
||||
.simpletest-test-label label {
|
||||
margin-left: 1em; /* LTR */
|
||||
}
|
||||
.simpletest-test-description .description {
|
||||
margin: 0;
|
||||
}
|
||||
#simpletest-form-table tr td {
|
||||
color: #494949;
|
||||
background-color: white;
|
||||
}
|
||||
#simpletest-form-table tr.simpletest-group td {
|
||||
color: #494949;
|
||||
background-color: #edf5fa;
|
||||
}
|
||||
|
||||
table#simpletest-form-table tr.simpletest-group label {
|
||||
display: inline;
|
||||
}
|
||||
|
||||
div.message > div.item-list {
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
div.simpletest-pass {
|
||||
color: #33a333;
|
||||
}
|
||||
.simpletest-fail {
|
||||
color: #981010;
|
||||
}
|
||||
|
||||
tr.simpletest-pass,
|
||||
tr.simpletest-pass.odd {
|
||||
background-color: #b6ffb6;
|
||||
}
|
||||
tr.simpletest-pass.even {
|
||||
background-color: #9bff9b;
|
||||
}
|
||||
tr.simpletest-fail,
|
||||
tr.simpletest-fail.odd {
|
||||
background-color: #ffc9c9;
|
||||
}
|
||||
tr.simpletest-fail.even {
|
||||
background-color: #ffacac;
|
||||
}
|
||||
tr.simpletest-exception,
|
||||
tr.simpletest-exception.odd {
|
||||
background-color: #f4ea71;
|
||||
}
|
||||
tr.simpletest-exception.even {
|
||||
background-color: #f5e742;
|
||||
}
|
||||
tr.simpletest-debug,
|
||||
tr.simpletest-debug.odd {
|
||||
background-color: #eee;
|
||||
}
|
||||
tr.simpletest-debug.even {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
a.simpletest-collapse {
|
||||
position: absolute;
|
||||
top: -99em;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
a.simpletest-collapse:focus,
|
||||
a.simpletest-collapse:hover {
|
||||
position: relative;
|
||||
z-index: 1000;
|
||||
top: 0;
|
||||
overflow: visible;
|
||||
width: auto;
|
||||
height: auto;
|
||||
font-size: 80%;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
id: d6_simpletest_settings
|
||||
label: Simpletest configuration
|
||||
migration_tags:
|
||||
- Drupal 6
|
||||
- Configuration
|
||||
source:
|
||||
plugin: variable
|
||||
variables:
|
||||
- simpletest_clear_results
|
||||
- simpletest_httpauth_method
|
||||
- simpletest_httpauth_password
|
||||
- simpletest_httpauth_username
|
||||
- simpletest_verbose
|
||||
source_module: simpletest
|
||||
process:
|
||||
clear_results: simpletest_clear_results
|
||||
'httpauth/method': simpletest_httpauth_method
|
||||
'httpauth/password': simpletest_httpauth_password
|
||||
'httpauth/username': simpletest_httpauth_username
|
||||
verbose: simpletest_verbose
|
||||
destination:
|
||||
plugin: config
|
||||
config_name: simpletest.settings
|
||||
@@ -0,0 +1,23 @@
|
||||
id: d7_simpletest_settings
|
||||
label: SimpleTest configuration
|
||||
migration_tags:
|
||||
- Drupal 7
|
||||
- Configuration
|
||||
source:
|
||||
plugin: variable
|
||||
variables:
|
||||
- simpletest_clear_results
|
||||
- simpletest_httpauth_method
|
||||
- simpletest_httpauth_password
|
||||
- simpletest_httpauth_username
|
||||
- simpletest_verbose
|
||||
source_module: simpletest
|
||||
process:
|
||||
clear_results: simpletest_clear_results
|
||||
'httpauth/method': simpletest_httpauth_method
|
||||
'httpauth/password': simpletest_httpauth_password
|
||||
'httpauth/username': simpletest_httpauth_username
|
||||
verbose: simpletest_verbose
|
||||
destination:
|
||||
plugin: config
|
||||
config_name: simpletest.settings
|
||||
@@ -0,0 +1,5 @@
|
||||
finished:
|
||||
6:
|
||||
simpletest: simpletest
|
||||
7:
|
||||
simpletest: simpletest
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Hooks provided by the SimpleTest module.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @addtogroup hooks
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* Alter the list of tests.
|
||||
*
|
||||
* This hook will not be invoked by the phpunit tool.
|
||||
*
|
||||
* @param $groups
|
||||
* A two dimensional array, the first key is the test group, the second is the
|
||||
* name of the test class, and the value is in associative array containing
|
||||
* 'name', 'description', 'group', and 'requires' keys.
|
||||
*
|
||||
* @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Convert
|
||||
* your test to a PHPUnit-based one and implement test listeners.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2939892
|
||||
*/
|
||||
function hook_simpletest_alter(&$groups) {
|
||||
// An alternative session handler module would not want to run the original
|
||||
// Session HTTPS handling test because it checks the sessions table in the
|
||||
// database.
|
||||
unset($groups['Session']['testHttpsSession']);
|
||||
}
|
||||
|
||||
/**
|
||||
* A test group has started.
|
||||
*
|
||||
* This hook is called just once at the beginning of a test group.
|
||||
*
|
||||
* This hook is only invoked by the Simpletest UI form runner. It will not be
|
||||
* invoked by run-tests.sh or the phpunit tool.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Convert your
|
||||
* test to a PHPUnit-based one and implement test listeners.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2934242
|
||||
*/
|
||||
function hook_test_group_started() {
|
||||
}
|
||||
|
||||
/**
|
||||
* A test group has finished.
|
||||
*
|
||||
* This hook is called just once at the end of a test group.
|
||||
*
|
||||
* This hook is only invoked by the Simpletest UI form runner. It will not be
|
||||
* invoked by run-tests.sh or the phpunit tool.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Convert your
|
||||
* test to a PHPUnit-based one and implement test listeners.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2934242
|
||||
*/
|
||||
function hook_test_group_finished() {
|
||||
}
|
||||
|
||||
/**
|
||||
* An individual test has finished.
|
||||
*
|
||||
* This hook is called when an individual test has finished.
|
||||
*
|
||||
* This hook is only invoked by the Simpletest UI form runner. It will not be
|
||||
* invoked by run-tests.sh or the phpunit tool.
|
||||
*
|
||||
* @param
|
||||
* $results The results of the test as gathered by
|
||||
* \Drupal\simpletest\WebTestBase.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Convert your
|
||||
* test to a PHPUnit-based one and implement test listeners.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2934242
|
||||
* @see _simpletest_batch_operation()
|
||||
*/
|
||||
function hook_test_finished($results) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @} End of "addtogroup hooks".
|
||||
*/
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* @file
|
||||
* Simpletest behaviors.
|
||||
*/
|
||||
|
||||
(function($, Drupal, drupalSettings) {
|
||||
/**
|
||||
* Collapses table rows followed by group rows on the test listing page.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attach collapse behavior on the test listing page.
|
||||
*/
|
||||
Drupal.behaviors.simpleTestGroupCollapse = {
|
||||
attach(context) {
|
||||
$(context)
|
||||
.find('.simpletest-group')
|
||||
.once('simpletest-group-collapse')
|
||||
.each(function() {
|
||||
const $group = $(this);
|
||||
const $image = $group.find('.simpletest-image');
|
||||
$image.html(drupalSettings.simpleTest.images[0]).on('click', () => {
|
||||
const $tests = $group.nextUntil('.simpletest-group');
|
||||
const expand = !$group.hasClass('expanded');
|
||||
$group.toggleClass('expanded', expand);
|
||||
$tests.toggleClass('js-hide', !expand);
|
||||
$image.html(drupalSettings.simpleTest.images[+expand]);
|
||||
});
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Toggles test checkboxes to match the group checkbox.
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches behavior for selecting all tests in a group.
|
||||
*/
|
||||
Drupal.behaviors.simpleTestSelectAll = {
|
||||
attach(context) {
|
||||
$(context)
|
||||
.find('.simpletest-group')
|
||||
.once('simpletest-group-select-all')
|
||||
.each(function() {
|
||||
const $group = $(this);
|
||||
const $cell = $group.find('.simpletest-group-select-all');
|
||||
const $groupCheckbox = $(Drupal.theme('checkbox')).attr(
|
||||
'id',
|
||||
`${$cell.attr('id')}-group-select-all`,
|
||||
);
|
||||
const $testCheckboxes = $group
|
||||
.nextUntil('.simpletest-group')
|
||||
.find('input[type=checkbox]');
|
||||
$cell.append($groupCheckbox);
|
||||
|
||||
// Toggle the test checkboxes when the group checkbox is toggled.
|
||||
$groupCheckbox.on('change', function() {
|
||||
const checked = $(this).prop('checked');
|
||||
$testCheckboxes.prop('checked', checked);
|
||||
});
|
||||
|
||||
// Update the group checkbox when a test checkbox is toggled.
|
||||
function updateGroupCheckbox() {
|
||||
let allChecked = true;
|
||||
$testCheckboxes.each(function() {
|
||||
if (!$(this).prop('checked')) {
|
||||
allChecked = false;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
$groupCheckbox.prop('checked', allChecked);
|
||||
}
|
||||
|
||||
$testCheckboxes.on('change', updateGroupCheckbox);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Filters the test list table by a text input search string.
|
||||
*
|
||||
* Text search input: input.table-filter-text
|
||||
* Target table: input.table-filter-text[data-table]
|
||||
* Source text: .table-filter-text-source
|
||||
*
|
||||
* @type {Drupal~behavior}
|
||||
*
|
||||
* @prop {Drupal~behaviorAttach} attach
|
||||
* Attaches the filter behavior to the text input element.
|
||||
*/
|
||||
Drupal.behaviors.simpletestTableFilterByText = {
|
||||
attach(context) {
|
||||
const $input = $('input.table-filter-text').once('table-filter-text');
|
||||
const $table = $($input.attr('data-table'));
|
||||
let $rows;
|
||||
let searched = false;
|
||||
|
||||
function filterTestList(e) {
|
||||
const query = $(e.target)
|
||||
.val()
|
||||
.toLowerCase();
|
||||
|
||||
function showTestRow(index, row) {
|
||||
const $row = $(row);
|
||||
const $sources = $row.find('.table-filter-text-source');
|
||||
const textMatch =
|
||||
$sources
|
||||
.text()
|
||||
.toLowerCase()
|
||||
.indexOf(query) !== -1;
|
||||
$row.closest('tr').toggle(textMatch);
|
||||
}
|
||||
|
||||
// Filter if the length of the query is at least 3 characters.
|
||||
if (query.length >= 3) {
|
||||
// Indicate that a search has been performed, and hide the
|
||||
// "select all" checkbox.
|
||||
searched = true;
|
||||
$('#simpletest-form-table thead th.select-all input').hide();
|
||||
|
||||
$rows.each(showTestRow);
|
||||
}
|
||||
// Restore to the original state if any searching has occurred.
|
||||
else if (searched) {
|
||||
searched = false;
|
||||
$('#simpletest-form-table thead th.select-all input').show();
|
||||
// Restore all rows to their original display state.
|
||||
$rows.css('display', '');
|
||||
}
|
||||
}
|
||||
|
||||
if ($table.length) {
|
||||
$rows = $table.find('tbody tr');
|
||||
$input
|
||||
.trigger('focus')
|
||||
.on('keyup', Drupal.debounce(filterTestList, 200));
|
||||
}
|
||||
},
|
||||
};
|
||||
})(jQuery, Drupal, drupalSettings);
|
||||
@@ -0,0 +1,7 @@
|
||||
name: Testing
|
||||
type: module
|
||||
description: 'Provides a framework for unit and functional testing.'
|
||||
package: Core
|
||||
version: VERSION
|
||||
core: 8.x
|
||||
configure: simpletest.settings
|
||||
@@ -0,0 +1,110 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Install, update and uninstall functions for the simpletest module.
|
||||
*/
|
||||
|
||||
use Drupal\Component\FileSecurity\FileSecurity;
|
||||
use Drupal\Component\Utility\Environment;
|
||||
use Drupal\Core\File\Exception\FileException;
|
||||
use Drupal\Core\Test\TestDatabase;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Minimum value of PHP memory_limit for SimpleTest.
|
||||
*/
|
||||
const SIMPLETEST_MINIMUM_PHP_MEMORY_LIMIT = '128M';
|
||||
|
||||
/**
|
||||
* Implements hook_requirements().
|
||||
*/
|
||||
function simpletest_requirements($phase) {
|
||||
$requirements = [];
|
||||
|
||||
$requirements['deprecation'] = [
|
||||
'title' => t('Testing (SimpleTest)'),
|
||||
'value' => t('The <em>Testing</em> (SimpleTest) module is deprecated for removal in Drupal 9. It should not be enabled on production sites. Read <a href="https://www.drupal.org/node/3091784">The Drupal core SimpleTest module is deprecated</a> for alternative ways to run tests during development.'),
|
||||
'severity' => $phase === 'runtime' ? REQUIREMENT_WARNING : REQUIREMENT_INFO,
|
||||
];
|
||||
|
||||
$has_phpunit = class_exists(TestCase::class);
|
||||
$has_curl = function_exists('curl_init');
|
||||
|
||||
$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' 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 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>.');
|
||||
}
|
||||
|
||||
// Check the current memory limit. If it is set too low, SimpleTest will fail
|
||||
// to load all tests and throw a fatal error.
|
||||
$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>.', ['%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'] = [
|
||||
'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.', [
|
||||
'%sites-simpletest' => $site_directory,
|
||||
]),
|
||||
];
|
||||
}
|
||||
elseif (!FileSecurity::writeHtaccess(\Drupal::root() . '/' . $site_directory, FALSE)) {
|
||||
$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.', [
|
||||
'%file' => $site_directory . '/.htaccess',
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
return $requirements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_schema().
|
||||
*/
|
||||
function simpletest_schema() {
|
||||
return TestDatabase::testingSchema();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_uninstall().
|
||||
*/
|
||||
function simpletest_uninstall() {
|
||||
// Do not clean the environment in case the Simpletest module is uninstalled
|
||||
// in a (recursive) test for itself, since simpletest_clean_environment()
|
||||
// would also delete the test site of the parent test process.
|
||||
if (!drupal_valid_test_ua()) {
|
||||
\Drupal::service('environment_cleaner')->cleanEnvironment();
|
||||
}
|
||||
// Delete verbose test output and any other testing framework files.
|
||||
try {
|
||||
\Drupal::service('file_system')->deleteRecursive('public://simpletest');
|
||||
}
|
||||
catch (FileException $e) {
|
||||
// Ignore.
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* DO NOT EDIT THIS FILE.
|
||||
* See the following change record for more information,
|
||||
* https://www.drupal.org/node/2815083
|
||||
* @preserve
|
||||
**/
|
||||
|
||||
(function ($, Drupal, drupalSettings) {
|
||||
Drupal.behaviors.simpleTestGroupCollapse = {
|
||||
attach: function attach(context) {
|
||||
$(context).find('.simpletest-group').once('simpletest-group-collapse').each(function () {
|
||||
var $group = $(this);
|
||||
var $image = $group.find('.simpletest-image');
|
||||
$image.html(drupalSettings.simpleTest.images[0]).on('click', function () {
|
||||
var $tests = $group.nextUntil('.simpletest-group');
|
||||
var expand = !$group.hasClass('expanded');
|
||||
$group.toggleClass('expanded', expand);
|
||||
$tests.toggleClass('js-hide', !expand);
|
||||
$image.html(drupalSettings.simpleTest.images[+expand]);
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Drupal.behaviors.simpleTestSelectAll = {
|
||||
attach: function attach(context) {
|
||||
$(context).find('.simpletest-group').once('simpletest-group-select-all').each(function () {
|
||||
var $group = $(this);
|
||||
var $cell = $group.find('.simpletest-group-select-all');
|
||||
var $groupCheckbox = $(Drupal.theme('checkbox')).attr('id', $cell.attr('id') + '-group-select-all');
|
||||
var $testCheckboxes = $group.nextUntil('.simpletest-group').find('input[type=checkbox]');
|
||||
$cell.append($groupCheckbox);
|
||||
|
||||
$groupCheckbox.on('change', function () {
|
||||
var checked = $(this).prop('checked');
|
||||
$testCheckboxes.prop('checked', checked);
|
||||
});
|
||||
|
||||
function updateGroupCheckbox() {
|
||||
var allChecked = true;
|
||||
$testCheckboxes.each(function () {
|
||||
if (!$(this).prop('checked')) {
|
||||
allChecked = false;
|
||||
return false;
|
||||
}
|
||||
});
|
||||
$groupCheckbox.prop('checked', allChecked);
|
||||
}
|
||||
|
||||
$testCheckboxes.on('change', updateGroupCheckbox);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Drupal.behaviors.simpletestTableFilterByText = {
|
||||
attach: function attach(context) {
|
||||
var $input = $('input.table-filter-text').once('table-filter-text');
|
||||
var $table = $($input.attr('data-table'));
|
||||
var $rows = void 0;
|
||||
var searched = false;
|
||||
|
||||
function filterTestList(e) {
|
||||
var query = $(e.target).val().toLowerCase();
|
||||
|
||||
function showTestRow(index, row) {
|
||||
var $row = $(row);
|
||||
var $sources = $row.find('.table-filter-text-source');
|
||||
var textMatch = $sources.text().toLowerCase().indexOf(query) !== -1;
|
||||
$row.closest('tr').toggle(textMatch);
|
||||
}
|
||||
|
||||
if (query.length >= 3) {
|
||||
searched = true;
|
||||
$('#simpletest-form-table thead th.select-all input').hide();
|
||||
|
||||
$rows.each(showTestRow);
|
||||
} else if (searched) {
|
||||
searched = false;
|
||||
$('#simpletest-form-table thead th.select-all input').show();
|
||||
|
||||
$rows.css('display', '');
|
||||
}
|
||||
}
|
||||
|
||||
if ($table.length) {
|
||||
$rows = $table.find('tbody tr');
|
||||
$input.trigger('focus').on('keyup', Drupal.debounce(filterTestList, 200));
|
||||
}
|
||||
}
|
||||
};
|
||||
})(jQuery, Drupal, drupalSettings);
|
||||
@@ -0,0 +1,14 @@
|
||||
drupal.simpletest:
|
||||
version: VERSION
|
||||
js:
|
||||
simpletest.js: {}
|
||||
css:
|
||||
component:
|
||||
css/simpletest.module.css: {}
|
||||
dependencies:
|
||||
- core/jquery
|
||||
- core/drupal
|
||||
- core/drupalSettings
|
||||
- core/jquery.once
|
||||
- core/drupal.tableselect
|
||||
- core/drupal.debounce
|
||||
@@ -0,0 +1,6 @@
|
||||
simpletest.test_form:
|
||||
title: Testing
|
||||
description: 'Run tests against the site''s core code and enabled modules to review your code.'
|
||||
route_name: simpletest.test_form
|
||||
parent: system.admin_config_development
|
||||
weight: -5
|
||||
@@ -0,0 +1,9 @@
|
||||
simpletest.test_form:
|
||||
title: List
|
||||
route_name: simpletest.test_form
|
||||
base_route: simpletest.test_form
|
||||
simpletest.settings:
|
||||
title: Settings
|
||||
route_name: simpletest.settings
|
||||
base_route: simpletest.test_form
|
||||
weight: 100
|
||||
@@ -0,0 +1,828 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Provides testing functionality.
|
||||
*/
|
||||
|
||||
use Drupal\Component\Uuid\Php;
|
||||
use Drupal\Core\Asset\AttachedAssets;
|
||||
use Drupal\Core\Asset\AttachedAssetsInterface;
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\Core\File\Exception\FileException;
|
||||
use Drupal\Core\File\FileSystemInterface;
|
||||
use Drupal\Core\Render\Element;
|
||||
use Drupal\Core\Routing\RouteMatchInterface;
|
||||
use Drupal\Core\StreamWrapper\PublicStream;
|
||||
use Drupal\Core\Test\JUnitConverter;
|
||||
use Drupal\Core\Test\PhpUnitTestRunner;
|
||||
use Drupal\Core\Test\TestDatabase;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\simpletest\Form\SimpletestResultsForm;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Implements hook_help().
|
||||
*/
|
||||
function simpletest_help($route_name, RouteMatchInterface $route_match) {
|
||||
switch ($route_name) {
|
||||
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>.', [':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.', [':admin-simpletest' => Url::fromRoute('simpletest.test_form')->toString()]) . '</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;
|
||||
|
||||
case 'simpletest.test_form':
|
||||
$output = t('Select the test(s) or test group(s) you would like to run, and click <em>Run tests</em>.');
|
||||
return $output;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_theme().
|
||||
*/
|
||||
function simpletest_theme() {
|
||||
return [
|
||||
'simpletest_result_summary' => [
|
||||
'variables' => ['label' => NULL, 'items' => [], 'pass' => 0, 'fail' => 0, 'exception' => 0, 'debug' => 0],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_js_alter().
|
||||
*/
|
||||
function simpletest_js_alter(&$javascript, AttachedAssetsInterface $assets) {
|
||||
// Since SimpleTest is a special use case for the table select, stick the
|
||||
// SimpleTest JavaScript above the table select.
|
||||
$simpletest = drupal_get_path('module', 'simpletest') . '/simpletest.js';
|
||||
if (array_key_exists($simpletest, $javascript) && array_key_exists('core/misc/tableselect.js', $javascript)) {
|
||||
$javascript[$simpletest]['weight'] = $javascript['core/misc/tableselect.js']['weight'] - 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Prepares variables for simpletest result summary templates.
|
||||
*
|
||||
* Default template: simpletest-result-summary.html.twig.
|
||||
*
|
||||
* @param array $variables
|
||||
* An associative array containing:
|
||||
* - label: An optional label to be rendered before the results.
|
||||
* - ok: The overall group result pass or fail.
|
||||
* - pass: The number of passes.
|
||||
* - fail: The number of fails.
|
||||
* - exception: The number of exceptions.
|
||||
* - debug: The number of debug messages.
|
||||
*/
|
||||
function template_preprocess_simpletest_result_summary(&$variables) {
|
||||
$variables['items'] = _simpletest_build_summary_line($variables);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats each test result type pluralized summary.
|
||||
*
|
||||
* @param array $summary
|
||||
* A summary of the test results.
|
||||
*
|
||||
* @return array
|
||||
* The pluralized test summary items.
|
||||
*/
|
||||
function _simpletest_build_summary_line($summary) {
|
||||
$translation = \Drupal::translation();
|
||||
$items['pass'] = $translation->formatPlural($summary['pass'], '1 pass', '@count passes');
|
||||
$items['fail'] = $translation->formatPlural($summary['fail'], '1 fail', '@count fails');
|
||||
$items['exception'] = $translation->formatPlural($summary['exception'], '1 exception', '@count exceptions');
|
||||
if ($summary['debug']) {
|
||||
$items['debug'] = $translation->formatPlural($summary['debug'], '1 debug message', '@count debug messages');
|
||||
}
|
||||
return $items;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats test result summaries into a comma separated string for run-tests.sh.
|
||||
*
|
||||
* @param array $summary
|
||||
* A summary of the test results.
|
||||
*
|
||||
* @return string
|
||||
* A concatenated string of the formatted test results.
|
||||
*/
|
||||
function _simpletest_format_summary_line($summary) {
|
||||
$parts = _simpletest_build_summary_line($summary);
|
||||
return implode(', ', $parts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs tests.
|
||||
*
|
||||
* @param array[] $test_list
|
||||
* List of tests to run. The top level is keyed by type of test, either
|
||||
* 'simpletest' or 'phpunit'. Under that is an array of class names to run.
|
||||
*
|
||||
* @return string
|
||||
* The test ID.
|
||||
*/
|
||||
function simpletest_run_tests($test_list) {
|
||||
// We used to separate PHPUnit and Simpletest tests for a performance
|
||||
// optimization. In order to support backwards compatibility check if these
|
||||
// keys are set and create a single test list.
|
||||
// @todo https://www.drupal.org/node/2748967 Remove BC support in Drupal 9.
|
||||
if (isset($test_list['simpletest'])) {
|
||||
$test_list = array_merge($test_list, $test_list['simpletest']);
|
||||
unset($test_list['simpletest']);
|
||||
}
|
||||
if (isset($test_list['phpunit'])) {
|
||||
$test_list = array_merge($test_list, $test_list['phpunit']);
|
||||
unset($test_list['phpunit']);
|
||||
}
|
||||
|
||||
$test_id = \Drupal::database()->insert('simpletest_test_id')
|
||||
->useDefaults(['test_id'])
|
||||
->execute();
|
||||
|
||||
// Clear out the previous verbose files.
|
||||
try {
|
||||
\Drupal::service('file_system')->deleteRecursive('public://simpletest/verbose');
|
||||
}
|
||||
catch (FileException $e) {
|
||||
// Ignore failed deletes.
|
||||
}
|
||||
|
||||
// Get the info for the first test being run.
|
||||
$first_test = reset($test_list);
|
||||
$info = TestDiscovery::getTestInfo($first_test);
|
||||
|
||||
$batch = [
|
||||
'title' => t('Running tests'),
|
||||
'operations' => [
|
||||
['_simpletest_batch_operation', [$test_list, $test_id]],
|
||||
],
|
||||
'finished' => '_simpletest_batch_finished',
|
||||
'progress_message' => '',
|
||||
'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()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_group_started');
|
||||
|
||||
return $test_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes PHPUnit tests and returns the results of the run.
|
||||
*
|
||||
* @param $test_id
|
||||
* The current test ID.
|
||||
* @param $unescaped_test_classnames
|
||||
* An array of test class names, including full namespaces, to be passed as
|
||||
* a regular expression to PHPUnit's --filter option.
|
||||
* @param int $status
|
||||
* (optional) The exit status code of the PHPUnit process will be assigned to
|
||||
* this variable.
|
||||
*
|
||||
* @return array
|
||||
* The parsed results of PHPUnit's JUnit XML output, in the format of
|
||||
* {simpletest}'s schema.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\PhpUnitTestRunner::runTests() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_run_phpunit_tests($test_id, array $unescaped_test_classnames, &$status = NULL) {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::runTests() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return $runner->runTests($test_id, $unescaped_test_classnames, $status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the parsed PHPUnit results into {simpletest}.
|
||||
*
|
||||
* @param array[] $phpunit_results
|
||||
* An array of test results returned from simpletest_phpunit_xml_to_rows().
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\TestDatabase::processPhpUnitResults() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3075252
|
||||
*/
|
||||
function simpletest_process_phpunit_results($phpunit_results) {
|
||||
@trigger_error(__FUNCTION__ . '() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::processPhpUnitResults() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
|
||||
TestDatabase::processPhpUnitResults($phpunit_results);
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps phpunit results to a data structure for batch messages and run-tests.sh.
|
||||
*
|
||||
* @param array $results
|
||||
* The output from simpletest_run_phpunit_tests().
|
||||
*
|
||||
* @return array
|
||||
* The test result summary. A row per test class.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\PhpUnitTestRunner::summarizeResults() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_summarize_phpunit_result($results) {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::summarizeResults() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return $runner->summarizeResults($results);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path to use for PHPUnit's --log-junit option.
|
||||
*
|
||||
* @param $test_id
|
||||
* The current test ID.
|
||||
*
|
||||
* @return string
|
||||
* Path to the PHPUnit XML file to use for the current $test_id.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_xml_filepath($test_id) {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return $runner->xmlLogFilePath($test_id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the path to core's phpunit.xml.dist configuration file.
|
||||
*
|
||||
* @return string
|
||||
* The path to core's phpunit.xml.dist configuration file.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. PHPUnit test
|
||||
* runners should change directory into core/ and then run the phpunit tool.
|
||||
* See simpletest_phpunit_run_command() for an example.
|
||||
*
|
||||
* @see simpletest_phpunit_run_command()
|
||||
*/
|
||||
function simpletest_phpunit_configuration_filepath() {
|
||||
@trigger_error('The ' . __FUNCTION__ . ' function is deprecated since version 8.4.x and will be removed in 9.0.0.', E_USER_DEPRECATED);
|
||||
return \Drupal::root() . '/core/phpunit.xml.dist';
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes the PHPUnit command.
|
||||
*
|
||||
* @param array $unescaped_test_classnames
|
||||
* An array of test class names, including full namespaces, to be passed as
|
||||
* a regular expression to PHPUnit's --filter option.
|
||||
* @param string $phpunit_file
|
||||
* A filepath to use for PHPUnit's --log-junit option.
|
||||
* @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().
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\PhpUnitTestRunner::runCommand() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_run_command(array $unescaped_test_classnames, $phpunit_file, &$status = NULL, &$output = NULL) {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::runCommand() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return $runner->runCommand($unescaped_test_classnames, $phpunit_file, $status, $output);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the command to run PHPUnit.
|
||||
*
|
||||
* @return string
|
||||
* The command that can be run through exec().
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\PhpUnitTestRunner::phpUnitCommand() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_command() {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::phpUnitCommand() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return $runner->phpUnitCommand();
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements callback_batch_operation().
|
||||
*/
|
||||
function _simpletest_batch_operation($test_list_init, $test_id, &$context) {
|
||||
\Drupal::service('test_discovery')->registerTestNamespaces();
|
||||
// Get working values.
|
||||
if (!isset($context['sandbox']['max'])) {
|
||||
// First iteration: initialize working values.
|
||||
$test_list = $test_list_init;
|
||||
$context['sandbox']['max'] = count($test_list);
|
||||
$test_results = ['#pass' => 0, '#fail' => 0, '#exception' => 0, '#debug' => 0];
|
||||
}
|
||||
else {
|
||||
// Nth iteration: get the current values where we last stored them.
|
||||
$test_list = $context['sandbox']['tests'];
|
||||
$test_results = $context['sandbox']['test_results'];
|
||||
}
|
||||
$max = $context['sandbox']['max'];
|
||||
|
||||
// Perform the next test.
|
||||
$test_class = array_shift($test_list);
|
||||
if (is_subclass_of($test_class, TestCase::class)) {
|
||||
$runner = PhpUnitTestRunner::create(\Drupal::getContainer());
|
||||
$phpunit_results = $runner->runTests($test_id, [$test_class]);
|
||||
TestDatabase::processPhpUnitResults($phpunit_results);
|
||||
$test_results[$test_class] = simpletest_summarize_phpunit_result($phpunit_results)[$test_class];
|
||||
}
|
||||
else {
|
||||
$test = new $test_class($test_id);
|
||||
$test->run();
|
||||
\Drupal::moduleHandler()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_finished', [$test->results]);
|
||||
$test_results[$test_class] = $test->results;
|
||||
}
|
||||
$size = count($test_list);
|
||||
$info = TestDiscovery::getTestInfo($test_class);
|
||||
|
||||
// Gather results and compose the report.
|
||||
foreach ($test_results[$test_class] as $key => $value) {
|
||||
$test_results[$key] += $value;
|
||||
}
|
||||
$test_results[$test_class]['#name'] = $info['name'];
|
||||
$items = [];
|
||||
foreach (Element::children($test_results) as $class) {
|
||||
$class_test_result = $test_results[$class] + [
|
||||
'#theme' => 'simpletest_result_summary',
|
||||
'#label' => t($test_results[$class]['#name'] . ':'),
|
||||
];
|
||||
array_unshift($items, \Drupal::service('renderer')->render($class_test_result));
|
||||
}
|
||||
$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::service('renderer')->render($overall_results);
|
||||
|
||||
$item_list = [
|
||||
'#theme' => 'item_list',
|
||||
'#items' => $items,
|
||||
];
|
||||
$context['message'] .= \Drupal::service('renderer')->render($item_list);
|
||||
|
||||
// Save working values for the next iteration.
|
||||
$context['sandbox']['tests'] = $test_list;
|
||||
$context['sandbox']['test_results'] = $test_results;
|
||||
// The test_id is the only thing we need to save for the report page.
|
||||
$context['results']['test_id'] = $test_id;
|
||||
|
||||
// Multistep processing: report progress.
|
||||
$context['finished'] = 1 - $size / $max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements callback_batch_finished().
|
||||
*/
|
||||
function _simpletest_batch_finished($success, $results, $operations, $elapsed) {
|
||||
if ($success) {
|
||||
\Drupal::messenger()->addStatus(t('The test run finished in @elapsed.', ['@elapsed' => $elapsed]));
|
||||
}
|
||||
else {
|
||||
// Use the test_id passed as a parameter to _simpletest_batch_operation().
|
||||
$test_id = $operations[0][1][1];
|
||||
|
||||
// Retrieve the last database prefix used for testing and the last test
|
||||
// class that was run from. Use the information to read the lgo file
|
||||
// in case any fatal errors caused the test to crash.
|
||||
$last_test = TestDatabase::lastTestGet($test_id);
|
||||
(new TestDatabase($last_test['last_prefix']))->logRead($test_id, $last_test['test_class']);
|
||||
|
||||
\Drupal::messenger()->addError(t('The test run did not successfully finish.'));
|
||||
\Drupal::messenger()->addWarning(t('Use the <em>Clean environment</em> button to clean-up temporary files and tables.'));
|
||||
}
|
||||
\Drupal::moduleHandler()->invokeAllDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242', 'test_group_finished');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get information about the last test that ran given a test ID.
|
||||
*
|
||||
* @param $test_id
|
||||
* The test ID to get the last test from.
|
||||
* @return array
|
||||
* Array containing the last database prefix used and the last test class
|
||||
* that ran.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\TestDatabase::lastTestGet() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3075252
|
||||
*/
|
||||
function simpletest_last_test_get($test_id) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::lastTestGet() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
|
||||
return array_values(TestDatabase::lastTestGet($test_id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the error log and reports any errors as assertion failures.
|
||||
*
|
||||
* The errors in the log should only be fatal errors since any other errors
|
||||
* will have been recorded by the error handler.
|
||||
*
|
||||
* @param $test_id
|
||||
* The test ID to which the log relates.
|
||||
* @param $database_prefix
|
||||
* The database prefix to which the log relates.
|
||||
* @param $test_class
|
||||
* The test class to which the log relates.
|
||||
*
|
||||
* @return bool
|
||||
* Whether any fatal errors were found.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\TestDatabase::logRead() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3075252
|
||||
*/
|
||||
function simpletest_log_read($test_id, $database_prefix, $test_class) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::logRead() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
|
||||
$test_db = new TestDatabase($database_prefix);
|
||||
return $test_db->logRead($test_id, $test_class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Store an assertion from outside the testing context.
|
||||
*
|
||||
* This is useful for inserting assertions that can only be recorded after
|
||||
* the test case has been destroyed, such as PHP fatal errors. The caller
|
||||
* information is not automatically gathered since the caller is most likely
|
||||
* inserting the assertion on behalf of other code. In all other respects
|
||||
* the method behaves just like \Drupal\simpletest\TestBase::assert() in terms
|
||||
* of storing the assertion.
|
||||
*
|
||||
* @param string $test_id
|
||||
* The test ID to which the assertion relates.
|
||||
* @param string $test_class
|
||||
* The test class to store an assertion for.
|
||||
* @param bool|string $status
|
||||
* A boolean or a string of 'pass' or 'fail'. TRUE means 'pass'.
|
||||
* @param string $message
|
||||
* The assertion message.
|
||||
* @param string $group
|
||||
* The assertion message group.
|
||||
* @param array $caller
|
||||
* The an array containing the keys 'file' and 'line' that represent the file
|
||||
* and line number of that file that is responsible for the assertion.
|
||||
*
|
||||
* @return
|
||||
* Message ID of the stored assertion.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\TestDatabase::insertAssert() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3075252
|
||||
*/
|
||||
function simpletest_insert_assert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::insertAssert() instead. See https://www.drupal.org/node/3075252', E_USER_DEPRECATED);
|
||||
TestDatabase::insertAssert($test_id, $test_class, $status, $message, $group, $caller);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of all of the tests provided by the system.
|
||||
*
|
||||
* The list of test classes is loaded by searching the designated directory for
|
||||
* each module for files matching the PSR-4 standard. Once loaded the test list
|
||||
* is cached and stored in a static variable.
|
||||
*
|
||||
* @param string $extension
|
||||
* (optional) The name of an extension to limit discovery to; e.g., 'node'.
|
||||
* @param string[] $types
|
||||
* An array of included test types.
|
||||
*
|
||||
* @return array[]
|
||||
* An array of tests keyed with the groups, and then keyed by test classes.
|
||||
* For example:
|
||||
* @code
|
||||
* $groups['Block'] => array(
|
||||
* 'BlockTestCase' => array(
|
||||
* 'name' => 'Block functionality',
|
||||
* 'description' => 'Add, edit and delete custom block.',
|
||||
* 'group' => 'Block',
|
||||
* ),
|
||||
* );
|
||||
* @endcode
|
||||
*
|
||||
* @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal::service('test_discovery')->getTestClasses($extension, $types)
|
||||
* instead.
|
||||
*/
|
||||
function simpletest_test_get_all($extension = NULL, array $types = []) {
|
||||
@trigger_error('The ' . __FUNCTION__ . ' function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service(\'test_discovery\')->getTestClasses($extension, $types) instead.', E_USER_DEPRECATED);
|
||||
return \Drupal::service('test_discovery')->getTestClasses($extension, $types);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers test namespaces of all extensions and core test classes.
|
||||
*
|
||||
* @deprecated in drupal:8.3.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal::service('test_discovery')->registerTestNamespaces() instead.
|
||||
*/
|
||||
function simpletest_classloader_register() {
|
||||
@trigger_error('The ' . __FUNCTION__ . ' function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service(\'test_discovery\')->registerTestNamespaces() instead.', E_USER_DEPRECATED);
|
||||
\Drupal::service('test_discovery')->registerTestNamespaces();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates a test file.
|
||||
*
|
||||
* @param string $filename
|
||||
* The name of the file, including the path. The suffix '.txt' is appended to
|
||||
* the supplied file name and the file is put into the public:// files
|
||||
* directory.
|
||||
* @param int $width
|
||||
* The number of characters on one line.
|
||||
* @param int $lines
|
||||
* The number of lines in the file.
|
||||
* @param string $type
|
||||
* (optional) The type, one of:
|
||||
* - text: The generated file contains random ASCII characters.
|
||||
* - binary: The generated file contains random characters whose codes are in
|
||||
* the range of 0 to 31.
|
||||
* - binary-text: The generated file contains random sequence of '0' and '1'
|
||||
* values.
|
||||
*
|
||||
* @return string
|
||||
* The name of the file, including the path.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\TestFileCreationTrait::generateFile() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3077768
|
||||
*/
|
||||
function simpletest_generate_file($filename, $width, $lines, $type = 'binary-text') {
|
||||
@trigger_error(__FUNCTION__ . '() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Tests\TestFileCreationTrait::generateFile() instead. See https://www.drupal.org/node/3077768', E_USER_DEPRECATED);
|
||||
$text = '';
|
||||
for ($i = 0; $i < $lines; $i++) {
|
||||
// Generate $width - 1 characters to leave space for the "\n" character.
|
||||
for ($j = 0; $j < $width - 1; $j++) {
|
||||
switch ($type) {
|
||||
case 'text':
|
||||
$text .= chr(rand(32, 126));
|
||||
break;
|
||||
case 'binary':
|
||||
$text .= chr(rand(0, 31));
|
||||
break;
|
||||
case 'binary-text':
|
||||
default:
|
||||
$text .= rand(0, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
$text .= "\n";
|
||||
}
|
||||
|
||||
// Create filename.
|
||||
file_put_contents('public://' . $filename . '.txt', $text);
|
||||
return $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all temporary database tables and directories.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
|
||||
* environment_cleaner service and call its cleanEnvironment() method, or use
|
||||
* \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3076634
|
||||
*/
|
||||
function simpletest_clean_environment() {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanEnvironment() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
|
||||
/* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
|
||||
$cleaner = \Drupal::service('environment_cleaner');
|
||||
$cleaner->cleanEnvironment();
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes prefixed tables from the database from crashed tests.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
|
||||
* environment_cleaner service and call its cleanDatabase() method, or use
|
||||
* \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3076634
|
||||
*/
|
||||
function simpletest_clean_database() {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanDatabase() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
|
||||
/* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
|
||||
$cleaner = \Drupal::service('environment_cleaner');
|
||||
$cleaner->cleanDatabase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all leftover temporary directories and removes them.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
|
||||
* environment_cleaner service and call its cleanTemporaryDirectories()
|
||||
* method, or use
|
||||
* \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3076634
|
||||
*/
|
||||
function simpletest_clean_temporary_directories() {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanTemporaryDirectories() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
|
||||
/* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
|
||||
$cleaner = \Drupal::service('environment_cleaner');
|
||||
$cleaner->cleanTemporaryDirectories();
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the test result tables.
|
||||
*
|
||||
* @param $test_id
|
||||
* Test ID to remove results for, or NULL to remove all results.
|
||||
*
|
||||
* @return int
|
||||
* The number of results that were removed.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the
|
||||
* environment_cleaner service and call its cleanResultsTable() method, or use
|
||||
* \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3076634
|
||||
*/
|
||||
function simpletest_clean_results_table($test_id = NULL) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanResultsTable() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead. See https://www.drupal.org/node/3076634', E_USER_DEPRECATED);
|
||||
$count = 0;
|
||||
if (\Drupal::config('simpletest.settings')->get('clear_results')) {
|
||||
/* @var $cleaner \Drupal\simpletest\EnvironmentCleanerService */
|
||||
$cleaner = \Drupal::service('environment_cleaner');
|
||||
$count = $cleaner->cleanResultsTable($test_id);
|
||||
}
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts PHPUnit's JUnit XML output to an array.
|
||||
*
|
||||
* @param $test_id
|
||||
* The current test ID.
|
||||
* @param $phpunit_xml_file
|
||||
* Path to the PHPUnit XML file.
|
||||
*
|
||||
* @return array[]|null
|
||||
* The results as array of rows in a format that can be inserted into
|
||||
* {simpletest}. If the phpunit_xml_file does not have any contents then the
|
||||
* function will return NULL.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\JUnitConverter::xmlToRows() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_xml_to_rows($test_id, $phpunit_xml_file) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::xmlToRows() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return JUnitConverter::xmlToRows($test_id, $phpunit_xml_file) ?: NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all test cases recursively from a test suite list.
|
||||
*
|
||||
* @param \SimpleXMLElement $element
|
||||
* The PHPUnit xml to search for test cases.
|
||||
* @param \SimpleXMLElement $parent
|
||||
* (Optional) The parent of the current element. Defaults to NULL.
|
||||
*
|
||||
* @return array
|
||||
* A list of all test cases.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\JUnitConverter::findTestCases() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_find_testcases(\SimpleXMLElement $element, \SimpleXMLElement $parent = NULL) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::findTestCases() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return JUnitConverter::findTestCases($element, $parent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a PHPUnit test case result to a {simpletest} result row.
|
||||
*
|
||||
* @param int $test_id
|
||||
* The current test ID.
|
||||
* @param \SimpleXMLElement $test_case
|
||||
* The PHPUnit test case represented as XML element.
|
||||
*
|
||||
* @return array
|
||||
* An array containing the {simpletest} result row.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2948547
|
||||
*/
|
||||
function simpletest_phpunit_testcase_to_row($test_id, \SimpleXMLElement $test_case) {
|
||||
@trigger_error(__FUNCTION__ . ' is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead. See https://www.drupal.org/node/2948547', E_USER_DEPRECATED);
|
||||
return JUnitConverter::convertTestCaseToSimpletestRow($test_id, $test_case);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display test results from run-tests.sh in a browser.
|
||||
*
|
||||
* @internal
|
||||
* This function is only used by run-tests.sh
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. This function
|
||||
* supports the --browser option in this script. Use the --verbose option
|
||||
* instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/3083549
|
||||
*/
|
||||
function _simpletest_run_tests_script_open_browser() {
|
||||
global $test_ids;
|
||||
|
||||
try {
|
||||
$connection = Database::getConnection('default', 'test-runner');
|
||||
$results = $connection->select('simpletest')
|
||||
->fields('simpletest')
|
||||
->condition('test_id', $test_ids, 'IN')
|
||||
->orderBy('test_class')
|
||||
->orderBy('message_id')
|
||||
->execute()
|
||||
->fetchAll();
|
||||
}
|
||||
catch (Exception $e) {
|
||||
echo (string) $e;
|
||||
exit(SIMPLETEST_SCRIPT_EXIT_EXCEPTION);
|
||||
}
|
||||
|
||||
// Get the results form.
|
||||
$form = [];
|
||||
SimpletestResultsForm::addResultForm($form, $results);
|
||||
|
||||
// Get the assets to make the details element collapsible and theme the result
|
||||
// form.
|
||||
$assets = new AttachedAssets();
|
||||
$assets->setLibraries([
|
||||
'core/drupal.collapse',
|
||||
'system/admin',
|
||||
'simpletest/drupal.simpletest',
|
||||
]);
|
||||
$resolver = \Drupal::service('asset.resolver');
|
||||
list($js_assets_header, $js_assets_footer) = $resolver->getJsAssets($assets, FALSE);
|
||||
$js_collection_renderer = \Drupal::service('asset.js.collection_renderer');
|
||||
$js_assets_header = $js_collection_renderer->render($js_assets_header);
|
||||
$js_assets_footer = $js_collection_renderer->render($js_assets_footer);
|
||||
$css_assets = \Drupal::service('asset.css.collection_renderer')->render($resolver->getCssAssets($assets, FALSE));
|
||||
|
||||
// Make the html page to write to disk.
|
||||
$render_service = \Drupal::service('renderer');
|
||||
$html = '<head>' . $render_service->renderPlain($js_assets_header) . $render_service->renderPlain($css_assets) . '</head><body>' . $render_service->renderPlain($form) . $render_service->renderPlain($js_assets_footer) . '</body>';
|
||||
|
||||
// Ensure we have assets verbose directory - tests with no verbose output will
|
||||
// not have created one.
|
||||
$directory = PublicStream::basePath() . '/simpletest/verbose';
|
||||
\Drupal::service('file_system')->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
|
||||
$php = new Php();
|
||||
$uuid = $php->generate();
|
||||
$filename = $directory . '/results-' . $uuid . '.html';
|
||||
$base_url = getenv('SIMPLETEST_BASE_URL');
|
||||
if (empty($base_url)) {
|
||||
simpletest_script_print_error("--browser needs argument --url.");
|
||||
}
|
||||
$url = $base_url . '/' . PublicStream::basePath() . '/simpletest/verbose/results-' . $uuid . '.html';
|
||||
file_put_contents($filename, $html);
|
||||
|
||||
// See if we can find an OS helper to open URLs in default browser.
|
||||
$browser = FALSE;
|
||||
if (shell_exec('which xdg-open')) {
|
||||
$browser = 'xdg-open';
|
||||
}
|
||||
elseif (shell_exec('which open')) {
|
||||
$browser = 'open';
|
||||
}
|
||||
elseif (substr(PHP_OS, 0, 3) == 'WIN') {
|
||||
$browser = 'start';
|
||||
}
|
||||
|
||||
if ($browser) {
|
||||
shell_exec($browser . ' ' . escapeshellarg($url));
|
||||
}
|
||||
else {
|
||||
// Can't find assets valid browser.
|
||||
print 'Open file://' . realpath($filename) . ' in your browser to see the verbose output.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
administer unit tests:
|
||||
title: 'Administer tests'
|
||||
restrict access: true
|
||||
@@ -0,0 +1,23 @@
|
||||
simpletest.settings:
|
||||
path: '/admin/config/development/testing/settings'
|
||||
defaults:
|
||||
_form: '\Drupal\simpletest\Form\SimpletestSettingsForm'
|
||||
_title: 'Test settings'
|
||||
requirements:
|
||||
_permission: 'administer unit tests'
|
||||
|
||||
simpletest.test_form:
|
||||
path: '/admin/config/development/testing'
|
||||
defaults:
|
||||
_form: '\Drupal\simpletest\Form\SimpletestTestForm'
|
||||
_title: 'Testing'
|
||||
requirements:
|
||||
_permission: 'administer unit tests'
|
||||
|
||||
simpletest.result_form:
|
||||
path: '/admin/config/development/testing/results/{test_id}'
|
||||
defaults:
|
||||
_form: '\Drupal\simpletest\Form\SimpletestResultsForm'
|
||||
_title: 'Test result'
|
||||
requirements:
|
||||
_permission: 'administer unit tests'
|
||||
@@ -0,0 +1,15 @@
|
||||
services:
|
||||
test_discovery:
|
||||
class: Drupal\simpletest\TestDiscovery
|
||||
arguments: ['@app.root', '@class_loader', '@module_handler']
|
||||
environment_cleaner_factory:
|
||||
class: Drupal\simpletest\EnvironmentCleanerFactory
|
||||
arguments: ['@service_container']
|
||||
environment_cleaner:
|
||||
class: Drupal\simpletest\EnvironmentCleanerService
|
||||
factory: 'environment_cleaner_factory:createCleaner'
|
||||
cache_context.test_discovery:
|
||||
class: Drupal\simpletest\Cache\Context\TestDiscoveryCacheContext
|
||||
arguments: ['@test_discovery', '@private_key']
|
||||
tags:
|
||||
- { name: cache.context}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\KernelTests\AssertContentTrait as CoreAssertContentTrait;
|
||||
|
||||
@trigger_error('\Drupal\simpletest\AssertContentTrait is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Instead, use \Drupal\KernelTests\AssertContentTrait.', E_USER_DEPRECATED);
|
||||
|
||||
/**
|
||||
* Provides test methods to assert content.
|
||||
*
|
||||
* @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Use
|
||||
* Drupal\KernelTests\AssertContentTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2943146
|
||||
*/
|
||||
trait AssertContentTrait {
|
||||
|
||||
use CoreAssertContentTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\AssertHelperTrait is deprecated in Drupal 8.4.x. Will be removed before Drupal 9.0.0. Use Drupal\Tests\AssertHelperTrait instead. See https://www.drupal.org/node/2884454.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\AssertHelperTrait as BaseAssertHelperTrait;
|
||||
|
||||
/**
|
||||
* Provides helper methods for assertions.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. Use
|
||||
* Drupal\Tests\AssertHelperTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2884454
|
||||
*/
|
||||
trait AssertHelperTrait {
|
||||
|
||||
use BaseAssertHelperTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\BlockCreationTrait is deprecated in Drupal 8.4.x. Will be removed before Drupal 9.0.0. Use \Drupal\Tests\block\Traits\BlockCreationTrait instead. See https://www.drupal.org/node/2884454.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\block\Traits\BlockCreationTrait as BaseBlockCreationTrait;
|
||||
|
||||
/**
|
||||
* Provides methods to create and place block with default settings.
|
||||
*
|
||||
* This trait is meant to be used only by test classes.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\block\Traits\BlockCreationTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2884454
|
||||
*/
|
||||
trait BlockCreationTrait {
|
||||
|
||||
use BaseBlockCreationTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\BrowserTestBase is deprecated in Drupal 8.1.x, will be removed before Drupal 9.0. Use Drupal\Tests\BrowserTestBase instead.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\BrowserTestBase as BaseBrowserTestBase;
|
||||
|
||||
/**
|
||||
* Provides a test case for functional Drupal tests.
|
||||
*
|
||||
* Tests extending BrowserTestBase must exist in the
|
||||
* Drupal\Tests\yourmodule\Functional namespace and live in the
|
||||
* modules/yourmodule/tests/src/Functional directory.
|
||||
*
|
||||
* @ingroup testing
|
||||
*
|
||||
* @see \Drupal\simpletest\WebTestBase
|
||||
* @see \Drupal\Tests\BrowserTestBase
|
||||
*
|
||||
* @deprecated in drupal:8.1.0 and is removed from drupal:9.0.0.
|
||||
* Use Drupal\Tests\BrowserTestBase instead.
|
||||
*/
|
||||
abstract class BrowserTestBase extends BaseBrowserTestBase {
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Cache\Context;
|
||||
|
||||
use Drupal\Core\Cache\CacheableMetadata;
|
||||
use Drupal\Core\Cache\Context\CacheContextInterface;
|
||||
use Drupal\Core\PrivateKey;
|
||||
use Drupal\Core\Site\Settings;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
|
||||
/**
|
||||
* Defines the TestDiscoveryCacheContext service.
|
||||
*
|
||||
* Cache context ID: 'test_discovery'.
|
||||
*/
|
||||
class TestDiscoveryCacheContext implements CacheContextInterface {
|
||||
|
||||
/**
|
||||
* The test discovery service.
|
||||
*
|
||||
* @var \Drupal\simpletest\TestDiscovery
|
||||
*/
|
||||
protected $testDiscovery;
|
||||
|
||||
/**
|
||||
* The private key service.
|
||||
*
|
||||
* @var \Drupal\Core\PrivateKey
|
||||
*/
|
||||
protected $privateKey;
|
||||
|
||||
/**
|
||||
* The hash of discovered test information.
|
||||
*
|
||||
* Services should not be stateful, but we only keep this information per
|
||||
* request. That way we don't perform a file scan every time we need this
|
||||
* hash. The test scan results are unlikely to change during the request.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $hash;
|
||||
|
||||
/**
|
||||
* Construct a test discovery cache context.
|
||||
*
|
||||
* @param \Drupal\simpletest\TestDiscovery $test_discovery
|
||||
* The test discovery service.
|
||||
* @param \Drupal\Core\PrivateKey $private_key
|
||||
* The private key service.
|
||||
*/
|
||||
public function __construct(TestDiscovery $test_discovery, PrivateKey $private_key) {
|
||||
$this->testDiscovery = $test_discovery;
|
||||
$this->privateKey = $private_key;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function getLabel() {
|
||||
return t('Test discovery');
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getContext() {
|
||||
if (empty($this->hash)) {
|
||||
$tests = $this->testDiscovery->getTestClasses();
|
||||
$this->hash = $this->hash(serialize($tests));
|
||||
}
|
||||
return $this->hash;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getCacheableMetadata() {
|
||||
return new CacheableMetadata();
|
||||
}
|
||||
|
||||
/**
|
||||
* Hashes the given string.
|
||||
*
|
||||
* @param string $identifier
|
||||
* The string to be hashed.
|
||||
*
|
||||
* @return string
|
||||
* The hash.
|
||||
*/
|
||||
protected function hash($identifier) {
|
||||
return hash('sha256', $this->privateKey->get() . Settings::getHashSalt() . $identifier);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\ContentTypeCreationTrait is deprecated in Drupal 8.4.x. Will be removed before Drupal 9.0.0. Use \Drupal\Tests\node\Traits\ContentTypeCreationTrait instead. See https://www.drupal.org/node/2884454.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\node\Traits\ContentTypeCreationTrait as BaseContentTypeCreationTrait;
|
||||
|
||||
/**
|
||||
* Provides methods to create content type from given values.
|
||||
*
|
||||
* This trait is meant to be used only by test classes.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\node\Traits\ContentTypeCreationTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2884454
|
||||
*/
|
||||
trait ContentTypeCreationTrait {
|
||||
|
||||
use BaseContentTypeCreationTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\Core\DependencyInjection\Container;
|
||||
use Drupal\Core\Test\TestDatabase;
|
||||
use Drupal\Core\Database\Database;
|
||||
|
||||
/**
|
||||
* Test environment cleaner factory.
|
||||
*
|
||||
* We use a factory pattern here so that we can inject the test results database
|
||||
* which is not a service (and should not be).
|
||||
*/
|
||||
class EnvironmentCleanerFactory {
|
||||
|
||||
/**
|
||||
* The container.
|
||||
*
|
||||
* @var \Drupal\Core\DependencyInjection\Container
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* Construct an environment cleaner factory.
|
||||
*
|
||||
* @param \Drupal\Core\DependencyInjection\Container $container
|
||||
* The container.
|
||||
*/
|
||||
public function __construct(Container $container) {
|
||||
$this->container = $container;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory method to create the environment cleaner service.
|
||||
*
|
||||
* @return \Drupal\simpletest\EnvironmentCleanerService
|
||||
* The environment cleaner service.
|
||||
*/
|
||||
public function createCleaner() {
|
||||
$cleaner = new EnvironmentCleanerService(
|
||||
$this->container->get('app.root'),
|
||||
Database::getConnection(),
|
||||
TestDatabase::getConnection(),
|
||||
$this->container->get('messenger'),
|
||||
$this->container->get('string_translation'),
|
||||
$this->container->get('config.factory'),
|
||||
$this->container->get('cache.default'),
|
||||
$this->container->get('file_system')
|
||||
);
|
||||
|
||||
return $cleaner;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Messenger\MessengerInterface;
|
||||
use Drupal\Core\StringTranslation\TranslationInterface;
|
||||
use Drupal\Core\Config\ConfigFactory;
|
||||
use Drupal\Core\Cache\CacheBackendInterface;
|
||||
use Drupal\Core\File\FileSystem;
|
||||
use Drupal\Core\Test\EnvironmentCleaner;
|
||||
|
||||
/**
|
||||
* Uses containerized services to perform post-test cleanup.
|
||||
*/
|
||||
class EnvironmentCleanerService extends EnvironmentCleaner {
|
||||
|
||||
/**
|
||||
* Messenger service.
|
||||
*
|
||||
* @var \Drupal\Core\Messenger\MessengerInterface
|
||||
*/
|
||||
protected $messenger;
|
||||
|
||||
/**
|
||||
* The translation service.
|
||||
*
|
||||
* @var \Drupal\Core\StringTranslation\TranslationInterface
|
||||
*/
|
||||
protected $translation;
|
||||
|
||||
/**
|
||||
* The config factory.
|
||||
*
|
||||
* @var \Drupal\Core\Config\ConfigFactory
|
||||
*/
|
||||
protected $configFactory;
|
||||
|
||||
/**
|
||||
* Default cache.
|
||||
*
|
||||
* @var \Drupal\Core\Cache\CacheBackendInterface
|
||||
*/
|
||||
protected $cacheDefault;
|
||||
|
||||
/**
|
||||
* Construct an environment cleaner.
|
||||
*
|
||||
* @param string $root
|
||||
* The path to the root of the Drupal installation.
|
||||
* @param \Drupal\Core\Database\Connection $test_database
|
||||
* Connection to the database against which tests were run.
|
||||
* @param \Drupal\Core\Database\Connection $results_database
|
||||
* Connection to the database where test results were stored. This could be
|
||||
* the same as $test_database, or it could be different.
|
||||
* @param \Drupal\Core\StringTranslation\TranslationInterface|null $translation
|
||||
* (optional) The translation service. If none is supplied, this class will
|
||||
* attempt to discover one using \Drupal.
|
||||
*/
|
||||
public function __construct($root, Connection $test_database, Connection $results_database, MessengerInterface $messenger, TranslationInterface $translation, ConfigFactory $config, CacheBackendInterface $cache_default, FileSystem $file_system) {
|
||||
$this->root = $root;
|
||||
$this->testDatabase = $test_database;
|
||||
$this->resultsDatabase = $results_database;
|
||||
$this->messenger = $messenger;
|
||||
$this->translation = $translation;
|
||||
$this->configFactory = $config;
|
||||
$this->cacheDefault = $cache_default;
|
||||
$this->fileSystem = $file_system;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function cleanEnvironment($clear_results = TRUE, $clear_temp_directories = TRUE, $clear_database = TRUE) {
|
||||
$results_removed = 0;
|
||||
$clear_results = $this->configFactory->get('simpletest.settings')->get('clear_results');
|
||||
|
||||
if ($clear_database) {
|
||||
$this->cleanDatabase();
|
||||
}
|
||||
if ($clear_temp_directories) {
|
||||
$this->cleanTemporaryDirectories();
|
||||
}
|
||||
if ($clear_results) {
|
||||
$results_removed = $this->cleanResultsTable();
|
||||
}
|
||||
$this->cacheDefault->delete('simpletest');
|
||||
$this->cacheDefault->delete('simpletest_phpunit');
|
||||
|
||||
if ($clear_results) {
|
||||
$this->messenger->addMessage($this->translation->formatPlural($results_removed, 'Removed 1 test result.', 'Removed @count test results.'));
|
||||
}
|
||||
else {
|
||||
$this->messenger->addMessage($this->translation->translate('Clear results is disabled and the test results table will not be cleared.'), 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function cleanDatabase() {
|
||||
$tables_removed = $this->doCleanDatabase();
|
||||
if ($tables_removed > 0) {
|
||||
$this->messenger->addMessage($this->translation->formatPlural($tables_removed, 'Removed 1 leftover table.', 'Removed @count leftover tables.'));
|
||||
}
|
||||
else {
|
||||
$this->messenger->addMessage($this->translation->translate('No leftover tables to remove.'));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function cleanTemporaryDirectories() {
|
||||
$directories_removed = $this->doCleanTemporaryDirectories();
|
||||
if ($directories_removed > 0) {
|
||||
$this->messenger->addMessage($this->translation->formatPlural($directories_removed, 'Removed 1 temporary directory.', 'Removed @count temporary directories.'));
|
||||
}
|
||||
else {
|
||||
$this->messenger->addMessage($this->translation->translate('No temporary directories to remove.'));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Exception;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\\MissingGroupException is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\Exception\MissingGroupException instead. See https://www.drupal.org/node/2949692', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Core\Test\Exception\MissingGroupException as CoreMissingGroupException;
|
||||
|
||||
/**
|
||||
* Exception thrown when a simpletest class is missing an @group annotation.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\Exception\MissingGroupException instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2949692
|
||||
*/
|
||||
class MissingGroupException extends CoreMissingGroupException {
|
||||
}
|
||||
@@ -0,0 +1,357 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Form;
|
||||
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Form\FormBase;
|
||||
use Drupal\Core\Form\FormState;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
use Drupal\Core\Test\EnvironmentCleanerInterface;
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
use Symfony\Component\DependencyInjection\ContainerInterface;
|
||||
|
||||
/**
|
||||
* Test results form for $test_id.
|
||||
*
|
||||
* Note that the UI strings are not translated because this form is also used
|
||||
* from run-tests.sh.
|
||||
*
|
||||
* @internal
|
||||
*
|
||||
* @see simpletest_script_open_browser()
|
||||
* @see run-tests.sh
|
||||
*/
|
||||
class SimpletestResultsForm extends FormBase {
|
||||
|
||||
/**
|
||||
* Associative array of themed result images keyed by status.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $statusImageMap;
|
||||
|
||||
/**
|
||||
* The database connection service.
|
||||
*
|
||||
* @var \Drupal\Core\Database\Connection
|
||||
*/
|
||||
protected $database;
|
||||
|
||||
/**
|
||||
* The environment cleaner service.
|
||||
*
|
||||
* @var \Drupal\Core\Test\EnvironmentCleanerInterface
|
||||
*/
|
||||
protected $cleaner;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static function create(ContainerInterface $container) {
|
||||
return new static(
|
||||
$container->get('database'),
|
||||
$container->get('environment_cleaner')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a \Drupal\simpletest\Form\SimpletestResultsForm object.
|
||||
*
|
||||
* @param \Drupal\Core\Database\Connection $database
|
||||
* The database connection service.
|
||||
*/
|
||||
public function __construct(Connection $database, EnvironmentCleanerInterface $cleaner) {
|
||||
$this->database = $database;
|
||||
$this->cleaner = $cleaner;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the status image map.
|
||||
*/
|
||||
protected static function buildStatusImageMap() {
|
||||
$image_pass = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/icons/73b355/check.svg',
|
||||
'#width' => 18,
|
||||
'#height' => 18,
|
||||
'#alt' => 'Pass',
|
||||
];
|
||||
$image_fail = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/icons/e32700/error.svg',
|
||||
'#width' => 18,
|
||||
'#height' => 18,
|
||||
'#alt' => 'Fail',
|
||||
];
|
||||
$image_exception = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/icons/e29700/warning.svg',
|
||||
'#width' => 18,
|
||||
'#height' => 18,
|
||||
'#alt' => 'Exception',
|
||||
];
|
||||
$image_debug = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/icons/e29700/warning.svg',
|
||||
'#width' => 18,
|
||||
'#height' => 18,
|
||||
'#alt' => 'Debug',
|
||||
];
|
||||
return [
|
||||
'pass' => $image_pass,
|
||||
'fail' => $image_fail,
|
||||
'exception' => $image_exception,
|
||||
'debug' => $image_debug,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'simpletest_results_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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 = [];
|
||||
if (is_numeric($test_id) && !$results = $this->getResults($test_id)) {
|
||||
$this->messenger()->addError($this->t('No test results to display.'));
|
||||
return $this->redirect('simpletest.test_form');
|
||||
}
|
||||
|
||||
// Load all classes and include CSS.
|
||||
$form['#attached']['library'][] = 'simpletest/drupal.simpletest';
|
||||
// Add the results form.
|
||||
$filter = static::addResultForm($form, $results, $this->getStringTranslation());
|
||||
|
||||
// Actions.
|
||||
$form['#action'] = Url::fromRoute('simpletest.result_form', ['test_id' => 're-run'])->toString();
|
||||
$form['action'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => $this->t('Actions'),
|
||||
'#attributes' => ['class' => ['container-inline']],
|
||||
'#weight' => -11,
|
||||
];
|
||||
|
||||
$form['action']['filter'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => 'Filter',
|
||||
'#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'] = [
|
||||
'#type' => 'hidden',
|
||||
'#default_value' => implode(',', $filter['pass']),
|
||||
];
|
||||
$form['action']['filter_fail'] = [
|
||||
'#type' => 'hidden',
|
||||
'#default_value' => implode(',', $filter['fail']),
|
||||
];
|
||||
|
||||
$form['action']['op'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Run tests'),
|
||||
];
|
||||
|
||||
$form['action']['return'] = [
|
||||
'#type' => 'link',
|
||||
'#title' => $this->t('Return to list'),
|
||||
'#url' => Url::fromRoute('simpletest.test_form'),
|
||||
];
|
||||
|
||||
if (is_numeric($test_id)) {
|
||||
$this->cleaner->cleanResultsTable($test_id);
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$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);
|
||||
}
|
||||
elseif ($form_state->getValue('filter') == 'pass') {
|
||||
$classes = $pass;
|
||||
}
|
||||
else {
|
||||
$classes = $fail;
|
||||
}
|
||||
|
||||
if (!$classes) {
|
||||
$form_state->setRedirect('simpletest.test_form');
|
||||
return;
|
||||
}
|
||||
|
||||
$form_execute = [];
|
||||
$form_state_execute = new FormState();
|
||||
foreach ($classes as $class) {
|
||||
$form_state_execute->setValue(['tests', $class], $class);
|
||||
}
|
||||
|
||||
// Submit the simpletest test form to rerun the tests.
|
||||
// Under normal circumstances, a form object's submitForm() should never be
|
||||
// called directly, FormBuilder::submitForm() should be called instead.
|
||||
// However, it calls $form_state->setProgrammed(), which disables the Batch API.
|
||||
$simpletest_test_form = SimpletestTestForm::create(\Drupal::getContainer());
|
||||
$simpletest_test_form->buildForm($form_execute, $form_state_execute);
|
||||
$simpletest_test_form->submitForm($form_execute, $form_state_execute);
|
||||
if ($redirect = $form_state_execute->getRedirect()) {
|
||||
$form_state->setRedirectUrl($redirect);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get test results for $test_id.
|
||||
*
|
||||
* @param int $test_id
|
||||
* The test_id to retrieve results of.
|
||||
*
|
||||
* @return array
|
||||
* Array of results grouped by test_class.
|
||||
*/
|
||||
protected function getResults($test_id) {
|
||||
return $this->database->select('simpletest')
|
||||
->fields('simpletest')
|
||||
->condition('test_id', $test_id)
|
||||
->orderBy('test_class')
|
||||
->orderBy('message_id')
|
||||
->execute()
|
||||
->fetchAll();
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the result form to a $form.
|
||||
*
|
||||
* This is a static method so that run-tests.sh can use it to generate a
|
||||
* results page completely external to Drupal. This is why the UI strings are
|
||||
* not wrapped in t().
|
||||
*
|
||||
* @param array $form
|
||||
* The form to attach the results to.
|
||||
* @param array $results
|
||||
* The simpletest results.
|
||||
*
|
||||
* @return array
|
||||
* A list of tests the passed and failed. The array has two keys, 'pass' and
|
||||
* 'fail'. Each contains a list of test classes.
|
||||
*
|
||||
* @see simpletest_script_open_browser()
|
||||
* @see run-tests.sh
|
||||
*/
|
||||
public static function addResultForm(array &$form, array $results) {
|
||||
// Transform the test results to be grouped by test class.
|
||||
$test_results = [];
|
||||
foreach ($results as $result) {
|
||||
if (!isset($test_results[$result->test_class])) {
|
||||
$test_results[$result->test_class] = [];
|
||||
}
|
||||
$test_results[$result->test_class][] = $result;
|
||||
}
|
||||
|
||||
$image_status_map = static::buildStatusImageMap();
|
||||
|
||||
// Keep track of which test cases passed or failed.
|
||||
$filter = [
|
||||
'pass' => [],
|
||||
'fail' => [],
|
||||
];
|
||||
|
||||
// Summary result widget.
|
||||
$form['result'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => 'Results',
|
||||
// Because this is used in a theme-less situation need to provide a
|
||||
// default.
|
||||
'#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 = [
|
||||
'Message',
|
||||
'Group',
|
||||
'Filename',
|
||||
'Line',
|
||||
'Function',
|
||||
['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] = [
|
||||
'#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 = [];
|
||||
foreach ($assertions as $assertion) {
|
||||
$row = [];
|
||||
$row[] = ['data' => ['#markup' => $assertion->message]];
|
||||
$row[] = $assertion->message_group;
|
||||
$row[] = \Drupal::service('file_system')->basename(($assertion->file));
|
||||
$row[] = $assertion->line;
|
||||
$row[] = $assertion->function;
|
||||
$row[] = ['data' => $image_status_map[$assertion->status]];
|
||||
|
||||
$class = 'simpletest-' . $assertion->status;
|
||||
if ($assertion->message_group == 'Debug') {
|
||||
$class = 'simpletest-debug';
|
||||
}
|
||||
$rows[] = ['data' => $row, 'class' => [$class]];
|
||||
|
||||
$group_summary['#' . $assertion->status]++;
|
||||
$form['result']['summary']['#' . $assertion->status]++;
|
||||
}
|
||||
$form['result']['results'][$group]['table'] = [
|
||||
'#type' => 'table',
|
||||
'#header' => $header,
|
||||
'#rows' => $rows,
|
||||
];
|
||||
|
||||
// Set summary information.
|
||||
$group_summary['#ok'] = $group_summary['#fail'] + $group_summary['#exception'] == 0;
|
||||
$form['result']['results'][$group]['#open'] = !$group_summary['#ok'];
|
||||
|
||||
// Store test group (class) as for use in filter.
|
||||
$filter[$group_summary['#ok'] ? 'pass' : 'fail'][] = $group;
|
||||
}
|
||||
|
||||
// Overall summary status.
|
||||
$form['result']['summary']['#ok'] = $form['result']['summary']['#fail'] + $form['result']['summary']['#exception'] == 0;
|
||||
|
||||
return $filter;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Form;
|
||||
|
||||
use Drupal\Core\Form\ConfigFormBase;
|
||||
use Drupal\Core\Form\FormStateInterface;
|
||||
|
||||
/**
|
||||
* Configure simpletest settings for this site.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class SimpletestSettingsForm extends ConfigFormBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'simpletest_settings_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getEditableConfigNames() {
|
||||
return ['simpletest.settings'];
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$config = $this->config('simpletest.settings');
|
||||
$form['general'] = [
|
||||
'#type' => 'details',
|
||||
'#title' => $this->t('General'),
|
||||
'#open' => TRUE,
|
||||
];
|
||||
$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'] = [
|
||||
'#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'] = [
|
||||
'#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'] = [
|
||||
'#type' => 'select',
|
||||
'#title' => $this->t('Method'),
|
||||
'#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'] = [
|
||||
'#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'] = [
|
||||
'#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.');
|
||||
}
|
||||
|
||||
return parent::buildForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function validateForm(array &$form, FormStateInterface $form_state) {
|
||||
$config = $this->config('simpletest.settings');
|
||||
// If a username was provided but a password wasn't, preserve the existing
|
||||
// password.
|
||||
if (!$form_state->isValueEmpty('simpletest_httpauth_username') && $form_state->isValueEmpty('simpletest_httpauth_password')) {
|
||||
$form_state->setValue('simpletest_httpauth_password', $config->get('httpauth.password'));
|
||||
}
|
||||
|
||||
// If a password was provided but a username wasn't, the credentials are
|
||||
// incorrect, so throw an error.
|
||||
if ($form_state->isValueEmpty('simpletest_httpauth_username') && !$form_state->isValueEmpty('simpletest_httpauth_password')) {
|
||||
$form_state->setErrorByName('simpletest_httpauth_username', $this->t('HTTP authentication credentials must include a username in addition to a password.'));
|
||||
}
|
||||
|
||||
parent::validateForm($form, $form_state);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
$this->config('simpletest.settings')
|
||||
->set('clear_results', $form_state->getValue('simpletest_clear_results'))
|
||||
->set('verbose', $form_state->getValue('simpletest_verbose'))
|
||||
->set('httpauth.method', $form_state->getValue('simpletest_httpauth_method'))
|
||||
->set('httpauth.username', $form_state->getValue('simpletest_httpauth_username'))
|
||||
->set('httpauth.password', $form_state->getValue('simpletest_httpauth_password'))
|
||||
->save();
|
||||
|
||||
parent::submitForm($form, $form_state);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
<?php
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* List tests arranged in groups that can be selected and run.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class SimpletestTestForm extends FormBase {
|
||||
|
||||
/**
|
||||
* The renderer.
|
||||
*
|
||||
* @var \Drupal\Core\Render\RendererInterface
|
||||
*/
|
||||
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('test_discovery')
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a new SimpletestTestForm.
|
||||
*
|
||||
* @param \Drupal\Core\Render\RendererInterface $renderer
|
||||
* The renderer.
|
||||
* @param \Drupal\simpletest\TestDiscovery $test_discovery
|
||||
* The test discovery service.
|
||||
*/
|
||||
public function __construct(RendererInterface $renderer, TestDiscovery $test_discovery) {
|
||||
$this->renderer = $renderer;
|
||||
$this->testDiscovery = $test_discovery;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function getFormId() {
|
||||
return 'simpletest_test_form';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function buildForm(array $form, FormStateInterface $form_state) {
|
||||
$form['actions'] = ['#type' => 'actions'];
|
||||
$form['actions']['submit'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('Run tests'),
|
||||
'#tableselect' => TRUE,
|
||||
'#button_type' => 'primary',
|
||||
];
|
||||
$form['clean'] = [
|
||||
'#type' => 'fieldset',
|
||||
'#title' => $this->t('Clean test environment'),
|
||||
'#description' => $this->t('Remove tables with the prefix "test" followed by digits and temporary directories that are left over from tests that crashed. This is intended for developers when creating tests.'),
|
||||
'#weight' => 200,
|
||||
];
|
||||
$form['clean']['op'] = [
|
||||
'#type' => 'submit',
|
||||
'#value' => $this->t('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.
|
||||
$user_input = $form_state->getUserInput();
|
||||
if (!empty($user_input['tests'])) {
|
||||
return $form;
|
||||
}
|
||||
|
||||
// JavaScript-only table filters.
|
||||
$form['filters'] = [
|
||||
'#type' => 'container',
|
||||
'#attributes' => [
|
||||
'class' => ['table-filter', 'js-show'],
|
||||
],
|
||||
];
|
||||
$form['filters']['text'] = [
|
||||
'#type' => 'search',
|
||||
'#title' => $this->t('Search'),
|
||||
'#size' => 30,
|
||||
'#placeholder' => $this->t('Enter test name…'),
|
||||
'#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'] = [
|
||||
'#cache' => [
|
||||
'keys' => ['simpletest_ui_table'],
|
||||
'contexts' => ['test_discovery'],
|
||||
],
|
||||
'#type' => 'table',
|
||||
'#id' => 'simpletest-form-table',
|
||||
'#tableselect' => TRUE,
|
||||
'#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' => [
|
||||
'library' => [
|
||||
'simpletest/drupal.simpletest',
|
||||
],
|
||||
],
|
||||
];
|
||||
|
||||
// Define the images used to expand/collapse the test groups.
|
||||
$image_collapsed = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/menu-collapsed.png',
|
||||
'#width' => '7',
|
||||
'#height' => '7',
|
||||
'#alt' => $this->t('Expand'),
|
||||
'#title' => $this->t('Expand'),
|
||||
'#suffix' => '<a href="#" class="simpletest-collapse">(' . $this->t('Expand') . ')</a>',
|
||||
];
|
||||
$image_extended = [
|
||||
'#theme' => 'image',
|
||||
'#uri' => 'core/misc/menu-expanded.png',
|
||||
'#width' => '7',
|
||||
'#height' => '7',
|
||||
'#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 = $this->testDiscovery->getTestClasses();
|
||||
foreach ($groups as $group => $tests) {
|
||||
$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 (-).
|
||||
$group_class = 'module-' . strtolower(trim(preg_replace("/[^\w\d]/", "-", $group)));
|
||||
|
||||
// Override tableselect column with custom selector for this group.
|
||||
// This group-select-all checkbox is injected via JavaScript.
|
||||
$form['tests'][$group]['select'] = [
|
||||
'#wrapper_attributes' => [
|
||||
'id' => $group_class,
|
||||
'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' => [
|
||||
'class' => ['simpletest-group-label'],
|
||||
],
|
||||
];
|
||||
$form['tests'][$group]['description'] = [
|
||||
'#markup' => ' ',
|
||||
'#wrapper_attributes' => [
|
||||
'class' => ['simpletest-group-description'],
|
||||
],
|
||||
];
|
||||
|
||||
// Cycle through each test within the current group.
|
||||
foreach ($tests as $class => $info) {
|
||||
$form['tests'][$class] = [
|
||||
'#attributes' => ['class' => [$group_class . '-test', 'js-hide']],
|
||||
];
|
||||
$form['tests'][$class]['title'] = [
|
||||
'#type' => 'label',
|
||||
'#title' => '\\' . $info['name'],
|
||||
'#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' => [
|
||||
'class' => ['simpletest-test-description', 'table-filter-text-source'],
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function submitForm(array &$form, FormStateInterface $form_state) {
|
||||
// Test discovery does not run upon form submission.
|
||||
$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
|
||||
// fatal error. Regular user access mechanisms to this form are intact.
|
||||
// The only validation effectively being skipped is the validation of
|
||||
// available checkboxes vs. submitted checkboxes.
|
||||
// @todo Refactor Form API to allow to POST values without constructing the
|
||||
// entire form more easily, BUT retaining routing access security and
|
||||
// retaining Form API CSRF #token security validation, and without having
|
||||
// to rely on form caching.
|
||||
$user_input = $form_state->getUserInput();
|
||||
if ($form_state->isValueEmpty('tests') && !empty($user_input['tests'])) {
|
||||
$form_state->setValue('tests', $user_input['tests']);
|
||||
}
|
||||
|
||||
$tests_list = array_filter($form_state->getValue('tests'));
|
||||
if (!empty($tests_list)) {
|
||||
$test_id = simpletest_run_tests($tests_list, 'drupal');
|
||||
$form_state->setRedirect(
|
||||
'simpletest.result_form',
|
||||
['test_id' => $test_id]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\InstallerTestBase is deprecated in Drupal 8.6.0 and will be removed before Drupal 9.0.0. Instead, use \Drupal\FunctionalTests\Installer\InstallerTestBase, see https://www.drupal.org/node/2988752.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Core\DrupalKernel;
|
||||
use Drupal\Core\Language\Language;
|
||||
use Drupal\Core\Session\UserSession;
|
||||
use Drupal\Core\Site\Settings;
|
||||
use Drupal\Tests\RequirementsPageTrait;
|
||||
use Symfony\Component\DependencyInjection\ContainerBuilder;
|
||||
use Symfony\Component\DependencyInjection\Reference;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\RequestStack;
|
||||
|
||||
/**
|
||||
* Base class for testing the interactive installer.
|
||||
*
|
||||
* @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0.
|
||||
* Use \Drupal\FunctionalTests\Installer\InstallerTestBase. See
|
||||
* https://www.drupal.org/node/2988752
|
||||
*/
|
||||
abstract class InstallerTestBase extends WebTestBase {
|
||||
|
||||
use RequirementsPageTrait;
|
||||
|
||||
/**
|
||||
* Custom settings.php values to write for a test run.
|
||||
*
|
||||
* @var array
|
||||
* An array of settings to write out, in the format expected by
|
||||
* drupal_rewrite_settings().
|
||||
*/
|
||||
protected $settings = [];
|
||||
|
||||
/**
|
||||
* The language code in which to install Drupal.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $langcode = 'en';
|
||||
|
||||
/**
|
||||
* The installation profile to install.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $profile = 'testing';
|
||||
|
||||
/**
|
||||
* Additional parameters to use for installer screens.
|
||||
*
|
||||
* @see WebTestBase::installParameters()
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $parameters = [];
|
||||
|
||||
/**
|
||||
* A string translation map used for translated installer screens.
|
||||
*
|
||||
* Keys are English strings, values are translated strings.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $translations = [
|
||||
'Save and continue' => 'Save and continue',
|
||||
];
|
||||
|
||||
/**
|
||||
* Whether the installer has completed.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected $isInstalled = FALSE;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
$this->isInstalled = FALSE;
|
||||
|
||||
// Define information about the user 1 account.
|
||||
$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.
|
||||
if (!empty($this->settings)) {
|
||||
// Not using File API; a potential error must trigger a PHP warning.
|
||||
copy(DRUPAL_ROOT . '/sites/default/default.settings.php', DRUPAL_ROOT . '/' . $this->siteDirectory . '/settings.php');
|
||||
$this->writeSettings($this->settings);
|
||||
}
|
||||
|
||||
// Note that WebTestBase::installParameters() returns form input values
|
||||
// suitable for a programmed \Drupal::formBuilder()->submitForm().
|
||||
// @see WebTestBase::translatePostValues()
|
||||
$this->parameters = $this->installParameters();
|
||||
|
||||
// Set up a minimal container (required by WebTestBase). Set cookie and
|
||||
// server information so that XDebug works.
|
||||
// @see install_begin_request()
|
||||
$request = Request::create($GLOBALS['base_url'] . '/core/install.php', 'GET', [], $_COOKIE, [], $_SERVER);
|
||||
$this->container = new ContainerBuilder();
|
||||
$request_stack = new RequestStack();
|
||||
$request_stack->push($request);
|
||||
$this->container
|
||||
->set('request_stack', $request_stack);
|
||||
$this->container
|
||||
->setParameter('language.default_values', Language::$defaultValues);
|
||||
$this->container
|
||||
->register('language.default', 'Drupal\Core\Language\LanguageDefault')
|
||||
->addArgument('%language.default_values%');
|
||||
$this->container
|
||||
->register('string_translation', 'Drupal\Core\StringTranslation\TranslationManager')
|
||||
->addArgument(new Reference('language.default'));
|
||||
$this->container
|
||||
->set('app.root', DRUPAL_ROOT);
|
||||
\Drupal::setContainer($this->container);
|
||||
|
||||
$this->visitInstaller();
|
||||
|
||||
// Select language.
|
||||
$this->setUpLanguage();
|
||||
|
||||
// Select profile.
|
||||
$this->setUpProfile();
|
||||
|
||||
// Address the requirements problem screen, if any.
|
||||
$this->setUpRequirementsProblem();
|
||||
|
||||
// Configure settings.
|
||||
$this->setUpSettings();
|
||||
|
||||
// @todo Allow test classes based on this class to act on further installer
|
||||
// screens.
|
||||
|
||||
// Configure site.
|
||||
$this->setUpSite();
|
||||
|
||||
if ($this->isInstalled) {
|
||||
// Import new settings.php written by the installer.
|
||||
$request = Request::createFromGlobals();
|
||||
$class_loader = require $this->container->get('app.root') . '/autoload.php';
|
||||
Settings::initialize($this->container->get('app.root'), DrupalKernel::findSitePath($request), $class_loader);
|
||||
$this->configDirectories['sync'] = Settings::get('config_sync_directory');
|
||||
|
||||
// After writing settings.php, the installer removes write permissions
|
||||
// from the site directory. To allow drupal_generate_test_ua() to write
|
||||
// a file containing the private key for drupal_valid_test_ua(), the site
|
||||
// directory has to be writable.
|
||||
// WebTestBase::tearDown() will delete the entire test site directory.
|
||||
// Not using File API; a potential error must trigger a PHP warning.
|
||||
chmod($this->container->get('app.root') . '/' . $this->siteDirectory, 0777);
|
||||
$this->kernel = DrupalKernel::createFromRequest($request, $class_loader, 'prod', FALSE);
|
||||
$this->kernel->boot();
|
||||
$this->kernel->preHandle($request);
|
||||
$this->container = $this->kernel->getContainer();
|
||||
// Ensure our request includes the session if appropriate.
|
||||
if (PHP_SAPI !== 'cli') {
|
||||
$request->setSession($this->container->get('session'));
|
||||
}
|
||||
|
||||
// Manually configure the test mail collector implementation to prevent
|
||||
// tests from sending out emails and collect them in state instead.
|
||||
$this->container->get('config.factory')
|
||||
->getEditable('system.mail')
|
||||
->set('interface.default', 'test_mail_collector')
|
||||
->save();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Visits the interactive installer.
|
||||
*/
|
||||
protected function visitInstaller() {
|
||||
$this->drupalGet($GLOBALS['base_url'] . '/core/install.php');
|
||||
}
|
||||
|
||||
/**
|
||||
* Installer step: Select language.
|
||||
*/
|
||||
protected function setUpLanguage() {
|
||||
$edit = [
|
||||
'langcode' => $this->langcode,
|
||||
];
|
||||
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installer step: Select installation profile.
|
||||
*/
|
||||
protected function setUpProfile() {
|
||||
$edit = [
|
||||
'profile' => $this->profile,
|
||||
];
|
||||
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installer step: Configure settings.
|
||||
*/
|
||||
protected function setUpSettings() {
|
||||
$edit = $this->translatePostValues($this->parameters['forms']['install_settings_form']);
|
||||
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Installer step: Requirements problem.
|
||||
*
|
||||
* Override this method to test specific requirements warnings or errors
|
||||
* during the installer.
|
||||
*
|
||||
* @see system_requirements()
|
||||
*/
|
||||
protected function setUpRequirementsProblem() {
|
||||
// Do nothing.
|
||||
}
|
||||
|
||||
/**
|
||||
* Final installer step: Configure site.
|
||||
*/
|
||||
protected function setUpSite() {
|
||||
$edit = $this->translatePostValues($this->parameters['forms']['install_configure_form']);
|
||||
$this->drupalPostForm(NULL, $edit, $this->translations['Save and continue']);
|
||||
// If we've got to this point the site is installed using the regular
|
||||
// installation workflow.
|
||||
$this->isInstalled = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* WebTestBase::refreshVariables() tries to operate on persistent storage,
|
||||
* which is only available after the installer completed.
|
||||
*/
|
||||
protected function refreshVariables() {
|
||||
if ($this->isInstalled) {
|
||||
parent::refreshVariables();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,651 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\KernelTestBase is deprecated in Drupal 8.0.x, will be removed before Drupal 9.0.0. Use \Drupal\KernelTests\KernelTestBase instead.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Component\Utility\Html;
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
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;
|
||||
use Drupal\Core\Entity\Sql\SqlEntityStorageInterface;
|
||||
use Drupal\Core\Extension\ExtensionDiscovery;
|
||||
use Drupal\Core\File\FileSystemInterface;
|
||||
use Drupal\Core\KeyValueStore\KeyValueMemoryFactory;
|
||||
use Drupal\Core\Language\Language;
|
||||
use Drupal\Core\Site\Settings;
|
||||
use Drupal\KernelTests\TestServiceProvider;
|
||||
use Symfony\Component\DependencyInjection\Parameter;
|
||||
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
|
||||
use Symfony\Component\DependencyInjection\Reference;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
|
||||
/**
|
||||
* Base class for functional integration tests.
|
||||
*
|
||||
* This base class should be useful for testing some types of integrations which
|
||||
* don't require the overhead of a fully-installed Drupal instance, but which
|
||||
* have many dependencies on parts of Drupal which can't or shouldn't be mocked.
|
||||
*
|
||||
* This base class partially boots a fixture Drupal. The state of the fixture
|
||||
* Drupal is comparable to the state of a system during the early part of the
|
||||
* installation process.
|
||||
*
|
||||
* Tests extending this base class can access services and the database, but the
|
||||
* system is initially empty. This Drupal runs in a minimal mocked filesystem
|
||||
* which operates within vfsStream.
|
||||
*
|
||||
* Modules specified in the $modules property are added to the service container
|
||||
* for each test. The module/hook system is functional. Additional modules
|
||||
* needed in a test should override $modules. Modules specified in this way will
|
||||
* be added to those specified in superclasses.
|
||||
*
|
||||
* Unlike \Drupal\Tests\BrowserTestBase, the modules are not installed. They are
|
||||
* loaded such that their services and hooks are available, but the install
|
||||
* process has not been performed.
|
||||
*
|
||||
* Other modules can be made available in this way using
|
||||
* KernelTestBase::enableModules().
|
||||
*
|
||||
* Some modules can be brought into a fully-installed state using
|
||||
* KernelTestBase::installConfig(), KernelTestBase::installSchema(), and
|
||||
* KernelTestBase::installEntitySchema(). Alternately, tests which need modules
|
||||
* to be fully installed could inherit from \Drupal\Tests\BrowserTestBase.
|
||||
*
|
||||
* @see \Drupal\Tests\KernelTestBase::$modules
|
||||
* @see \Drupal\Tests\KernelTestBase::enableModules()
|
||||
* @see \Drupal\Tests\KernelTestBase::installConfig()
|
||||
* @see \Drupal\Tests\KernelTestBase::installEntitySchema()
|
||||
* @see \Drupal\Tests\KernelTestBase::installSchema()
|
||||
* @see \Drupal\Tests\BrowserTestBase
|
||||
*
|
||||
* @deprecated in drupal:8.0.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\KernelTests\KernelTestBase instead.
|
||||
*
|
||||
* @ingroup testing
|
||||
*/
|
||||
abstract class KernelTestBase extends TestBase {
|
||||
|
||||
use AssertContentTrait;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* Test classes extending this class, and any classes in the hierarchy up to
|
||||
* this class, may specify individual lists of modules to enable by setting
|
||||
* this property. The values of all properties in all classes in the hierarchy
|
||||
* are merged.
|
||||
*
|
||||
* Any modules specified in the $modules property are automatically loaded and
|
||||
* set as the fixed module list.
|
||||
*
|
||||
* Unlike WebTestBase::setUp(), the specified modules are loaded only, but not
|
||||
* automatically installed. Modules need to be installed manually, if needed.
|
||||
*
|
||||
* @see \Drupal\simpletest\KernelTestBase::enableModules()
|
||||
* @see \Drupal\simpletest\KernelTestBase::setUp()
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = [];
|
||||
|
||||
private $moduleFiles;
|
||||
private $themeFiles;
|
||||
|
||||
/**
|
||||
* The configuration directories for this test run.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $configDirectories = [];
|
||||
|
||||
/**
|
||||
* A KeyValueMemoryFactory instance to use when building the container.
|
||||
*
|
||||
* @var \Drupal\Core\KeyValueStore\KeyValueMemoryFactory
|
||||
*/
|
||||
protected $keyValueFactory;
|
||||
|
||||
/**
|
||||
* Array of registered stream wrappers.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $streamWrappers = [];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function __construct($test_id = NULL) {
|
||||
parent::__construct($test_id);
|
||||
$this->skipClasses[__CLASS__] = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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') ?: [];
|
||||
$this->themeFiles = \Drupal::state()->get('system.theme.files') ?: [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and set new configuration directories.
|
||||
*
|
||||
* @see \Drupal\Core\Site\Settings::getConfigDirectory()
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* Thrown when the configuration sync directory cannot be created or made
|
||||
* writable.
|
||||
*
|
||||
* @return string
|
||||
* The config sync directory path.
|
||||
*/
|
||||
protected function prepareConfigDirectories() {
|
||||
$this->configDirectories = [];
|
||||
// Assign the relative path to the global variable.
|
||||
$path = $this->siteDirectory . '/config_' . CONFIG_SYNC_DIRECTORY;
|
||||
// Ensure the directory can be created and is writeable.
|
||||
if (!\Drupal::service('file_system')->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS)) {
|
||||
throw new \RuntimeException("Failed to create '" . CONFIG_SYNC_DIRECTORY . "' config directory $path");
|
||||
}
|
||||
// Provide the already resolved path for tests.
|
||||
$this->configDirectories[CONFIG_SYNC_DIRECTORY] = $path;
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
$this->keyValueFactory = new KeyValueMemoryFactory();
|
||||
|
||||
// Back up settings from TestBase::prepareEnvironment().
|
||||
$settings = Settings::getAll();
|
||||
|
||||
// Allow for test-specific overrides.
|
||||
$directory = DRUPAL_ROOT . '/' . $this->siteDirectory;
|
||||
$settings_services_file = DRUPAL_ROOT . '/' . $this->originalSite . '/testing.services.yml';
|
||||
$container_yamls = [];
|
||||
if (file_exists($settings_services_file)) {
|
||||
// Copy the testing-specific service overrides in place.
|
||||
$testing_services_file = $directory . '/services.yml';
|
||||
copy($settings_services_file, $testing_services_file);
|
||||
$container_yamls[] = $testing_services_file;
|
||||
}
|
||||
$settings_testing_file = DRUPAL_ROOT . '/' . $this->originalSite . '/settings.testing.php';
|
||||
if (file_exists($settings_testing_file)) {
|
||||
// Copy the testing-specific settings.php overrides in place.
|
||||
copy($settings_testing_file, $directory . '/settings.testing.php');
|
||||
}
|
||||
|
||||
if (file_exists($directory . '/settings.testing.php')) {
|
||||
// Add the name of the testing class to settings.php and include the
|
||||
// testing specific overrides
|
||||
$hash_salt = Settings::getHashSalt();
|
||||
$test_class = get_class($this);
|
||||
$container_yamls_export = Variable::export($container_yamls);
|
||||
$php = <<<EOD
|
||||
<?php
|
||||
|
||||
\$settings['hash_salt'] = '$hash_salt';
|
||||
\$settings['container_yamls'] = $container_yamls_export;
|
||||
|
||||
\$test_class = '$test_class';
|
||||
include DRUPAL_ROOT . '/' . \$site_path . '/settings.testing.php';
|
||||
EOD;
|
||||
file_put_contents($directory . '/settings.php', $php);
|
||||
}
|
||||
|
||||
// Add this test class as a service provider.
|
||||
// @todo Remove the indirection; implement ServiceProviderInterface instead.
|
||||
$GLOBALS['conf']['container_service_providers']['TestServiceProvider'] = TestServiceProvider::class;
|
||||
|
||||
// Bootstrap a new kernel.
|
||||
$class_loader = require DRUPAL_ROOT . '/autoload.php';
|
||||
$this->kernel = new DrupalKernel('testing', $class_loader, FALSE);
|
||||
$request = Request::create('/');
|
||||
$site_path = DrupalKernel::findSitePath($request);
|
||||
$this->kernel->setSitePath($site_path);
|
||||
if (file_exists($directory . '/settings.testing.php')) {
|
||||
Settings::initialize(DRUPAL_ROOT, $site_path, $class_loader);
|
||||
}
|
||||
// Set the module list upfront to avoid setting the kernel into the
|
||||
// pre-installer mode.
|
||||
$this->kernel->updateModules([], []);
|
||||
$this->kernel->boot();
|
||||
|
||||
// Ensure database install tasks have been run.
|
||||
require_once __DIR__ . '/../../../includes/install.inc';
|
||||
$connection = Database::getConnection();
|
||||
$errors = db_installer_object($connection->driver())->runTasks();
|
||||
if (!empty($errors)) {
|
||||
$this->fail('Failed to run installer database tasks: ' . implode(', ', $errors));
|
||||
}
|
||||
|
||||
// Reboot the kernel because the container might contain a connection to the
|
||||
// database that has been closed during the database install tasks. This
|
||||
// prevents any services created during the first boot from having stale
|
||||
// database connections, for example, \Drupal\Core\Config\DatabaseStorage.
|
||||
$this->kernel->shutdown();
|
||||
// Set the module list upfront to avoid setting the kernel into the
|
||||
// pre-installer mode.
|
||||
$this->kernel->updateModules([], []);
|
||||
$this->kernel->boot();
|
||||
|
||||
// Save the original site directory path, so that extensions in the
|
||||
// site-specific directory can still be discovered in the test site
|
||||
// environment.
|
||||
// @see \Drupal\Core\Extension\ExtensionDiscovery::scan()
|
||||
$settings['test_parent_site'] = $this->originalSite;
|
||||
|
||||
// Create and set new configuration directories.
|
||||
$settings['config_sync_directory'] = $this->prepareConfigDirectories();
|
||||
|
||||
// Restore and merge settings.
|
||||
// DrupalKernel::boot() initializes new Settings, and the containerBuild()
|
||||
// method sets additional settings.
|
||||
new Settings($settings + Settings::getAll());
|
||||
|
||||
// Set the request scope.
|
||||
$this->container = $this->kernel->getContainer();
|
||||
$this->container->get('request_stack')->push($request);
|
||||
|
||||
// Re-inject extension file listings into state, unless the key/value
|
||||
// service was overridden (in which case its storage does not exist yet).
|
||||
if ($this->container->get('keyvalue') instanceof KeyValueMemoryFactory) {
|
||||
$this->container->get('state')->set('system.module.files', $this->moduleFiles);
|
||||
$this->container->get('state')->set('system.theme.files', $this->themeFiles);
|
||||
}
|
||||
|
||||
// Create a minimal core.extension configuration object so that the list of
|
||||
// enabled modules can be maintained allowing
|
||||
// \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', ['module' => [], 'theme' => [], 'profile' => '']);
|
||||
|
||||
// Collect and set a fixed module list.
|
||||
$class = get_class($this);
|
||||
$modules = [];
|
||||
while ($class) {
|
||||
if (property_exists($class, 'modules')) {
|
||||
// Only add the modules, if the $modules property was not inherited.
|
||||
$rp = new \ReflectionProperty($class, 'modules');
|
||||
if ($rp->class == $class) {
|
||||
$modules[$class] = $class::$modules;
|
||||
}
|
||||
}
|
||||
$class = get_parent_class($class);
|
||||
}
|
||||
// Modules have been collected in reverse class hierarchy order; modules
|
||||
// defined by base classes should be sorted first. Then, merge the results
|
||||
// together.
|
||||
$modules = array_reverse($modules);
|
||||
$modules = call_user_func_array('array_merge_recursive', $modules);
|
||||
if ($modules) {
|
||||
$this->enableModules($modules);
|
||||
}
|
||||
|
||||
// Tests based on this class are entitled to use Drupal's File and
|
||||
// StreamWrapper APIs.
|
||||
\Drupal::service('file_system')->prepareDirectory($this->publicFilesDirectory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS);
|
||||
$this->settingsSet('file_public_path', $this->publicFilesDirectory);
|
||||
$this->streamWrappers = [];
|
||||
$this->registerStreamWrapper('public', 'Drupal\Core\StreamWrapper\PublicStream');
|
||||
// The temporary stream wrapper is able to operate both with and without
|
||||
// configuration.
|
||||
$this->registerStreamWrapper('temporary', 'Drupal\Core\StreamWrapper\TemporaryStream');
|
||||
|
||||
// Manually configure the test mail collector implementation to prevent
|
||||
// tests from sending out emails and collect them in state instead.
|
||||
// While this should be enforced via settings.php prior to installation,
|
||||
// some tests expect to be able to test mail system implementations.
|
||||
$GLOBALS['config']['system.mail']['interface']['default'] = 'test_mail_collector';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function tearDown() {
|
||||
if ($this->kernel instanceof DrupalKernel) {
|
||||
$this->kernel->shutdown();
|
||||
}
|
||||
// Before tearing down the test environment, ensure that no stream wrapper
|
||||
// of this test leaks into the parent environment. Unlike all other global
|
||||
// state variables in Drupal, stream wrappers are a global state construct
|
||||
// of PHP core, which has to be maintained manually.
|
||||
// @todo Move StreamWrapper management into DrupalKernel.
|
||||
// @see https://www.drupal.org/node/2028109
|
||||
foreach ($this->streamWrappers as $scheme => $type) {
|
||||
$this->unregisterStreamWrapper($scheme, $type);
|
||||
}
|
||||
parent::tearDown();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the base service container for this test.
|
||||
*
|
||||
* Extend this method in your test to register additional service overrides
|
||||
* that need to persist a DrupalKernel reboot. This method is called whenever
|
||||
* the kernel is rebuilt.
|
||||
*
|
||||
* @see \Drupal\simpletest\KernelTestBase::setUp()
|
||||
* @see \Drupal\simpletest\KernelTestBase::enableModules()
|
||||
* @see \Drupal\simpletest\KernelTestBase::disableModules()
|
||||
*/
|
||||
public function containerBuild(ContainerBuilder $container) {
|
||||
// Keep the container object around for tests.
|
||||
$this->container = $container;
|
||||
|
||||
// Set the default language on the minimal container.
|
||||
$this->container->setParameter('language.default_values', $this->defaultLanguageData());
|
||||
|
||||
$container->register('lock', 'Drupal\Core\Lock\NullLockBackend');
|
||||
$container->register('cache_factory', 'Drupal\Core\Cache\MemoryBackendFactory');
|
||||
|
||||
$container
|
||||
->register('config.storage', 'Drupal\Core\Config\DatabaseStorage')
|
||||
->addArgument(Database::getConnection())
|
||||
->addArgument('config');
|
||||
|
||||
if ($this->strictConfigSchema) {
|
||||
$container
|
||||
->register('testing.config_schema_checker', ConfigSchemaChecker::class)
|
||||
->addArgument(new Reference('config.typed'))
|
||||
->addArgument($this->getConfigSchemaExclusions())
|
||||
->addTag('event_subscriber');
|
||||
}
|
||||
|
||||
$keyvalue_options = $container->getParameter('factory.keyvalue') ?: [];
|
||||
$keyvalue_options['default'] = 'keyvalue.memory';
|
||||
$container->setParameter('factory.keyvalue', $keyvalue_options);
|
||||
$container->set('keyvalue.memory', $this->keyValueFactory);
|
||||
if (!$container->has('keyvalue')) {
|
||||
// TestBase::setUp puts a completely empty container in
|
||||
// $this->container which is somewhat the mirror of the empty
|
||||
// environment being set up. Unit tests need not to waste time with
|
||||
// getting a container set up for them. Drupal Unit Tests might just get
|
||||
// away with a simple container holding the absolute bare minimum. When
|
||||
// a kernel is overridden then there's no need to re-register the keyvalue
|
||||
// service but when a test is happy with the superminimal container put
|
||||
// together here, it still might a keyvalue storage for anything using
|
||||
// \Drupal::state() -- that's why a memory service was added in the first
|
||||
// place.
|
||||
$container->register('settings', 'Drupal\Core\Site\Settings')
|
||||
->setFactoryClass('Drupal\Core\Site\Settings')
|
||||
->setFactoryMethod('getInstance');
|
||||
|
||||
$container
|
||||
->register('keyvalue', 'Drupal\Core\KeyValueStore\KeyValueFactory')
|
||||
->addArgument(new Reference('service_container'))
|
||||
->addArgument(new Parameter('factory.keyvalue'));
|
||||
|
||||
$container->register('state', 'Drupal\Core\State\State')
|
||||
->addArgument(new Reference('keyvalue'));
|
||||
}
|
||||
|
||||
if ($container->hasDefinition('path_alias.path_processor')) {
|
||||
// The alias-based processor requires the path_alias entity schema to be
|
||||
// installed, so we prevent it from being registered to the path processor
|
||||
// manager. We do this by removing the tags that the compiler pass looks
|
||||
// for. This means that the URL generator can safely be used within tests.
|
||||
$definition = $container->getDefinition('path_alias.path_processor');
|
||||
$definition->clearTag('path_processor_inbound')->clearTag('path_processor_outbound');
|
||||
}
|
||||
|
||||
if ($container->hasDefinition('password')) {
|
||||
$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', [new Reference('service_container')]);
|
||||
|
||||
$request = Request::create('/');
|
||||
$container->get('request_stack')->push($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides the data for setting the default language on the container.
|
||||
*
|
||||
* @return array
|
||||
* The data array for the default language.
|
||||
*/
|
||||
protected function defaultLanguageData() {
|
||||
return Language::$defaultValues;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs default configuration for a given list of modules.
|
||||
*
|
||||
* @param array $modules
|
||||
* A list of modules for which to install default configuration.
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* Thrown when any module listed in $modules is not enabled.
|
||||
*/
|
||||
protected function installConfig(array $modules) {
|
||||
foreach ($modules as $module) {
|
||||
if (!$this->container->get('module_handler')->moduleExists($module)) {
|
||||
throw new \RuntimeException("'$module' module is not enabled");
|
||||
}
|
||||
\Drupal::service('config.installer')->installDefaultConfig('module', $module);
|
||||
}
|
||||
$this->pass(new FormattableMarkup('Installed default config: %modules.', [
|
||||
'%modules' => implode(', ', $modules),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs a specific table from a module schema definition.
|
||||
*
|
||||
* @param string $module
|
||||
* The name of the module that defines the table's schema.
|
||||
* @param string|array $tables
|
||||
* The name or an array of the names of the tables to install.
|
||||
*
|
||||
* @throws \RuntimeException
|
||||
* Thrown when $module is not enabled or when the table schema cannot be
|
||||
* found in the module specified.
|
||||
*/
|
||||
protected function installSchema($module, $tables) {
|
||||
// drupal_get_module_schema() is technically able to install a schema
|
||||
// of a non-enabled module, but its ability to load the module's .install
|
||||
// file depends on many other factors. To prevent differences in test
|
||||
// behavior and non-reproducible test failures, we only allow the schema of
|
||||
// explicitly loaded/enabled modules to be installed.
|
||||
if (!$this->container->get('module_handler')->moduleExists($module)) {
|
||||
throw new \RuntimeException("'$module' module is not enabled");
|
||||
}
|
||||
|
||||
$tables = (array) $tables;
|
||||
foreach ($tables as $table) {
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
if (empty($schema)) {
|
||||
// BC layer to avoid some contrib tests to fail.
|
||||
// @todo Remove the BC layer before 8.1.x release.
|
||||
// @see https://www.drupal.org/node/2670360
|
||||
// @see https://www.drupal.org/node/2670454
|
||||
if ($module == 'system') {
|
||||
continue;
|
||||
}
|
||||
throw new \RuntimeException("Unknown '$table' table schema in '$module' module.");
|
||||
}
|
||||
$this->container->get('database')->schema()->createTable($table, $schema);
|
||||
}
|
||||
$this->pass(new FormattableMarkup('Installed %module tables: %tables.', [
|
||||
'%tables' => '{' . implode('}, {', $tables) . '}',
|
||||
'%module' => $module,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the storage schema for a specific entity type.
|
||||
*
|
||||
* @param string $entity_type_id
|
||||
* The ID of the entity type.
|
||||
*/
|
||||
protected function installEntitySchema($entity_type_id) {
|
||||
/** @var \Drupal\Core\Entity\EntityManagerInterface $entity_manager */
|
||||
$entity_manager = $this->container->get('entity.manager');
|
||||
$entity_type = $entity_manager->getDefinition($entity_type_id);
|
||||
$entity_manager->onEntityTypeCreate($entity_type);
|
||||
|
||||
// For test runs, the most common storage backend is a SQL database. For
|
||||
// this case, ensure the tables got created.
|
||||
$storage = $entity_manager->getStorage($entity_type_id);
|
||||
if ($storage instanceof SqlEntityStorageInterface) {
|
||||
$tables = $storage->getTableMapping()->getTableNames();
|
||||
$db_schema = $this->container->get('database')->schema();
|
||||
$all_tables_exist = TRUE;
|
||||
foreach ($tables as $table) {
|
||||
if (!$db_schema->tableExists($table)) {
|
||||
$this->fail(new FormattableMarkup('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(new FormattableMarkup('Installed entity type tables for the %entity_type entity type: %tables', [
|
||||
'%entity_type' => $entity_type_id,
|
||||
'%tables' => '{' . implode('}, {', $tables) . '}',
|
||||
]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables modules for this test.
|
||||
*
|
||||
* To install test modules outside of the testing environment, add
|
||||
* @code
|
||||
* $settings['extension_discovery_scan_tests'] = TRUE;
|
||||
* @endcode
|
||||
* to your settings.php.
|
||||
*
|
||||
* @param array $modules
|
||||
* A list of modules to enable. Dependencies are not resolved; i.e.,
|
||||
* multiple modules have to be specified with dependent modules first.
|
||||
* The new modules are only added to the active module list and loaded.
|
||||
*/
|
||||
protected function enableModules(array $modules) {
|
||||
// Perform an ExtensionDiscovery scan as this function may receive a
|
||||
// profile that is not the current profile, and we don't yet have a cached
|
||||
// way to receive inactive profile information.
|
||||
// @todo Remove as part of https://www.drupal.org/node/2186491
|
||||
$listing = new ExtensionDiscovery(\Drupal::root());
|
||||
$module_list = $listing->scan('module');
|
||||
// In ModuleHandlerTest we pass in a profile as if it were a module.
|
||||
$module_list += $listing->scan('profile');
|
||||
// Set the list of modules in the extension handler.
|
||||
$module_handler = $this->container->get('module_handler');
|
||||
|
||||
// Write directly to active storage to avoid early instantiation of
|
||||
// the event dispatcher which can prevent modules from registering events.
|
||||
$active_storage = \Drupal::service('config.storage');
|
||||
$extensions = $active_storage->read('core.extension');
|
||||
|
||||
foreach ($modules as $module) {
|
||||
$module_handler->addModule($module, $module_list[$module]->getPath());
|
||||
// Maintain the list of enabled modules in configuration.
|
||||
$extensions['module'][$module] = 0;
|
||||
}
|
||||
$active_storage->write('core.extension', $extensions);
|
||||
|
||||
// Update the kernel to make their services available.
|
||||
$module_filenames = $module_handler->getModuleList();
|
||||
$this->kernel->updateModules($module_filenames, $module_filenames);
|
||||
|
||||
// Ensure isLoaded() is TRUE in order to make
|
||||
// \Drupal\Core\Theme\ThemeManagerInterface::render() work.
|
||||
// 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(new FormattableMarkup('Enabled modules: %modules.', [
|
||||
'%modules' => implode(', ', $modules),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables modules for this test.
|
||||
*
|
||||
* @param array $modules
|
||||
* A list of modules to disable. Dependencies are not resolved; i.e.,
|
||||
* multiple modules have to be specified with dependent modules first.
|
||||
* Code of previously active modules is still loaded. The modules are only
|
||||
* removed from the active module list.
|
||||
*/
|
||||
protected function disableModules(array $modules) {
|
||||
// Unset the list of modules in the extension handler.
|
||||
$module_handler = $this->container->get('module_handler');
|
||||
$module_filenames = $module_handler->getModuleList();
|
||||
$extension_config = $this->config('core.extension');
|
||||
foreach ($modules as $module) {
|
||||
unset($module_filenames[$module]);
|
||||
$extension_config->clear('module.' . $module);
|
||||
}
|
||||
$extension_config->save();
|
||||
$module_handler->setModuleList($module_filenames);
|
||||
$module_handler->resetImplementations();
|
||||
// Update the kernel to remove their services.
|
||||
$this->kernel->updateModules($module_filenames, $module_filenames);
|
||||
|
||||
// Ensure isLoaded() is TRUE in order to make
|
||||
// \Drupal\Core\Theme\ThemeManagerInterface::render() work.
|
||||
// Note that the kernel has rebuilt the container; this $module_handler is
|
||||
// no longer the $module_handler instance from above.
|
||||
$module_handler = $this->container->get('module_handler');
|
||||
$module_handler->reload();
|
||||
$this->pass(new FormattableMarkup('Disabled modules: %modules.', [
|
||||
'%modules' => implode(', ', $modules),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a stream wrapper for this test.
|
||||
*
|
||||
* @param string $scheme
|
||||
* The scheme to register.
|
||||
* @param string $class
|
||||
* The fully qualified class name to register.
|
||||
* @param int $type
|
||||
* The Drupal Stream Wrapper API type. Defaults to
|
||||
* StreamWrapperInterface::NORMAL.
|
||||
*/
|
||||
protected function registerStreamWrapper($scheme, $class, $type = StreamWrapperInterface::NORMAL) {
|
||||
$this->container->get('stream_wrapper_manager')->registerWrapper($scheme, $class, $type);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a render array.
|
||||
*
|
||||
* @param array $elements
|
||||
* The elements to render.
|
||||
*
|
||||
* @return string
|
||||
* The rendered string output (typically HTML).
|
||||
*/
|
||||
protected function render(array &$elements) {
|
||||
// Use the bare HTML page renderer to render our links.
|
||||
$renderer = $this->container->get('bare_html_page_renderer');
|
||||
$response = $renderer->renderBarePage($elements, '', 'maintenance_page');
|
||||
|
||||
// Glean the content from the response object.
|
||||
$content = $response->getContent();
|
||||
$this->setRawContent($content);
|
||||
$this->verbose('<pre style="white-space: pre-wrap">' . Html::escape($content));
|
||||
return $content;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\NodeCreationTrait is deprecated in Drupal 8.4.x. Will be removed before Drupal 9.0.0. Use \Drupal\Tests\node\Traits\NodeCreationTrait instead. See https://www.drupal.org/node/2884454.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\node\Traits\NodeCreationTrait as BaseNodeCreationTrait;
|
||||
|
||||
/**
|
||||
* Provides methods to create node based on default settings.
|
||||
*
|
||||
* This trait is meant to be used only by test classes.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\node\Traits\NodeCreationTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2884454
|
||||
*/
|
||||
trait NodeCreationTrait {
|
||||
|
||||
use BaseNodeCreationTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\RandomGeneratorTrait is deprecated in Drupal 8.1.1, will be removed before Drupal 9.0.0. Use \Drupal\Tests\RandomGeneratorTrait instead.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\RandomGeneratorTrait as BaseGeneratorTrait;
|
||||
|
||||
/**
|
||||
* Provides random generator utility methods.
|
||||
*
|
||||
* @deprecated in drupal:8.1.1 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\RandomGeneratorTrait instead.
|
||||
*
|
||||
* @see \Drupal\Tests
|
||||
*/
|
||||
trait RandomGeneratorTrait {
|
||||
use BaseGeneratorTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\KernelTests\RouteProvider as CoreRouteProvider;
|
||||
|
||||
/**
|
||||
* Rebuilds the router when the provider is instantiated.
|
||||
*
|
||||
* @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Use
|
||||
* Drupal\KernelTests\RouteProvider instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2943146
|
||||
*/
|
||||
class RouteProvider extends CoreRouteProvider {
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\SessionTestTrait is deprecated in Drupal 8.1.1 will be removed before 9.0.0. Use \Drupal\Tests\SessionTestTrait instead.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\SessionTestTrait as BaseSessionTestTrait;
|
||||
|
||||
/**
|
||||
* Provides methods to generate and get session name in tests.
|
||||
*
|
||||
* @deprecated in drupal:8.1.1 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Tests\SessionTestTrait instead.
|
||||
*
|
||||
* @see \Drupal\Tests
|
||||
*/
|
||||
trait SessionTestTrait {
|
||||
|
||||
use BaseSessionTestTrait;
|
||||
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,150 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\\TestDiscovery is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDiscovery instead. See https://www.drupal.org/node/2949692', E_USER_DEPRECATED);
|
||||
|
||||
use Doctrine\Common\Reflection\StaticReflectionParser;
|
||||
use Drupal\Component\Annotation\Reflection\MockFileFinder;
|
||||
use Drupal\Component\Utility\NestedArray;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\Core\Test\Exception\MissingGroupException;
|
||||
use Drupal\Core\Test\TestDiscovery as CoreTestDiscovery;
|
||||
|
||||
/**
|
||||
* Discovers available tests.
|
||||
*
|
||||
* This class provides backwards compatibility for code which uses the legacy
|
||||
* \Drupal\simpletest\TestDiscovery.
|
||||
*
|
||||
* @deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use
|
||||
* \Drupal\Core\Test\TestDiscovery instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2949692
|
||||
*/
|
||||
class TestDiscovery extends CoreTestDiscovery {
|
||||
|
||||
/**
|
||||
* The module handler.
|
||||
*
|
||||
* @var \Drupal\Core\Extension\ModuleHandlerInterface
|
||||
*/
|
||||
protected $moduleHandler;
|
||||
|
||||
/**
|
||||
* Constructs a new test discovery.
|
||||
*
|
||||
* @param string $root
|
||||
* The app root.
|
||||
* @param $class_loader
|
||||
* The class loader. Normally Composer's ClassLoader, as included by the
|
||||
* front controller, but may also be decorated; e.g.,
|
||||
* \Symfony\Component\ClassLoader\ApcClassLoader.
|
||||
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
|
||||
* The module handler.
|
||||
*/
|
||||
public function __construct($root, $class_loader, ModuleHandlerInterface $module_handler) {
|
||||
parent::__construct($root, $class_loader);
|
||||
$this->moduleHandler = $module_handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Discovers all available tests in all extensions.
|
||||
*
|
||||
* This method is a near-duplicate of
|
||||
* \Drupal\Core\Tests\TestDiscovery::getTestClasses(). It exists so that we
|
||||
* can provide a BC invocation of hook_simpletest_alter().
|
||||
*
|
||||
* @param string $extension
|
||||
* (optional) The name of an extension to limit discovery to; e.g., 'node'.
|
||||
* @param string[] $types
|
||||
* An array of included test types.
|
||||
*
|
||||
* @return array
|
||||
* An array of tests keyed by the group name. If a test is annotated to
|
||||
* belong to multiple groups, it will appear under all group keys it belongs
|
||||
* to.
|
||||
* @code
|
||||
* $groups['block'] => array(
|
||||
* 'Drupal\Tests\block\Functional\BlockTest' => array(
|
||||
* 'name' => 'Drupal\Tests\block\Functional\BlockTest',
|
||||
* 'description' => 'Tests block UI CRUD functionality.',
|
||||
* 'group' => 'block',
|
||||
* 'groups' => ['block', 'group2', 'group3'],
|
||||
* ),
|
||||
* );
|
||||
* @endcode
|
||||
*/
|
||||
public function getTestClasses($extension = NULL, array $types = []) {
|
||||
if (!isset($extension) && empty($types)) {
|
||||
if (!empty($this->testClasses)) {
|
||||
return $this->testClasses;
|
||||
}
|
||||
}
|
||||
$list = [];
|
||||
|
||||
$classmap = $this->findAllClassFiles($extension);
|
||||
|
||||
// Prevent expensive class loader lookups for each reflected test class by
|
||||
// registering the complete classmap of test classes to the class loader.
|
||||
// This also ensures that test classes are loaded from the discovered
|
||||
// pathnames; a namespace/classname mismatch will throw an exception.
|
||||
$this->classLoader->addClassMap($classmap);
|
||||
|
||||
foreach ($classmap as $classname => $pathname) {
|
||||
$finder = MockFileFinder::create($pathname);
|
||||
$parser = new StaticReflectionParser($classname, $finder, TRUE);
|
||||
try {
|
||||
$info = static::getTestInfo($classname, $parser->getDocComment());
|
||||
}
|
||||
catch (MissingGroupException $e) {
|
||||
// If the class name ends in Test and is not a migrate table dump.
|
||||
if (preg_match('/Test$/', $classname) && strpos($classname, 'migrate_drupal\Tests\Table') === FALSE) {
|
||||
throw $e;
|
||||
}
|
||||
// If the class is @group annotation just skip it. Most likely it is an
|
||||
// abstract class, trait or test fixture.
|
||||
continue;
|
||||
}
|
||||
// Skip this test class if it is a Simpletest-based test and requires
|
||||
// unavailable modules. TestDiscovery should not filter out module
|
||||
// requirements for PHPUnit-based test classes.
|
||||
// @todo Move this behavior to \Drupal\simpletest\TestBase so tests can be
|
||||
// marked as skipped, instead.
|
||||
// @see https://www.drupal.org/node/1273478
|
||||
if ($info['type'] == 'Simpletest') {
|
||||
if (!empty($info['requires']['module'])) {
|
||||
if (array_diff($info['requires']['module'], $this->availableExtensions['module'])) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($info['groups'] as $group) {
|
||||
$list[$group][$classname] = $info;
|
||||
}
|
||||
}
|
||||
|
||||
// Sort the groups and tests within the groups by name.
|
||||
uksort($list, 'strnatcasecmp');
|
||||
foreach ($list as &$tests) {
|
||||
uksort($tests, 'strnatcasecmp');
|
||||
}
|
||||
|
||||
// Allow modules extending core tests to disable originals.
|
||||
$this->moduleHandler->alterDeprecated('Convert your test to a PHPUnit-based one and implement test listeners. See: https://www.drupal.org/node/2939892', 'simpletest', $list);
|
||||
|
||||
if (!isset($extension) && empty($types)) {
|
||||
$this->testClasses = $list;
|
||||
}
|
||||
|
||||
if ($types) {
|
||||
$list = NestedArray::filter($list, function ($element) use ($types) {
|
||||
return !(is_array($element) && isset($element['type']) && !in_array($element['type'], $types));
|
||||
});
|
||||
}
|
||||
|
||||
return $list;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\KernelTests\TestServiceProvider as CoreTestServiceProvider;
|
||||
|
||||
/**
|
||||
* Provides special routing services for tests.
|
||||
*
|
||||
* @deprecated in drupal:8.6.0 and is removed from drupal:9.0.0. Use
|
||||
* Drupal\KernelTests\TestServiceProvider instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2943146
|
||||
*/
|
||||
class TestServiceProvider extends CoreTestServiceProvider {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests a test case that does not call parent::setUp().
|
||||
*
|
||||
* If a test case does not call parent::setUp(), running
|
||||
* \Drupal\simpletest\WebTestBase::tearDown() would destroy the main site's
|
||||
* database tables. Therefore, we ensure that tests which are not set up
|
||||
* properly are skipped.
|
||||
*
|
||||
* @group WebTestBase
|
||||
* @group legacy
|
||||
*
|
||||
* @see \Drupal\simpletest\WebTestBase
|
||||
*/
|
||||
class BrokenSetUpTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* The path to the shared trigger file.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $sharedTriggerFile;
|
||||
|
||||
protected function setUp() {
|
||||
// If the test is being run from the main site, set up normally.
|
||||
if (!$this->isInChildSite()) {
|
||||
parent::setUp();
|
||||
|
||||
$this->sharedTriggerFile = $this->publicFilesDirectory . '/trigger';
|
||||
|
||||
// Create and log in user.
|
||||
$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.
|
||||
else {
|
||||
$this->sharedTriggerFile = $this->originalFileDirectory . '/trigger';
|
||||
|
||||
if (file_get_contents($this->sharedTriggerFile) === 'setup') {
|
||||
throw new \Exception('Broken setup');
|
||||
}
|
||||
$this->pass('The setUp() method has run.');
|
||||
}
|
||||
}
|
||||
|
||||
protected function tearDown() {
|
||||
// If the test is being run from the main site, tear down normally.
|
||||
if (!$this->isInChildSite()) {
|
||||
unlink($this->sharedTriggerFile);
|
||||
parent::tearDown();
|
||||
}
|
||||
// If the test is being run from within simpletest, output a message.
|
||||
else {
|
||||
if (file_get_contents($this->sharedTriggerFile) === 'teardown') {
|
||||
throw new \Exception('Broken teardown');
|
||||
}
|
||||
$this->pass('The tearDown() method has run.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs this test case from within the simpletest child site.
|
||||
*/
|
||||
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()) {
|
||||
// Verify that a broken setUp() method is caught.
|
||||
file_put_contents($this->sharedTriggerFile, 'setup');
|
||||
$edit['tests[Drupal\simpletest\Tests\BrokenSetUpTest]'] = TRUE;
|
||||
$this->drupalPostForm('admin/config/development/testing', $edit, t('Run tests'));
|
||||
$this->assertRaw('Broken setup');
|
||||
$this->assertNoRaw('The setUp() method has run.');
|
||||
$this->assertNoRaw('Broken test');
|
||||
$this->assertNoRaw('The test method has run.');
|
||||
$this->assertNoRaw('Broken teardown');
|
||||
$this->assertNoRaw('The tearDown() method has run.');
|
||||
|
||||
// Verify that a broken tearDown() method is caught.
|
||||
file_put_contents($this->sharedTriggerFile, 'teardown');
|
||||
$edit['tests[Drupal\simpletest\Tests\BrokenSetUpTest]'] = TRUE;
|
||||
$this->drupalPostForm('admin/config/development/testing', $edit, t('Run tests'));
|
||||
$this->assertNoRaw('Broken setup');
|
||||
$this->assertRaw('The setUp() method has run.');
|
||||
$this->assertNoRaw('Broken test');
|
||||
$this->assertRaw('The test method has run.');
|
||||
$this->assertRaw('Broken teardown');
|
||||
$this->assertNoRaw('The tearDown() method has run.');
|
||||
|
||||
// Verify that a broken test method is caught.
|
||||
file_put_contents($this->sharedTriggerFile, 'test');
|
||||
$edit['tests[Drupal\simpletest\Tests\BrokenSetUpTest]'] = TRUE;
|
||||
$this->drupalPostForm('admin/config/development/testing', $edit, t('Run tests'));
|
||||
$this->assertNoRaw('Broken setup');
|
||||
$this->assertRaw('The setUp() method has run.');
|
||||
$this->assertRaw('Broken test');
|
||||
$this->assertNoRaw('The test method has run.');
|
||||
$this->assertNoRaw('Broken teardown');
|
||||
$this->assertRaw('The tearDown() method has run.');
|
||||
}
|
||||
// If the test is being run from within simpletest, output a message.
|
||||
else {
|
||||
if (file_get_contents($this->sharedTriggerFile) === 'test') {
|
||||
throw new \Exception('Broken test');
|
||||
}
|
||||
$this->pass('The test method has run.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests the internal browser of the testing framework.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*/
|
||||
class BrowserTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* A flag indicating whether a cookie has been set in a test.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
protected static $cookieSet = FALSE;
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
public static $modules = ['block'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->drupalPlaceBlock('local_tasks_block');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test \Drupal\simpletest\WebTestBase::getAbsoluteUrl().
|
||||
*/
|
||||
public function testGetAbsoluteUrl() {
|
||||
$url = 'user/login';
|
||||
|
||||
$this->drupalGet($url);
|
||||
$absolute = Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString();
|
||||
$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, [], 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 = Url::fromRoute('user.register', [], ['absolute' => TRUE])->toString();
|
||||
$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.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests XPath escaping.
|
||||
*/
|
||||
public function testXPathEscaping() {
|
||||
$testpage = <<< EOF
|
||||
<html>
|
||||
<body>
|
||||
<a href="link1">A "weird" link, just to bother the dumb "XPath 1.0"</a>
|
||||
<a href="link2">A second "even more weird" link, in memory of George O'Malley</a>
|
||||
<a href="link3">A \$third$ link, so weird it's worth $1 million</a>
|
||||
<a href="link4">A fourth link, containing alternative \\1 regex backreferences \\2</a>
|
||||
</body>
|
||||
</html>
|
||||
EOF;
|
||||
$this->setRawContent($testpage);
|
||||
|
||||
// Matches the first link.
|
||||
$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]', [':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]', [':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]', [':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).');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that cookies set during a request are available for testing.
|
||||
*/
|
||||
public function testCookies() {
|
||||
// Check that the $this->cookies property is populated when a user logs in.
|
||||
$user = $this->drupalCreateUser();
|
||||
$edit = ['name' => $user->getAccountName(), 'pass' => $user->pass_raw];
|
||||
$this->drupalPostForm('<front>', $edit, t('Log in'));
|
||||
$this->assertEqual(count($this->cookies), 1, 'A cookie is set when the user logs in.');
|
||||
|
||||
// Check that the name and value of the cookie match the request data.
|
||||
$cookie_header = $this->drupalGetHeader('set-cookie', TRUE);
|
||||
|
||||
// The name and value are located at the start of the string, separated by
|
||||
// an equals sign and ending in a semicolon.
|
||||
preg_match('/^([^=]+)=([^;]+)/', $cookie_header, $matches);
|
||||
$name = $matches[1];
|
||||
$value = $matches[2];
|
||||
|
||||
$this->assertTrue(array_key_exists($name, $this->cookies), 'The cookie name is correct.');
|
||||
$this->assertEqual($value, $this->cookies[$name]['value'], 'The cookie value is correct.');
|
||||
|
||||
// Set a flag indicating that a cookie has been set in this test.
|
||||
// @see testCookieDoesNotBleed()
|
||||
static::$cookieSet = TRUE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the cookies from a previous test do not bleed into a new test.
|
||||
*
|
||||
* @see static::testCookies()
|
||||
*/
|
||||
public function testCookieDoesNotBleed() {
|
||||
// In order for this test to be effective it should always run after the
|
||||
// testCookies() test.
|
||||
$this->assertTrue(static::$cookieSet, 'Tests have been executed in the expected order.');
|
||||
$this->assertEqual(count($this->cookies), 0, 'No cookies are present at the start of a new test.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\field\Entity\FieldConfig;
|
||||
use Drupal\simpletest\KernelTestBase;
|
||||
use Drupal\field\Entity\FieldStorageConfig;
|
||||
use Drupal\Core\Entity\Entity\EntityViewDisplay;
|
||||
|
||||
/**
|
||||
* Tests KernelTestBase functionality.
|
||||
*
|
||||
* @group simpletest
|
||||
*/
|
||||
class KernelTestBaseTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['entity_test'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
$php = <<<'EOS'
|
||||
<?php
|
||||
# Make sure that the $test_class variable is defined when this file is included.
|
||||
if ($test_class) {
|
||||
}
|
||||
|
||||
# Define a function to be able to check that this file was loaded with
|
||||
# function_exists().
|
||||
if (!function_exists('simpletest_test_stub_settings_function')) {
|
||||
function simpletest_test_stub_settings_function() {}
|
||||
}
|
||||
EOS;
|
||||
|
||||
$settings_testing_file = $this->siteDirectory . '/settings.testing.php';
|
||||
file_put_contents($settings_testing_file, $php);
|
||||
|
||||
$original_container = $this->originalContainer;
|
||||
parent::setUp();
|
||||
$this->assertNotIdentical(\Drupal::getContainer(), $original_container, 'KernelTestBase test creates a new container.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected behavior of setUp().
|
||||
*/
|
||||
public function testSetUp() {
|
||||
$modules = ['entity_test'];
|
||||
$table = 'entity_test';
|
||||
|
||||
// Verify that specified $modules have been loaded.
|
||||
$this->assertTrue(function_exists('entity_test_entity_bundle_info'), 'entity_test.module was loaded.');
|
||||
// Verify that there is a fixed module list.
|
||||
$this->assertIdentical(array_keys(\Drupal::moduleHandler()->getModuleList()), $modules);
|
||||
$this->assertIdentical(\Drupal::moduleHandler()->getImplementations('entity_bundle_info'), ['entity_test']);
|
||||
$this->assertIdentical(\Drupal::moduleHandler()->getImplementations('entity_type_alter'), ['entity_test']);
|
||||
|
||||
// Verify that no modules have been installed.
|
||||
$this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
|
||||
|
||||
// Verify that the settings.testing.php got taken into account.
|
||||
$this->assertTrue(function_exists('simpletest_test_stub_settings_function'));
|
||||
|
||||
// Ensure that the database tasks have been run during set up. Neither MySQL
|
||||
// nor SQLite make changes that are testable.
|
||||
$database = $this->container->get('database');
|
||||
if ($database->driver() == 'pgsql') {
|
||||
$this->assertEqual('on', $database->query("SHOW standard_conforming_strings")->fetchField());
|
||||
$this->assertEqual('escape', $database->query("SHOW bytea_output")->fetchField());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected load behavior of enableModules().
|
||||
*/
|
||||
public function testEnableModulesLoad() {
|
||||
$module = 'field_test';
|
||||
|
||||
// Verify that the module does not exist yet.
|
||||
$this->assertFalse(\Drupal::moduleHandler()->moduleExists($module), "$module module not found.");
|
||||
$list = array_keys(\Drupal::moduleHandler()->getModuleList());
|
||||
$this->assertFalse(in_array($module, $list), "$module module not found in the extension handler's module list.");
|
||||
$list = \Drupal::moduleHandler()->getImplementations('entity_display_build_alter');
|
||||
$this->assertFalse(in_array($module, $list), "{$module}_entity_display_build_alter() in \Drupal::moduleHandler()->getImplementations() not found.");
|
||||
|
||||
// Enable the module.
|
||||
$this->enableModules([$module]);
|
||||
|
||||
// Verify that the module exists.
|
||||
$this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
|
||||
$list = array_keys(\Drupal::moduleHandler()->getModuleList());
|
||||
$this->assertTrue(in_array($module, $list), "$module module found in the extension handler's module list.");
|
||||
$list = \Drupal::moduleHandler()->getImplementations('query_efq_table_prefixing_test_alter');
|
||||
$this->assertTrue(in_array($module, $list), "{$module}_query_efq_table_prefixing_test_alter() in \Drupal::moduleHandler()->getImplementations() found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected installation behavior of enableModules().
|
||||
*/
|
||||
public function testEnableModulesInstall() {
|
||||
$module = 'module_test';
|
||||
$table = 'module_test';
|
||||
|
||||
// Verify that the module does not exist yet.
|
||||
$this->assertFalse(\Drupal::moduleHandler()->moduleExists($module), "$module module not found.");
|
||||
$list = array_keys(\Drupal::moduleHandler()->getModuleList());
|
||||
$this->assertFalse(in_array($module, $list), "$module module not found in the extension handler's module list.");
|
||||
$list = \Drupal::moduleHandler()->getImplementations('hook_info');
|
||||
$this->assertFalse(in_array($module, $list), "{$module}_hook_info() in \Drupal::moduleHandler()->getImplementations() not found.");
|
||||
|
||||
$this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
|
||||
|
||||
// Install the module.
|
||||
\Drupal::service('module_installer')->install([$module]);
|
||||
|
||||
// Verify that the enabled module exists.
|
||||
$this->assertTrue(\Drupal::moduleHandler()->moduleExists($module), "$module module found.");
|
||||
$list = array_keys(\Drupal::moduleHandler()->getModuleList());
|
||||
$this->assertTrue(in_array($module, $list), "$module module found in the extension handler's module list.");
|
||||
$list = \Drupal::moduleHandler()->getImplementations('hook_info');
|
||||
$this->assertTrue(in_array($module, $list), "{$module}_hook_info() in \Drupal::moduleHandler()->getImplementations() found.");
|
||||
|
||||
$this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
$this->assertTrue($schema, "'$table' table schema found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests installing modules with DependencyInjection services.
|
||||
*/
|
||||
public function testEnableModulesInstallContainer() {
|
||||
// Install Node module.
|
||||
$this->enableModules(['user', 'field', 'node']);
|
||||
|
||||
$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.
|
||||
$query->accessCheck(FALSE);
|
||||
$query->condition('nid', 1);
|
||||
$query->execute();
|
||||
$this->pass('Entity field query was executed.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected behavior of installSchema().
|
||||
*/
|
||||
public function testInstallSchema() {
|
||||
$module = 'entity_test';
|
||||
$table = 'entity_test_example';
|
||||
// Verify that we can install a table from the module schema.
|
||||
$this->installSchema($module, $table);
|
||||
$this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
|
||||
|
||||
// Verify that the schema is known to Schema API.
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
$this->assertTrue($schema, "'$table' table schema found.");
|
||||
|
||||
// Verify that a unknown table from an enabled module throws an error.
|
||||
$table = 'unknown_entity_test_table';
|
||||
try {
|
||||
$this->installSchema($module, $table);
|
||||
$this->fail('Exception for non-retrievable schema found.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$this->pass('Exception for non-retrievable schema found.');
|
||||
}
|
||||
$this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
$this->assertFalse($schema, "'$table' table schema not found.");
|
||||
|
||||
// Verify that a table from a unknown module cannot be installed.
|
||||
$module = 'database_test';
|
||||
$table = 'test';
|
||||
try {
|
||||
$this->installSchema($module, $table);
|
||||
$this->fail('Exception for non-retrievable schema found.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$this->pass('Exception for non-retrievable schema found.');
|
||||
}
|
||||
$this->assertFalse(Database::getConnection()->schema()->tableExists($table), "'$table' database table not found.");
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
$this->assertTrue($schema, "'$table' table schema found.");
|
||||
|
||||
// Verify that the same table can be installed after enabling the module.
|
||||
$this->enableModules([$module]);
|
||||
$this->installSchema($module, $table);
|
||||
$this->assertTrue(Database::getConnection()->schema()->tableExists($table), "'$table' database table found.");
|
||||
$schema = drupal_get_module_schema($module, $table);
|
||||
$this->assertTrue($schema, "'$table' table schema found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected behavior of installEntitySchema().
|
||||
*/
|
||||
public function testInstallEntitySchema() {
|
||||
$entity = 'entity_test';
|
||||
// The entity_test Entity has a field that depends on the User module.
|
||||
$this->enableModules(['user']);
|
||||
// Verity that the entity schema is created properly.
|
||||
$this->installEntitySchema($entity);
|
||||
$this->assertTrue(Database::getConnection()->schema()->tableExists($entity), "'$entity' database table found.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests expected behavior of installConfig().
|
||||
*/
|
||||
public function testInstallConfig() {
|
||||
// The user module has configuration that depends on system.
|
||||
$this->enableModules(['system']);
|
||||
$module = 'user';
|
||||
|
||||
// Verify that default config can only be installed for enabled modules.
|
||||
try {
|
||||
$this->installConfig([$module]);
|
||||
$this->fail('Exception for non-enabled module found.');
|
||||
}
|
||||
catch (\Exception $e) {
|
||||
$this->pass('Exception for non-enabled module found.');
|
||||
}
|
||||
$this->assertFalse($this->container->get('config.storage')->exists('user.settings'));
|
||||
|
||||
// Verify that default config can be installed.
|
||||
$this->enableModules(['user']);
|
||||
$this->installConfig(['user']);
|
||||
$this->assertTrue($this->container->get('config.storage')->exists('user.settings'));
|
||||
$this->assertTrue($this->config('user.settings')->get('register'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that the module list is retained after enabling/installing/disabling.
|
||||
*/
|
||||
public function testEnableModulesFixedList() {
|
||||
// Install system module.
|
||||
$this->container->get('module_installer')->install(['system', 'user', 'menu_link_content']);
|
||||
$entity_manager = \Drupal::entityTypeManager();
|
||||
|
||||
// entity_test is loaded via $modules; its entity type should exist.
|
||||
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
|
||||
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
|
||||
|
||||
// Load some additional modules; entity_test should still exist.
|
||||
$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(['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(['field_test']);
|
||||
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
|
||||
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
|
||||
|
||||
// Set the weight of a module; entity_test should still exist.
|
||||
module_set_weight('field', -1);
|
||||
$this->assertEqual($this->container->get('module_handler')->moduleExists('entity_test'), TRUE);
|
||||
$this->assertTrue(TRUE == $entity_manager->getDefinition('entity_test'));
|
||||
|
||||
// Reactivate the previously uninstalled module.
|
||||
$this->enableModules(['field_test']);
|
||||
|
||||
// Create a field.
|
||||
$this->installEntitySchema('entity_test');
|
||||
$display = EntityViewDisplay::create([
|
||||
'targetEntityType' => 'entity_test',
|
||||
'bundle' => 'entity_test',
|
||||
'mode' => 'default',
|
||||
]);
|
||||
$field_storage = FieldStorageConfig::create([
|
||||
'field_name' => 'test_field',
|
||||
'entity_type' => 'entity_test',
|
||||
'type' => 'test_field',
|
||||
]);
|
||||
$field_storage->save();
|
||||
FieldConfig::create([
|
||||
'field_storage' => $field_storage,
|
||||
'bundle' => 'entity_test',
|
||||
])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that ThemeManager works right after loading a module.
|
||||
*/
|
||||
public function testEnableModulesTheme() {
|
||||
/** @var \Drupal\Core\Render\RendererInterface $renderer */
|
||||
$renderer = $this->container->get('renderer');
|
||||
$original_element = $element = [
|
||||
'#type' => 'container',
|
||||
'#markup' => 'Foo',
|
||||
'#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(['entity_test']);
|
||||
$this->assertTrue($renderer->renderRoot($element));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that there is no theme by default.
|
||||
*/
|
||||
public function testNoThemeByDefault() {
|
||||
$themes = $this->config('core.extension')->get('theme');
|
||||
$this->assertEqual($themes, []);
|
||||
|
||||
$extensions = $this->container->get('config.storage')->read('core.extension');
|
||||
$this->assertEqual($extensions['theme'], []);
|
||||
|
||||
$active_theme = $this->container->get('theme.manager')->getActiveTheme();
|
||||
$this->assertEqual($active_theme->getName(), 'core');
|
||||
}
|
||||
|
||||
/**
|
||||
* 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::installProfile());
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function run(array $methods = []) {
|
||||
parent::run($methods);
|
||||
|
||||
// Check that all tables of the test instance have been deleted. At this
|
||||
// point the original database connection is restored so we need to prefix
|
||||
// the tables.
|
||||
$connection = Database::getConnection();
|
||||
if ($connection->databaseType() != 'sqlite') {
|
||||
$tables = $connection->schema()->findTables($this->databasePrefix . '%');
|
||||
$this->assertTrue(empty($tables), 'All test tables have been removed.');
|
||||
}
|
||||
else {
|
||||
// We don't have the test instance connection anymore so we have to
|
||||
// re-attach its database and then use the same query as
|
||||
// \Drupal\Core\Database\Driver\sqlite\Schema::findTables().
|
||||
// @see \Drupal\Core\Database\Driver\sqlite\Connection::__construct()
|
||||
$info = Database::getConnectionInfo();
|
||||
$connection->query('ATTACH DATABASE :database AS :prefix', [
|
||||
':database' => $info['default']['database'] . '-' . $this->databasePrefix,
|
||||
':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", [
|
||||
':type' => 'table',
|
||||
':table_name' => '%',
|
||||
':pattern' => 'sqlite_%',
|
||||
])->fetchAllKeyed(0, 0);
|
||||
|
||||
$this->assertTrue(empty($result), 'All test tables have been removed.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests a test case with missing requirements.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
* @group legacy
|
||||
*/
|
||||
class MissingCheckedRequirementsTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$admin_user = $this->drupalCreateUser(['administer unit tests']);
|
||||
$this->drupalLogin($admin_user);
|
||||
}
|
||||
|
||||
/**
|
||||
* Overrides checkRequirements().
|
||||
*/
|
||||
protected function checkRequirements() {
|
||||
if ($this->isInChildSite()) {
|
||||
return [
|
||||
'Test is not allowed to run.',
|
||||
];
|
||||
}
|
||||
return parent::checkRequirements();
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures test will not run when requirements are missing.
|
||||
*/
|
||||
public function testCheckRequirements() {
|
||||
// If this is the main request, run the web test script and then assert
|
||||
// that the child tests did not run.
|
||||
if (!$this->isInChildSite()) {
|
||||
// Run this test from web interface.
|
||||
$edit['tests[Drupal\simpletest\Tests\MissingCheckedRequirementsTest]'] = TRUE;
|
||||
$this->drupalPostForm('admin/config/development/testing', $edit, t('Run tests'));
|
||||
$this->assertRaw('Test is not allowed to run.', 'Test check for requirements came up.');
|
||||
$this->assertNoText('Test ran when it failed requirements check.', 'Test requirements stopped test from running.');
|
||||
}
|
||||
else {
|
||||
$this->fail('Test ran when it failed requirements check.');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests the WebTestBase internal browser.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*/
|
||||
class SimpleTestBrowserTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['simpletest', 'test_page_test'];
|
||||
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
// Create and log in an admin user.
|
||||
$this->drupalLogin($this->drupalCreateUser(['administer unit tests']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Test the internal browsers functionality.
|
||||
*/
|
||||
public function testInternalBrowser() {
|
||||
// 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', [
|
||||
'@site-name' => $this->config('system.site')->get('name'),
|
||||
]));
|
||||
$this->assertNoTitle('Foo');
|
||||
|
||||
$old_user_id = $this->container->get('current_user')->id();
|
||||
$user = $this->drupalCreateUser();
|
||||
$this->drupalLogin($user);
|
||||
// Check that current user service updated.
|
||||
$this->assertNotEqual($old_user_id, $this->container->get('current_user')->id(), 'Current user service updated.');
|
||||
$headers = $this->drupalGetHeaders(TRUE);
|
||||
$this->assertEqual(count($headers), 2, 'There was one intermediate request.');
|
||||
$this->assertTrue(strpos($headers[0][':status'], '303') !== FALSE, 'Intermediate response code was 303.');
|
||||
$this->assertFalse(empty($headers[0]['location']), 'Intermediate request contained a Location header.');
|
||||
$this->assertEqual($this->getUrl(), $headers[0]['location'], 'HTTP redirect was followed');
|
||||
$this->assertFalse($this->drupalGetHeader('Location'), 'Headers from intermediate request were reset.');
|
||||
$this->assertResponse(200, 'Response code from intermediate request was reset.');
|
||||
|
||||
$this->drupalLogout();
|
||||
// Check that current user service updated to anonymous user.
|
||||
$this->assertEqual(0, $this->container->get('current_user')->id(), 'Current user service updated.');
|
||||
|
||||
// Test the maximum redirection option.
|
||||
$this->maximumRedirects = 1;
|
||||
$edit = [
|
||||
'name' => $user->getAccountName(),
|
||||
'pass' => $user->pass_raw,
|
||||
];
|
||||
$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.');
|
||||
|
||||
// Remove the Simpletest private key file so we can test the protection
|
||||
// against requests that forge a valid testing user agent to gain access
|
||||
// to the installer.
|
||||
// @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', ['external' => TRUE, 'absolute' => TRUE])->toString());
|
||||
$this->assertResponse(403, 'Cannot access install.php.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Test validation of the User-Agent header we use to perform test requests.
|
||||
*/
|
||||
public function testUserAgentValidation() {
|
||||
global $base_url;
|
||||
|
||||
// Logout the user which was logged in during test-setup.
|
||||
$this->drupalLogout();
|
||||
|
||||
$system_path = $base_url . '/' . drupal_get_path('module', 'system');
|
||||
$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('/test\d+/', $this->databasePrefix, $matches), 'Database prefix contains test prefix.');
|
||||
$test_ua = drupal_generate_test_ua($matches[0]);
|
||||
$this->additionalCurlOptions = [CURLOPT_USERAGENT => $test_ua];
|
||||
|
||||
// Test pages only available for testing.
|
||||
$this->drupalGet($http_path);
|
||||
$this->assertResponse(200, 'Requesting http.php with a legitimate simpletest User-Agent returns OK.');
|
||||
$this->drupalGet($https_path);
|
||||
$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 = [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);
|
||||
$this->assertResponse(403, 'Requesting https.php with a bad simpletest User-Agent fails.');
|
||||
|
||||
// Use a real User-Agent and verify that the special files http.php and
|
||||
// https.php can't be accessed.
|
||||
$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);
|
||||
$this->assertResponse(403, 'Requesting https.php with a normal User-Agent fails.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests SimpleTest error and exception collector.
|
||||
*
|
||||
* @group WebTestBase
|
||||
*/
|
||||
class SimpleTestErrorCollectorTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['system_test', 'error_test'];
|
||||
|
||||
/**
|
||||
* Errors triggered during the test.
|
||||
*
|
||||
* Errors are intercepted by the overridden implementation
|
||||
* of Drupal\simpletest\WebTestBase::error() below.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $collectedErrors = [];
|
||||
|
||||
/**
|
||||
* Tests that simpletest collects errors from the tested site.
|
||||
*/
|
||||
public function testErrorCollect() {
|
||||
$this->collectedErrors = [];
|
||||
$this->drupalGet('error-test/generate-warnings-with-report');
|
||||
$this->assertEqual(count($this->collectedErrors), 3, 'Three errors were collected');
|
||||
|
||||
if (count($this->collectedErrors) == 3) {
|
||||
$this->assertError($this->collectedErrors[0], 'Notice', 'Drupal\error_test\Controller\ErrorTestController->generateWarnings()', 'ErrorTestController.php', 'Undefined variable: bananas');
|
||||
$this->assertError($this->collectedErrors[1], 'Warning', 'Drupal\error_test\Controller\ErrorTestController->generateWarnings()', 'ErrorTestController.php', 'Division by zero');
|
||||
$this->assertError($this->collectedErrors[2], 'User warning', 'Drupal\error_test\Controller\ErrorTestController->generateWarnings()', 'ErrorTestController.php', 'Drupal & awesome');
|
||||
}
|
||||
else {
|
||||
// Give back the errors to the log report.
|
||||
foreach ($this->collectedErrors as $error) {
|
||||
parent::error($error['message'], $error['group'], $error['caller']);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stores errors into an array.
|
||||
*
|
||||
* This test class is trying to verify that simpletest correctly sees errors
|
||||
* and warnings. However, it can't generate errors and warnings that
|
||||
* propagate up to the testing framework itself, or these tests would always
|
||||
* fail. So, this special copy of error() doesn't propagate the errors up
|
||||
* the class hierarchy. It just stuffs them into a protected collectedErrors
|
||||
* array for various assertions to inspect.
|
||||
*/
|
||||
protected function error($message = '', $group = 'Other', array $caller = NULL) {
|
||||
// Due to a WTF elsewhere, simpletest treats debug() and verbose()
|
||||
// messages as if they were an 'error'. But, we don't want to collect
|
||||
// those here. This function just wants to collect the real errors (PHP
|
||||
// notices, PHP fatal errors, etc.), and let all the 'errors' from the
|
||||
// 'User notice' group bubble up to the parent classes to be handled (and
|
||||
// eventually displayed) as normal.
|
||||
if ($group == 'User notice') {
|
||||
parent::error($message, $group, $caller);
|
||||
}
|
||||
// Everything else should be collected but not propagated.
|
||||
else {
|
||||
$this->collectedErrors[] = [
|
||||
'message' => $message,
|
||||
'group' => $group,
|
||||
'caller' => $caller,
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that a collected error matches what we are expecting.
|
||||
*/
|
||||
public function assertError($error, $group, $function, $file, $message = NULL) {
|
||||
$this->assertEqual($error['group'], $group, new FormattableMarkup("Group was %group", ['%group' => $group]));
|
||||
$this->assertEqual($error['caller']['function'], $function, new FormattableMarkup("Function was %function", ['%function' => $function]));
|
||||
$this->assertEqual(\Drupal::service('file_system')->basename($error['caller']['file']), $file, new FormattableMarkup("File was %file", ['%file' => $file]));
|
||||
if (isset($message)) {
|
||||
$this->assertEqual($error['message'], $message, new FormattableMarkup("Message was %message", ['%message' => $message]));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\entity_test\Entity\EntityTest;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests batch operations during tests execution.
|
||||
*
|
||||
* This demonstrates that a batch will be successfully executed during module
|
||||
* installation when running tests.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
* @group FunctionalTestSetupTrait
|
||||
*
|
||||
* @see \Drupal\FunctionalTests\Core\Test\ModuleInstallBatchTest
|
||||
*/
|
||||
class SimpleTestInstallBatchTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['test_batch_test', 'entity_test'];
|
||||
|
||||
/**
|
||||
* Tests loading entities created in a batch in test_batch_test_install().
|
||||
*/
|
||||
public function testLoadingEntitiesCreatedInBatch() {
|
||||
$entity1 = EntityTest::load(1);
|
||||
$this->assertNotNull($entity1, 'Successfully loaded entity 1.');
|
||||
$entity2 = EntityTest::load(2);
|
||||
$this->assertNotNull($entity2, 'Successfully loaded entity 2.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\Component\Render\FormattableMarkup;
|
||||
use Drupal\Component\Utility\Crypt;
|
||||
use Drupal\Core\Test\TestDatabase;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests SimpleTest's web interface: check that the intended tests were run and
|
||||
* ensure that test reports display the intended results. Also test SimpleTest's
|
||||
* internal browser and APIs implicitly.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
* @group legacy
|
||||
*/
|
||||
class SimpleTestTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* The results array that has been parsed by getTestResults().
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
protected $childTestResults;
|
||||
|
||||
/**
|
||||
* Stores the test ID from each test run for comparison.
|
||||
*
|
||||
* Used to ensure they are incrementing.
|
||||
*/
|
||||
protected $testIds = [];
|
||||
|
||||
/**
|
||||
* Translated fail message.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $failMessage = '';
|
||||
|
||||
/**
|
||||
* Translated pass message.
|
||||
* @var string
|
||||
*/
|
||||
private $passMessage = '';
|
||||
|
||||
/**
|
||||
* A valid and recognized permission.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $validPermission;
|
||||
|
||||
/**
|
||||
* An invalid or unrecognized permission.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $invalidPermission;
|
||||
|
||||
protected function setUp() {
|
||||
if (!$this->isInChildSite()) {
|
||||
$php = <<<'EOD'
|
||||
<?php
|
||||
|
||||
# Make sure that the $test_class variable is defined when this file is included.
|
||||
if ($test_class) {
|
||||
}
|
||||
|
||||
# Define a function to be able to check that this file was loaded with
|
||||
# function_exists().
|
||||
if (!function_exists('simpletest_test_stub_settings_function')) {
|
||||
function simpletest_test_stub_settings_function() {}
|
||||
}
|
||||
EOD;
|
||||
|
||||
file_put_contents($this->siteDirectory . '/' . 'settings.testing.php', $php);
|
||||
// @see \Drupal\system\Tests\DrupalKernel\DrupalKernelSiteTest
|
||||
$class = __CLASS__;
|
||||
$yaml = <<<EOD
|
||||
services:
|
||||
# Add a new service.
|
||||
site.service.yml:
|
||||
class: $class
|
||||
# Swap out a core service.
|
||||
cache.backend.database:
|
||||
class: Drupal\Core\Cache\MemoryBackendFactory
|
||||
EOD;
|
||||
file_put_contents($this->siteDirectory . '/testing.services.yml', $yaml);
|
||||
|
||||
$original_container = $this->originalContainer;
|
||||
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(['administer unit tests']));
|
||||
}
|
||||
else {
|
||||
// This causes three of the five fails that are asserted in
|
||||
// confirmStubResults().
|
||||
self::$modules = ['non_existent_module'];
|
||||
parent::setUp();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the tests selected through the web interface are run and displayed.
|
||||
*/
|
||||
public function testWebTestRunner() {
|
||||
$this->passMessage = t('SimpleTest pass.');
|
||||
$this->failMessage = t('SimpleTest fail.');
|
||||
$this->validPermission = 'access administration pages';
|
||||
$this->invalidPermission = 'invalid permission';
|
||||
|
||||
if ($this->isInChildSite()) {
|
||||
// Only run following code if this test is running itself through a CURL
|
||||
// request.
|
||||
$this->stubTest();
|
||||
}
|
||||
else {
|
||||
// Run twice so test_ids can be accumulated.
|
||||
for ($i = 0; $i < 2; $i++) {
|
||||
// Run this test from web interface.
|
||||
$this->drupalGet('admin/config/development/testing');
|
||||
|
||||
$edit = [];
|
||||
$edit['tests[Drupal\simpletest\Tests\SimpleTestTest]'] = TRUE;
|
||||
$this->drupalPostForm(NULL, $edit, t('Run tests'));
|
||||
|
||||
// Parse results and confirm that they are correct.
|
||||
$this->getTestResults();
|
||||
$this->confirmStubTestResults();
|
||||
}
|
||||
|
||||
// Regression test for #290316.
|
||||
// Check that test_id is incrementing.
|
||||
$this->assertTrue($this->testIds[0] != $this->testIds[1], 'Test ID is incrementing.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test to be run and the results confirmed.
|
||||
*
|
||||
* Here we force test results which must match the expected results from
|
||||
* confirmStubResults().
|
||||
*/
|
||||
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();
|
||||
$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);
|
||||
|
||||
// Check to see if runtime assertions are indeed on, if successful this
|
||||
// will be the first of sixteen passes asserted in confirmStubResults()
|
||||
try {
|
||||
// Test with minimum possible arguments to make sure no notice for
|
||||
// missing argument is thrown.
|
||||
assert(FALSE);
|
||||
$this->fail('Runtime assertions are not working.');
|
||||
}
|
||||
catch (\AssertionError $e) {
|
||||
try {
|
||||
// Now test with an error message to ensure it is correctly passed
|
||||
// along by the rethrow.
|
||||
assert(FALSE, 'Lorem Ipsum');
|
||||
}
|
||||
catch (\AssertionError $e) {
|
||||
$this->assertEqual($e->getMessage(), 'Lorem Ipsum', 'Runtime assertions Enabled and running.');
|
||||
}
|
||||
}
|
||||
// This causes the second of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$this->pass($this->passMessage);
|
||||
|
||||
// The first three fails are caused by enabling a non-existent module in
|
||||
// setUp().
|
||||
|
||||
// This causes the fourth of the five fails asserted in
|
||||
// confirmStubResults().
|
||||
$this->fail($this->failMessage);
|
||||
|
||||
// This causes the third to fifth of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$user = $this->drupalCreateUser([$this->validPermission], 'SimpleTestTest');
|
||||
|
||||
// This causes the fifth of the five fails asserted in confirmStubResults().
|
||||
$this->drupalCreateUser([$this->invalidPermission]);
|
||||
|
||||
// Test logging in as a user.
|
||||
// This causes the sixth to tenth of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$this->drupalLogin($user);
|
||||
|
||||
// This causes the eleventh of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$this->pass('Test ID is ' . $this->testId . '.');
|
||||
|
||||
// These cause the twelfth to fifteenth of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$this->assertTrue(file_exists($site_path . '/settings.testing.php'));
|
||||
// Check the settings.testing.php file got included.
|
||||
$this->assertTrue(function_exists('simpletest_test_stub_settings_function'));
|
||||
// Check that the test-specific service file got loaded.
|
||||
$this->assertTrue($this->container->has('site.service.yml'));
|
||||
$this->assertIdentical(get_class($this->container->get('cache.backend.database')), 'Drupal\Core\Cache\MemoryBackendFactory');
|
||||
|
||||
// These cause the two exceptions asserted in confirmStubResults().
|
||||
// Call trigger_error() without the required argument to trigger an E_WARNING.
|
||||
trigger_error();
|
||||
// Generates a warning inside a PHP function.
|
||||
array_key_exists(NULL, NULL);
|
||||
|
||||
// This causes the sixteenth of the sixteen passes asserted in
|
||||
// confirmStubResults().
|
||||
$this->assertNothing();
|
||||
|
||||
// This causes the debug message asserted in confirmStubResults().
|
||||
debug('Foo', 'Debug', FALSE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert nothing.
|
||||
*/
|
||||
public function assertNothing() {
|
||||
$this->pass('This is nothing.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm that the stub test produced the desired results.
|
||||
*/
|
||||
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', ['@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()');
|
||||
|
||||
// Check that a warning is caught by simpletest. The exact error message
|
||||
// differs between PHP versions so only the function name is checked.
|
||||
$this->assertAssertion('trigger_error()', 'Warning', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
|
||||
|
||||
// Check that the backtracing code works for specific assert function.
|
||||
$this->assertAssertion('This is nothing.', 'Other', 'Pass', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
|
||||
|
||||
// Check that errors that occur inside PHP internal functions are correctly
|
||||
// reported. The exact error message differs between PHP versions so we
|
||||
// check only the function name 'array_key_exists'.
|
||||
$this->assertAssertion('array_key_exists', 'Warning', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
|
||||
|
||||
$this->assertAssertion("Debug: 'Foo'", 'Debug', 'Fail', 'SimpleTestTest.php', 'Drupal\simpletest\Tests\SimpleTestTest->stubTest()');
|
||||
|
||||
$this->assertEqual('16 passes, 3 fails, 2 exceptions, 3 debug messages', $this->childTestResults['summary']);
|
||||
|
||||
$this->testIds[] = $test_id = $this->getTestIdFromResults();
|
||||
$this->assertTrue($test_id, 'Found test ID in results.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the test id from the test results.
|
||||
*/
|
||||
public function getTestIdFromResults() {
|
||||
foreach ($this->childTestResults['assertions'] as $assertion) {
|
||||
if (preg_match('@^Test ID is ([0-9]*)\.$@', $assertion['message'], $matches)) {
|
||||
return $matches[1];
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that an assertion with specified values is displayed in results.
|
||||
*
|
||||
* @param string $message
|
||||
* Assertion message.
|
||||
* @param string $type
|
||||
* Assertion type.
|
||||
* @param string $status
|
||||
* Assertion status.
|
||||
* @param string $file
|
||||
* File where the assertion originated.
|
||||
* @param string $function
|
||||
* Function where the assertion originated.
|
||||
*
|
||||
* @return Assertion result.
|
||||
*/
|
||||
public function assertAssertion($message, $type, $status, $file, $function) {
|
||||
$message = trim(strip_tags($message));
|
||||
$found = FALSE;
|
||||
foreach ($this->childTestResults['assertions'] as $assertion) {
|
||||
if ((strpos($assertion['message'], $message) !== FALSE) &&
|
||||
$assertion['type'] == $type &&
|
||||
$assertion['status'] == $status &&
|
||||
$assertion['file'] == $file &&
|
||||
$assertion['function'] == $function) {
|
||||
$found = TRUE;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $this->assertTrue($found, new FormattableMarkup('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.
|
||||
*/
|
||||
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'] = [];
|
||||
$tbody = $details->div->table->tbody;
|
||||
foreach ($tbody->tr as $row) {
|
||||
$assertion = [];
|
||||
$assertion['message'] = $this->asText($row->td[0]);
|
||||
$assertion['type'] = $this->asText($row->td[1]);
|
||||
$assertion['file'] = $this->asText($row->td[2]);
|
||||
$assertion['line'] = $this->asText($row->td[3]);
|
||||
$assertion['function'] = $this->asText($row->td[4]);
|
||||
$ok_url = file_url_transform_relative(file_create_url('core/misc/icons/73b355/check.svg'));
|
||||
$assertion['status'] = ($row->td[5]->img['src'] == $ok_url) ? 'Pass' : 'Fail';
|
||||
$results['assertions'][] = $assertion;
|
||||
}
|
||||
}
|
||||
}
|
||||
$this->childTestResults = $results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the details containing the results for group this test is in.
|
||||
*/
|
||||
public function getResultFieldSet() {
|
||||
$all_details = $this->xpath('//details');
|
||||
foreach ($all_details as $details) {
|
||||
if ($this->asText($details->summary) == __CLASS__) {
|
||||
return $details;
|
||||
}
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract the text contained by the element.
|
||||
*
|
||||
* @param $element
|
||||
* Element to extract text from.
|
||||
*
|
||||
* @return
|
||||
* Extracted text.
|
||||
*/
|
||||
public function asText(\SimpleXMLElement $element) {
|
||||
if (!is_object($element)) {
|
||||
return $this->fail('The element is not an element.');
|
||||
}
|
||||
return trim(html_entity_decode(strip_tags($element->asXML())));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests if Simpletest-based tests are skipped based on module requirements.
|
||||
*
|
||||
* This test should always be skipped when TestDiscovery is used to discover it.
|
||||
* This means that if you specify this test to run-tests.sh with --class or
|
||||
* --file, this test will run and fail.
|
||||
*
|
||||
* Only WebTestBase tests are skipped by TestDiscovery. Other tests use the
|
||||
* PHPUnit @-require module annotation.
|
||||
*
|
||||
* @dependencies module_does_not_exist
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*
|
||||
* @todo Change or remove this test when Simpletest-based tests are able to skip
|
||||
* themselves based on requirements.
|
||||
* @see https://www.drupal.org/node/1273478
|
||||
*/
|
||||
class SkipRequiredModulesTest extends WebTestBase {
|
||||
|
||||
public function testModuleNotFound() {
|
||||
$this->fail('This test should have been skipped during discovery.');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* This test will check WebTestBase's default time zone handling.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*/
|
||||
class TimeZoneTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* A user with administrative privileges.
|
||||
*/
|
||||
protected $adminUser;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
|
||||
$this->adminUser = $this->drupalCreateUser(['administer site configuration']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that user accounts have the default time zone set.
|
||||
*/
|
||||
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,44 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
use Drupal\Tests\simpletest\Functional\SimpletestPhpunitBrowserTest;
|
||||
|
||||
/**
|
||||
* Test PHPUnit output for the Simpletest UI.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*
|
||||
* @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[20], 'HTML output was generated<br />');
|
||||
// Check that URLs are printed as HTML links.
|
||||
$this->assertIdentical(strpos($output[21], '<a href="http'), 0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest\Tests;
|
||||
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Tests the test-specifics customisations done in the installation.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*/
|
||||
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");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
@trigger_error(__NAMESPACE__ . '\UserCreationTrait is deprecated in Drupal 8.4.x. Will be removed before Drupal 9.0.0. Use Drupal\Tests\user\Traits\UserCreationTrait instead. See https://www.drupal.org/node/2884454.', E_USER_DEPRECATED);
|
||||
|
||||
use Drupal\Tests\user\Traits\UserCreationTrait as BaseUserCreationTrait;
|
||||
|
||||
/**
|
||||
* Provides methods to create additional test users and switch the currently
|
||||
* logged in one.
|
||||
*
|
||||
* This trait is meant to be used only by test classes extending
|
||||
* \Drupal\simpletest\TestBase.
|
||||
*
|
||||
* @deprecated in drupal:8.4.0 and is removed from drupal:9.0.0. Use
|
||||
* Drupal\Tests\user\Traits\UserCreationTrait instead.
|
||||
*
|
||||
* @see https://www.drupal.org/node/2884454
|
||||
*/
|
||||
trait UserCreationTrait {
|
||||
|
||||
use BaseUserCreationTrait;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\simpletest;
|
||||
|
||||
use Drupal\Tests\WebAssert as BaseWebAssert;
|
||||
|
||||
/**
|
||||
* Defines a class with methods for asserting presence of elements during tests.
|
||||
*
|
||||
* @deprecated in drupal:8.1.1 and is removed from drupal:9.0.0.
|
||||
* This was moved to another namespace.
|
||||
*
|
||||
* @see \Drupal\Tests
|
||||
*/
|
||||
class WebAssert extends BaseWebAssert {
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{#
|
||||
/**
|
||||
* @file
|
||||
* Default theme implementation for simpletest result summaries.
|
||||
*
|
||||
* Available variables:
|
||||
* - label: An optional label to be rendered before the results.
|
||||
* - items: Pluralized summaries for each result type (number of passes, fails,
|
||||
* exceptions, and debug messages).
|
||||
* - pass: The number of passes.
|
||||
* - fail: The number of fails.
|
||||
* - exception: The number of exceptions.
|
||||
* - debug: The number of debug messages.
|
||||
*
|
||||
* @see template_preprocess_simpletest_result_summary()
|
||||
*
|
||||
* @ingroup themeable
|
||||
*/
|
||||
#}
|
||||
<div class="simpletest-{{ fail + exception == 0 ? 'pass' : 'fail' }}">
|
||||
{{ label }} {{ items|join(', ') }}
|
||||
</div>
|
||||
@@ -0,0 +1,43 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<testsuites>
|
||||
<testsuite name="Drupal Unit Test Suite" tests="1" assertions="0" failures="0" errors="1" time="0.002680">
|
||||
<testsuite name="Drupal\Tests\Component\PhpStorage\FileStorageTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Component/PhpStorage/FileStorageTest.php" namespace="Drupal\Tests\Component\PhpStorage" fullPackage="Drupal.Tests.Component.PhpStorage" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\Tests\Component\PhpStorage\MTimeProtectedFastFileStorageTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Component/PhpStorage/MTimeProtectedFastFileStorageTest.php" namespace="Drupal\Tests\Component\PhpStorage" fullPackage="Drupal.Tests.Component.PhpStorage" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\Tests\Core\Cache\BackendChainImplementationUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Cache/BackendChainImplementationUnitTest.php" namespace="Drupal\Tests\Core\Cache" fullPackage="Drupal.Tests.Core.Cache" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\Tests\Core\Cache\NullBackendTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Cache/NullBackendTest.php" namespace="Drupal\Tests\Core\Cache" fullPackage="Drupal.Tests.Core.Cache" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\Tests\Core\Extension\ModuleHandlerUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php" namespace="Drupal\Tests\Core\Extension" fullPackage="Drupal.Tests.Core.Extension" tests="1" assertions="0" failures="0" errors="1" time="0.002680">
|
||||
<testcase name="testloadInclude" class="Drupal\Tests\Core\Extension\ModuleHandlerUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php" line="37" assertions="0" time="0.002680">
|
||||
<error type="PHPUnit\Framework\Error\Notice">Drupal\Tests\Core\Extension\ModuleHandlerUnitTest::testloadInclude
|
||||
Undefined index: foo
|
||||
|
||||
/home/chx/www/system/core/lib/Drupal/Core/Extension/ModuleHandler.php:219
|
||||
/home/chx/www/system/core/tests/Drupal/Tests/Core/Extension/ModuleHandlerUnitTest.php:40
|
||||
</error>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
<testsuite name="Drupal\Tests\Core\NestedArrayUnitTest" file="/home/chx/www/system/core/tests/Drupal/Tests/Core/NestedArrayUnitTest.php" namespace="Drupal\Tests\Core" fullPackage="Drupal.Tests.Core" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\breakpoint\Tests\BreakpointMediaQueryTest" file="/home/chx/www/system/core/modules/breakpoint/tests/Drupal/breakpoint/Tests/BreakpointMediaQueryTest.php" namespace="Drupal\breakpoint\Tests" fullPackage="Drupal.breakpoint.Tests" tests="0" assertions="0" failures="0" errors="0" time="0.000000"/>
|
||||
<testsuite name="Drupal\Tests\Core\Route\RoleAccessCheckTest" file="/var/www/d8/core/tests/Drupal/Tests/Core/Route/RoleAccessCheckTestkTest.php" namespace="Drupal\Tests\Core\Route" fullPackage="Drupal.Tests.Core.Route" tests="3" assertions="3" failures="3" errors="0" time="0.009176">
|
||||
<testsuite name="Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess" tests="3" assertions="3" failures="3" errors="0" time="0.009176">
|
||||
<testcase name="testRoleAccess with data set #0" assertions="1" time="0.004519">
|
||||
<failure type="PHPUnit\Framework\ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #0 ('role_test_1', array(Drupal\user\Entity\User, Drupal\user\Entity\User))
|
||||
Access granted for user with the roles role_test_1 on path: role_test_1
|
||||
Failed asserting that false is true.
|
||||
</failure>
|
||||
</testcase>
|
||||
<testcase name="testRoleAccess with data set #1" assertions="1" time="0.002354">
|
||||
<failure type="PHPUnit\Framework\ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #1 ('role_test_2', array(Drupal\user\Entity\User, Drupal\user\Entity\User))
|
||||
Access granted for user with the roles role_test_2 on path: role_test_2
|
||||
Failed asserting that false is true.
|
||||
</failure>
|
||||
</testcase>
|
||||
<testcase name="testRoleAccess with data set #2" assertions="1" time="0.002303">
|
||||
<failure type="PHPUnit\Framework\ExpectationFailedException">Drupal\Tests\Core\Route\RoleAccessCheckTest::testRoleAccess with data set #2 ('role_test_3', array(Drupal\user\Entity\User))
|
||||
Access granted for user with the roles role_test_1, role_test_2 on path: role_test_3
|
||||
Failed asserting that false is true.
|
||||
</failure>
|
||||
</testcase>
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
@@ -0,0 +1,4 @@
|
||||
<select name="test">
|
||||
<option value="1">One</option>
|
||||
<option value="2" selected="selected">Two</option>
|
||||
</select>
|
||||
@@ -0,0 +1,4 @@
|
||||
<select name="test">
|
||||
<option value="1">One</option>
|
||||
<option value="2">Two</option>
|
||||
</select>
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
// phpcs:ignoreFile
|
||||
|
||||
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>');
|
||||
}
|
||||
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
// phpcs:ignoreFile
|
||||
|
||||
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 {
|
||||
|
||||
/**
|
||||
* Performs the status specified by SimpletestPhpunitRunCommandTestWillDie.
|
||||
*/
|
||||
public function testWillDie() {
|
||||
$status = (int) getenv('SimpletestPhpunitRunCommandTestWillDie');
|
||||
if ($status == 0) {
|
||||
$this->assertTrue(TRUE, 'Assertion to ensure test pass');
|
||||
return;
|
||||
}
|
||||
exit($status);
|
||||
}
|
||||
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
name: 'Simpletest deprecation test'
|
||||
type: module
|
||||
description: 'Support module for Simpletest deprecation tests.'
|
||||
package: Testing
|
||||
version: VERSION
|
||||
core: 8.x
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @file
|
||||
* Mock module for testing simpletest.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Implements hook_simpletest_alter().
|
||||
*
|
||||
* This hook is deprecated and should trigger a deprecation error when invoked.
|
||||
*/
|
||||
function simpletest_deprecation_test_simpletest_alter(&$groups) {
|
||||
// No-op.
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_test_group_started().
|
||||
*
|
||||
* This hook is deprecated and should trigger a deprecation error when invoked.
|
||||
*/
|
||||
function simpletest_deprecation_test_test_group_started() {
|
||||
// No-op.
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_test_group_finished().
|
||||
*
|
||||
* This hook is deprecated and should trigger a deprecation error when invoked.
|
||||
*/
|
||||
function simpletest_deprecation_test_test_group_finished() {
|
||||
// No-op.
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements hook_test_finished().
|
||||
*
|
||||
* This hook is deprecated and should trigger a deprecation error when invoked.
|
||||
*/
|
||||
function simpletest_deprecation_test_test_finished($results) {
|
||||
// No-op.
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
use Drupal\Core\Url;
|
||||
|
||||
/**
|
||||
* Verifies that tests in other installation profiles are found.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*
|
||||
* @see \Drupal\simpletest\Tests\InstallationProfileModuleTestsTest
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @var string
|
||||
*
|
||||
* @see \Drupal\simpletest\Tests\InstallationProfileModuleTestsTest
|
||||
* @see \Drupal\Tests\drupal_system_listing_compatible_test\Kernel\SystemListingCrossProfileCompatibleTest
|
||||
*/
|
||||
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.
|
||||
*
|
||||
* @expectedDeprecation Drupal\simpletest\TestDiscovery is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDiscovery instead. See https://www.drupal.org/node/2949692
|
||||
*/
|
||||
public function testOtherInstallationProfile() {
|
||||
// Assert the existence of a test in a different installation profile than
|
||||
// the current.
|
||||
$this->drupalGet(Url::fromRoute('simpletest.test_form'));
|
||||
$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\Tests\drupal_system_listing_compatible_test\Kernel\SystemListingCrossProfileCompatibleTest');
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Functional;
|
||||
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Basic functionality of the Testing module.
|
||||
*
|
||||
* @group simpletest
|
||||
*/
|
||||
class SimpletestTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* Modules to enable.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected $defaultTheme = 'stark';
|
||||
|
||||
/**
|
||||
* Test that we can uninstall the module without mishap.
|
||||
*
|
||||
* Upon uninstall, simpletest will clean up after itself. This should neither
|
||||
* break the test runner's expectations, nor cause any kind of exception.
|
||||
*
|
||||
* Note that this might break run-tests.sh test runs that don't use the
|
||||
* --sqlite argument.
|
||||
*/
|
||||
public function testUninstallModule() {
|
||||
/* @var $installer \Drupal\Core\Extension\ModuleInstallerInterface */
|
||||
$installer = $this->container->get('module_installer');
|
||||
$this->assertTrue($installer->uninstall(['simpletest']));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Functional;
|
||||
|
||||
use Drupal\Core\Url;
|
||||
use Drupal\KernelTests\KernelTestBaseTest;
|
||||
use Drupal\Tests\action\Unit\Menu\ActionLocalTasksTest;
|
||||
use Drupal\Tests\BrowserTestBase;
|
||||
|
||||
/**
|
||||
* Test various aspects of testing through the UI form.
|
||||
*
|
||||
* @group #slow
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class SimpletestUiTest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->drupalLogin($this->createUser(['administer unit tests']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests that unit, kernel, and functional tests work through the UI.
|
||||
*
|
||||
* @expectedDeprecation Drupal\simpletest\TestDiscovery is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDiscovery instead. See https://www.drupal.org/node/2949692
|
||||
*/
|
||||
public function testTestingThroughUI() {
|
||||
$url = Url::fromRoute('simpletest.test_form');
|
||||
$assertion = $this->assertSession();
|
||||
|
||||
$this->drupalGet($url);
|
||||
$settings = $this->getDrupalSettings();
|
||||
$this->assertTrue(strpos($settings['simpleTest']['images'][0], 'core/misc/menu-collapsed.png') > 0, 'drupalSettings contains a link to core/misc/menu-collapsed.png.');
|
||||
|
||||
// We can not test WebTestBase tests here since they require a valid .htkey
|
||||
// to be created. However this scenario is covered by the testception of
|
||||
// \Drupal\simpletest\Tests\SimpleTestTest.
|
||||
$tests = [
|
||||
// A KernelTestBase test.
|
||||
KernelTestBaseTest::class,
|
||||
// A PHPUnit unit test.
|
||||
ActionLocalTasksTest::class,
|
||||
// A PHPUnit functional test.
|
||||
ThroughUITest::class,
|
||||
];
|
||||
|
||||
foreach ($tests as $test) {
|
||||
$edit = [
|
||||
"tests[$test]" => TRUE,
|
||||
];
|
||||
$this->drupalPostForm($url, $edit, t('Run tests'));
|
||||
$assertion->pageTextContains('0 fails, 0 exceptions');
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?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
|
||||
* @group legacy
|
||||
*/
|
||||
class ThroughUITest extends BrowserTestBase {
|
||||
|
||||
/**
|
||||
* This test method must always pass.
|
||||
*/
|
||||
public function testThroughUi() {
|
||||
$this->pass('Success!');
|
||||
}
|
||||
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel\Cache\Context;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\simpletest\Cache\Context\TestDiscoveryCacheContext;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
|
||||
/**
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class TestDiscoveryCacheContextTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* Tests that test context hashes are unique.
|
||||
*
|
||||
* @expectedDeprecation Drupal\simpletest\TestDiscovery is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDiscovery instead. See https://www.drupal.org/node/2949692
|
||||
*/
|
||||
public function testContext() {
|
||||
// Mock test discovery.
|
||||
$discovery = $this->getMockBuilder(TestDiscovery::class)
|
||||
->setMethods(['getTestClasses'])
|
||||
->disableOriginalConstructor()
|
||||
->getMock();
|
||||
// Set getTestClasses() to return different results on subsequent calls.
|
||||
// This emulates changed tests in the filesystem.
|
||||
$discovery->expects($this->any())
|
||||
->method('getTestClasses')
|
||||
->willReturnOnConsecutiveCalls(
|
||||
['group1' => ['Test']],
|
||||
['group2' => ['Test2']]
|
||||
);
|
||||
|
||||
// Make our cache context object.
|
||||
$cache_context = new TestDiscoveryCacheContext($discovery, $this->container->get('private_key'));
|
||||
|
||||
// Generate a context hash.
|
||||
$context_hash = $cache_context->getContext();
|
||||
|
||||
// Since the context stores the hash, we have to reset it.
|
||||
$hash_ref = new \ReflectionProperty($cache_context, 'hash');
|
||||
$hash_ref->setAccessible(TRUE);
|
||||
$hash_ref->setValue($cache_context, NULL);
|
||||
|
||||
// And then assert that we did not generate the same hash for different
|
||||
// content.
|
||||
$this->assertNotSame($context_hash, $cache_context->getContext());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel;
|
||||
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
use Drupal\Core\Test\EnvironmentCleanerInterface;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Symfony\Component\DependencyInjection\Definition;
|
||||
|
||||
/**
|
||||
* Verify deprecation errors for the cleanup functions.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class DeprecatedCleanupTest extends KernelTestBase {
|
||||
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function register(ContainerBuilder $container) {
|
||||
parent::register($container);
|
||||
$cleaner_definition = new Definition(StubEnvironmentCleanerService::class);
|
||||
$container->setDefinition('environment_cleaner', $cleaner_definition);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation simpletest_clean_environment is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanEnvironment() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanEnvironment() instead.. See https://www.drupal.org/node/3076634
|
||||
* @expectedDeprecation simpletest_clean_database is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanDatabase() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanDatabase() instead. See https://www.drupal.org/node/3076634
|
||||
* @expectedDeprecation simpletest_clean_temporary_directories is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanTemporaryDirectories() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanTemporaryDirectories() instead. See https://www.drupal.org/node/3076634
|
||||
* @expectedDeprecation simpletest_clean_results_table is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Access the environment_cleaner service and call its cleanResultsTable() method, or use \Drupal\Core\Test\EnvironmentCleaner::cleanResultsTable() instead. See https://www.drupal.org/node/3076634
|
||||
*/
|
||||
public function testDeprecatedCleanFunctions() {
|
||||
$this->assertNull(simpletest_clean_environment());
|
||||
$this->assertNull(simpletest_clean_database());
|
||||
$this->assertNull(simpletest_clean_temporary_directories());
|
||||
$this->assertEquals(0, simpletest_clean_results_table());
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock environment_cleaner service that does not perform any cleaning.
|
||||
*/
|
||||
class StubEnvironmentCleanerService implements EnvironmentCleanerInterface {
|
||||
|
||||
public function cleanDatabase() {
|
||||
|
||||
}
|
||||
|
||||
public function cleanEnvironment($clear_results = TRUE, $clear_temp_directories = TRUE, $clear_database = TRUE) {
|
||||
|
||||
}
|
||||
|
||||
public function cleanResultsTable($test_id = NULL) {
|
||||
|
||||
}
|
||||
|
||||
public function cleanTemporaryDirectories() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel\Migrate\d6;
|
||||
|
||||
use Drupal\Tests\SchemaCheckTestTrait;
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d6\MigrateDrupal6TestBase;
|
||||
|
||||
/**
|
||||
* Upgrade variables to simpletest.settings.yml.
|
||||
*
|
||||
* @group migrate_drupal_6
|
||||
*/
|
||||
class MigrateSimpletestConfigsTest extends MigrateDrupal6TestBase {
|
||||
|
||||
use SchemaCheckTestTrait;
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(['simpletest']);
|
||||
$this->executeMigration('d6_simpletest_settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests migration of simpletest variables to simpletest.settings.yml.
|
||||
*/
|
||||
public function testSimpletestSettings() {
|
||||
$config = $this->config('simpletest.settings');
|
||||
$this->assertIdentical(TRUE, $config->get('clear_results'));
|
||||
$this->assertIdentical(CURLAUTH_BASIC, $config->get('httpauth.method'));
|
||||
// NULL in the dump means defaults which is empty string. Same as omitting
|
||||
// them.
|
||||
$this->assertIdentical('', $config->get('httpauth.password'));
|
||||
$this->assertIdentical('', $config->get('httpauth.username'));
|
||||
$this->assertIdentical(TRUE, $config->get('verbose'));
|
||||
$this->assertConfigSchema(\Drupal::service('config.typed'), 'simpletest.settings', $config->get());
|
||||
}
|
||||
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel\Migrate\d7;
|
||||
|
||||
use Drupal\Tests\migrate_drupal\Kernel\d7\MigrateDrupal7TestBase;
|
||||
|
||||
/**
|
||||
* Tests migration of SimpleTest's variables to configuration.
|
||||
*
|
||||
* @group simpletest
|
||||
*/
|
||||
class MigrateSimpletestSettingsTest extends MigrateDrupal7TestBase {
|
||||
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function setUp() {
|
||||
parent::setUp();
|
||||
$this->installConfig(static::$modules);
|
||||
$this->executeMigration('d7_simpletest_settings');
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests migration of SimpleTest settings to configuration.
|
||||
*/
|
||||
public function testMigration() {
|
||||
$config = \Drupal::config('simpletest.settings')->get();
|
||||
$this->assertTrue($config['clear_results']);
|
||||
$this->assertIdentical(CURLAUTH_BASIC, $config['httpauth']['method']);
|
||||
$this->assertIdentical('testbot', $config['httpauth']['username']);
|
||||
$this->assertIdentical('foobaz', $config['httpauth']['password']);
|
||||
$this->assertTrue($config['verbose']);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
|
||||
/**
|
||||
* Tests PHPUnit errors are getting converted to Simpletest errors.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class PhpUnitErrorTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* Enable the simpletest module.
|
||||
*
|
||||
* @var string[]
|
||||
*/
|
||||
protected static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* Test errors reported.
|
||||
*
|
||||
* @expectedDeprecation simpletest_phpunit_xml_to_rows is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::xmlToRows() instead. See https://www.drupal.org/node/2948547
|
||||
*/
|
||||
public function testPhpUnitXmlParsing() {
|
||||
$phpunit_error_xml = __DIR__ . '/../../fixtures/phpunit_error.xml';
|
||||
|
||||
$res = simpletest_phpunit_xml_to_rows(1, $phpunit_error_xml);
|
||||
$this->assertCount(4, $res, 'All testcases got extracted');
|
||||
$this->assertNotEquals($res[0]['status'], 'pass');
|
||||
$this->assertEquals($res[0]['status'], 'fail');
|
||||
|
||||
// Test nested testsuites, which appear when you use @dataProvider.
|
||||
for ($i = 0; $i < 3; $i++) {
|
||||
$this->assertNotEquals($res[$i + 1]['status'], 'pass');
|
||||
$this->assertEquals($res[$i + 1]['status'], 'fail');
|
||||
}
|
||||
|
||||
// Make sure simpletest_phpunit_xml_to_rows() does not balk if the test
|
||||
// didn't run.
|
||||
$this->assertNull(simpletest_phpunit_xml_to_rows(1, 'does_not_exist'));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
|
||||
/**
|
||||
* Verify deprecations within the simpletest module.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class SimpletestDeprecationTest extends KernelTestBase {
|
||||
|
||||
public static $modules = ['simpletest'];
|
||||
|
||||
/**
|
||||
* @expectedDeprecation The simpletest_phpunit_configuration_filepath function is deprecated since version 8.4.x and will be removed in 9.0.0.
|
||||
* @expectedDeprecation The simpletest_test_get_all function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service('test_discovery')->getTestClasses($extension, $types) instead.
|
||||
* @expectedDeprecation The simpletest_classloader_register function is deprecated in version 8.3.x and will be removed in 9.0.0. Use \Drupal::service('test_discovery')->registerTestNamespaces() instead.
|
||||
*/
|
||||
public function testDeprecatedFunctions() {
|
||||
$this->assertNotEmpty(simpletest_phpunit_configuration_filepath());
|
||||
$this->assertNotEmpty(simpletest_test_get_all());
|
||||
simpletest_classloader_register();
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation Drupal\simpletest\TestDiscovery is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDiscovery instead. See https://www.drupal.org/node/2949692
|
||||
* @expectedDeprecation The "test_discovery" service relies on the deprecated "Drupal\simpletest\TestDiscovery" class. It should either be deprecated or its implementation upgraded.
|
||||
*/
|
||||
public function testDeprecatedServices() {
|
||||
$this->assertInstanceOf(TestDiscovery::class, $this->container->get('test_discovery'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation simpletest_phpunit_xml_filepath is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead. See https://www.drupal.org/node/2948547
|
||||
* @expectedDeprecation simpletest_phpunit_command is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::phpUnitCommand() instead. See https://www.drupal.org/node/2948547
|
||||
* @expectedDeprecation simpletest_phpunit_find_testcases is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::findTestCases() instead. See https://www.drupal.org/node/2948547
|
||||
* @expectedDeprecation simpletest_phpunit_testcase_to_row is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\JUnitConverter::convertTestCaseToSimpletestRow() instead. See https://www.drupal.org/node/2948547
|
||||
* @expectedDeprecation simpletest_summarize_phpunit_result is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::summarizeResults() instead. See https://www.drupal.org/node/2948547
|
||||
*/
|
||||
public function testDeprecatedPhpUnitFunctions() {
|
||||
// We can't test the deprecation errors for the following functions because
|
||||
// they cannot be mocked, and calling them would change the test results:
|
||||
// - simpletest_run_phpunit_tests().
|
||||
// - simpletest_phpunit_run_command().
|
||||
// - simpletest_phpunit_xml_to_rows().
|
||||
$this->assertStringEndsWith('/phpunit-23.xml', simpletest_phpunit_xml_filepath(23));
|
||||
|
||||
$this->assertInternalType('string', simpletest_phpunit_command());
|
||||
|
||||
$this->assertEquals([], simpletest_phpunit_find_testcases(new \SimpleXMLElement('<not_testcase></not_testcase>')));
|
||||
|
||||
$this->assertEquals([
|
||||
'test_id' => 23,
|
||||
'test_class' => '',
|
||||
'status' => 'pass',
|
||||
'message' => '',
|
||||
'message_group' => 'Other',
|
||||
'function' => '->()',
|
||||
'line' => 0,
|
||||
'file' => NULL,
|
||||
], simpletest_phpunit_testcase_to_row(23, new \SimpleXMLElement('<not_testcase></not_testcase>')));
|
||||
|
||||
$this->assertEquals(
|
||||
[
|
||||
static::class => [
|
||||
'#pass' => 0,
|
||||
'#fail' => 0,
|
||||
'#exception' => 0,
|
||||
'#debug' => 1,
|
||||
],
|
||||
],
|
||||
simpletest_summarize_phpunit_result([
|
||||
[
|
||||
'test_class' => static::class,
|
||||
'status' => 'debug',
|
||||
],
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation simpletest_generate_file() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Tests\TestFileCreationTrait::generateFile() instead. See https://www.drupal.org/node/3077768
|
||||
*/
|
||||
public function testDeprecatedSimpletestGenerateFile() {
|
||||
$file = simpletest_generate_file('foo', 40, 10);
|
||||
$public_file = 'public://' . $file . '.txt';
|
||||
$this->assertFileExists($public_file);
|
||||
$this->assertTrue(unlink($public_file));
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation simpletest_process_phpunit_results() is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\TestDatabase::processPhpUnitResults() instead. See https://www.drupal.org/node/3075252
|
||||
*/
|
||||
public function testProcessPhpUnitResults() {
|
||||
// The only safe way to test this deprecation is to call it with an empty
|
||||
// result set. This should not touch the results database.
|
||||
$this->assertNull(simpletest_process_phpunit_results([]));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel;
|
||||
|
||||
use Drupal\Core\Database\Connection;
|
||||
use Drupal\Core\Database\Query\Insert;
|
||||
use Drupal\Core\Render\Renderer;
|
||||
use Drupal\Core\StreamWrapper\PublicStream;
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
use Drupal\simpletest\WebTestBase;
|
||||
|
||||
/**
|
||||
* Test the deprecation messages for Simpletest test hooks.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class TestDeprecatedTestHooks extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['simpletest', 'simpletest_deprecation_test'];
|
||||
|
||||
/**
|
||||
* @expectedDeprecation The deprecated hook hook_test_group_finished() is implemented in these functions: simpletest_deprecation_test_test_group_finished(). Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242
|
||||
*/
|
||||
public function testHookTestGroupFinished() {
|
||||
// @todo Mock the messenger service and add expectations when
|
||||
// \Drupal::messenger() actually uses the service.
|
||||
// @see https://www.drupal.org/node/2928994
|
||||
$this->assertNull(_simpletest_batch_finished(TRUE, [], [], 10));
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation The deprecated hook hook_test_group_started() is implemented in these functions: simpletest_deprecation_test_test_group_started(). Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242
|
||||
*/
|
||||
public function testHookTestGroupStarted() {
|
||||
// Mock a database connection enough for simpletest_run_tests().
|
||||
$insert = $this->getMockBuilder(Insert::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['execute', 'useDefaults'])
|
||||
->getMock();
|
||||
$insert->expects($this->any())
|
||||
->method('useDefaults')
|
||||
->willReturn($insert);
|
||||
$insert->expects($this->any())
|
||||
->method('execute')
|
||||
// Return an arbitrary test ID.
|
||||
->willReturn(__METHOD__);
|
||||
|
||||
$connection = $this->getMockBuilder(Connection::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['insert'])
|
||||
->getMockForAbstractClass();
|
||||
$connection->expects($this->once())
|
||||
->method('insert')
|
||||
->willReturn($insert);
|
||||
|
||||
// Mock public stream wrapper enough for simpletest_run_tests().
|
||||
$public = $this->getMockBuilder(PublicStream::class)
|
||||
->disableOriginalConstructor()
|
||||
// Mock all methods to do nothing and return NULL.
|
||||
->setMethods([])
|
||||
->getMock();
|
||||
|
||||
// Set up the container.
|
||||
$this->container->set('database', $connection);
|
||||
$this->container->set('stream_wrapper.public', $public);
|
||||
|
||||
// Make sure our mocked database is in use by expecting a test ID that is
|
||||
// __METHOD__.
|
||||
$this->assertEquals(__METHOD__, simpletest_run_tests([static::class]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @expectedDeprecation The deprecated hook hook_test_finished() is implemented in these functions: simpletest_deprecation_test_test_finished(). Convert your test to a PHPUnit-based one and implement test listeners. See https://www.drupal.org/node/2934242
|
||||
*/
|
||||
public function testHookTestFinished() {
|
||||
// Mock test_discovery.
|
||||
$discovery = $this->getMockBuilder(TestDiscovery::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['registerTestNamespaces'])
|
||||
->getMock();
|
||||
$discovery->expects($this->once())
|
||||
->method('registerTestNamespaces')
|
||||
->willReturn([]);
|
||||
|
||||
// Mock renderer.
|
||||
$renderer = $this->getMockBuilder(Renderer::class)
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['render'])
|
||||
->getMock();
|
||||
// We don't care what the rendered batch elements look like.
|
||||
$renderer->expects($this->any())
|
||||
->method('render')
|
||||
->willReturn('');
|
||||
|
||||
// Set up the container.
|
||||
$this->container->set('test_discovery', $discovery);
|
||||
$this->container->set('renderer', $renderer);
|
||||
|
||||
// A mock batch.
|
||||
$context = [];
|
||||
|
||||
// InnocuousTest is a WebTestBase test class which passes and never touches
|
||||
// the database.
|
||||
_simpletest_batch_operation([InnocuousTest::class], __METHOD__, $context);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A very simple WebTestBase test that never touches the database.
|
||||
*
|
||||
* @group WebTestBase
|
||||
* @group legacy
|
||||
*/
|
||||
class InnocuousTest extends WebTestBase {
|
||||
|
||||
/**
|
||||
* Override to prevent any environmental side-effects.
|
||||
*/
|
||||
protected function prepareEnvironment() {
|
||||
}
|
||||
|
||||
/**
|
||||
* Override run() since it uses TestBase.
|
||||
*/
|
||||
public function run(array $methods = []) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Override to prevent any assertions from being stored.
|
||||
*/
|
||||
protected function storeAssertion(array $assertion) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Override to prevent any assertions from being stored.
|
||||
*/
|
||||
public static function insertAssert($test_id, $test_class, $status, $message = '', $group = 'Other', array $caller = []) {
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Kernel;
|
||||
|
||||
use Drupal\KernelTests\KernelTestBase;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
|
||||
/**
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*
|
||||
* @coversDefaultClass \Drupal\simpletest\TestDiscovery
|
||||
*/
|
||||
class TestDiscoveryDeprecationTest extends KernelTestBase {
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public static $modules = ['simpletest', 'simpletest_deprecation_test'];
|
||||
|
||||
/**
|
||||
* @expectedDeprecation The deprecated alter hook hook_simpletest_alter() is implemented in these functions: simpletest_deprecation_test_simpletest_alter. Convert your test to a PHPUnit-based one and implement test listeners. See: https://www.drupal.org/node/2939892
|
||||
* @covers ::getTestClasses
|
||||
*/
|
||||
public function testHookSimpletestAlter() {
|
||||
$test_discovery = $this->container->get('test_discovery');
|
||||
|
||||
$this->assertEquals(TestDiscovery::class, get_class($test_discovery));
|
||||
|
||||
// The simpletest_test module implements hook_simpletest_alter(), which
|
||||
// should trigger a deprecation error during getTestClasses().
|
||||
$this->assertNotEmpty($test_discovery->getTestClasses());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Unit;
|
||||
|
||||
use Drupal\Core\Database\Database;
|
||||
use Drupal\Core\DependencyInjection\ContainerBuilder;
|
||||
use Drupal\Core\File\FileSystemInterface;
|
||||
use Drupal\Core\Test\PhpUnitTestRunner;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/**
|
||||
* Tests simpletest_run_phpunit_tests() handles PHPunit fatals correctly.
|
||||
*
|
||||
* We don't extend \Drupal\Tests\UnitTestCase here because its $root property is
|
||||
* not static and we need it to be static here.
|
||||
*
|
||||
* The file simpletest_phpunit_run_command_test.php contains the test class
|
||||
* \Drupal\Tests\simpletest\Unit\SimpletestPhpunitRunCommandTestWillDie which
|
||||
* can be made to exit with result code 2. It lives in a file which won't be
|
||||
* autoloaded, so that it won't fail test runs.
|
||||
*
|
||||
* Here, we run SimpletestPhpunitRunCommandTestWillDie, make it die, and see
|
||||
* what happens.
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*
|
||||
* @runTestsInSeparateProcesses
|
||||
* @preserveGlobalState disabled
|
||||
*/
|
||||
class SimpletestPhpunitRunCommandTest extends TestCase {
|
||||
|
||||
/**
|
||||
* Path to the app root.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected static $root;
|
||||
|
||||
/**
|
||||
* A fixture container.
|
||||
*
|
||||
* @var \Symfony\Component\DependencyInjection\ContainerInterface
|
||||
*/
|
||||
protected $fixtureContainer;
|
||||
|
||||
/**
|
||||
* {@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', 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);
|
||||
$this->fixtureContainer = $container;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* Also tests backwards-compatibility of PhpUnitTestRunner::runTests().
|
||||
*
|
||||
* @covers ::simpletest_run_phpunit_tests
|
||||
*
|
||||
* @dataProvider provideStatusCodes
|
||||
*
|
||||
* @expectedDeprecation simpletest_run_phpunit_tests is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::runTests() instead. See https://www.drupal.org/node/2948547
|
||||
* @expectedDeprecation simpletest_phpunit_xml_filepath is deprecated in drupal:8.8.0 and is removed from drupal:9.0.0. Use \Drupal\Core\Test\PhpUnitTestRunner::xmlLogFilepath() instead. See https://www.drupal.org/node/2948547
|
||||
*/
|
||||
public function testSimpletestPhpUnitRunCommand($status, $label) {
|
||||
// Add a default database connection in order for
|
||||
// Database::getConnectionInfoAsUrl() to return valid information.
|
||||
Database::addConnectionInfo('default', 'default', [
|
||||
'driver' => 'mysql',
|
||||
'username' => 'test_user',
|
||||
'password' => 'test_pass',
|
||||
'host' => 'test_host',
|
||||
'database' => 'test_database',
|
||||
'port' => 3306,
|
||||
'namespace' => 'Drupal\Core\Database\Driver\mysql',
|
||||
]
|
||||
);
|
||||
$test_id = basename(tempnam(sys_get_temp_dir(), 'xxx'));
|
||||
putenv('SimpletestPhpunitRunCommandTestWillDie=' . $status);
|
||||
|
||||
// Test against simpletest_run_phpunit_tests().
|
||||
$bc_ret = simpletest_run_phpunit_tests($test_id, [SimpletestPhpunitRunCommandTestWillDie::class]);
|
||||
$this->assertSame($bc_ret[0]['status'], $label);
|
||||
|
||||
// Test against PhpUnitTestRunner::runTests().
|
||||
$runner = PhpUnitTestRunner::create($this->fixtureContainer);
|
||||
$ret = $runner->runTests($test_id, [SimpletestPhpunitRunCommandTestWillDie::class]);
|
||||
$this->assertSame($ret[0]['status'], $label);
|
||||
|
||||
// Unset our environmental variable.
|
||||
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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Unit;
|
||||
|
||||
use Drupal\Tests\Listeners\SimpletestUiPrinter;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\Tests\Listeners\SimpletestUiPrinter
|
||||
*
|
||||
* @group simpletest
|
||||
*/
|
||||
class SimpletestUiPrinterTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Data provider for testWrite().
|
||||
*
|
||||
* @return string[]
|
||||
* Array of data for testWrite().
|
||||
* - Expected output from SimpletestUiPrinter->write().
|
||||
* - Buffer to pass into SimpletestUiPrinter->write().
|
||||
*/
|
||||
public function provideBuffer() {
|
||||
return [
|
||||
['&"'<>', '&"\'<>'],
|
||||
['<a href="http:////www.example.com" target="_blank" title="http:////www.example.com">http:////www.example.com</a>', 'http:////www.example.com'],
|
||||
['this is some text <a href="http://www.example.com/" target="_blank" title="http://www.example.com/">http://www.example.com/</a> with a link in it.', 'this is some text http://www.example.com/ with a link in it.'],
|
||||
["HTML output was generated<br />\n", "HTML output was generated\n"],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::write
|
||||
*
|
||||
* @dataProvider provideBuffer
|
||||
*/
|
||||
public function testWrite($expected, $buffer) {
|
||||
$printer = new SimpletestUiPrinter();
|
||||
// Set up our expectation.
|
||||
$this->expectOutputString($expected);
|
||||
// Write the buffer.
|
||||
$printer->write($buffer);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Unit;
|
||||
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* @requires extension curl
|
||||
* @coversDefaultClass \Drupal\simpletest\TestBase
|
||||
* @group simpletest
|
||||
* @group TestBase
|
||||
*/
|
||||
class TestBaseTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Helper method for constructing a mock TestBase object.
|
||||
*
|
||||
* TestBase is abstract, so we have to mock it. We'll also
|
||||
* mock the storeAssertion() method so we don't need the database.
|
||||
*
|
||||
* @param string $test_id
|
||||
* An identifying name for the mocked test.
|
||||
*
|
||||
* @return object
|
||||
* Mock of Drupal\simpletest\TestBase.
|
||||
*/
|
||||
public function getTestBaseForAssertionTests($test_id) {
|
||||
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
|
||||
->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));
|
||||
return $mock_test_base;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke methods that are protected or private.
|
||||
*
|
||||
* @param object $object
|
||||
* Object on which to invoke the method.
|
||||
* @param string $method_name
|
||||
* Name of the method to invoke.
|
||||
* @param array $arguments
|
||||
* Array of arguments to be passed to the method.
|
||||
*
|
||||
* @return mixed
|
||||
* Value returned by the invoked method.
|
||||
*/
|
||||
public function invokeProtectedMethod($object, $method_name, array $arguments) {
|
||||
$ref_method = new \ReflectionMethod($object, $method_name);
|
||||
$ref_method->setAccessible(TRUE);
|
||||
return $ref_method->invokeArgs($object, $arguments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides data for the random string validation test.
|
||||
*
|
||||
* @return array
|
||||
* - The expected result of the validation.
|
||||
* - The string to validate.
|
||||
*/
|
||||
public function providerRandomStringValidate() {
|
||||
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'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::randomStringValidate
|
||||
* @dataProvider providerRandomStringValidate
|
||||
*/
|
||||
public function testRandomStringValidate($expected, $string) {
|
||||
$mock_test_base = $this->getMockForAbstractClass('Drupal\simpletest\TestBase');
|
||||
$actual = $mock_test_base->randomStringValidate($string);
|
||||
$this->assertEquals($expected, $actual);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides data for testRandomString() and others.
|
||||
*
|
||||
* @return array
|
||||
* - The number of items (characters, object properties) we expect any of
|
||||
* the random functions to give us.
|
||||
*/
|
||||
public function providerRandomItems() {
|
||||
return [
|
||||
[NULL],
|
||||
[0],
|
||||
[1],
|
||||
[2],
|
||||
[3],
|
||||
[4],
|
||||
[7],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::randomString
|
||||
* @dataProvider providerRandomItems
|
||||
*/
|
||||
public function testRandomString($length) {
|
||||
$mock_test_base = $this->getMockForAbstractClass('Drupal\simpletest\TestBase');
|
||||
$string = $mock_test_base->randomString($length);
|
||||
$this->assertEquals($length, strlen($string));
|
||||
// randomString() should always include an ampersand ('&') and a
|
||||
// greater than ('>') if $length is greater than 3.
|
||||
if ($length > 4) {
|
||||
$this->assertContains('&', $string);
|
||||
$this->assertContains('>', $string);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::randomObject
|
||||
* @dataProvider providerRandomItems
|
||||
*/
|
||||
public function testRandomObject($size) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
// Note: count((array)object) works for now, maybe not later.
|
||||
$this->assertEquals($size, count((array) $test_base->randomObject($size)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::checkRequirements
|
||||
*/
|
||||
public function testCheckRequirements() {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertInternalType(
|
||||
'array',
|
||||
$this->invokeProtectedMethod($test_base, 'checkRequirements', [])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testAssert().
|
||||
*
|
||||
* @return array
|
||||
* Standard dataProvider array of arrays:
|
||||
* - Expected result from assert().
|
||||
* - Expected status stored in TestBase->assertions.
|
||||
* - Status, passed to assert().
|
||||
* - Message, passed to assert().
|
||||
* - Group, passed to assert().
|
||||
* - Caller, passed to assert().
|
||||
*/
|
||||
public function providerAssert() {
|
||||
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', []],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assert
|
||||
* @dataProvider providerAssert
|
||||
*/
|
||||
public function testAssert($expected, $assertion_status, $status, $message, $group, $caller) {
|
||||
$test_id = 'luke_i_am_your_' . $assertion_status;
|
||||
$test_base = $this->getTestBaseForAssertionTests($test_id);
|
||||
|
||||
// Verify some startup values.
|
||||
$this->assertAttributeEmpty('assertions', $test_base);
|
||||
if (is_string($status)) {
|
||||
$this->assertEquals(0, $test_base->results['#' . $status]);
|
||||
}
|
||||
|
||||
// assert() is protected so we have to make it accessible.
|
||||
$ref_assert = new \ReflectionMethod($test_base, 'assert');
|
||||
$ref_assert->setAccessible(TRUE);
|
||||
|
||||
// Call assert() from within our hall of mirrors.
|
||||
$this->assertEquals(
|
||||
$expected,
|
||||
$ref_assert->invokeArgs($test_base,
|
||||
[$status, $message, $group, $caller]
|
||||
)
|
||||
);
|
||||
|
||||
// Check the side-effects of assert().
|
||||
if (is_string($status)) {
|
||||
$this->assertEquals(1, $test_base->results['#' . $status]);
|
||||
}
|
||||
$this->assertAttributeNotEmpty('assertions', $test_base);
|
||||
// Make a ReflectionProperty for the assertions property,
|
||||
// since it's protected.
|
||||
$ref_assertions = new \ReflectionProperty($test_base, 'assertions');
|
||||
$ref_assertions->setAccessible(TRUE);
|
||||
$assertions = $ref_assertions->getValue($test_base);
|
||||
$assertion = reset($assertions);
|
||||
$this->assertEquals($assertion_status, $assertion['status']);
|
||||
$this->assertEquals($test_id, $assertion['test_id']);
|
||||
$this->assertEquals(get_class($test_base), $assertion['test_class']);
|
||||
$this->assertEquals($message, $assertion['message']);
|
||||
$this->assertEquals($group, $assertion['message_group']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for assertTrue().
|
||||
*/
|
||||
public function providerAssertTrue() {
|
||||
return [
|
||||
[TRUE, TRUE],
|
||||
[FALSE, FALSE],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertTrue
|
||||
* @dataProvider providerAssertTrue
|
||||
*/
|
||||
public function testAssertTrue($expected, $value) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
$expected,
|
||||
$this->invokeProtectedMethod($test_base, 'assertTrue', [$value])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertFalse
|
||||
* @dataProvider providerAssertTrue
|
||||
*/
|
||||
public function testAssertFalse($expected, $value) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
(!$expected),
|
||||
$this->invokeProtectedMethod($test_base, 'assertFalse', [$value])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for assertNull().
|
||||
*/
|
||||
public function providerAssertNull() {
|
||||
return [
|
||||
[TRUE, NULL],
|
||||
[FALSE, ''],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertNull
|
||||
* @dataProvider providerAssertNull
|
||||
*/
|
||||
public function testAssertNull($expected, $value) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
$expected,
|
||||
$this->invokeProtectedMethod($test_base, 'assertNull', [$value])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertNotNull
|
||||
* @dataProvider providerAssertNull
|
||||
*/
|
||||
public function testAssertNotNull($expected, $value) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
(!$expected),
|
||||
$this->invokeProtectedMethod($test_base, 'assertNotNull', [$value])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for tests of equality assertions.
|
||||
*
|
||||
* Used by testAssertIdentical(), testAssertEqual(), testAssertNotIdentical(),
|
||||
* and testAssertNotEqual().
|
||||
*
|
||||
* @return
|
||||
* Array of test data.
|
||||
* - Expected assertion value for identical comparison.
|
||||
* - Expected assertion value for equal comparison.
|
||||
* - First value to compare.
|
||||
* - Second value to compare.
|
||||
*/
|
||||
public function providerEqualityAssertions() {
|
||||
return [
|
||||
// Integers and floats.
|
||||
[TRUE, TRUE, 0, 0],
|
||||
[FALSE, TRUE, 0, 0.0],
|
||||
[FALSE, TRUE, '0', 0],
|
||||
[FALSE, TRUE, '0.0', 0.0],
|
||||
[FALSE, FALSE, 23, 77],
|
||||
[TRUE, TRUE, 23.0, 23.0],
|
||||
// Strings.
|
||||
[FALSE, FALSE, 'foof', 'yay'],
|
||||
[TRUE, TRUE, 'yay', 'yay'],
|
||||
// Bools with type conversion.
|
||||
[TRUE, TRUE, TRUE, TRUE],
|
||||
[TRUE, TRUE, FALSE, FALSE],
|
||||
[FALSE, TRUE, NULL, FALSE],
|
||||
[FALSE, TRUE, 'TRUE', TRUE],
|
||||
[FALSE, FALSE, 'FALSE', FALSE],
|
||||
[FALSE, TRUE, 0, FALSE],
|
||||
[FALSE, TRUE, 1, TRUE],
|
||||
[FALSE, TRUE, -1, TRUE],
|
||||
[FALSE, TRUE, '1', TRUE],
|
||||
[FALSE, TRUE, '1.3', TRUE],
|
||||
// Null.
|
||||
[FALSE, FALSE, 'NULL', NULL],
|
||||
[TRUE, TRUE, NULL, NULL],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertIdentical
|
||||
* @dataProvider providerEqualityAssertions
|
||||
*/
|
||||
public function testAssertIdentical($expected_identical, $expected_equal, $first, $second) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
$expected_identical,
|
||||
$this->invokeProtectedMethod($test_base, 'assertIdentical', [$first, $second])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertNotIdentical
|
||||
* @dataProvider providerEqualityAssertions
|
||||
*/
|
||||
public function testAssertNotIdentical($expected_identical, $expected_equal, $first, $second) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
(!$expected_identical),
|
||||
$this->invokeProtectedMethod($test_base, 'assertNotIdentical', [$first, $second])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertEqual
|
||||
* @dataProvider providerEqualityAssertions
|
||||
*/
|
||||
public function testAssertEqual($expected_identical, $expected_equal, $first, $second) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
$expected_equal,
|
||||
$this->invokeProtectedMethod($test_base, 'assertEqual', [$first, $second])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertNotEqual
|
||||
* @dataProvider providerEqualityAssertions
|
||||
*/
|
||||
public function testAssertNotEqual($expected_identical, $expected_equal, $first, $second) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
(!$expected_equal),
|
||||
$this->invokeProtectedMethod($test_base, 'assertNotEqual', [$first, $second])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testAssertIdenticalObject().
|
||||
*/
|
||||
public function providerAssertIdenticalObject() {
|
||||
$obj1 = new \stdClass();
|
||||
$obj1->foof = 'yay';
|
||||
$obj2 = $obj1;
|
||||
$obj3 = clone $obj1;
|
||||
$obj4 = new \stdClass();
|
||||
return [
|
||||
[TRUE, $obj1, $obj2],
|
||||
[TRUE, $obj1, $obj3],
|
||||
[FALSE, $obj1, $obj4],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::assertIdenticalObject
|
||||
* @dataProvider providerAssertIdenticalObject
|
||||
*/
|
||||
public function testAssertIdenticalObject($expected, $first, $second) {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
$expected,
|
||||
$this->invokeProtectedMethod($test_base, 'assertIdenticalObject', [$first, $second])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::pass
|
||||
*/
|
||||
public function testPass() {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
TRUE,
|
||||
$this->invokeProtectedMethod($test_base, 'pass', [])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::fail
|
||||
*/
|
||||
public function testFail() {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertEquals(
|
||||
FALSE,
|
||||
$this->invokeProtectedMethod($test_base, 'fail', [])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testError().
|
||||
*
|
||||
* @return array
|
||||
* - Expected status for assertion.
|
||||
* - Group for use in assert().
|
||||
*/
|
||||
public function providerError() {
|
||||
return [
|
||||
['debug', 'User notice'],
|
||||
['exception', 'Not User notice'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::error
|
||||
* @dataProvider providerError
|
||||
*/
|
||||
public function testError($status, $group) {
|
||||
// Mock up a TestBase object.
|
||||
$mock_test_base = $this->getMockBuilder('Drupal\simpletest\TestBase')
|
||||
->setMethods(['assert'])
|
||||
->getMockForAbstractClass();
|
||||
|
||||
// Set expectations for assert().
|
||||
$mock_test_base->expects($this->once())
|
||||
->method('assert')
|
||||
// The first argument to assert() should be the expected $status. This is
|
||||
// the most important expectation of this test.
|
||||
->with($status)
|
||||
// Arbitrary return value.
|
||||
->willReturn("$status:$group");
|
||||
|
||||
// Invoke error().
|
||||
$this->assertEquals(
|
||||
"$status:$group",
|
||||
$this->invokeProtectedMethod($mock_test_base, 'error', ['msg', $group])
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getRandomGenerator
|
||||
*/
|
||||
public function testGetRandomGenerator() {
|
||||
$test_base = $this->getTestBaseForAssertionTests('test_id');
|
||||
$this->assertInstanceOf(
|
||||
'Drupal\Component\Utility\Random',
|
||||
$this->invokeProtectedMethod($test_base, 'getRandomGenerator', [])
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Unit;
|
||||
|
||||
use Composer\Autoload\ClassLoader;
|
||||
use Drupal\Core\DependencyInjection\Container;
|
||||
use Drupal\Core\DrupalKernel;
|
||||
use Drupal\Core\Extension\Extension;
|
||||
use Drupal\Core\Extension\ModuleHandlerInterface;
|
||||
use Drupal\simpletest\TestDiscovery;
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
use org\bovigo\vfs\vfsStream;
|
||||
|
||||
/**
|
||||
* @coversDefaultClass \Drupal\simpletest\TestDiscovery
|
||||
*
|
||||
* @group simpletest
|
||||
* @group legacy
|
||||
*/
|
||||
class TestDiscoveryTest extends UnitTestCase {
|
||||
|
||||
protected function setupVfsWithTestClasses() {
|
||||
vfsStream::setup('drupal');
|
||||
|
||||
$test_file = <<<EOF
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Test description
|
||||
* @group example
|
||||
*/
|
||||
class FunctionalExampleTest {}
|
||||
EOF;
|
||||
|
||||
$test_profile_info = <<<EOF
|
||||
name: Testing
|
||||
type: profile
|
||||
core: 8.x
|
||||
EOF;
|
||||
|
||||
$test_module_info = <<<EOF
|
||||
name: Testing
|
||||
type: module
|
||||
core: 8.x
|
||||
EOF;
|
||||
|
||||
vfsStream::create([
|
||||
'modules' => [
|
||||
'test_module' => [
|
||||
'test_module.info.yml' => $test_module_info,
|
||||
'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\n * @group kernel\n"], $test_file),
|
||||
'KernelExampleTestBase.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleTestBase', '@group example2'], $test_file),
|
||||
'KernelExampleTrait.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleTrait', '@group example2'], $test_file),
|
||||
'KernelExampleInterface.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleInterface', '@group example2'], $test_file),
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'profiles' => [
|
||||
'test_profile' => [
|
||||
'test_profile.info.yml' => $test_profile_info,
|
||||
'modules' => [
|
||||
'test_profile_module' => [
|
||||
'test_profile_module.info.yml' => $test_module_info,
|
||||
'tests' => [
|
||||
'src' => [
|
||||
'Kernel' => [
|
||||
'KernelExampleTest4.php' => str_replace(['FunctionalExampleTest', '@group example'], ['KernelExampleTest4', '@group example3'], $test_file),
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock a TestDiscovery object to return specific extension values.
|
||||
*/
|
||||
protected function getTestDiscoveryMock($app_root, $extensions) {
|
||||
$class_loader = $this->prophesize(ClassLoader::class);
|
||||
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
|
||||
|
||||
$test_discovery = $this->getMockBuilder(TestDiscovery::class)
|
||||
->setConstructorArgs([$app_root, $class_loader->reveal(), $module_handler->reveal()])
|
||||
->setMethods(['getExtensions'])
|
||||
->getMock();
|
||||
|
||||
$test_discovery->expects($this->any())
|
||||
->method('getExtensions')
|
||||
->willReturn($extensions);
|
||||
|
||||
return $test_discovery;
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getTestClasses
|
||||
*/
|
||||
public function testGetTestClasses() {
|
||||
$this->setupVfsWithTestClasses();
|
||||
$extensions = [
|
||||
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
|
||||
];
|
||||
$test_discovery = $this->getTestDiscoveryMock('vfs://drupal', $extensions);
|
||||
|
||||
$result = $test_discovery->getTestClasses();
|
||||
$this->assertCount(3, $result);
|
||||
$this->assertEquals([
|
||||
'example' => [
|
||||
'Drupal\Tests\test_module\Functional\FunctionalExampleTest' => [
|
||||
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example',
|
||||
'groups' => ['example'],
|
||||
'type' => 'PHPUnit-Functional',
|
||||
],
|
||||
],
|
||||
'example2' => [
|
||||
'Drupal\Tests\test_module\Functional\FunctionalExampleTest2' => [
|
||||
'name' => 'Drupal\Tests\test_module\Functional\FunctionalExampleTest2',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example2',
|
||||
'groups' => ['example2'],
|
||||
'type' => 'PHPUnit-Functional',
|
||||
],
|
||||
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
|
||||
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example2',
|
||||
'groups' => ['example2', 'kernel'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
'kernel' => [
|
||||
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
|
||||
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example2',
|
||||
'groups' => ['example2', 'kernel'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
], $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getTestClasses
|
||||
*/
|
||||
public function testGetTestClassesWithSelectedTypes() {
|
||||
$this->setupVfsWithTestClasses();
|
||||
$extensions = [
|
||||
'test_module' => new Extension('vfs://drupal', 'module', 'modules/test_module/test_module.info.yml'),
|
||||
'test_profile_module' => new Extension('vfs://drupal', 'profile', 'profiles/test_profile/modules/test_profile_module/test_profile_module.info.yml'),
|
||||
];
|
||||
$test_discovery = $this->getTestDiscoveryMock('vfs://drupal', $extensions);
|
||||
|
||||
$result = $test_discovery->getTestClasses(NULL, ['PHPUnit-Kernel']);
|
||||
$this->assertCount(4, $result);
|
||||
$this->assertEquals([
|
||||
'example' => [],
|
||||
'example2' => [
|
||||
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
|
||||
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example2',
|
||||
'groups' => ['example2', 'kernel'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
'kernel' => [
|
||||
'Drupal\Tests\test_module\Kernel\KernelExampleTest3' => [
|
||||
'name' => 'Drupal\Tests\test_module\Kernel\KernelExampleTest3',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example2',
|
||||
'groups' => ['example2', 'kernel'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
'example3' => [
|
||||
'Drupal\Tests\test_profile_module\Kernel\KernelExampleTest4' => [
|
||||
'name' => 'Drupal\Tests\test_profile_module\Kernel\KernelExampleTest4',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example3',
|
||||
'groups' => ['example3'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
], $result);
|
||||
}
|
||||
|
||||
/**
|
||||
* @covers ::getTestClasses
|
||||
*/
|
||||
public function testGetTestsInProfiles() {
|
||||
$this->setupVfsWithTestClasses();
|
||||
$class_loader = $this->prophesize(ClassLoader::class);
|
||||
$module_handler = $this->prophesize(ModuleHandlerInterface::class);
|
||||
|
||||
$container = new Container();
|
||||
$container->set('kernel', new DrupalKernel('prod', new ClassLoader()));
|
||||
$container->set('site.path', 'sites/default');
|
||||
\Drupal::setContainer($container);
|
||||
|
||||
$test_discovery = new TestDiscovery('vfs://drupal', $class_loader->reveal(), $module_handler->reveal());
|
||||
|
||||
$result = $test_discovery->getTestClasses('test_profile_module', ['PHPUnit-Kernel']);
|
||||
$expected = [
|
||||
'example3' => [
|
||||
'Drupal\Tests\test_profile_module\Kernel\KernelExampleTest4' => [
|
||||
'name' => 'Drupal\Tests\test_profile_module\Kernel\KernelExampleTest4',
|
||||
'description' => 'Test description',
|
||||
'group' => 'example3',
|
||||
'groups' => ['example3'],
|
||||
'type' => 'PHPUnit-Kernel',
|
||||
],
|
||||
],
|
||||
];
|
||||
$this->assertEquals($expected, $result);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
<?php
|
||||
|
||||
namespace Drupal\Tests\simpletest\Unit;
|
||||
|
||||
use Drupal\Tests\UnitTestCase;
|
||||
|
||||
/**
|
||||
* @requires extension curl
|
||||
* @coversDefaultClass \Drupal\simpletest\WebTestBase
|
||||
* @group simpletest
|
||||
* @group WebTestBase
|
||||
*/
|
||||
class WebTestBaseTest extends UnitTestCase {
|
||||
|
||||
/**
|
||||
* Provides data for testing the assertFieldByName() helper.
|
||||
*
|
||||
* @return array
|
||||
* An array of values passed to the test method.
|
||||
*/
|
||||
public function providerAssertFieldByName() {
|
||||
$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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tests the assertFieldByName() helper.
|
||||
*
|
||||
* @param string $filename
|
||||
* Name of file containing the output to test.
|
||||
* @param string $name
|
||||
* Name of field to assert.
|
||||
* @param string $value
|
||||
* Value of the field to assert.
|
||||
* @param bool $expected
|
||||
* The expected result of the assert.
|
||||
*
|
||||
* @see \Drupal\simpletest\WebTestBase::assertFieldByName()
|
||||
*
|
||||
* @dataProvider providerAssertFieldByName
|
||||
* @covers ::assertFieldByName
|
||||
*/
|
||||
public function testAssertFieldByName($filename, $name, $value, $expected) {
|
||||
$content = file_get_contents(__DIR__ . '/../../fixtures/' . $filename . '.html');
|
||||
|
||||
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['getRawContent', 'assertTrue', 'pass'])
|
||||
->getMock();
|
||||
|
||||
$web_test->expects($this->any())
|
||||
->method('getRawContent')
|
||||
->will($this->returnValue($content));
|
||||
|
||||
$web_test->expects($this->once())
|
||||
->method('assertTrue')
|
||||
->with($this->identicalTo($expected),
|
||||
$this->identicalTo('message'),
|
||||
$this->identicalTo('Browser'));
|
||||
|
||||
$test_method = new \ReflectionMethod('Drupal\simpletest\WebTestBase', 'assertFieldByName');
|
||||
$test_method->setAccessible(TRUE);
|
||||
$test_method->invokeArgs($web_test, [$name, $value, 'message']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Data provider for testClickLink().
|
||||
*
|
||||
* In the test method, we mock drupalGet() to return a known string:
|
||||
* 'This Text Returned By drupalGet()'. Since clickLink() can only return
|
||||
* either the value of drupalGet() or FALSE, our expected return value is the
|
||||
* same as this mocked return value when we expect a link to be found.
|
||||
*
|
||||
* @see https://www.drupal.org/node/1452896
|
||||
*
|
||||
* @return array
|
||||
* Array of arrays of test data. Test data is structured as follows:
|
||||
* - Expected return value of clickLink().
|
||||
* - Parameter $label to clickLink().
|
||||
* - Parameter $index to clickLink().
|
||||
* - Test data to be returned by mocked xpath(). Return an empty array here
|
||||
* to mock no link found on the page.
|
||||
*/
|
||||
public function providerTestClickLink() {
|
||||
return [
|
||||
// Test for a non-existent label.
|
||||
[
|
||||
FALSE,
|
||||
'does_not_exist',
|
||||
0,
|
||||
[],
|
||||
],
|
||||
// Test for an existing label.
|
||||
[
|
||||
'This Text Returned By drupalGet()',
|
||||
'exists',
|
||||
0,
|
||||
[0 => ['href' => 'this_is_a_url']],
|
||||
],
|
||||
// Test for an existing label that isn't the first one.
|
||||
[
|
||||
'This Text Returned By drupalGet()',
|
||||
'exists',
|
||||
1,
|
||||
[
|
||||
0 => ['href' => 'this_is_a_url'],
|
||||
1 => ['href' => 'this_is_another_url'],
|
||||
],
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Test WebTestBase::clickLink().
|
||||
*
|
||||
* @param mixed $expected
|
||||
* Expected return value of clickLink().
|
||||
* @param string $label
|
||||
* Parameter $label to clickLink().
|
||||
* @param int $index
|
||||
* Parameter $index to clickLink().
|
||||
* @param array $xpath_data
|
||||
* Test data to be returned by mocked xpath().
|
||||
*
|
||||
* @dataProvider providerTestClickLink
|
||||
* @covers ::clickLink
|
||||
*/
|
||||
public function testClickLink($expected, $label, $index, $xpath_data) {
|
||||
// Mock a WebTestBase object and some of its methods.
|
||||
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
|
||||
->disableOriginalConstructor()
|
||||
->setMethods([
|
||||
'pass',
|
||||
'fail',
|
||||
'getUrl',
|
||||
'xpath',
|
||||
'drupalGet',
|
||||
'getAbsoluteUrl',
|
||||
])
|
||||
->getMock();
|
||||
|
||||
// Mocked getUrl() is only used for reporting so we just return a string.
|
||||
$web_test->expects($this->any())
|
||||
->method('getUrl')
|
||||
->will($this->returnValue('url_before'));
|
||||
|
||||
// Mocked xpath() should return our test data.
|
||||
$web_test->expects($this->any())
|
||||
->method('xpath')
|
||||
->will($this->returnValue($xpath_data));
|
||||
|
||||
if ($expected === FALSE) {
|
||||
// If link does not exist clickLink() will not try to do a drupalGet() or
|
||||
// a getAbsoluteUrl()
|
||||
$web_test->expects($this->never())
|
||||
->method('drupalGet');
|
||||
$web_test->expects($this->never())
|
||||
->method('getAbsoluteUrl');
|
||||
// The test should fail and not pass.
|
||||
$web_test->expects($this->never())
|
||||
->method('pass');
|
||||
$web_test->expects($this->once())
|
||||
->method('fail')
|
||||
->will($this->returnValue(NULL));
|
||||
}
|
||||
else {
|
||||
// Mocked getAbsoluteUrl() should return whatever comes in.
|
||||
$web_test->expects($this->once())
|
||||
->method('getAbsoluteUrl')
|
||||
->with($xpath_data[$index]['href'])
|
||||
->will($this->returnArgument(0));
|
||||
// We're only testing clickLink(), so drupalGet() always returns a string.
|
||||
$web_test->expects($this->once())
|
||||
->method('drupalGet')
|
||||
->with($xpath_data[$index]['href'])
|
||||
->will($this->returnValue('This Text Returned By drupalGet()'));
|
||||
// The test should pass and not fail.
|
||||
$web_test->expects($this->never())
|
||||
->method('fail');
|
||||
$web_test->expects($this->once())
|
||||
->method('pass')
|
||||
->will($this->returnValue(NULL));
|
||||
}
|
||||
|
||||
// Set the clickLink() method to public so we can test it.
|
||||
$clicklink_method = new \ReflectionMethod($web_test, 'clickLink');
|
||||
$clicklink_method->setAccessible(TRUE);
|
||||
|
||||
$this->assertSame($expected, $clicklink_method->invoke($web_test, $label, $index));
|
||||
}
|
||||
|
||||
/**
|
||||
* @dataProvider providerTestGetAbsoluteUrl
|
||||
*/
|
||||
public function testGetAbsoluteUrl($href, $expected_absolute_path) {
|
||||
$web_test = $this->getMockBuilder('Drupal\simpletest\WebTestBase')
|
||||
->disableOriginalConstructor()
|
||||
->setMethods(['getUrl'])
|
||||
->getMock();
|
||||
|
||||
$web_test->expects($this->any())
|
||||
->method('getUrl')
|
||||
->willReturn('http://example.com/drupal/current-path?foo=baz');
|
||||
|
||||
$GLOBALS['base_url'] = 'http://example.com';
|
||||
$GLOBALS['base_path'] = 'drupal';
|
||||
|
||||
$get_absolute_url_method = new \ReflectionMethod($web_test, 'getAbsoluteUrl');
|
||||
$get_absolute_url_method->setAccessible(TRUE);
|
||||
|
||||
$this->assertSame($expected_absolute_path, $get_absolute_url_method->invoke($web_test, $href));
|
||||
unset($GLOBALS['base_url'], $GLOBALS['base_path']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provides test data for testGetAbsoluteUrl.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function providerTestGetAbsoluteUrl() {
|
||||
$data = [];
|
||||
$data['host'] = ['http://example.com/drupal/test-example', 'http://example.com/drupal/test-example'];
|
||||
$data['path'] = ['/drupal/test-example', 'http://example.com/drupal/test-example'];
|
||||
$data['path-with-query'] = ['/drupal/test-example?foo=bar', 'http://example.com/drupal/test-example?foo=bar'];
|
||||
$data['just-query'] = ['?foo=bar', 'http://example.com/drupal/current-path?foo=bar'];
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user