1. 概述
Mock測試是在測試過程中對可能不穩(wěn)定、有副作用、不容易構(gòu)造或者不容易獲取的對象,用一個虛擬的對象來創(chuàng)建以便完成測試的方法。在Python中這種測試是通過第三方的mock庫完成的,mock在Python3.3的時候被引入到Python標(biāo)準(zhǔn)庫中,改名為unittest.mock。之前的Python版本都需要安裝:pip install mock
初學(xué)者理解mock比較抽象,可以簡單理解為函數(shù)指針,通過mock成員方法或變量,可以指定mock對象的返回值,獲取是否被調(diào)用、被調(diào)用次數(shù)、調(diào)用時的參數(shù)等。
2. 使用方法
2.1. 簡介
- 在test方法前,添加decorator @mock.patch('pyfile.func', return_value='None'),可以完成對pyfile.func的mock,并指定return_value為‘None’,在test方法的參數(shù)中增加mock_func即可
- 單個test方法引用多個mock.patch decorator時,patch從下向上,test方法的參數(shù)從左向右,依次對應(yīng)(可以有剩余的參數(shù),但是必學(xué)是已經(jīng)聲明的fixture),樣例如下
@mock.patch('os.remove')
@mock.patch('os.listdir')
@mock.patch('shutil.copy')
def test_unix_fs(mocked_copy, mocked_listdir, mocked_remove):
UnixFS.rm('file')
os.remove.assert_called_once_with('file')
assert UnixFS.ls('dir') == expected
# ...
UnixFS.cp('src', 'dst')
# ...
2.2. 示例代碼
pytest2.py
# -*- coding:utf-8 -*-
import pytest
import mock
@pytest.fixture(scope='function', params=[1, 2, 3]) # multiple test cases
def mock_data_params(request):
return request.param
def test_not_2(mock_data_params):
print('test_data: %s' % mock_data_params)
assert mock_data_params != 2
##################
def _call(x):
return '{} _call'.format(x)
def func(x):
return '{} func'.format(_call(x))
def test_func_normal():
for x in [11, 22, 33]: # multiple test cases
# print '{} - {}'.format(x, func(x))
assert func(x) == '{} _call func'.format(x)
@mock.patch('pytest2._call', return_value='None') # set mock 'pytest2._call'.return_value is 'None', also could use mock_call.return_value='None'
def test_func_mock(mock_call):
for x in [11, 22, 33]:
# print '{} - {}'.format(x, func(x))
ret = func(x)
assert mock_call.called # True or False
assert mock_call.call_args == ((x,),) # This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with
assert ret == 'None func' # because mock_call.return_value is 'None', so the result here is 'None func'
如何獲取mock方法的調(diào)用次數(shù)和參數(shù)數(shù)據(jù)
mock_call.called # True or False
mock_call.call_args # This is either None (if the mock hasn’t been called), or the arguments that the mock was last called with
-
mock_call.return_value
image.png -
mock_call.side_effect # This can either be a function to be called when the mock is called, an iterable or an exception (class or instance) to be raised
image.png
詳細內(nèi)容參考官網(wǎng)
- Python3 unittest.mock.Mock
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock - pytest-mock
https://pypi.python.org/pypi/pytest-mock - pytest-mock github
https://github.com/pytest-dev/pytest-mock/
2.3. 執(zhí)行結(jié)果
通過fixture的param功能,完成多用例測試
$ pytest -v pytest2.py::test_not_2
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.14, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /home/kevin/soft/anaconda2/bin/python
cachedir: .cache
Using --randomly-seed=1522926920
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: randomly-1.0.0, mock-1.2, cov-2.0.0
collected 3 items
pytest2.py::test_not_2[3] PASSED
pytest2.py::test_not_2[2] FAILED
pytest2.py::test_not_2[1] PASSED
==================================================================================== FAILURES ====================================================================================
_________________________________________________________________________________ test_not_2[2] __________________________________________________________________________________
mock_data_params = 2
def test_not_2(mock_data_params):
print('test_data: %s' % mock_data_params)
> assert mock_data_params != 2
E assert 2 != 2
pytest2.py:10: AssertionError
------------------------------------------------------------------------------ Captured stdout call ------------------------------------------------------------------------------
test_data: 2
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
============================================================= 1 failed, 2 passed, 1 pytest-warnings in 0.02 seconds ==============================================================
在test方法中通過循環(huán)dataset完成多用例測試
$ pytest -vs pytest2.py::test_func_normal
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.12, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /usr/bin/python
cachedir: .cache
Using --randomly-seed=1522930543
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: xdist-1.15.0, randomly-1.0.0, mock-1.2, cov-2.0.0, celery-4.0.1
collected 6 items
pytest2.py::test_func_normal PASSED
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
================================================================== 1 passed, 1 pytest-warnings in 0.01 seconds ===================================================================
通過mock,構(gòu)造虛擬函數(shù)的調(diào)用
$ pytest -vs pytest2.py::test_func_mock
============================================================================== test session starts ===============================================================================
platform linux2 -- Python 2.7.12, pytest-3.0.0, py-1.5.2, pluggy-0.3.1 -- /usr/bin/python
cachedir: .cache
Using --randomly-seed=1522930553
rootdir: /home/kevin/learn/python-web/tox/case2, inifile:
plugins: xdist-1.15.0, randomly-1.0.0, mock-1.2, cov-2.0.0, celery-4.0.1
collected 6 items
pytest2.py::test_func_mock PASSED
============================================================================= pytest-warning summary =============================================================================
WC1 None pytest_funcarg__cov: declaring fixtures using "pytest_funcarg__" prefix is deprecated and scheduled to be removed in pytest 4.0. Please remove the prefix and use the @pytest.fixture decorator instead.
================================================================== 1 passed, 1 pytest-warnings in 0.00 seconds ===================================================================
3. 參考
- pytest
https://docs.pytest.org/en/latest/example/markers.html - pytest-mock
https://pypi.python.org/pypi/pytest-mock - Python3 unittest.mock.Mock
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock

