测试开发技术网站
博客
设计
设计
开发
Python
测试
unittest
运维
Linux基础应用
CI/CD
CI/CD
数据库
数据库
云计算
云计算
云原生
云原生
爬虫
爬虫
数据分析
数据分析
人工智能
人工智能
登录
注册
Pytest----fixture高级应用
收藏本文
作者:redrose2100 类别: 日期:2022-05-13 16:11:16 阅读:1028 次 消耗积分:0 分
[TOC] ![](https://redrose2100.oss-cn-hangzhou.aliyuncs.com/img/7cd47362-951c-11ee-986a-0242ac110004.png) ## 一、通过request获取模块及文件中的属性 通过request可以获取到测试文件及模块的属性值,这样就可以动态的对测试文件做一些操作或者控制,本质上就是pytest中的反射 如下在test_demo.py的代码,其中定义了一个变量name ```python name="张无忌" def test_func3(): assert 10==9 ``` 如下为conftest.py代码,这里定义了一个module级的fixture,在这个fixture中可以获取到用例中的name属性,在实际应用中,比如就可以通过获取到的属性值进一步做一些判断或者处理等等,这里仅仅打印出来展示一下 ```python import pytest @pytest.fixture(autouse=True,scope="module") def session_fixture(request): name=getattr(request.module,"name",None) print(name) ``` 执行结果如下: ```bash $ pytest -s ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 1 item test_demo.py 张无忌 F =============================================================================== FAILURES =============================================================================== ______________________________________________________________________________ test_func3 ______________________________________________________________________________ def test_func3(): > assert 10==9 E assert 10 == 9 test_demo.py:6: AssertionError ======================================================================= short test summary info ======================================================================== FAILED test_demo.py::test_func3 - assert 10 == 9 ========================================================================== 1 failed in 0.10s =========================================================================== ``` ## 二、通过marker向fixture传值 可以通过request.node获取到marker对象,进而获取到其参数,从而可以向fixture传递此参数,具体示例如下 test_demo.py代码如下: ```python import pytest @pytest.fixture() def fixt(request): marker = request.node.get_closest_marker("fixt_data") if marker is None: data = None else: data = marker.args[0] return data @pytest.mark.fixt_data(42) def test_fixt(fixt): assert fixt == 42 ``` 执行结果为: ```bash $ pytest ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 1 item test_demo.py . [100%] =========================================================================== warnings summary =========================================================================== test_demo.py:14 D:\src\blog\tests\test_demo.py:14: PytestUnknownMarkWarning: Unknown pytest.mark.fixt_data - is this a typo? You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/stable/mark.html @pytest.mark.fixt_data(42) -- Docs: https://docs.pytest.org/en/stable/warnings.html ===================================================================== 1 passed, 1 warning in 0.02s ===================================================================== ``` ## 三、将工厂函数作为fixture 可以将工厂函数作为fixture,这样可以在测试用例中很方便的构造一些对象,如下 test_demo.py代码如下: ```python import pytest @pytest.fixture def make_customer_record(): def _make_customer_record(name): return {"name": name, "orders": []} return _make_customer_record def test_customer_records(make_customer_record): customer_1 = make_customer_record("Lisa") customer_2 = make_customer_record("Mike") customer_3 = make_customer_record("Meredith") print("\n") print(customer_1) print(customer_2) print(customer_3) ``` 执行结果如下: ```bash $ pytest -s ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 1 item test_demo.py {'name': 'Lisa', 'orders': []} {'name': 'Mike', 'orders': []} {'name': 'Meredith', 'orders': []} . ========================================================================== 1 passed in 0.03s =========================================================================== ``` ## 四、支持参数化的fixture 定义fixture中使用params,然后再fixture中通过request.param抛出,则可以实现参数化的过程,即params中有几个参数就可以执行几个测试用例,亦即数据驱动,如下params中有三个参数,虽然这里只有一个测试函数,但从执行结果可以看出仍然显示是执行了三个测试用例 test_demo.py代码如下 ```python import pytest @pytest.fixture(scope="function",params=[1,2,3]) def f1(request): print("in f1 fixture ...") yield request.param def test_func(f1): print(f1) assert f1>0 ``` 执行结果如下 ```bash $ pytest -s ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 3 items test_demo.py in f1 fixture ... 1 .in f1 fixture ... 2 .in f1 fixture ... 3 . ========================================================================== 3 passed in 0.04s =========================================================================== ``` ## 五、参数化的fixture指定用例id 如下,通过pytest --collect-only 查看id test_demo.py的代码如下: ```python import pytest @pytest.fixture(scope="function",params=[1,2,3]) def f1(request): print("in f1 fixture ...") yield request.param def test_func(f1): print(f1) assert f1 > 0 ``` 执行结果如下 ```bash $ pytest --collect-only ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 3 items
====================================================================== 3 tests collected in 0.02s ====================================================================== ``` 修改test_demo.py代码如下,通过ids设置用例id ```python import pytest @pytest.fixture(scope="function",params=[1,2,3],ids=["test_01", "test_02","test_03"]) def f1(request): print("in f1 fixture ...") yield request.param def test_func(f1): print(f1) assert f1 > 0 ``` 然后执行,结果如下,可以发现,此时用例id已经发生了变化 ```bash $ pytest --collect-only ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.7, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 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 3 items
====================================================================== 3 tests collected in 0.03s ====================================================================== ``` ## 六、参数化的fixture指定某个参数使用skip标记 在使用参数的fixture的时候,对一些被测数值也可以像普通的测试函数一样使用skip标记跳过,如下 test_demo.py代码如下: ```python import pytest @pytest.fixture(scope="function",params=[1,2,pytest.param(3,marks=pytest.mark.skip)]) def f1(request): print("in f1 fixture ...") yield request.param def test_func(f1): print(f1) assert f1 > 0 ``` 执行结果如下: ```bash $ pytest -v ========================================================================= test session starts ========================================================================== platform win32 -- Python 3.9.6, pytest-6.2.5, py-1.10.0, pluggy-1.0.0 -- D:\python39\python.exe cachedir: .pytest_cache hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('G:\\src\\blog\\tests\\.hypothesis\\examples') rootdir: G:\src\blog\tests 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 3 items test_demo.py::test_func[1] PASSED [ 33%] test_demo.py::test_func[2] PASSED [ 66%] test_demo.py::test_func[3] SKIPPED (unconditional skip) [100%] ===================================================================== 2 passed, 1 skipped in 0.19s ===================================================================== ``` ## 七、调用参数化的fixture可以实现两组数据的全排列组合测试数据 当在一个测试函数中调用两个参数化的fixture,可以实现两组参数的全排列组合,比如一个参数列表为[1,2],另一个fixture的参数列表为[10,20],当一个测试函数同时调用此两个fixture时,则会产生[(1,10),(1,20),(2,10),(2,20)]这样四组被测数据 test_demo.py代码如下 ```python import pytest @pytest.fixture(scope="function",params=[1,2]) def f1(request): print("in f1 fixture setup...") yield request.param print("in f1 fixture teardown...") @pytest.fixture(scope="function",params=[10,20]) def f2(request): print("in f2 fixture setup...") yield request.param print("in f2 fixture teardown...") def test_func(f1,f2): assert f2
assert f2
assert f2
assert f2
assert f2
始终坚持开源开放共享精神,同时感谢您的充电鼓励和支持!
版权所有,转载本站文章请注明出处:redrose2100, http://blog.redrose2100.com/article/182
上一篇:
Pytest----Pytest中fixture基础应用
下一篇:
Pytest----Pytest如何使用临时目录和文件
搜索
个人成就
出版书籍
《Pytest企业级应用实战》
测试开发技术全栈公众号
测试开发技术全栈公众号
DevOps技术交流微信群
加微信邀请进群
常用网站链接
开源软件洞察
云原生技术栈全景图
Python语言官方文档
Golang官方文档
Docker官方文档
Jenkins中文用户手册
Scrapy官方文档
VUE官方文档
Harbor官方文档
openQA官方文档
云原生开源社区
开源中国
Kubernetes中文文档
Markdown语法官方教程
Kubernetes中文社区
Kubersphere官方文档
BootStrap中文网站
JavaScript中文网
NumPy官方文档
Pandas官方文档
GitLink确实开源网站
数据库排名网站
编程语言排名网站
SEO综合查询网站
数学加减法练习自动生成网站
Kickstart Generator
文章分类
最新文章
最多阅读
特别推荐
×
Close
登录
注册
找回密码
登录邮箱:
登录密码:
图片验证码:
注册邮箱:
注册密码:
邮箱验证码:
发送邮件
注册邮箱:
新的密码:
邮箱验证码:
发送邮件