确定将在php中发送的http状态 [英] determine the http status that will be sent in php

查看:69
本文介绍了确定将在php中发送的http状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为管理我的应用程序标头的类编写测试用例.它发送的标头中有http状态标头.我正在使用headers_list()来查看要发送的标头,是否现在要发送标头. headers_list()的问题在于它不包含http状态头(尽管php.net上似乎没有记载).因此,我无法找到一种方法来确定将发送什么HTTP状态.即使我确实发送了标头(我试图不发送标头,所以我也可以一次测试很多不同的东西),但该状态不会显示在headers_list()中.有任何想法吗?

I am trying to write a test case for a class that is managing headers for my application. Among the headers it sends are http status headers. I am using headers_list() to see which headers would be send, were I to send headers now. The problem with headers_list() is that it does not include the http status header (although this seems to be undocumented on php.net). So, I cannot find a way to determine what http status would be sent. Even if I do send the headers (which I'm trying not to do, so I can test a bunch of different things all in one go), the status does not show up in headers_list(). Any ideas?

P.S.我意识到我可以通过请求页面并检查响应来做到这一点,但是这使得将测试保持在 unit 级别非常困难,因此我试图避免这种情况.

P.S. I realize I could do this by requesting the page and examining the response, but that makes it very difficult to keep tests at a unit level, so I'm trying to avoid it.

推荐答案

要么使用

Either use a Mock that returns the header but doesnt send it or write a Response object, e.g.

class HttpResponse 
{
    protected $_status = '200 OK';
    protected $_headers = array();
    protected $_body = null;

    public function setStatus($status)
    {
        $this->_status = $status;
    }

    public function getStatus()
    {
        return $this->_status;
    }

    public function addHeader($name, $value)
    {
        $this->_headers[$name] = $value;
        return $this;
    }

    public function getHeaders()
    {
        return $this->_headers;
    }    

    public function write($data)
    {
        $this->_body .= $data;
        return $this;
    }

    public function send()
    {
        header('HTTP/1.0 ' . $this->_status);
        foreach ($this->headers as $name => $value) {
            header("$name : $value");
        }
        echo $this->_body;
        $this->resetRequest();
    }

   public function resetRequest()
   {
        $this->_status  = '200 OK';
        $this->_headers = array();
        $this->_body    = null;
   }
}

只要您不send(),就可以通过吸气剂检查状态.您还可以添加__toString()方法,该方法以字符串形式返回整个响应,并对其进行正则表达式以查看其外观是否像您期望的那样.

So as long as you dont send() you can inspect the state through the getters. You could also add a __toString() method, that returns the Entire Response as a string and regex it to see if it looks like you expect it to look.

这篇关于确定将在php中发送的http状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆