我一直在尝试测试下面的方法,特别是if块,并尝试了多种方法,如修补、在pyodbc的各种组合中模拟,但我无法模拟if条件。
def execute_read(self, query):
dbconn = pyodbc.connect(self.connection_string, convert_unicode=True)
with dbconn.cursor() as cur:
cursor = cur.execute(query)
if not cursor.messages:
res = cursor.fetchall()
else:
raise Exception(cursor.messages[0][1])
return res;
# unit test method
@patch.object(pyodbc, 'connect')
def test_execute_read(self, pyodbc_mock):
pyodbc_mock.return_value = MagicMock()
self.assertIsNotNone(execute_read('query'))我已经阅读了unittest.mock的文档,但是如果条件已经解决了,我还没有找到一种方法来实现这一点。谢谢。
发布于 2022-09-03 13:11:51
您可能希望修补Connection类(给定游标对象是不可变的),并提供一个返回值来覆盖if块。可能看起来像:
with patch.object("pyodbc.Connection") as conn:
conn.cursor().messages = []
...我和sqlite3试过了,这对我来说很管用。
下面是一个使用修补程序对象的示例,这是我为弗雷普/编写的
def test_db_update(self):
with patch.object(Database, "sql") as sql_called:
frappe.db.set_value(
self.todo1.doctype,
self.todo1.name,
"description",
f"{self.todo1.description}-edit by `test_for_update`",
)
first_query = sql_called.call_args_list[0].args[0]
second_query = sql_called.call_args_list[1].args[0]
self.assertTrue(sql_called.call_count == 2)
self.assertTrue("FOR UPDATE" in first_query)https://stackoverflow.com/questions/73559339
复制相似问题