无法对特定的类方法使用`unittest.create_autospec`

时间:2017-08-12 21:42:00

标签: python python-unittest

我尝试使用create_autospec来重新创建方法的签名。我发现这个功能没有按照我的意图运作。如果create_autospec函数由于某种原因无法创建规范,而不是默默地无法完全约束函数,那么unittest.mock函数就足以引发异常。我目前的解决方法是修改create_autospec模块中的源代码,但这个解决方案并不能让我满意。有没有正确的,pythonic'在没有签名的情况下使from inspect import signature from unittest.mock import create_autospec, Mock import sqlite3 class Class(object): def method(self): return 'Class_method' def function(): return 'function' method_mock = create_autospec(Class.method, return_value='mock_Class_method') function_mock = create_autospec(function, return_value='mock_function') cursor = sqlite3.connect(':memory:').execute('Select 1') fetchall_mock = create_autospec(cursor.fetchall, return_value='mock_cursor') print(method_mock('self')) print(function_mock()) print(fetchall_mock()) print(fetchall_mock(1)) print(cursor.fetchall()) print(cursor.fetchall()) try: method_mock() except TypeError: print('autospec working for method_mock!') try: function_mock(1234) except TypeError: print('autospec working for function_mock!') try: print(cursor.fetchall(1)) except TypeError as e: print('autospec NOT working for fetchall_mock: {0}'.format(e)) try: signature(cursor.fetchall) except ValueError as e: print(e) 失败的方法?我也想避免包装模块。我使用的是Python 3.5.2。

mock_Class_method
mock_function
mock_cursor
mock_cursor
[(1,)]
[]
autospec working for method_mock!
autospec working for function_mock!
autospec NOT working for fetchall_mock: fetchall() takes no arguments (1 given)
no signature found for builtin <built-in method fetchall of sqlite3.Cursor object at 0x7f2e8b885ea0>

输出:

filter: {'genre' : search}  

1 个答案:

答案 0 :(得分:0)

cursor = sqlite3.connect(':memory:').execute('Select 1')
fetchall_mock = create_autospec(cursor.fetchall, ...)  # This line doesn't effect cursor.

你需要修补它。

with mock.patch.object(cursor, 'fetchall', autospec=True, ...) as fetchall_mock:
   try:
       print(cursor.fetchall(1))
   except TypeError as e:
       print('autospec NOT working for fetchall_mock: {0}'.format(e))