如何在模拟请求对象时测试下一部分代码?

时间:2015-09-12 06:39:05

标签: python unit-testing

我有一些以这种方式编写的Python函数:

    def verify_secondary_hostnames(self, publishedName, hostnames):
        cname = self.get_cname(publishedName)
        edge_ip = requests.get('http://{}'.format(cname)).headers['X-Edge-IP']
        for hostname in hostnames:
            headers = {"host": hostname}
            data = requests.head("http://{}".format(edge_ip), headers=headers)
            data.raise_for_status()

我试图为它编写的单元测试如下所示:

    @patch("requests.get")
    @patch("requests.head")
    @patch("FrontEnd.FrontEnd.get_cname")
    def test_verify_secondary_hostnames(self, mock_get_cname, mock_head, mock_get):
        mock_get_cname.return_value = "hulahoop"
        mock_get.return_value.headers = {"X-Edge-IP": "hulahoop"}
        self.fe.verify_secondary_hostnames('publishedName', ['hostname'])
        self.assertEqual(mock_head.call_args,
                         call('http://hulahoop', headers={'host': 'hostname'}))

在此测试中,实际执行此操作的最后一部分raise_for_status

def raise_for_status(self):
        """Raises stored :class:`HTTPError`, if one occurred."""

        http_error_msg = ''

        if 400 <= self.status_code < 500:
            http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)

        elif 500 <= self.status_code < 600:
            http_error_msg = '%s Server Error: %s' % (self.status_code, self.reason)

        if http_error_msg:
            raise HTTPError(http_error_msg, response=self)

我不能在这里做,因为我已经嘲笑了requests.head。我怎样才能编写测试来覆盖它?我的意思是&#34;覆盖&#34;这是因为对象是一个模拟对象,我怎样才能使它成为raise_for_status?我是否必须创建一个模拟方法来执行此操作或在我的测试中模拟加注?

编辑:这是我对所列问题的最新测试:

@patch("requests.get")
@patch("requests.head")
@patch("FrontEnd.FrontEnd.get_cname")
@patch("requests.models.Response.raise_for_status")
def test_verify_secondary_hostnames(self, mock_raise,
                                    mock_get_cname, mock_head, mock_get):
    mock_get_cname.return_value = "hulahoop"
    mock_get.return_value.headers = {"X-Edge-IP": "hulahoop"}
    mock_head.return_value.status_code = 200
    self.fe.verify_secondary_hostnames('publishedName', ['hostname'])
    self.assertEqual(mock_head.call_args,
                     call('http://hulahoop', headers={'host': 'hostname'}))
    mock_head.raise_for_status.called <=== False here
    mock_head.reset_mock()
    mock_head.return_value.status_code = 400
    self.fe.verify_secondary_hostnames('publishedName', ['hostname'])
    mock_head.raise_for_status.called <=== Still false here.

1 个答案:

答案 0 :(得分:0)

您可以在单元测试中尝试这样的事情:

(102400 - 1023) * 0.0832 + (102400 - 1023 - 51200) * 0.0819