gpt4 book ai didi

Python Mock_requests : Can I use wildcards in the url parameter of the Mocker? 与pytest一起使用时如何实现url的模式匹配?

转载 作者:行者123 更新时间:2023-12-04 16:45:40 25 4
gpt4 key购买 nike

我编写了一个测试,试图将异常模拟为请求获取操作的副作用。我正在使用 requests_mock库,如下面的代码 list 所示:

def test_owm_client_raises_error_for_timeout_error(owm_proxy: OWMProxy) -> None:

with requests_mock.Mocker() as m:
m.get(
"http://api.openweathermap.org/geo/1.0/direct/*",
exc=request_exceptions.Timeout,
)

city = "london"
utc_now = datetime.now(timezone.utc)
target_time = int((utc_now + timedelta(hours=10)).timestamp())

with pytest.raises(APIException):
owm_proxy.for_time(city, datetime.fromtimestamp(target_time).isoformat())
是否可以使用通配符参数模拟 url,例如 http://api.openweathermap.org/geo/1.0/direct/* ?到目前为止,我可以模拟模拟超时错误的预期效果的唯一方法是使用 requests.ANY作为模拟中的 url 参数。

最佳答案

创建一个 regex pattern来自 re.compile()您可以将其作为 documented 输入到请求模拟程序中:

import re

import pytest
import requests
import requests_mock


def test_owm_client_raises_error_for_timeout_error():
with requests_mock.Mocker() as m:
# This is the regex pattern. Currently, it will accept any text after the base URL below. Update this if your requirements are stricter.
matcher = re.compile('http://api.openweathermap.org/geo/1.0/direct/.*')

# For simplicity, let's say we will just raise ValueError for the target URL
m.get(
matcher,
exc=ValueError("Mocked error!"),
)

# Test if the exception ValueError will be raised if we accessed the target URLs
with pytest.raises(ValueError):
requests.get("http://api.openweathermap.org/geo/1.0/direct/")
with pytest.raises(ValueError):
requests.get("http://api.openweathermap.org/geo/1.0/direct/abcde")
with pytest.raises(ValueError):
requests.get("http://api.openweathermap.org/geo/1.0/direct/12345")
with pytest.raises(ValueError):
requests.get("http://api.openweathermap.org/geo/1.0/direct/abcde/12345")
with pytest.raises(ValueError):
requests.get("http://api.openweathermap.org/geo/1.0/direct/abcde/12345?any=thing&in=here")

# Test if the mocked request wouldn't be used if the URL is different. Thus, the exception should show that the URL wasn't mocked.
with pytest.raises(requests_mock.exceptions.NoMockAddress):
requests.get("http://api.openweathermap.org/geo/1.0/direct2/")
with pytest.raises(requests_mock.exceptions.NoMockAddress):
requests.get("http://api.openweathermap.org/geo/1.0/direct2/abcde")
输出:
$ pytest -q
.
1 passed in 0.07s

关于Python Mock_requests : Can I use wildcards in the url parameter of the Mocker? 与pytest一起使用时如何实现url的模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69179740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com