2015-08-21 28 views
2

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

+0

而不是使用'patch'你可以只是做'example.MyClass.my_function =假()'。這確實意味着你沒有清理。 –

+1

@ThomWiggers在做完這樣的猴子補丁後,我該如何去清理呢? –

+0

恩,我想'del example.MyClass.my_function'應該可以工作... –

回答

-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' 
... 
+0

我不能模擬出整個類,因爲我想讓所有真正的代碼執行,而不是我試圖模擬的函數。而且,這隻有在類上定義了'method()'時纔有效。我的問題具體問到如何模擬一個沒有在課堂上定義的功能。沒有'def method ...'部分運行你的代碼給了我這個錯誤:'AttributeError:'Class'對象沒有屬性'method''。 –