使用Python模拟框架进行模拟时的TypeError

时间:2017-07-17 09:17:08

标签: python mocking

我在尝试使用python mock框架模拟一个类函数时,得到TypeError正好需要2个参数(给定0)。

>>> 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)
>>> 

1 个答案:

答案 0 :(得分: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'