【问题标题】:Getting cookie for PHPUnit ajax test获取 PHPUnit ajax 测试的 cookie
【发布时间】:2015-11-12 22:59:56
【问题描述】:

我正在尝试为 ajax 端点编写一些 PHPUnit 测试。当用户不必登录时,我可以毫不费力地做到这一点。但要测试有问题的端点,用户必须登录,并且我想以编程方式获取 cookie 作为测试的一部分。基本上我想运行的测试看起来像:

    $url = "https://example.com/ajax/endpoint";
    $fields = array(
        'name'=>'test '.rand(),       
        'host'=>rand(0,255).'.'.rand(0,255).'.'.rand(0,255).'.'.rand(0,255),
        'port'=>rand(1,1000)
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    ob_start();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_COOKIE, $userCookie);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);
    $this->assertEquals(true, $response);
    $json = ob_get_contents();
    $return = json_decode($json);
    $this->assertEquals('false', $return->success);
    $this->assertEquals('', $return->data);
    ob_end_clean();

但除了打开浏览器,登录,然后从浏览器中的 cookie 中读取 PHPSESSID 之外,我不知道获得$userCookie 的好方法。如何在不手动抓取的情况下获取 cookie?我希望能够从 curl 请求到登录端点获取它:

    $url = "https://example.com/ajax/login";
    $fields = array(
        'username'=>$username,
        'password'=>$password
    );
    $fields_string = "";
    foreach ($fields as $key=>$value) {
        $fields_string .= $key.'='.$value.'&';
    }
    $fields_string = rtrim($fields_string, '&');
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_URL, $url);
    $response = curl_exec($ch);

【问题讨论】:

  • 我手头的问题没有解决方案。但是当我在同一个句子中看到 unittest ajax call 这个词时,我开始怀疑了。单元测试不应访问网络/IO 或任何其他系统板。尝试模拟网络访问或在集成测试中进行测试。
  • 你应该添加 curl 标签。此外,就像@lukassteiner 所说,这确实是一个集成测试,因为您既依赖于网络/IO 和会话/登录。

标签: php session cookies phpunit session-cookies


【解决方案1】:

有什么阻止您以编程方式获取它吗?

$ch = curl_init('https://example.com/login');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "login=root&password=toor");
curl_setopt($ch, CURLOPT_HEADER, 1);

$result = curl_exec($ch);
preg_match_all('/^Set-Cookie: PHPSESSID=(.*?);/mi', $result, $matches);
$userCookie = $matches[1];

【讨论】:

    【解决方案2】:

    您的登录 cURL 请求已经完成了一半。您需要做的是从响应标头中检索 cookie 以获取 PHPSESSID。

    您可以找到here 的另一个问题中询问了如何使用 cURL 获取响应标头。

    获得响应标头后,您必须对其进行解析以获取 Set-Cookie 标头。使用该标题的内容进行后续测试应该可以从那里开始。

    【讨论】:

      猜你喜欢
      • 2018-05-08
      • 2014-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-04
      • 2018-01-25
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      相关资源
      最近更新 更多