【发布时间】:2017-12-07 21:04:09
【问题描述】:
我对@987654323@ 有一个特殊的问题。我想将它与 pytest 一起使用来测试我的 API 包装库。
我尝试使用first example in the requests_mock docs,但我把它放在一个test_mock()-函数中,并添加了一个assert-statement 供pytest 发现它。
以下代码失败:
# 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'
因为我可以通过 ipython 使 requests_mock 工作,所以我认为问题出在 pytest 上,但我可能错了。
似乎根本没有使用适配器,因此 requests 将真正的 http 请求发送到目标 url,而不是使用模拟对象。
我正在使用 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 ===========================
【问题讨论】:
标签: python mocking python-requests pytest