python 模拟 mysql

python mock for mysql

我有以下 file1.py,其中有代码。 我正在尝试创建模拟测试来测试 run_q()

file1.py

def exec_mysql(query):
    mysql_conn = MySqlActions(..)
    ..
    cur.execute(query)
    mysql_conn.commit()
    mysql_conn.close()

def run_q():
    qa = "delete from table where dts = '%s'" % val
    exec_mysql(qa)

下面是模拟代码。不确定如何呈现 run_q() 方法的模拟。这是正确的呈现方式吗?

test_file1.py

import mock
@mock.patch('file1.exec_mysql')
def test_run(mysql_mock)
    run_q = mock.Mock()
    query = "delete from table where dts = '2015-01-01'"
    mysql_mock.assert_called_with(query)

你几乎做对了。无需模拟 run_q - 您只需在测试中调用它即可。

工作示例:

app.py

def exec_mysql(query):
    # do something
    return query


def run_q():
    qa = 'blahblahblah'
    exec_mysql(qa)

tests.py

from unittest import mock
from app import run_q

@mock.patch('app.exec_mysql')
def test_run_q(mysql_mock):
    run_q()
    mysql_mock.assert_called_with('blahblahblah')

测试执行:

$ pytest -vvv tests.py 
===================== test session starts =====================
platform linux -- Python 3.5.2, pytest-3.2.1, py-1.4.34 
cachedir: .cache
rootdir: /home/kris/projects/tmp, inifile:
plugins: mock-1.6.2, celery-4.1.0
collected 1 item                                               

tests.py::test_run_q PASSED

================== 1 passed in 0.00 seconds ===================