4
我无法单元测试使用肯尼斯·赖茨的requests库中的函数它的响应:如何单元测试/模拟requests.get(URL)
下面的功能是进行单元测试:
def getPage(url):
r = requests.get(url)
r.raise_for_status() # raises HTTPError if necessary
dom = fromstring(r.text)
dom.make_links_absolute(url)
return dom
我的单元测试目前如下。 (虽然显然这是行不通的。)
@patch('requests.Response')
@patch('requests.Response.raise_for_status', return_value=None)
@patch('requests.get', return_value=requests.Response)
def test_getPage(mock_requests_get, mock_RFS, mock_response):
with open("domtest.htm", "r") as testfile:
mock_response.text = testfile.read()
dom = getPage('http://www.test.com')
eq_(dom, dom_test)
产生的回溯是:
Traceback (most recent call last):
File "C:\Anaconda\lib\site-packages\nose\case.py", line 197, in runTest
self.test(*self.arg)
File "C:\Anaconda\lib\site-packages\mock.py", line 1201, in patched
return func(*args, **keywargs)
File "C:\...\test_myfile.py", line 79, in test_getPage
dom = getPage('http://www.test.com')
File "C:\...\myfile.py", line 67, in getPage
r.raise_for_status() # raises HTTPError if necessary
TypeError: unbound method raise_for_status() must be called with Response instance as first argument (got nothing instead)
怎样一个单元测试,这样使用嘲讽,而不是暂时性的网络服务器的功能?我尝试酸洗响应并将其设置为requests.get()的返回值,但不能进行酸洗。
我也用,这是件好事。 – Adeel
该文档缺少有关如何检查代码所做请求的信息。根据我迄今为止收集的内容,您只能访问上次提出的请求,但在测试发出多个请求的函数/方法时,这是不够的。否则,这是一个相当不错的项目。 - 另外,过去我使用过https://pypi.python.org/pypi/wsgi_intercept,但这对于简单的外部服务调用来说有点矫枉过正。 – pumazi