我无法在post方法中修补请求。我看了http://www.voidspace.org.uk/python/mock/patch.html#where-to-patch。但是我不知道我在哪里犯了这个错误。
结构
tests.py
package
__init__.py
module.py
包/ module.py
import requests
import mock
class Class(object):
def send_request(self):
...
response = requests.post(url, data=data, headers=headers)
return response
tests.py
@mock.patch('package.module.requests.post')
def some_test(request_mock):
...
data = {...}
request_mock.return_value = data
# invoke some class which create instance of Class
# and invokes send_request behind the scene
request_mock.assert_called_once_with()
回溯
Traceback (most recent call last):
File "tests.py", line 343, in some_test
request_mock.assert_called_once_with()
File "/home/discort/python/project/env/local/lib/python2.7/site-packages/mock/mock.py", line 941, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'post' to be called once. Called 0 times.
答案 0 :(得分:1)
您正在使用requests.post(...)
而不是
from requests import post
...
post()
无论在哪里修补&package; module.module.requests.post'或者' requests.post'。两种方式都可以。
#package.module
...
class Class(object):
def send_request(self):
response = requests.post('https://www.google.ru/')
return response
#tests.test_module
...
@patch('requests.post')
def some_test(request_mock):
obj = Class()
res = obj.send_request()
request_mock.assert_called_once_with('https://www.google.ru/')
这个带有send_request
显式调用的变体是通过的。你觉得send_request
被召唤了吗?