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

Python 为什么我用请求模拟URL不起作用?,python,python-requests,mocking,python-unittest,Python,Python Requests,Mocking,Python Unittest,我试图模拟一个特定的URL,如本例所示: 要测试我自己的功能: class URLStatus(): @staticmethod def check(url, redirects): try: session = requests.Session() session.max_redirects = redirects urlcheck = session.get(url) return urlcheck.status_code 问

我试图模拟一个特定的URL,如本例所示: 要测试我自己的功能:

class URLStatus():
  @staticmethod
  def check(url, redirects):
    try:
      session = requests.Session()
      session.max_redirects = redirects
      urlcheck = session.get(url)
      return urlcheck.status_code
问题是它从不使用模拟的url,而是只使用真实的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()
例如,这个失败是因为它将“”视为404而不是200。我不知道为什么会这样


如何使用模拟的URL?

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

考虑到您没有在其他地方重用此会话,更改其实现以利用
请求可能是最简单的方法。get

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

您正在模拟
请求。获取
;您的函数调用会话。获取。