3 namespace Drupal\Core\Test\HttpClientMiddleware;
5 use Drupal\Core\Utility\Error;
6 use Psr\Http\Message\RequestInterface;
7 use Psr\Http\Message\ResponseInterface;
10 * Overrides the User-Agent HTTP header for outbound HTTP requests.
12 class TestHttpClientMiddleware {
17 * HTTP middleware that replaces the user agent for simpletest requests.
19 public function __invoke() {
20 // If the database prefix is being used by SimpleTest to run the tests in a copied
21 // database then set the user-agent header to the database prefix so that any
22 // calls to other Drupal pages will run the SimpleTest prefixed database. The
23 // user-agent is used to ensure that multiple testing sessions running at the
24 // same time won't interfere with each other as they would if the database
25 // prefix were stored statically in a file or database variable.
26 return function ($handler) {
27 return function (RequestInterface $request, array $options) use ($handler) {
28 if ($test_prefix = drupal_valid_test_ua()) {
29 $request = $request->withHeader('User-Agent', drupal_generate_test_ua($test_prefix));
31 return $handler($request, $options)
32 ->then(function (ResponseInterface $response) use ($request) {
33 if (!drupal_valid_test_ua()) {
36 $headers = $response->getHeaders();
37 foreach ($headers as $header_name => $header_values) {
38 if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $header_name, $matches)) {
39 foreach ($header_values as $header_value) {
40 // Call \Drupal\simpletest\WebTestBase::error() with the parameters from
42 $parameters = unserialize(urldecode($header_value));
43 if (count($parameters) === 3) {
44 throw new \Exception($parameters[1] . ': ' . $parameters[0] . "\n" . Error::formatBacktrace([$parameters[2]]));
47 throw new \Exception('Error thrown with the wrong amount of parameters.');