Python 使用_uinit__uu.py模拟修补程序
我的代码组织如下: dir/A.py:Python 使用_uinit__uu.py模拟修补程序,python,unit-testing,mocking,Python,Unit Testing,Mocking,我的代码组织如下: dir/A.py: from X import Y class A: ... dir/\uuuu init\uuuuu.py: from .A import A __all__ = ['A'] 测试/测试结果: class test_A: @patch("dir.A.Y") def test(self, mock_Y): .... 在运行tests/test_A.py时,我(如预期)得到错误: AttributeError: &
from X import Y
class A:
...
dir/\uuuu init\uuuuu.py:
from .A import A
__all__ = ['A']
测试/测试结果:
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'
AttributeError:没有属性“Y”
问题是@patch(“dir.A.y”)
试图在类dir.A.A
中查找y
,而不是在模块dir.A
中(它实际存在的地方)
这显然是因为我的\uuuu init\uuuu.py
。我可以通过将模块名A
和类名A
更改为不同的符号来克服这个问题
从代码的组织方式来看,我希望避免这样的命名更改。如何使用
patch
,使其在正确的位置找到Y
。您可以使用patch.object()
装饰器,并从sys.modules
检索模块:
@patch.object(sys.modules['dir.A'], 'Y')
def test(self, mock_Y):
...
基本上是我所说的,但更早。:-)@MartijnPieters:这个问题基本上只有一个答案