使用 __init__.py 进行 Mock 补丁

11

我的代码组织结构如下:

dir/A.py:

from X import Y

class A:
    ...

dir/__init__.py:

from .A import A
__all__ = ['A']

测试/test_A.py:

class test_A:
    @patch("dir.A.Y")
    def test(self, mock_Y):
        ....
在运行 tests/test_A.py 时,我(如预期)收到以下错误:
AttributeError: <class 'dir.A.A'> does not have the attribute 'Y'
问题在于@patch("dir.A.y")试图在类dir.A.A中查找Y,而不是在模块dir.A中(实际上它在那里)。
这显然是由于我的__init__.py引起的。我可以通过更改模块名称A和类名称A为不同的符号来克服这个问题。
按照代码组织方式,我想避免这样的命名更改。如何使用patch以便它可以在正确的位置找到Y
1个回答

15
你可以使用patch.object()修饰器,而且可以从sys.modules中检索模块:
@patch.object(sys.modules['dir.A'], 'Y')
def test(self, mock_Y):
    ...

基本上是我之前说的话。 :-) - Martijn Pieters
1
@MartijnPieters:这个问题基本上只有一个答案。 :) - Sven Marnach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接