[英]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.