【问题标题】:Mock patch a function that doesn't exist on a class模拟修补类中不存在的函数
【发布时间】:2015-11-15 15:18:30
【问题描述】:

使用 Python 的 mock 框架,是否可以模拟修补类中不存在的函数。如果有,怎么做?

例如:

example.py

import mock
import unittest


class MyClass(object):
    pass


class MyTests(unittest.TestCase):

    def test_mock_non_existent_function(self):
        with mock.patch('example.MyClass.my_function'):
            pass

运行该测试会引发错误:

Error
Traceback (most recent call last):
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1193, in patched
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1268, in __enter__
  File "/Users/jesse/Code/my_proj/lib/mock.py", line 1242, in get_original
AttributeError: <class 'example.MyClass'> does not have the attribute 'my_function'

使用Python 2.7.9mock 1.0.1

【问题讨论】:

  • 你可以使用example.MyClass.my_function = Mock(),而不是使用patch。这确实意味着您没有进行清理。
  • @ThomWiggers 在做了这样的猴子补丁后,我该如何清理?
  • 呃,我猜del example.MyClass.my_function 应该可以工作...

标签: python python-2.7 unit-testing mocking


【解决方案1】:

我相信这里的答案是使用create 参数:

with mock.patch.object(MyClass, 'my_function', create=True)

这在替换原始代码中的等效行时有效。

【讨论】:

    【解决方案2】:

    您需要以某种方式指定要修补的功能。 来自mock docs

    >>> class Class(object):
    ...     def method(self):
    ...         pass
    ...
    >>> with patch('__main__.Class') as MockClass:
    ...     instance = MockClass.return_value
    ...     instance.method.return_value = 'foo'
    ...     assert Class() is instance
    ...     assert Class().method() == 'foo'
    ...
    

    【讨论】:

    • 我无法模拟出整个类,因为我希望执行所有真实代码,而不是我试图模拟的函数。此外,这仅在类上定义了method() 时才有效。我的问题专门询问如何模拟未在类中定义的函数。在没有def method... 部分的情况下运行您的代码会给我这个错误:AttributeError: 'Class' object has no attribute 'method'
    猜你喜欢
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-10
    • 2023-03-16
    • 2011-09-12
    相关资源
    最近更新 更多