我有以下带有代码的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)
答案 0 :(得分:1)
你几乎做对了。无需模拟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 ===================