使用 mock.patch 给我 AttributeError("<module 'package1''> does not have the attribute 'myfunc'"?

Gol*_*ame 12 python testing unit-testing pytest python-unittest

我正在尝试使用mock.patch 来模拟几个函数。为了便于阅读,我已经缩减了示例。这是带有我的测试用例的 test.py:

from unittest import mock
import pytest
@mock.patch("package1.myfunc")
def test_myfunc(mymock):
    inst1 = MyClass()
    inst1.myfunc()
Run Code Online (Sandbox Code Playgroud)

这是 mycode.py 中的源代码

import package1
class MyClass:
    def__init__(self):
        pass
    def myfunc(self): #wrapper
        package1.myfunc()
    
Run Code Online (Sandbox Code Playgroud)

我这样做正确吗?为什么我会收到属性错误?我没有对“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
Run Code Online (Sandbox Code Playgroud)

小智 11

从python自己的文档中你可以看到装饰器是这样使用的: @patch('package.module.ClassName.attribute', sentinel.attribute)

来源:https://docs.python.org/3/library/unittest.mock-examples.html

在这种情况下,您似乎缺少 ClassName。你应该使用

@mock.patch("package1.MyClass.myfunc")
Run Code Online (Sandbox Code Playgroud)