简体   繁体   English

模拟导入模块时调用的 function

[英]Mock a function which is called when a module is imported

I want to test a module A which uses decorators with arguments.我想测试一个模块A ,它使用带有 arguments 的装饰器。 The arguments get evaluated when the module A is loaded. arguments 在模块A加载时得到评估。 For some of the decorator args, I set the value by calling a function foo in module B .对于一些装饰器参数,我通过调用模块B中的 function foo来设置值。

# A.py
import B

@deco(arg1=B.foo())
def bar():
  ...

When I want to test A , I want to mock B.foo so that the decorator argument is set for my test cases.当我想测试A时,我想模拟B.foo以便为我的测试用例设置装饰器参数。 I think that B.foo must be mocked before A loads B .我认为B.foo必须在A加载B之前被嘲笑。

In the unit test, as a caller of A , how do I mock B.foo to ensure the mocked version is used when evaluating the decorator arguments in A ?在单元测试中,作为A的调用者,我如何模拟B.foo以确保在评估A中的装饰器 arguments 时使用模拟版本?

If you want to ensure that the mock is really used, you have to reload module A after patching foo , as bar already had been evaluated with the original foo .如果要确保真正使用模拟,则必须在修补foo后重新加载模块A ,因为bar已经使用原始foo进行了评估。 You could wrap that in a fixture like this (untested):您可以将其包装在这样的夹具中(未经测试):

import importlib
import pytest
from unittest import mock
import A

@pytest.fixture
def mocked_foo():
    with mock.patch('B.foo') as mocked:
        importlib.reload(A)
        yield mocked

def test_bar(mocked_foo):
    ...

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

相关问题 如何模拟从不同模块导入的方法中导入的函数 - How to mock a function, that is imported within an imported method from different module 使用模拟来模拟导入的模块以测试Pylons控制器功能 - Using mock to mock an imported module for testing a Pylons controller function 从导入的模块重新定义被调用的函数 - Redefining a called function from an imported module 在Python中模拟导入的模块 - Mock imported module in Python 如何在导入模块中模拟 function 的 class 但在 function 的 scope 之外? - How to mock a function of a class in an imported module but outside the scope of a function? python - 如何在使用Pytest的模块的全局范围内调用python中的函数? - How to mock a function in python which is called in the global scope of a module using Pytest? Python AWS Lambda 的单元测试:在导入模块之前模拟 function - Unit test for Python AWS Lambda: mock function before module is imported pytest 模拟我自己在测试 function 中导入的模块 - pytest mock my own module imported in tested function 在导入模块之前,正在从模块调用 function - A function is being called from a module, before the module was imported 如何模拟使用别名导入的 function? - How do I mock a function which is imported with an alias?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM