我可以在python中修补静态方法吗?

eld*_*evy 6 python

我在python中有一个包含静态方法的类.我想要mock.patch它,看看它是否被调用.当我尝试这样做时,我收到一个错误: AttributeError: path.to.A does not have the attribute 'foo'

我的设置可以简化为:

class A:
    @staticMethod
    def foo():
        bla bla
Run Code Online (Sandbox Code Playgroud)

现在测试代码失败并出现错误:

def test():
    with mock.patch.object("A", "foo") as mock_helper:
        mock_helper.return_value = ""
        A.some_other_static_function_that_could_call_foo()
        assert mock_helper.call_count == 1
Run Code Online (Sandbox Code Playgroud)

veg*_*ie1 7

您可以随时使用patch装饰器,这是我首选的修补方法:

from mock import patch

@patch('absolute.path.to.class.A.foo')
def test(mock_foo):
    mock_foo.return_value = ''
    # ... continue with test here
Run Code Online (Sandbox Code Playgroud)

编辑:您的错误似乎暗示您的代码中的其他地方有问题.可能是某些需要此方法失败的信号或触发器?


The*_*ude 7

当我尝试使用装饰器修补方法时,我收到了同样的错误消息@patch

这是我得到的完整错误。

Traceback (most recent call last):
File "/usr/local/lib/python3.6/site-packages/tornado/testing.py", line 136, in __call__ 
    result = self.orig_method(*args, **kwargs)
File "/usr/local/lib/python3.6/unittest/mock.py", line 1171, in patched     
    arg = patching.__enter__()
File "/usr/local/lib/python3.6/unittest/mock.py", line 1243, in __enter__
    original, local = self.get_original()
File "/usr/local/lib/python3.6/unittest/mock.py", line 1217, in get_original
    "%s does not have the attribute %r" % (target, name)
AttributeError: <module 'py-repo.models.Device' from
        '/usr/share/projects/py-repo/models/Device.py'> does not have the attribute 'get_device_from_db'
Run Code Online (Sandbox Code Playgroud)

我最终解决这个问题的方法是更改​​我使用的补丁装饰器

@patch('py-repo.models.Device.get_device_from_db')

@patch.object(DeviceModel, 'get_device_from_db')

我真的希望我能进一步解释为什么这是问题所在,但我自己对 Python 还很陌生。补丁文档对于确定可用的内容特别有帮助。重要提示:我应该注意,get_device_from_db使用@staticmethod装饰器可能会改变一些事情。希望它有帮助。