使用mysql.connector数据库连接时要修补哪个目标?

时间:2015-07-20 09:03:55

标签: python unit-testing python-3.x dependency-injection mocking

修补数据库查询:

导入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.connectorg)作为目标?

如何模仿execute()close()

1 个答案:

答案 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.closecursor.execute以及cursor.close