BrowserHtmlDebugTrait.php 8.1 KB

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