Python 将请求\u模拟适配器传递到测试函数
我试图在我正在测试的函数上使用requests\u mockPython 将请求\u模拟适配器传递到测试函数,python,mocking,python-requests,Python,Mocking,Python Requests,我试图在我正在测试的函数上使用requests\u mock #the function def getModificationTimeHTTP(url): head = requests.head(url) modtime = head.headers['Last-Modified'] if 'Last-Modified' in head.headers \ else datetime.fromtimestamp(0, pytz.UTC) retur
#the function
def getModificationTimeHTTP(url):
head = requests.head(url)
modtime = head.headers['Last-Modified'] if 'Last-Modified' in head.headers \
else datetime.fromtimestamp(0, pytz.UTC)
return modtime
#in a test_ file
def test_needsUpdatesHTTP():
session = requests.Session()
adapter = requests_mock.Adapter()
session.mount('mock', adapter)
adapter.register_uri('HEAD', 'mock://test.com', headers= \
{'Last-Modified': 'Mon, 30 Jan 1970 15:33:03 GMT'})
update = getModificationTimeHTTP('mock://test.com')
assert update
这将返回一个错误,表明模拟适配器没有进入测试函数
InvalidSchema: No connection adapters were found for 'mock://test.com'
如何将模拟适配器传递到函数中?这不起作用,因为您必须使用
会话.head
而不是请求.head
。
在不干扰主函数代码的情况下执行此操作的一种可能性是使用:
谢谢您!从文档中可以看出:patch()的使用非常简单。关键是在正确的名称空间中进行修补。
from unittest.mock import patch
[...]
with patch('requests.head', session.head):
update = getModificationTimeHTTP('mock://test.com')
assert update