如何模拟任何未直接调用的函数?

2024-02-13

TL;DR

我如何修补或模拟“任何未被直接调用/使用的函数”?

设想

我有一个简单的单元测试片段

# utils/functions.py
def get_user_agents():
    # sends requests to a private network and pulls data
    return pulled_data


# my_module/tasks.py
def create_foo():
    from utils.functions import get_user_agents
    value = get_user_agents()
    # do something with value
    return some_value


# test.py
class TestFooKlass(unittest.TestCase):
    def setUp(self):
        create_foo()

    def test_foo(self):
        ...

Here in setUp()我正在调用的方法get_user_agents()功能间接地通过致电create_foo()。在这次执行期间我得到了socket.timeout例外,因为get_user_agents()尝试访问专用网络。

那么,我如何操作返回数据或整个get_user_agents测试期间功能?

另外,有什么方法可以在整个测试套件执行期间保留这个模拟/补丁吗?


间接调用该函数并不重要 - 重要的是对其进行修补因为它是进口的 https://docs.python.org/3/library/unittest.mock.html#id6。在您的示例中,您将要在测试函数内部进行本地修补的函数导入,因此它只会在函数运行时导入。在这种情况下,您必须修补从其模块导入的函数(例如'utils.functions.get_user_agents'):

class TestFooKlass(unittest.TestCase):
    def setUp(self):
        self.patcher = mock.patch('utils.functions.get_user_agents',
                                  return_value='foo')  # whatever it shall return in the test 
        self.patcher.start()  # this returns the patched object, i  case you need it
        create_foo()

    def tearDown(self):
        self.patcher.stop()

    def test_foo(self):
        ...

如果您在模块级别导入了该函数,例如:

from utils.functions import get_user_agents

def create_foo():
    value = get_user_agents()
    ...

您应该修补导入的实例:

        self.patcher = mock.patch('my_module.tasks.get_user_agents',
                                  return_value='foo')

至于为所有测试修补模块:您可以开始修补setUp如上所示,并将其停止在tearDown.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何模拟任何未直接调用的函数? 的相关文章

随机推荐