为什么我用请求模拟 URL 不起作用?

Why does my mocking of an URL with requests not work?

我尝试模拟一个特定的 URL,如本例所示: How can I mock requests and the response? 测试我自己的功能:

class URLStatus():
  @staticmethod
  def check(url, redirects):
    try:
      session = requests.Session()
      session.max_redirects = redirects
      urlcheck = session.get(url)
      return urlcheck.status_code

问题是它从不接受模拟的 url,而是只接受真实的。

import requests

from unittest import TestCase, mock
from unittest.mock import patch

from lib.checks.url_status import URLStatus


def mocked_requests_get(*args, **kwargs):
  class MockResponse:
    def __init__(self, json_data, status_code):
      self.json_data = json_data
      self.status_code = status_code

    def json(self):
      return self.json_data

  if args[0] == 'http://someurl.com/test.json':
    return MockResponse({"key1": "value1"}, 200)
  elif args[0] == 'http://someotherurl.com/anothertest.json':
    return MockResponse({"key2": "value2"}, 200)

  return MockResponse(None, 404)

class URLStatusTestCase(TestCase):

  @mock.patch('lib.checks.url_status.requests.get', side_effect=mocked_requests_get)
  def test_check(self, mock_get):

    url_status = URLStatus()
    test_data = url_status.check('http://someurl.com/test.json', 5)
    self.assertEqual(test_data, 200)


if __name__ == '__main__':
  unittest.main()

例如,这个失败,因为它将“http://someurl.com/test.json”视为 404,而不是 200。我不知道为什么会这样。

如何让它接受模拟的 URL?

您在模拟错误的函数。 requests.get 是一个方便的函数,它创建自己的一次性 Session,然后使用其 get 方法提供结果。您的 check 方法正在使用其 own Session 对象;您至少需要模拟该对象的 get 方法。

鉴于您没有在其他地方重复使用此会话,最简单的方法可能是更改 实现以利用 requests.get:

class URLStatus():
    @staticmethod
    def check(url, redirects):
        return requests.get(url, max_redirects=redirects).status_code