繁体   English   中英

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

[英]How to mock a url path returning response in Django / Python?

我有一个像这样的 function:

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): 

Any ideas on how to create an url path returning a response within the scope of the test (only standard Django, Python, pytest, unittest) would be very much appreciated

该文档写得非常好,并且非常清楚如何模拟您想要的任何内容。 但是,假设您有一项服务可以让第 3 方 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM