3 namespace Drupal\Tests;
5 use Drupal\Component\Utility\Html;
6 use Drupal\Core\Utility\Error;
7 use Psr\Http\Message\RequestInterface;
8 use Psr\Http\Message\ResponseInterface;
11 * Provides the debug functions for browser tests.
13 trait BrowserHtmlDebugTrait {
16 * Class name for HTML output logging.
20 protected $htmlOutputClassName;
23 * Directory name for HTML output logging.
27 protected $htmlOutputDirectory;
30 * Counter storage for HTML output logging.
34 protected $htmlOutputCounterStorage;
37 * Counter for HTML output logging.
41 protected $htmlOutputCounter = 1;
44 * HTML output output enabled.
48 protected $htmlOutputEnabled = FALSE;
51 * The file name to write the list of URLs to.
53 * This file is read by the PHPUnit result printer.
57 * @see \Drupal\Tests\Listeners\HtmlOutputPrinter
59 protected $htmlOutputFile;
62 * HTML output test ID.
66 protected $htmlOutputTestId;
69 * Formats HTTP headers as string for HTML output logging.
71 * @param array[] $headers
72 * Headers that should be formatted.
75 * The formatted HTML string.
77 protected function formatHtmlOutputHeaders(array $headers) {
78 $flattened_headers = array_map(function ($header) {
79 if (is_array($header)) {
80 return implode(';', array_map('trim', $header));
86 return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
90 * Returns headers in HTML output format.
93 * HTML output headers.
95 protected function getHtmlOutputHeaders() {
96 return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
100 * Logs a HTML output message in a text file.
102 * The link to the HTML output message will be printed by the results printer.
104 * @param string|null $message
105 * (optional) The HTML output message to be stored. If not supplied the
106 * current page content is used.
108 * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
110 protected function htmlOutput($message = NULL) {
111 if (!$this->htmlOutputEnabled) {
114 $message = $message ?: $this->getSession()->getPage()->getContent();
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;
116 $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
117 file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
118 file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
119 // Do not use file_create_url() as the module_handler service might not be
121 $uri = $GLOBALS['base_url'] . '/sites/simpletest/browser_output/' . $html_output_filename;
122 file_put_contents($this->htmlOutputFile, $uri . "\n", FILE_APPEND);
126 * Creates the directory to store browser output.
128 * Creates the directory to store browser output in if a file to write
129 * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
131 protected function initBrowserOutputFile() {
132 $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
133 $this->htmlOutputEnabled = is_file($browser_output_file);
134 if ($this->htmlOutputEnabled) {
135 $this->htmlOutputFile = $browser_output_file;
136 $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
137 $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
138 // Do not use the file_system service so this method can be called before
140 if (!is_dir($this->htmlOutputDirectory)) {
141 mkdir($this->htmlOutputDirectory, 0775, TRUE);
143 if (!file_exists($this->htmlOutputDirectory . '/.htaccess')) {
144 file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
146 $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
147 $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
148 if (is_file($this->htmlOutputCounterStorage)) {
149 $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
155 * Provides a Guzzle middleware handler to log every response received.
158 * The callable handler that will do the logging.
160 protected function getResponseLogHandler() {
161 return function (callable $handler) {
162 return function (RequestInterface $request, array $options) use ($handler) {
163 return $handler($request, $options)
164 ->then(function (ResponseInterface $response) use ($request) {
165 if ($this->htmlOutputEnabled) {
167 $caller = $this->getTestMethodCaller();
168 $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
169 $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
171 // On redirect responses (status code starting with '3') we need
172 // to remove the meta tag that would do a browser refresh. We
173 // don't want to redirect developers away when they look at the
174 // debug output file in their browser.
175 $body = $response->getBody();
176 $status_code = (string) $response->getStatusCode();
177 if ($status_code[0] === '3') {
178 $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
180 $html_output .= '<hr />' . $body;
181 $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
183 $this->htmlOutput($html_output);
192 * Retrieves the current calling line in the class under test.
195 * An associative array with keys 'file', 'line' and 'function'.
197 protected function getTestMethodCaller() {
198 $backtrace = debug_backtrace();
199 // Find the test class that has the test method.
200 while ($caller = Error::getLastCaller($backtrace)) {
201 if (isset($caller['class']) && $caller['class'] === get_class($this)) {
204 // If the test method is implemented by a test class's parent then the
205 // class name of $this will not be part of the backtrace.
206 // In that case we process the backtrace until the caller is not a
207 // subclass of $this and return the previous caller.
208 if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
209 // Return the last caller since that has to be the test class.
210 $caller = $last_caller;
213 // Otherwise we have not reached our test class yet: save the last caller
214 // and remove an element from to backtrace to process the next call.
215 $last_caller = $caller;
216 array_shift($backtrace);