BrowserHtmlDebugTrait.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. * Formats HTTP headers as string for HTML output logging.
  59. *
  60. * @param array[] $headers
  61. * Headers that should be formatted.
  62. *
  63. * @return string
  64. * The formatted HTML string.
  65. */
  66. protected function formatHtmlOutputHeaders(array $headers) {
  67. $flattened_headers = array_map(function ($header) {
  68. if (is_array($header)) {
  69. return implode(';', array_map('trim', $header));
  70. }
  71. else {
  72. return $header;
  73. }
  74. }, $headers);
  75. return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
  76. }
  77. /**
  78. * Returns headers in HTML output format.
  79. *
  80. * @return string
  81. * HTML output headers.
  82. */
  83. protected function getHtmlOutputHeaders() {
  84. return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
  85. }
  86. /**
  87. * Logs a HTML output message in a text file.
  88. *
  89. * The link to the HTML output message will be printed by the results printer.
  90. *
  91. * @param string|null $message
  92. * (optional) The HTML output message to be stored. If not supplied the
  93. * current page content is used.
  94. *
  95. * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult()
  96. */
  97. protected function htmlOutput($message = NULL) {
  98. if (!$this->htmlOutputEnabled) {
  99. return;
  100. }
  101. $message = $message ?: $this->getSession()->getPage()->getContent();
  102. $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;
  103. $html_output_filename = $this->htmlOutputClassName . '-' . $this->htmlOutputCounter . '-' . $this->htmlOutputTestId . '.html';
  104. file_put_contents($this->htmlOutputDirectory . '/' . $html_output_filename, $message);
  105. file_put_contents($this->htmlOutputCounterStorage, $this->htmlOutputCounter++);
  106. // Do not use file_create_url() as the module_handler service might not be
  107. // available.
  108. $uri = $GLOBALS['base_url'] . '/sites/simpletest/browser_output/' . $html_output_filename;
  109. file_put_contents($this->htmlOutputFile, $uri . "\n", FILE_APPEND);
  110. }
  111. /**
  112. * Creates the directory to store browser output.
  113. *
  114. * Creates the directory to store browser output in if a file to write
  115. * URLs to has been created by \Drupal\Tests\Listeners\HtmlOutputPrinter.
  116. */
  117. protected function initBrowserOutputFile() {
  118. $browser_output_file = getenv('BROWSERTEST_OUTPUT_FILE');
  119. $this->htmlOutputEnabled = is_file($browser_output_file);
  120. if ($this->htmlOutputEnabled) {
  121. $this->htmlOutputFile = $browser_output_file;
  122. $this->htmlOutputClassName = str_replace("\\", "_", get_called_class());
  123. $this->htmlOutputDirectory = DRUPAL_ROOT . '/sites/simpletest/browser_output';
  124. // Do not use the file_system service so this method can be called before
  125. // it is available.
  126. if (!is_dir($this->htmlOutputDirectory)) {
  127. mkdir($this->htmlOutputDirectory, 0775, TRUE);
  128. }
  129. if (!file_exists($this->htmlOutputDirectory . '/.htaccess')) {
  130. file_put_contents($this->htmlOutputDirectory . '/.htaccess', "<IfModule mod_expires.c>\nExpiresActive Off\n</IfModule>\n");
  131. }
  132. $this->htmlOutputCounterStorage = $this->htmlOutputDirectory . '/' . $this->htmlOutputClassName . '.counter';
  133. $this->htmlOutputTestId = str_replace('sites/simpletest/', '', $this->siteDirectory);
  134. if (is_file($this->htmlOutputCounterStorage)) {
  135. $this->htmlOutputCounter = max(1, (int) file_get_contents($this->htmlOutputCounterStorage)) + 1;
  136. }
  137. }
  138. }
  139. /**
  140. * Provides a Guzzle middleware handler to log every response received.
  141. *
  142. * @return callable
  143. * The callable handler that will do the logging.
  144. */
  145. protected function getResponseLogHandler() {
  146. return function (callable $handler) {
  147. return function (RequestInterface $request, array $options) use ($handler) {
  148. return $handler($request, $options)
  149. ->then(function (ResponseInterface $response) use ($request) {
  150. if ($this->htmlOutputEnabled) {
  151. $caller = $this->getTestMethodCaller();
  152. $html_output = 'Called from ' . $caller['function'] . ' line ' . $caller['line'];
  153. $html_output .= '<hr />' . $request->getMethod() . ' request to: ' . $request->getUri();
  154. // On redirect responses (status code starting with '3') we need
  155. // to remove the meta tag that would do a browser refresh. We
  156. // don't want to redirect developers away when they look at the
  157. // debug output file in their browser.
  158. $body = $response->getBody();
  159. $status_code = (string) $response->getStatusCode();
  160. if ($status_code[0] === '3') {
  161. $body = preg_replace('#<meta http-equiv="refresh" content=.+/>#', '', $body, 1);
  162. }
  163. $html_output .= '<hr />' . $body;
  164. $html_output .= $this->formatHtmlOutputHeaders($response->getHeaders());
  165. $this->htmlOutput($html_output);
  166. }
  167. return $response;
  168. });
  169. };
  170. };
  171. }
  172. /**
  173. * Retrieves the current calling line in the class under test.
  174. *
  175. * @return array
  176. * An associative array with keys 'file', 'line' and 'function'.
  177. */
  178. protected function getTestMethodCaller() {
  179. $backtrace = debug_backtrace();
  180. // Find the test class that has the test method.
  181. while ($caller = Error::getLastCaller($backtrace)) {
  182. if (isset($caller['class']) && $caller['class'] === get_class($this)) {
  183. break;
  184. }
  185. // If the test method is implemented by a test class's parent then the
  186. // class name of $this will not be part of the backtrace.
  187. // In that case we process the backtrace until the caller is not a
  188. // subclass of $this and return the previous caller.
  189. if (isset($last_caller) && (!isset($caller['class']) || !is_subclass_of($this, $caller['class']))) {
  190. // Return the last caller since that has to be the test class.
  191. $caller = $last_caller;
  192. break;
  193. }
  194. // Otherwise we have not reached our test class yet: save the last caller
  195. // and remove an element from to backtrace to process the next call.
  196. $last_caller = $caller;
  197. array_shift($backtrace);
  198. }
  199. return $caller;
  200. }
  201. }