模拟修补一个在类上不存在的函数

时间:2015-08-21 15:41:05

标签: python python-2.7 unit-testing mocking

使用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

2 个答案:

答案 0 :(得分:2)

我相信这里的答案是使用[1] "f:" [1] "f test" [1] "o:" [1] "o test" [1] "n:" [1] "n test" [1] "c:" [1] "c test" [1] "s:" [1] "s test" [1] "i:" [1] "i test" [1] "m:" [1] "m test" [1] "x:" [1] "x test" [1] "d:" [1] "d test" [1] "y:" [1] "y test" [1] "t:" [1] "t test" [1] "p:" [1] FALSE 参数:

create

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

答案 1 :(得分:-1)

您需要以某种方式指定要修补的功能。 来自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'
...