Pytest - 高级进阶mock

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Startup 单元测试的核心价值在于两点: 更加精确地定义某段代码的作用,从而使代码的耦合性更低 避免程序员写出...
    wuwenxiang阅读 13,412评论 1 27
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    小迈克阅读 8,175评论 1 3
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,736评论 6 427
  • 本文试图总结编写单元测试的流程,以及自己在写单元测试时踩到的一些坑。如有遗漏,纯属必然,欢迎补充。 目录概览: 编...
    苏尚君阅读 8,753评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,084评论 19 139

友情链接更多精彩内容