如何在Django/Python中模拟返回响应的url路径



我有一个这样的函数:

def get_some_data(api_url, **kwargs)
# some logic on generating headers
# some more logic
response = requests.get(api_url, headers, params)
return response

我需要创建一个假的/模拟的";api_url";,当向发出请求时,将生成有效的响应。我知道如何嘲笑回应:

def mock_response(data):
response = requests.Response()
response.status_code = 200
response._content = json.dumps(data)
return response

但我需要这样做测试调用:

def test_get_some_data(api_url: some_magic_url_path_that_will_return_mock_response): 

任何关于如何在测试范围内创建返回响应的url路径的想法(只有标准的Django、Python、pytest、unittest(都将非常感谢

文档写得很好,非常清楚如何模拟您想要的任何东西。但是,假设你有一个服务,使第三方API调用:

def foo(url, params):
# some logic on generating headers
# some more logic
response = requests.get(url, headers, params)
return response

在测试中,您希望模拟此服务的返回值。

@patch("path_to_service.foo")
def test_api_call_response(self, mock_response):
mock_response.return_value = # Whatever the return value you want it to be
# Here you call the service as usual 
response = foo(..., ...)

# Assert your response

最新更新