2017-03-22 58 views
1

我有以下file1.py其中有代碼。 我試圖創建模擬測試,測試run_q()蟒蛇模擬爲mysql

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) 

回答

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 ===================