我尝试使用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}
答案 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))