annotate core/tests/Drupal/Tests/BrowserHtmlDebugTrait.php @ 19:fa3358dc1485 tip

Add ndrum files
author Chris Cannam
date Wed, 28 Aug 2019 13:14:47 +0100
parents af1871eacc83
children
rev   line source
Chris@17 1 <?php
Chris@17 2
Chris@17 3 namespace Drupal\Tests;
Chris@17 4
Chris@17 5 use Drupal\Component\Utility\Html;
Chris@17 6 use Drupal\Core\Utility\Error;
Chris@17 7 use Psr\Http\Message\RequestInterface;
Chris@17 8 use Psr\Http\Message\ResponseInterface;
Chris@17 9
Chris@17 10 /**
Chris@17 11 * Provides the debug functions for browser tests.
Chris@17 12 */
Chris@17 13 trait BrowserHtmlDebugTrait {
Chris@17 14
Chris@17 15 /**
Chris@17 16 * Class name for HTML output logging.
Chris@17 17 *
Chris@17 18 * @var string
Chris@17 19 */
Chris@17 20 protected $htmlOutputClassName;
Chris@17 21
Chris@17 22 /**
Chris@17 23 * Directory name for HTML output logging.
Chris@17 24 *
Chris@17 25 * @var string
Chris@17 26 */
Chris@17 27 protected $htmlOutputDirectory;
Chris@17 28
Chris@17 29 /**
Chris@17 30 * Counter storage for HTML output logging.
Chris@17 31 *
Chris@17 32 * @var string
Chris@17 33 */
Chris@17 34 protected $htmlOutputCounterStorage;
Chris@17 35
Chris@17 36 /**
Chris@17 37 * Counter for HTML output logging.
Chris@17 38 *
Chris@17 39 * @var int
Chris@17 40 */
Chris@17 41 protected $htmlOutputCounter = 1;
Chris@17 42
Chris@17 43 /**
Chris@17 44 * HTML output output enabled.
Chris@17 45 *
Chris@17 46 * @var bool
Chris@17 47 */
Chris@17 48 protected $htmlOutputEnabled = FALSE;
Chris@17 49
Chris@17 50 /**
Chris@17 51 * The file name to write the list of URLs to.
Chris@17 52 *
Chris@17 53 * This file is read by the PHPUnit result printer.
Chris@17 54 *
Chris@17 55 * @var string
Chris@17 56 *
Chris@17 57 * @see \Drupal\Tests\Listeners\HtmlOutputPrinter
Chris@17 58 */
Chris@17 59 protected $htmlOutputFile;
Chris@17 60
Chris@17 61 /**
Chris@17 62 * HTML output test ID.
Chris@17 63 *
Chris@17 64 * @var int
Chris@17 65 */
Chris@17 66 protected $htmlOutputTestId;
Chris@17 67
Chris@17 68 /**
Chris@17 69 * Formats HTTP headers as string for HTML output logging.
Chris@17 70 *
Chris@17 71 * @param array[] $headers
Chris@17 72 * Headers that should be formatted.
Chris@17 73 *
Chris@17 74 * @return string
Chris@17 75 * The formatted HTML string.
Chris@17 76 */
Chris@17 77 protected function formatHtmlOutputHeaders(array $headers) {
Chris@17 78 $flattened_headers = array_map(function ($header) {
Chris@17 79 if (is_array($header)) {
Chris@17 80 return implode(';', array_map('trim', $header));
Chris@17 81 }
Chris@17 82 else {
Chris@17 83 return $header;
Chris@17 84 }
Chris@17 85 }, $headers);
Chris@17 86 return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
Chris@17 87 }
Chris@17 88
Chris@17 89 /**
Chris@17 90 * Returns headers in HTML output format.
Chris@17 91 *
Chris@17 92 * @return string
Chris@17 93 * HTML output headers.
Chris@17 94 */
Chris@17 95 protected function getHtmlOutputHeaders() {
Chris@17 96 return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
Chris@17 97 }
Chris@17 98
Chris@17 99 /**
Chris@17 100 * Logs a HTML output message in a text file.
Chris@17 101 *
Chris@17 102 * The link to the HTML output message will be printed by the results printer.
Chris@17 103 *
Chris@17 104 * @param string|null $message
Chris@17 105 * (optional) The HTML output message to be stored. If not supplied the
Chris@17 106 * current page content is used.
Chris@17 107 *
Chris@17 108 * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
Chris@17 109 */
Chris@17 110 protected function htmlOutput($message = NULL) {
Chris@17 111 if (!$this->htmlOutputEnabled) {
Chris@17 112 return;
Chris@17 113 }
Chris@17 114 $message = $message ?: $this->getSession()->getPage()->getContent();
Chris@17 115 $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;
Chris@17 116 $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
Chris@17 117 file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
Chris@17 118 file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
Chris@17 119 // Do not use file_create_url() as the module_handler service might not be
Chris@17 120 // available.
Chris@17 121 $uri = $GLOBALS['base_url'] . '/sites/simpletest/browser_output/' . $html_output_filename;
Chris@17 122 file_put_contents($this->htmlOutputFile, $uri . "\n", FILE_APPEND);
Chris@17 123 }
Chris@17 124
Chris@17 125 /**
Chris@17 126 * Creates the directory to store browser output.
Chris@17 127 *
Chris@17 128 * Creates the directory to store browser output in if a file to write
Chris@17 129 * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
Chris@17 130 */
Chris@17 131 protected function initBrowserOutputFile() {
Chris@17 132 $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
Chris@17 133 $this->htmlOutputEnabled = is_file($browser_output_file);
Chris@17 134 if ($this->htmlOutputEnabled) {
Chris@17 135 $this->htmlOutputFile = $browser_output_file;
Chris@17 136 $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
Chris@17 137 $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
Chris@17 138 // Do not use the file_system service so this method can be called before
Chris@18 139 // it is available. Checks !is_dir() twice around mkdir() because a
Chris@18 140 // concurrent test might have made the directory and caused mkdir() to
Chris@18 141 // fail. In this case we can still use the directory even though we failed
Chris@18 142 // to make it.
Chris@18 143 if (!is_dir($this->htmlOutputDirectory) && !mkdir($this->htmlOutputDirectory, 0775, TRUE) && !is_dir($this->htmlOutputDirectory)) {
Chris@18 144 throw new \RuntimeException(sprintf('Unable to create directory: %s', $this->htmlOutputDirectory));
Chris@17 145 }
Chris@17 146 if (!file_exists($this->htmlOutputDirectory . '/.htaccess')) {
Chris@17 147 file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
Chris@17 148 }
Chris@17 149 $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
Chris@17 150 $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
Chris@17 151 if (is_file($this->htmlOutputCounterStorage)) {
Chris@17 152 $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
Chris@17 153 }
Chris@17 154 }
Chris@17 155 }
Chris@17 156
Chris@17 157 /**
Chris@17 158 * Provides a Guzzle middleware handler to log every response received.
Chris@17 159 *
Chris@17 160 * @return callable
Chris@17 161 * The callable handler that will do the logging.
Chris@17 162 */
Chris@17 163 protected function getResponseLogHandler() {
Chris@17 164 return function (callable $handler) {
Chris@17 165 return function (RequestInterface $request, array $options) use ($handler) {
Chris@17 166 return $handler($request, $options)
Chris@17 167 ->then(function (ResponseInterface $response) use ($request) {
Chris@17 168 if ($this->htmlOutputEnabled) {
Chris@17 169
Chris@17 170 $caller = $this->getTestMethodCaller();
Chris@17 171 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
Chris@17 172 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
Chris@17 173
Chris@17 174 // On redirect responses (status code starting with '3') we need
Chris@17 175 // to remove the meta tag that would do a browser refresh. We
Chris@17 176 // don't want to redirect developers away when they look at the
Chris@17 177 // debug output file in their browser.
Chris@17 178 $body = $response->getBody();
Chris@17 179 $status_code = (string) $response->getStatusCode();
Chris@17 180 if ($status_code[0] === '3') {
Chris@17 181 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
Chris@17 182 }
Chris@17 183 $html_output .= '<hr />' . $body;
Chris@17 184 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
Chris@17 185
Chris@17 186 $this->htmlOutput($html_output);
Chris@17 187 }
Chris@17 188 return $response;
Chris@17 189 });
Chris@17 190 };
Chris@17 191 };
Chris@17 192 }
Chris@17 193
Chris@17 194 /**
Chris@17 195 * Retrieves the current calling line in the class under test.
Chris@17 196 *
Chris@17 197 * @return array
Chris@17 198 * An associative array with keys 'file', 'line' and 'function'.
Chris@17 199 */
Chris@17 200 protected function getTestMethodCaller() {
Chris@17 201 $backtrace = debug_backtrace();
Chris@17 202 // Find the test class that has the test method.
Chris@17 203 while ($caller = Error::getLastCaller($backtrace)) {
Chris@17 204 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
Chris@17 205 break;
Chris@17 206 }
Chris@17 207 // If the test method is implemented by a test class's parent then the
Chris@17 208 // class name of $this will not be part of the backtrace.
Chris@17 209 // In that case we process the backtrace until the caller is not a
Chris@17 210 // subclass of $this and return the previous caller.
Chris@17 211 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
Chris@17 212 // Return the last caller since that has to be the test class.
Chris@17 213 $caller = $last_caller;
Chris@17 214 break;
Chris@17 215 }
Chris@17 216 // Otherwise we have not reached our test class yet: save the last caller
Chris@17 217 // and remove an element from to backtrace to process the next call.
Chris@17 218 $last_caller = $caller;
Chris@17 219 array_shift($backtrace);
Chris@17 220 }
Chris@17 221
Chris@17 222 return $caller;
Chris@17 223 }
Chris@17 224
Chris@17 225 }