2017-07-17 44 views
0

我越來越TypeError需要正好2個參數(0給出),而試圖嘲笑類功能使用python模擬框架。使用Python模擬框架嘲笑時TypeError

>>> class ExampleClass(): 
...  @staticmethod 
...  def _process_updates(arg1, arg2): 
...   pass 
... 
>>> 
>>> @patch("ExampleClass._process_updates") 
... def process_updates(arg1, arg2): 
... return "test" 
... 
>>> ExampleClass._process_updates() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: _process_updates() takes exactly 2 arguments (0 given) 
>>> 
+0

你如何運行第二個代碼段?修補程序修飾器僅適用於它所修飾的方法;在其他任何時候調用'_process_updates'時,該補丁不是活動的,並且使用了原始方法。 –

+0

我認爲你在'process_updates'中缺少裝飾器發送的'MagicMock'的第二個參數。 – Grimmy

+0

@DanielRoseman所有這些代碼都是在python控制檯中定義的。第二個代碼片段從上面提到的代碼已經寫入的同一個python控制檯運行。 – user2819403

回答

0

正如@DanielRoseman說,@patch替代的功能(方法)由函數將其修補使用。即在下面的例子中,函數calling_func_with_mockcalling_func的修補版本,因爲我們用process_updates代替_process_updates(在本地ExampleClass對象內)。

我認爲他們對你的關鍵是使用ExampleClass修補更高級別的功能,即。 HTH

from unittest.mock import patch 

class ExampleClass(): 
    @staticmethod 
    def _process_updates(arg1, arg2): 
     return arg1 

def patched_process_updates(arg1, arg2): 
    return arg2 

def calling_func(): 
    """Uses normal ExampleClass._process_updates""" 
    print(ExampleClass._process_updates('Hello','world')) 

@patch('__main__.ExampleClass._process_updates', new=patched_process_updates) 
def calling_func_with_mock(): 
    """Uses ExampleClass._process_updates patch""" 
    print(ExampleClass._process_updates('Hello','world')) 

if __name__=='__main__': 
    calling_func() 
    # 'Hello' 
    calling_func_with_mock() 
    # 'world'