2

我有一个 PHPUnit Mink 测试,可确保一些 HTTP 重定向到位。

这被缩减了,但测试基本上看起来像,testRedirect()由 a 提供@dataProvider

class Testbase extends BrowserTestCase {

  public static $browsers = [
    [
      'driver' => 'goutte',
    ],
  ];

  public function testRedirect($from, $to) {
    $session = $this->getSession();
    $session->visit($from);

    $this->assertEquals(200, $session->getDriver()->getStatusCode(), sprintf('Final destination from %s was a 200', $to));
    $this->assertEquals($to, $session->getCurrentUrl(), sprintf('Redirected from %s to %s', $from, $to));
  }

}

这适用于在网络服务器本身上处理的重定向(例如,mod_rewrite 重定向)。但是,我需要检查的一些重定向是由 DNS 提供商处理的(我不控制它,但我认为它是 NetNames)。

如果我用 wget 测试重定向,它看起来很好

$ wget --max-redirect=0 http://example1.com/
Resolving example1.com... A.B.C.D
Connecting to example1.com|A.B.C.D|:80... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: https://example2.com/some/path?foo=bar [following]
0 redirections exceeded.

但是,当我从测试中转储响应时,标题是

Date: Thu, 06 Sep 2018 15:37:47 GMT
Content-Length: 94
X-Powered-By: Servlet/2.4 JSP/2.0

响应是

<head>
<title></title>
<meta name="revised" content="1.1.7">
</head>
<body></body>

带有 200 状态码。

我需要明确设置请求标头吗?我试过了

$session->setRequestHeader('Host', 'example1.com');

但这没有帮助。

什么会导致这种情况?

4

1 回答 1

1

我认为在接收端,这原来是 Host 标头的一种奇怪情况。

我的测试提供商有一些带有大写字符的主机名,例如“ http://Example1.com/ ”。我必须将测试功能更新为

public function testRedirect($from, $to) {
  $parts = parse_url($from);
  $host = strtolower($parts['host']);

  $session = $this->getSession();
  $session->setRequestHeader('Host', $host);
  $session->visit($from);

  $this->assertEquals(200, $session->getDriver()->getStatusCode(), sprintf('Final destination from %s was a 200', $to));
  $this->assertEquals($to, $session->getCurrentUrl(), sprintf('Redirected from %s to %s', $from, $to));
}

强制 Host 标头为小写。

于 2018-09-17T20:18:22.357 回答