首页 > 其他分享 >pytest中的monkeypatch

pytest中的monkeypatch

时间:2023-04-11 20:22:06浏览次数:37  
标签:tests demo py pytest monkeypatch test

一、猴子补丁简介

在有些场景下的测试可能需要修改全局配置或者系统变量等操作,而这些操作仅仅是为了做一些测试,不希望永久的修改,此时就需要使用猴子补丁了,猴子补丁,即monkeypatch,是一个fixture,它提供了以下方法:

monkeypatch.setattr(obj, name, value, raising=True)
monkeypatch.setattr("somemodule.obj.name", value, raising=True)
monkeypatch.delattr(obj, name, raising=True)
monkeypatch.setitem(mapping, name, value)
monkeypatch.delitem(obj, name, raising=True)
monkeypatch.setenv(name, value, prepend=None)
monkeypatch.delenv(name, raising=True)
monkeypatch.syspath_prepend(path)
monkeypatch.chdir(path)

当测试结束后或者fixture执行完成后,monkeypatch中做的所有修改都将恢复

二、通过猴子补丁临时修改函数功能

如下,可以通过猴子补丁修改Path的home属性,进而临时修改函数的功能,然后进行测试,这样测试结束后,Path的home属性并不会真的发生修改

 

执行结果如下,很明显,在test_home测试函数中,Path.home属性并没有发生修改

$ pytest -s -v
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('D:\\src\\blog\\tests\\.hypothesis\\examples')
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 2 items

test_demo.py::test_getssh PASSED
test_demo.py::test_home C:\Users\hitre
PASSED

========================================================================== 2 passed in 0.13s ===========================================================================

三、通过猴子补丁取消测试函数中request的使用

在conftest.py中编写如下代码即可

 

 

四、通过猴子补丁对环境变量测测试

如下,假设get_os_user_lower函数为被测函数,用例中可以通过猴子补丁对变量进行临时设置或删除,这样可以保证测试用例的准确性,否则当环境变量被修改或者被删除后,用例的稳定性将会收到影响

test_demo.py代码如下:

 

 执行结果如下:

$ pytest -v
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('D:\\src\\blog\\tests\\.hypothesis\\examples')
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 2 items

test_demo.py::test_upper_to_lower PASSED [ 50%]
test_demo.py::test_raise_exception PASSED [100%]

========================================================================== 2 passed in 0.13s ===========================================================================

上述代码可以通过fixture继续优化如下:

 

 执行结果如下:

$ pytest -v
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('D:\\src\\blog\\tests\\.hypothesis\\examples')
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 2 items

test_demo.py::test_upper_to_lower PASSED [ 50%]
test_demo.py::test_raise_exception PASSED [100%]

========================================================================== 2 passed in 0.13s ===========================================================================

五、通过猴子补丁对字典数据模拟测试

test_demo.py代码如下,其中DEFAULT_CONFIG为被测字典,create_connection_string为被测函数,测试当被测字典被修改或者被删除时的情况

 

 执行结果如下:

$ pytest -v
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('D:\\src\\blog\\tests\\.hypothesis\\examples')
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 2 items

test_demo.py::test_connection PASSED [ 50%]
test_demo.py::test_missing_user PASSED [100%]

========================================================================== 2 passed in 0.13s ===========================================================================

上述代码可以通过fixture进行优化,如下:

 

 执行结果如下:

$ pytest -v
========================================================================= test session starts ==========================================================================
platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\Python39\python.exe
cachedir: .pytest_cache
hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('D:\\src\\blog\\tests\\.hypothesis\\examples')
rootdir: D:\src\blog\tests, configfile: pytest.ini
plugins: allure-pytest-2.9.43, caterpillar-pytest-0.0.2, hypothesis-6.31.6, forked-1.3.0, rerunfailures-10.1, xdist-2.3.0
collected 2 items

test_demo.py::test_connection PASSED [ 50%]
test_demo.py::test_missing_user PASSED [100%]

========================================================================== 2 passed in 0.12s ===========================================================================

 

标签:tests,demo,py,pytest,monkeypatch,test
From: https://www.cnblogs.com/zhang-ye/p/17307541.html

相关文章

  • python的pytest框架
    pytest和unittest的区别:1.安装需求不同。pytest为第三方单元测试库,需额外安装;unittest为标准库,无需额外安装。2.用例编写规则不同。pytest编写规则较为简单,兼容性较好;unittest需按照固定的格式编写,较为复杂。 pytest优点:能够支持简单的单元测试和复杂的功能测试,还可以用来做s......
  • unittest框架、Pytest框架
    unittest+pytestunittest单元测试框架unittest是python内置的单元测试框架,具备编写用例、组织用例、执行用例、输出报告等自动化框架的条件。unittest工作原理unittest结构图:testcase:一个完整的测试单元,执行该测试单元可以完成对某一个问题的验证,完整体现在:测试前环境准备......
  • python+playwright 学习-50 pytest-playwright 多账号操作解决方案
    前言pytest-playwright插件可以让我们快速编写pytest格式的测试用例,它提供了一个内置的page对象,可以直接打开页面操作。但是有时候我们需要2个账号是操作业务流程,比如A账号创建了一个任务,需要用到B账号去操作审批动作等。如果需要2个账号同时登录,可以使用context上下文,它可......
  • pytest多进程运行用例,缩短测试时间
    -n表示多进程执行用例,如下所示‘2'表示2个进程同时执行用例,数值的确定要根据执行机的cpu核数前置条件:安装pytest-xdist插件,安装命令“pipinstallpytest-xdist注意:每个进程执行的测试用例是随机的,不可控,所以测试用例要解耦1importos23importpytest45#整个项......
  • pytest生成简单测试报告命令,不用安装插件
    --junit-xml=./repot/result.xml生成JunitXML文件可在命令终端输入:pytest./case/test_DS_004.py--junit-xml=./repot/result.xml    --pastebin=all生成在线测试报告可在命令终端输入:pytest./case/test_DS_004.py--pastebin=all ......
  • pytest常用运行参数
    -s显示打印信息print()-v显示详细信息:执行的用例、结果、进度、用例个数、执行时间-k运行用例名称中包含某个字符串的测试用例-q简化输出信息:用例数量、进度、执行时间-x如果出现一条测试用例失败,则退出测试,一般用于调试测试用例指定运行测试目录  使用分隔符“::......
  • unittest和pytest的区别之用例编写规则更正
     搜索网上关于unittest和pytest区别大多数图1如下所示,但是pytest用例编写规则2)并非如此,在pycharm尝试发现:测试方法、测试函数以“test"开头即可,见图2-1,图2-2所示     ......
  • pytest--conftest.py全局用例公用
    前言当多个测试用例文件,需要调用同一个fixture时候。比如登陆的fixture,连接数据库的fixture,如果在每个测试用例文件里都加上fixture,代码就会看着十分别扭,且测试用例与fixture混杂在一起,不方便维护。那么pytest也提供了conftest.py这个文件来帮助我们完成对fixture的管理 conft......
  • 【Python】 pytest 之Hook函数 (钩子函数)
    Hook函数(钩子函数)钩子函数在pytest称之为Hook函数,它pytest框架的开发者,为了让用户更好的去扩展开发预留的一些函数。而预留的这些函数,在整个测试执行的生命周期中特定的阶段会自动去调用执行关于 pytest 中的预留钩子,可以通过开发插件,和在conftest.py去实现这些钩子......
  • 【pytest】 pytest自定义标记 PytestUnknownMarkWarning处理方式
    未注册标记会出现warningssummary-- PytestUnknownMarkWarningPytestUnknownMarkWarning:Unknownpytest.mark.demo-isthisatypo?Youcanregistercustommarkstoavoidthiswarning-fordetails,seehttps://docs.pytest.org/en/stable/how-to/mark.html@......