将请求模拟适配器传递到被测试函数

2024-10-03 17:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

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

这将返回一个错误,表明模拟适配器没有进入被测试函数。在

^{pr2}$

如何将模拟适配器传递到函数中?在


Tags: 函数intesturladaptersessiondefrequests
1条回答
网友
1楼 · 发布于 2024-10-03 17:27:34

这行不通,因为您必须使用session.head而不是requests.head。 在不干扰主函数代码的情况下这样做的一个可能性是使用^{}

from unittest.mock import patch

[...]

with patch('requests.head', session.head):
    update = getModificationTimeHTTP('mock://test.com')
assert update

相关问题 更多 >