Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将请求\u模拟适配器传递到测试函数_Python_Mocking_Python Requests - Fatal编程技术网

Python 将请求\u模拟适配器传递到测试函数

Python 将请求\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

我试图在我正在测试的函数上使用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)
    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