修补数据库查询:
导入mysql.connector 来自flask进口g
@before_request
def con():
g.db=mysql.connector.connect("credentials") #database connection
@route('/insert') #passing data for insertion as a 'json' string
def insert():
cursor = g.db.cursor()
cursor.execute('Insert into test("ID,name")')
cursor.close()
g.db.close()
test.py
def test_conn():
with patch(app.mysql.connector) as mock_mysql:
conn()
mock_mysql.connect.assert_called_with("credentials")
def test_insert():
with patch(target =?) as mock:
#mock execute() and close()?
我是否必须修补我的conn()
和g
)或(mysql.connector
和g
)作为目标?
如何模仿execute()
和close()
?
答案 0 :(得分:0)
你可以在这里模拟mysql.connector.connect
,模拟库从那里接管:
with patch(target='mysql.connector.connect') as mock:
然后代码调用connect
mock,返回存储在g.db
中的 new 模拟对象。您可以在测试函数中访问这些对象:
connection = mock.return_value
cursor = connection.cursor.return_value
然后您可以测试是否已调用connection.close
和cursor.execute
以及cursor.close
。