我正在尝试使用mock.patch模拟几个功能。为了简化可读性,我已经简化了示例。这是我的测试用例的test.py:
from unittest import mock
import pytest
@mock.patch("package1.myfunc")
def test_myfunc(mymock):
inst1 = MyClass()
inst1.myfunc()
这是mycode.py中的源代码
import package1
class MyClass:
def__init__(self):
pass
def myfunc(self): #wrapper
package1.myfunc()
我这样做正确吗?为什么会出现属性错误?我对“ mymock”不做任何其他事情的原因是,我只是希望调用的函数什么也不做。我还需要为其添加返回值吗?
详细的错误消息:
exc_info = (<class 'AttributeError'>, AttributeError("<module 'package1' from '/.../site-packages/package1/__init__.py'> does not have the attribute 'myfunc'"), <traceback object at 0x7f2b86392640>)
patching = <unittest.mock._patch object at 0x7f2b86a479d0>
@wraps(func)
def patched(*args, **keywargs):
extra_args = []
entered_patchers = []
exc_info = tuple()
try:
for patching in patched.patchings:
> arg = patching.__enter__()
/.../python3.7/lib/python3.7/unittest/mock.py:1247:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
/.../python3.7/unittest/mock.py:1319: in __enter__
original, local = self.get_original()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <unittest.mock._patch object at 0x7f2b86a479d0>
def get_original(self):
target = self.getter()
name = self.attribute
original = DEFAULT
local = False
try:
[name] original = target.__dict__
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
if name in _builtins and isinstance(target, ModuleType):
self.create = True
if not self.create and original is DEFAULT:
raise AttributeError(
> "%s does not have the attribute %r" % (target, name)
)
E AttributeError: <module 'package1' from '....'> does not have the attribute 'myfunc'
/.../python3.7/unittest/mock.py:1293: AttributeError
答案 0 :(得分:0)
从python自己的文档可以看到装饰器是这样使用的:
@patch('package.module.ClassName.attribute', sentinel.attribute)
来源:https://docs.python.org/3/library/unittest.mock-examples.html
在这种情况下,您似乎缺少 ClassName。你应该使用
@mock.patch("package1.MyClass.myfunc")