Unverified Commit 9409fb9d authored by alexpott's avatar alexpott

Issue #2973227 by jibran, benjy, alexpott, Mile23, Sam152, vaplas, larowlan:...

Issue #2973227 by jibran, benjy, alexpott, Mile23, Sam152, vaplas, larowlan: Move UI helper functions from BTB into the traits
parent c7afa35f
......@@ -4,7 +4,6 @@
use Drupal\Component\FileCache\FileCacheFactory;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Config\Development\ConfigSchemaChecker;
use Drupal\Core\Database\Database;
use Drupal\Core\DrupalKernel;
......@@ -13,6 +12,7 @@
use Drupal\Core\Session\UserSession;
use Drupal\Core\Site\Settings;
use Drupal\Core\StreamWrapper\StreamWrapperInterface;
use Drupal\Tests\SessionTestTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Yaml\Yaml as SymfonyYaml;
......@@ -22,6 +22,9 @@
*/
trait FunctionalTestSetupTrait {
use SessionTestTrait;
use RefreshVariablesTrait;
/**
* The "#1" admin user.
*
......@@ -219,32 +222,6 @@ protected function resetAll() {
$this->refreshVariables();
}
/**
* Refreshes in-memory configuration and state information.
*
* Useful after a page request is made that changes configuration or state in
* a different thread.
*
* In other words calling a settings page with $this->drupalPostForm() with a
* changed value would update configuration to reflect that change, but in the
* thread that made the call (thread running the test) the changed values
* would not be picked up.
*
* This method clears the cache and loads a fresh copy.
*/
protected function refreshVariables() {
// Clear the tag cache.
\Drupal::service('cache_tags.invalidator')->resetChecksums();
foreach (Cache::getBins() as $backend) {
if (is_callable([$backend, 'reset'])) {
$backend->reset();
}
}
$this->container->get('config.factory')->reset();
$this->container->get('state')->resetCache();
}
/**
* Creates a mock request and sets it on the generator.
*
......
<?php
namespace Drupal\Core\Test;
use Drupal\Core\Cache\Cache;
/**
* Provides a method to refresh in-memory configuration and state information.
*/
trait RefreshVariablesTrait {
/**
* Refreshes in-memory configuration and state information.
*
* Useful after a page request is made that changes configuration or state in
* a different thread.
*
* In other words calling a settings page with $this->drupalPostForm() with a
* changed value would update configuration to reflect that change, but in the
* thread that made the call (thread running the test) the changed values
* would not be picked up.
*
* This method clears the cache and loads a fresh copy.
*/
protected function refreshVariables() {
// Clear the tag cache.
\Drupal::service('cache_tags.invalidator')->resetChecksums();
foreach (Cache::getBins() as $backend) {
if (is_callable([$backend, 'reset'])) {
$backend->reset();
}
}
\Drupal::service('config.factory')->reset();
\Drupal::service('state')->resetCache();
}
}
......@@ -15,7 +15,6 @@
use Drupal\Tests\AssertHelperTrait as BaseAssertHelperTrait;
use Drupal\Tests\ConfigTestTrait;
use Drupal\Tests\RandomGeneratorTrait;
use Drupal\Tests\SessionTestTrait;
use Drupal\Tests\Traits\Core\GeneratePermutationsTrait;
/**
......@@ -27,7 +26,6 @@ abstract class TestBase {
use BaseAssertHelperTrait;
use TestSetupTrait;
use SessionTestTrait;
use RandomGeneratorTrait;
use GeneratePermutationsTrait;
// For backwards compatibility switch the visbility of the methods to public.
......
......@@ -8,7 +8,6 @@
use Drupal\Core\Test\TestSetupTrait;
use Drupal\TestSite\TestSetupInterface;
use Drupal\Tests\RandomGeneratorTrait;
use Drupal\Tests\SessionTestTrait;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
......@@ -26,7 +25,6 @@ class TestSiteInstallCommand extends Command {
installParameters as protected installParametersTrait;
}
use RandomGeneratorTrait;
use SessionTestTrait;
use TestSetupTrait {
changeDatabasePrefix as protected changeDatabasePrefixTrait;
}
......
<?php
namespace Drupal\Tests;
use Drupal\Component\Utility\Html;
use Drupal\Core\Utility\Error;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Provides the debug functions for browser tests.
*/
trait BrowserHtmlDebugTrait {
/**
* Class name for HTML output logging.
*
* @var string
*/
protected $htmlOutputClassName;
/**
* Directory name for HTML output logging.
*
* @var string
*/
protected $htmlOutputDirectory;
/**
* Counter storage for HTML output logging.
*
* @var string
*/
protected $htmlOutputCounterStorage;
/**
* Counter for HTML output logging.
*
* @var int
*/
protected $htmlOutputCounter = 1;
/**
* HTML output output enabled.
*
* @var bool
*/
protected $htmlOutputEnabled = FALSE;
/**
* The file name to write the list of URLs to.
*
* This file is read by the PHPUnit result printer.
*
* @var string
*
* @see \Drupal\Tests\Listeners\HtmlOutputPrinter
*/
protected $htmlOutputFile;
/**
* HTML output test ID.
*
* @var int
*/
protected $htmlOutputTestId;
/**
* Formats HTTP headers as string for HTML output logging.
*
* @param array[] $headers
* Headers that should be formatted.
*
* @return string
* The formatted HTML string.
*/
protected function formatHtmlOutputHeaders(array $headers) {
$flattened_headers = array_map(function ($header) {
if (is_array($header)) {
return implode(';', array_map('trim', $header));
}
else {
return $header;
}
}, $headers);
return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
}
/**
* Returns headers in HTML output format.
*
* @return string
* HTML output headers.
*/
protected function getHtmlOutputHeaders() {
return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
}
/**
* Logs a HTML output message in a text file.
*
* The link to the HTML output message will be printed by the results printer.
*
* @param string|null $message
* (optional) The HTML output message to be stored. If not supplied the
* current page content is used.
*
* @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
*/
protected function htmlOutput($message = NULL) {
if (!$this->htmlOutputEnabled) {
return;
}
$message = $message ?: $this->getSession()->getPage()->getContent();
$message = '<hr />ID #' . $this->htmlOutputCounter . ' (<a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter - 1) . '-' . $this->htmlOutputTestId . '.html">Previous</a> | <a href="' . $this->htmlOutputClassName . '-' . ($this->htmlOutputCounter + 1) . '-' . $this->htmlOutputTestId . '.html">Next</a>)<hr />' . $message;
$html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
// Do not use file_create_url() as the module_handler service might not be
// available.
$uri = $GLOBALS['base_url'] . '/sites/simpletest/browser_output/' . $html_output_filename;
file_put_contents($this->htmlOutputFile, $uri . "\n", FILE_APPEND);
}
/**
* Creates the directory to store browser output.
*
* Creates the directory to store browser output in if a file to write
* URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
*/
protected function initBrowserOutputFile() {
$browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
$this->htmlOutputEnabled = is_file($browser_output_file);
if ($this->htmlOutputEnabled) {
$this->htmlOutputFile = $browser_output_file;
$this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
$this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
// Do not use the file_system service so this method can be called before
// it is available.
if (!is_dir($this->htmlOutputDirectory)) {
mkdir($this->htmlOutputDirectory, 0775, TRUE);
}
if (!file_exists($this->htmlOutputDirectory . '/.htaccess')) {
file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
}
$this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
$this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
if (is_file($this->htmlOutputCounterStorage)) {
$this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
}
}
}
/**
* Provides a Guzzle middleware handler to log every response received.
*
* @return callable
* The callable handler that will do the logging.
*/
protected function getResponseLogHandler() {
return function (callable $handler) {
return function (RequestInterface $request, array $options) use ($handler) {
return $handler($request, $options)
->then(function (ResponseInterface $response) use ($request) {
if ($this->htmlOutputEnabled) {
$caller = $this->getTestMethodCaller();
$html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
$html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
// On redirect responses (status code starting with '3') we need
// to remove the meta tag that would do a browser refresh. We
// don't want to redirect developers away when they look at the
// debug output file in their browser.
$body = $response->getBody();
$status_code = (string) $response->getStatusCode();
if ($status_code[0] === '3') {
$body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
}
$html_output .= '<hr />' . $body;
$html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
$this->htmlOutput($html_output);
}
return $response;
});
};
};
}
/**
* Retrieves the current calling line in the class under test.
*
* @return array
* An associative array with keys 'file', 'line' and 'function'.
*/
protected function getTestMethodCaller() {
$backtrace = debug_backtrace();
// Find the test class that has the test method.
while ($caller = Error::getLastCaller($backtrace)) {
if (isset($caller['class']) && $caller['class'] === get_class($this)) {
break;
}
// If the test method is implemented by a test class's parent then the
// class name of $this will not be part of the backtrace.
// In that case we process the backtrace until the caller is not a
// subclass of $this and return the previous caller.
if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
// Return the last caller since that has to be the test class.
$caller = $last_caller;
break;
}
// Otherwise we have not reached our test class yet: save the last caller
// and remove an element from to backtrace to process the next call.
$last_caller = $caller;
array_shift($backtrace);
}
return $caller;
}
}
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment