如何从 python 中的不同文件修补 requests.get

How to patch requests.get from a different file in python

我有 2 个 python 文件:1 个用于单元测试 (tests.py) 和 1 个用于我要测试的脚本 (main.py):

# In main.py:

import requests

def get_response(url):
    response = requests.get(url);
    # Do stuff...
    return response

-

# In tests.py

from unittest import mock
from unittest.mock import patch
from my_project.main import get_response

def some_handler(url):
    return "test_response"

class GetResponseTestCase(unittest.TestCase):

    def setUp(self):

        # setup mocks
        patch('requests.get', mock.Mock(side_effect=some_handler)

    def run_test(self):

        result = get_response("test_response")

我想将 requests.get 修补到 return test_response,但是修补不起作用,因为它试图向 request/make 发送到 [=33= 的连接] 提供。我认为补丁名称 requests.get 并不像某些人在网上提到的那样针对它在 main.py 中使用的位置(因为它指的是定义它的位置)。但在这种情况下,我不确定如何解决这个问题。

如果 main.py 中使用了 import requests 那么我如何从另一个文件中修补它?谢谢。

发现我需要在创建补丁的调用末尾添加.start()

# setup mocks
patch('requests.get', mock.Mock(side_effect=some_handler).start()

如果此解决方案有任何问题,或者有更好的处理方法,我很乐意听到!

  1. 模拟 get_reponse 而不是模拟 requests.get(模拟内置函数;虽然可以在 python 中不需要这样一个简单的用例)。
  2. mocked get_response 函数的 return 值设置为 "test_response".

在tests.py

from unittest import mock

class GetResponseTestCase(unittest.TestCase):

    @mock.patch("my_project.main.get_response") ##mocking get_response
    def run_test(self, mocked_get_response):
        mocked_get_response.return_value = "test_response" ## setting return value