[英]How to mock cursor.execute
I am trying to write a test for the below code without integrating a mysql database.我正在尝试在不集成 mysql 数据库的情况下为以下代码编写测试。 Is it possible?
是否可以?
def sql_query_select(select, table, condition, variable):
cursor = database_connection("cursor")
sql_query = "SELECT " + select + " from " + table + " where " + condition + " = " + "'" + variable + "'"
cursor.execute(sql_query)
try:
response = cursor.fetchone()[0]
except:
response = cursor.fetchone()
cursor.close()
return response
I have tried the following code as a test我尝试了以下代码作为测试
@mock.patch("lambda_function.database_connection")
@mock.patch("pymysql.cursors.Cursor.execute")
def test_sql_query_select(self, mock_database_connection, mock_execute):
mock_database_connection.return_value = "cursor"
mock_execute.return_value = "test"
self.assertEqual(lambda_function.sql_query_select("select", "table", "condition", "variable"), "execute")
But get the following error and am not sure how to proceed.但是出现以下错误,我不确定如何继续。
E AttributeError: 'str' object has no attribute 'execute'
You are already trying to mock database_connection()
.您已经在尝试模拟
database_connection()
。 You don't need to also mock cursor.execute()
since you can inject the behavior you want to the return value of database_connection()
.您不需要也模拟
cursor.execute()
因为您可以将您想要的行为注入到database_connection()
的返回值中。 The problem is that you need to mock objects where they are used rather than where they are defined.问题是您需要在使用它们的地方而不是在定义它们的地方模拟对象。 It looks like
sql_query_select()
is in a file named lambda_function.py
, so the mock looks like this:看起来
sql_query_select()
位于名为lambda_function.py
的文件中,因此模拟看起来像这样:
@mock.patch(lambda_function.database_connection)
def test_sql_query_select(self, mock_database_connection):
mock_record = ('record one', 'record two')
mock_database_connection.return_value.fetchone.return_value = mock_record
result = lambda_function.sql_query_select("select", "table", "condition", "variable")
self.assert_equal(mock_record, result)
One problem with this kind of test is that it completely ignores the parameters to sql_query_select()
.这种测试的一个问题是它完全忽略了
sql_query_select()
的参数。 One solution is to verify that database_connection.return_value.execute
was called.一种解决方案是验证是否调用了
database_connection.return_value.execute
。
This is also unsatisfying since you are testing implementation rather than behavior.这也不令人满意,因为您正在测试实现而不是行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.