Pytest - 高级进阶mock

作者: 红薯爱帅 | 来源:发表于2018-04-05 22:02 被阅读73次

    1. 概述

    Mock测试是在测试过程中对可能不稳定、有副作用、不容易构造或者不容易获取的对象,用一个虚拟的对象来创建以便完成测试的方法。在Python中这种测试是通过第三方的mock库完成的,mock在Python3.3的时候被引入到Python标准库中,改名为unittest.mock。之前的Python版本都需要安装:pip install mock

    初学者理解mock比较抽象,可以简单理解为函数指针,通过mock成员方法或变量,可以指定mock对象的返回值,获取是否被调用、被调用次数、调用时的参数等。

    2. 使用方法

    2.1. 简介

    • 在test方法前,添加decorator @mock.patch('pyfile.func', return_value='None'),可以完成对pyfile.func的mock,并指定return_value为‘None’,在test方法的参数中增加mock_func即可
    • 单个test方法引用多个mock.patch decorator时,patch从下向上,test方法的参数从左向右,依次对应(可以有剩余的参数,但是必学是已经声明的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方法的调用次数和参数数据

    • 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

    详细内容参考官网

    2.3. 执行结果

    通过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方法中通过循环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,构造虚拟函数的调用

    $ 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 - 高级进阶mock

      本文链接:https://www.haomeiwen.com/subject/lnidhftx.html