为什么最简单的requests_mock示例使用pytest失败?

时间:2017-12-07 21:04:10

标签: python mocking python-requests pytest

我对requests_mock有一个奇怪的问题。我想将它与pytest一起使用来测试我的API包装器库。

我尝试使用first example in the requests_mock docs,除了我把它放在 test_mock() -function中并为pytest添加assert - 语句以便发现它

以下代码失败:

# tests/test_mock.py

import requests
import requests_mock

with requests_mock.Mocker() as m:
    def test_mock():
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'

但是,在ipython中运行以下示例时,它按预期工作。这是example

中的确切代码
with requests_mock.Mocker() as m:
    m.get('http://test.com', text='resp')
    print(requests.get('http://test.com').text)

# prints 'resp'

因为我可以让requests_mock从ipython开始工作,我认为问题出在pytest上,但我可能错了。

似乎根本没有使用适配器,因此请求会向目标网址发送真实的http请求,而不是使用模拟对象。

我使用的是Python 3.6.3(Anaconda3),requests_mock 1.3.0和pytest 3.3.0

运行失败代码的输出:

C:\dev\mylib>pytest -v
============================= test session starts =============================
platform win32 -- Python 3.6.3, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 -- e:\anaconda3\envs\benv\python.exe
cachedir: .cache
rootdir: C:\dev\mylib, inifile: setup.cfg
collected 1 item

tests/test_mocks.py::test_mock FAILED                                    [100%]

================================== FAILURES ===================================
__________________________________ test_mock __________________________________

    def test_mock():
        m.get('http://test.com', text='resp')
>       assert requests.get('http://test.com').text == 'resp'
E       assert '<!DOCTYPE ht...y>\n</html>\n' == 'resp'
E         + resp
E         - <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
E         - <html>
E         - <head>
E         - <title>Client Validation</title>
E         - <script type="text/javascript">
E         - function setCookie(c_name, value, expiredays) {...
E
E         ...Full output truncated (26 lines hidden), use '-vv' to show

tests\test_mocks.py:9: AssertionError
------------------------------ Captured log call ------------------------------
connectionpool.py          208 DEBUG    Starting new HTTP connection (1): test.com
connectionpool.py          396 DEBUG    http://test.com:80 "GET / HTTP/1.1" 302 161
connectionpool.py          824 DEBUG    Starting new HTTPS connection (1): www.test.com
connectionpool.py          396 DEBUG    https://www.test.com:443 "GET / HTTP/1.1" 200 None
========================== 1 failed in 2.05 seconds ===========================

1 个答案:

答案 0 :(得分:3)

为什么它在IPython中起作用对我来说似乎是一个谜。要解决这个问题,只需将函数定义的行与上下文管理器的开头交换。

# tests/test_mock.py

import requests
import requests_mock

def test_mock():
    with requests_mock.Mocker() as m:
        m.get('http://test.com', text='resp')
        assert requests.get('http://test.com').text == 'resp'