Pytest - 高級進階mock

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)

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. 參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Startup 單元測試的核心價值在于兩點: 更加精確地定義某段代碼的作用,從而使代碼的耦合性更低 避免程序員寫出...
    wuwenxiang閱讀 10,234評論 1 27
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    小邁克閱讀 3,124評論 1 3
  • # Python 資源大全中文版 我想很多程序員應(yīng)該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,836評論 6 427
  • 本文試圖總結(jié)編寫單元測試的流程,以及自己在寫單元測試時踩到的一些坑。如有遺漏,純屬必然,歡迎補充。 目錄概覽: 編...
    蘇尚君閱讀 3,556評論 0 4
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139

友情鏈接更多精彩內(nèi)容