【问题标题】:Which target to patch when using a mysql.connector database connection?使用 mysql.connector 数据库连接时要修补哪个目标?
【发布时间】:2015-07-20 09:03:55
【问题描述】:

修补数据库查询:

导入 mysql.connector 从烧瓶导入 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()

【问题讨论】:

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


    【解决方案1】:

    你可以在这里模拟mysql.connector.connect,模拟库从那里接管:

    with patch(target='mysql.connector.connect') as mock:
    

    然后代码调用connect 模拟,返回一个存储在g.db 中的 模拟对象。您可以在测试函数中访问这些对象:

    connection = mock.return_value
    cursor = connection.cursor.return_value
    

    然后你可以测试connection.closecursor.executecursor.close是否被调用。

    【讨论】:

    • 感谢您的帮助,但您不认为我还需要修补“g”,因为它是从 Flask 导入的库,否则代码将调用“g”库
    • @guri:只要使用 Flask 测试工具,比如测试客户端或者测试请求上下文;见flask.pocoo.org/docs/0.10/testing
    猜你喜欢
    • 2015-08-16
    • 2019-05-01
    • 2023-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2012-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多