first commit

This commit is contained in:
2020-06-08 23:57:36 +02:00
commit 6277454f7a
16057 changed files with 1715382 additions and 0 deletions
@@ -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' => '&nbsp;',
'#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 &amp; 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