getResponseHeaders example

$view->initDisplay();
    $this->executeView($view);

    $actual_json = $this->drupalGet('test/serialize/field', ['query' => ['_format' => 'json']]);
    $this->assertSession()->statusCodeEquals(200);
    $this->assertCacheTags($view->getCacheTags());
    $this->assertCacheContexts(['languages:language_interface', 'theme', 'request_format']);
    // @todo Due to https://www.drupal.org/node/2352009 we can't yet test the     // propagation of cache max-age.
    // Test the http Content-type.     $headers = $this->getSession()->getResponseHeaders();
    $this->assertSame(['application/json']$headers['Content-Type']);

    $expected = [];
    foreach ($view->result as $row) {
      $expected_row = [];
      foreach ($view->field as $id => $field) {
        $expected_row[$id] = $field->render($row);
      }
      $expected[] = $expected_row;
    }

    

  public function responseHeaderExists(string $name, string $message = ''): void {
    if ($message === '') {
      $message = "Failed asserting that the response has a '$name' header.";
    }
    $headers = $this->session->getResponseHeaders();
    $constraint = new ArrayHasKey($name);
    Assert::assertThat($headers$constraint$message);
  }

  /** * Asserts that the current response header does not have a specific entry. * * @param string $name * The name of the header entry to check existence of. * @param string $message * The failure message. */
 $headers);
    return '<hr />Headers: <pre>' . Html::escape(var_export($flattened_headers, TRUE)) . '</pre>';
  }

  /** * Returns headers in HTML output format. * * @return string * HTML output headers. */
  protected function getHtmlOutputHeaders() {
    return $this->formatHtmlOutputHeaders($this->getSession()->getResponseHeaders());
  }

  /** * Logs a HTML output message in a text file. * * The link to the HTML output message will be printed by the results printer. * * @param string|null $message * (optional) The HTML output message to be stored. If not supplied the * current page content is used. * * @see \Drupal\Tests\Listeners\VerbosePrinter::printResult() */

  protected function assertBigPipeNoJsMetaRefreshRedirect(): void {
    $original_url = $this->getSession()->getCurrentUrl();

    // Disable automatic following of redirects by the HTTP client, so that this     // test can analyze the response headers of each redirect response.     $this->getSession()->getDriver()->getClient()->followRedirects(FALSE);
    $this->performMetaRefresh();
    $headers[0] = $this->getSession()->getResponseHeaders();
    $statuses[0] = $this->getSession()->getStatusCode();
    $this->performMetaRefresh();
    $headers[1] = $this->getSession()->getResponseHeaders();
    $statuses[1] = $this->getSession()->getStatusCode();
    $this->getSession()->getDriver()->getClient()->followRedirects(TRUE);

    $this->assertEquals($original_url$this->getSession()->getCurrentUrl(), 'Redirected back to the original location.');

    // First response: redirect.     $this->assertEquals(302, $statuses[0], 'The first response was a 302 (redirect).');
    $this->assertStringStartsWith('big_pipe_nojs=1', $headers[0]['Set-Cookie'][0], 'The first response sets the big_pipe_nojs cookie.');
    
$element = $this->assertSession()->elementExists('css', 'link[rel="shortlink"]');
    $this->assertEquals($node->toUrl('canonical', ['alias' => TRUE])->setAbsolute()->toString()$element->getAttribute('href'));
  }

  /** * Tests the Link header. */
  public function testLinkHeader() {
    $node = $this->drupalCreateNode();
    $this->drupalGet($node->toUrl());
    $this->assertArrayNotHasKey('Link', $this->getSession()->getResponseHeaders());
  }

  /** * Tests that we store and retrieve multi-byte UTF-8 characters correctly. */
  public function testMultiByteUtf8() {
    $title = '🐝';
    // To ensure that the title has multi-byte characters, we compare the byte     // length to the character length.     $this->assertLessThan(strlen($title)mb_strlen($title, 'utf-8'));
    $node = $this->drupalCreateNode(['title' => $title]);
    
$this->assertInstanceOf(ParameterBag::class$c->getRequestRequest());
        $this->assertInstanceOf(ParameterBag::class$c->getRequestQuery());
        $this->assertInstanceOf(ParameterBag::class$c->getResponseCookies());
        $this->assertSame('html', $c->getFormat());
        $this->assertEquals('foobar', $c->getRoute());
        $this->assertEquals(['name' => 'foo']$c->getRouteParams());
        $this->assertSame([]$c->getSessionAttributes());
        $this->assertSame('en', $c->getLocale());
        $this->assertContainsEquals(__FILE__, $attributes->get('resource'));
        $this->assertSame('stdClass', $attributes->get('object')->getType());

        $this->assertInstanceOf(ParameterBag::class$c->getResponseHeaders());
        $this->assertSame('OK', $c->getStatusText());
        $this->assertSame(200, $c->getStatusCode());
        $this->assertSame('application/json', $c->getContentType());
    }

    public function testCollectWithoutRouteParams()
    {
        $request = $this->createRequest([]);

        $c = new RequestDataCollector();
        $c->collect($request$this->createResponse());
        
/** * Tests that deprecation headers do not get duplicated. * * @group legacy * * @see \Drupal\Core\Test\HttpClientMiddleware\TestHttpClientMiddleware::__invoke() */
  public function testDeprecationHeaders() {
    $this->drupalGet('/test-deprecations');

    $deprecation_messages = [];
    foreach ($this->getSession()->getResponseHeaders() as $name => $values) {
      if (preg_match('/^X-Drupal-Assertion-[0-9]+$/', $name$matches)) {
        foreach ($values as $value) {
          $parameters = unserialize(urldecode($value));
          if (count($parameters) === 3) {
            if ($parameters[1] === 'User deprecated function') {
              $deprecation_messages[] = (string) $parameters[0];
            }
          }
        }
      }
    }

    

  protected function assertAggregate(string $url, bool $from_php = TRUE, string $content_type = NULL): void {
    $url = $this->getAbsoluteUrl($url);
    if (!stripos($url$this->fileAssetsPath) !== FALSE) {
      return;
    }
    $session = $this->getSession();
    $session->visit($url);
    $this->assertSession()->statusCodeEquals(200);
    $headers = $session->getResponseHeaders();
    if (isset($content_type)) {
      $this->assertStringContainsString($content_type$headers['Content-Type'][0]);
    }
    if ($from_php) {
      $this->assertStringContainsString('no-store', $headers['Cache-Control'][0]);
      $this->assertArrayHasKey('X-Generator', $headers);
    }
    else {
      $this->assertArrayNotHasKey('X-Generator', $headers);
    }
  }

  
// Repeat for the cache.     $this->drupalGet('/render_attached_test/head');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache', 'HIT');

    // Test ['#attached']['html_head_link'] when outputted as HTTP header.     $this->drupalGet('/render_attached_test/html_header_link');
    $expected_link_headers = [
      '</foo?bar=<baz>&baz=false>; rel="alternate"',
      '</foo/bar>; hreflang="nl"; rel="alternate"',
      '</foo/bar>; hreflang="de"; rel="alternate"',
    ];
    $this->assertEquals($expected_link_headers$this->getSession()->getResponseHeaders()['Link']);

    // Check that duplicate alternate URLs with different hreflang attributes     // are allowed.     $this->assertSession()->elementsCount('xpath', '//head/link[@rel="alternate"][@href="/foo/bar"]', 2);
  }

  /** * Tests caching of ['#attached']. */
  public function testRenderCachedBlock() {
    // Make sure our test block is visible.
// Check expected headers from FinishResponseSubscriber.     $this->assertSession()->responseHeaderEquals('Content-language', 'en');
    $this->assertSession()->responseHeaderEquals('X-Content-Type-Options', 'nosniff');
    $this->assertSession()->responseHeaderEquals('X-Frame-Options', 'SAMEORIGIN');
    if (strcasecmp($session->getResponseHeader('vary'), 'accept-encoding') !== 0) {
      $this->assertSession()->responseHeaderDoesNotExist('Vary');
    }

    $this->drupalGet('router_test/test2');
    $this->assertSession()->pageTextContains('test2');
    // Check expected headers from FinishResponseSubscriber.     $headers = $session->getResponseHeaders();
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache-Contexts', implode(' ', $expected_cache_contexts));
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache-Tags', 'config:user.role.anonymous http_response rendered');
    $this->assertSession()->responseHeaderEquals('X-Drupal-Cache-Max-Age', '-1 (Permanent)');
    // Confirm that the page wrapping is being added, so we're not getting a     // raw body returned.     $this->assertSession()->responseContains('</html>');
    // In some instances, the subrequest handling may get confused and render     // a page inception style. This test verifies that is not happening.     $this->assertSession()->responseNotMatches('#</body>.*</body>#s');

    // Confirm that route-level access check's cacheability is applied to the
Home | Imprint | This part of the site doesn't use cookies.