首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >requests.raise_for_status()的Pytest raise测试失败

requests.raise_for_status()的Pytest raise测试失败
EN

Stack Overflow用户
提问于 2016-02-20 20:41:24
回答 1查看 6.3K关注 0票数 10

我最近开始使用pytest,甚至最近开始使用mock来模拟requests库。我已经创建了一个requests.Response对象,对于200状态代码,它工作得很好。我在这里尝试做的是,使用raise_for_status()来检查是否存在超过速率限制的错误,并测试它是否使用pytest处理了异常。

我使用的是模拟side_effect选项,它似乎触发了我希望的异常,但是pytest似乎没有意识到这是已经发生的,所以测试失败。

有什么想法吗?我相信这显然是我遗漏了一些东西!

我为这个类编写的代码是:

代码语言:javascript
复制
class APIClient:
    def get_records(self, url):
        try:
            r = requests.get(url)
            r.raise_for_status()
            return r.json()
        except requests.HTTPError as e:
            print("Handling the exception")

在测试类中,我得到了:

代码语言:javascript
复制
@pytest.fixture
def http_error_response(rate_limit_json):
    mock_response = mock.Mock()
    mock_response.json.return_value = rate_limit_json
    mock_response.status_code = 429

    mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError

    return mock_response


class TestRecovery(object):

    @mock.patch('requests.get')
    def test_throws_exception_for_rate_limit_error\
    (self, mock_get, api_query_object, http_error_response):

        mock_get.return_value = http_error_response
        print(http_error_response.raise_for_status.side_effect)

        url = api_query_object.get_next_url()

        with pytest.raises(requests.exceptions.HTTPError):
            api_query_object.get_records(url)

我得到的输出是:

代码语言:javascript
复制
    with pytest.raises(requests.exceptions.HTTPError):
>           api_query_object.get_records(url)
E           Failed: DID NOT RAISE

---------------------- Captured stdout call ---------------------- 
<class 'requests.exceptions.HTTPError'>
Handling the exception
EN

回答 1

Stack Overflow用户

发布于 2020-08-26 19:36:22

您正在指示pytest期待一个应该在APIClient.get_records中引发的异常,但是在该方法定义中,您已经捕获了该异常并只执行了一次打印。

异常实际上正在发生,并通过在控制台输出中查看打印结果证明了这一点。

相反,您应该通过模拟检查raise_for_status方法是否已被调用。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35523402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档