PropertyMock 在每次调用后更改值
PropertyMock with changing values after every call
我正在尝试模拟 psycopg2 并且需要处理 cursor.description
# run query 1
column_names = [desc[0] for desc in cursor.description]
# run query 2
# NB cursor.description now returns different value
column_names = [desc[0] for desc in cursor.description]
我可以通过 PropertyMock 做到这一点:
type(fake_cursor).description = PropertyMock(return_value=descriptions[0])
但这并没有解决我的问题,因为被测系统做了两次查询,第二次的描述会有所不同。
如何在第二次调用时更改模拟的 return 值?
我试过了:
cursor_execute_call_count = 0
def handle_cursor_execute(arg1, arg2):
cursor_execute_call_count = cursor_execute_call_count + 1
type(fake_cursor).description = PropertyMock(return_value=descriptions[cursor_execute_call_count])
fake_cursor.execute = Mock(side_effect=handle_cursor_execute)
但我明白了
E UnboundLocalError: local variable 'cursor_execute_call_count' referenced before assignment
(这对我来说没有意义。肯定存在奇怪的范围界定问题。)
我最终确实使用了这段代码,但似乎必须有更好的方法:
def handle_cursor_execute(arg1, arg2):
description = descriptions.pop()
type(fake_cursor).description = PropertyMock(return_value=description)
根据说明进行编辑:
我想你可以实现一个迭代器:
class MyDescription():
descriptions = iter([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
def __iter__(self):
for description_list in self.descriptions:
for description in description_list:
yield description
raise StopIteration
type(fake_cursor).description = PropertyMock(return_value=MyDescription())
所以它看起来像这样:
>>> z = MyDescription()
>>> [i for i in z]
[1, 2, 3]
>>> [i for i in z]
[4, 5, 6]
>>> [i for i in z]
[7, 8, 9]
>>>
我正在尝试模拟 psycopg2 并且需要处理 cursor.description
# run query 1
column_names = [desc[0] for desc in cursor.description]
# run query 2
# NB cursor.description now returns different value
column_names = [desc[0] for desc in cursor.description]
我可以通过 PropertyMock 做到这一点:
type(fake_cursor).description = PropertyMock(return_value=descriptions[0])
但这并没有解决我的问题,因为被测系统做了两次查询,第二次的描述会有所不同。
如何在第二次调用时更改模拟的 return 值?
我试过了:
cursor_execute_call_count = 0
def handle_cursor_execute(arg1, arg2):
cursor_execute_call_count = cursor_execute_call_count + 1
type(fake_cursor).description = PropertyMock(return_value=descriptions[cursor_execute_call_count])
fake_cursor.execute = Mock(side_effect=handle_cursor_execute)
但我明白了
E UnboundLocalError: local variable 'cursor_execute_call_count' referenced before assignment
(这对我来说没有意义。肯定存在奇怪的范围界定问题。)
我最终确实使用了这段代码,但似乎必须有更好的方法:
def handle_cursor_execute(arg1, arg2):
description = descriptions.pop()
type(fake_cursor).description = PropertyMock(return_value=description)
根据说明进行编辑:
我想你可以实现一个迭代器:
class MyDescription():
descriptions = iter([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
def __iter__(self):
for description_list in self.descriptions:
for description in description_list:
yield description
raise StopIteration
type(fake_cursor).description = PropertyMock(return_value=MyDescription())
所以它看起来像这样:
>>> z = MyDescription()
>>> [i for i in z]
[1, 2, 3]
>>> [i for i in z]
[4, 5, 6]
>>> [i for i in z]
[7, 8, 9]
>>>