当前位置: 首页>编程语言>正文

pytest中的pytest_addoption钩子函数 pytest标签

一、前言

mark主要用来标记用例,通过不同的标记实现不同的运行策略。一个大项目自动化用例时,可以划分多个模块,也可以使用标记功能,标明哪些是模块1用例,哪些是模块2的,运行代码时候指定mark名称运行就可以。

二、学习目标

1.@pytest.mark.自定义标签

2.组合运行用例

3.注册、管理 mark 标记

三、知识点

1.【@pytest.mark.自定义标签

(一)可以标记测试方法、测试类,标记名可以自定义,最好起有意义的名字;

(二)同一测试类/方法可同时拥有多个标记;

  • 语法:
@pytest.mark.标签名
  • 代码示例:
import pytest

@pytest.mark.login
class TestLogin:
    """登陆功能测试类"""

    @pytest.mark.smoke
    @pytest.mark.success
    def test_login_sucess(self):
        """登陆成功"""
        print("---用例1:登录成功---")

    @pytest.mark.failed
    def test_login_failed(self):
        """登陆失败"""
        print("---用例2:登陆失败---")


@pytest.mark.logout
class TestLogout:
    """退出功能测试类"""

    @pytest.mark.smoke
    @pytest.mark.success
    def test_logout_sucess(self):
        """退出成功"""
        print("---用例3:退出成功---")

    @pytest.mark.failed
    def test_logout_failed(self):
        """退出失败"""
        print("---用例4:退出失败---")
  • 运行效果:
    运行语法: pytest -m "自定义标签名"pytest.main(['-m 自定义标签名'])可以在终端运行或py文件的主函数运行。
pytest -m "smoke" test_demo.py
test_demo.py:4
  C:\Users\Admin\Desktop\教学资料\自动化教学源码+PPT\理论课代码\pytest_demo\test_demo.py:4: PytestUnknownMarkWarning: Unknown pytest.mark.login - is this a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/late
st/mark.html
    @pytest.mark.login
...
========================== 2 passed, 2 deselected, 8 warnings in 0.02s =======================

2.【注册、管理 mark 标记】

由上面的运行结果可以看出,用例只运行了标签为"smoke"的用例,但是运行会出现告警信息。那么如何解决这些告警呢?首先要明白,使用mark标记时,是需要注册的,如果不注册就会出现告警。

  • 方式一:在conftest.py文件当中,通过hock注册:
#conftest.py文件
def pytest_configure(config):
    config.addinivalue_line("markers", "smoke:标记只运行冒烟用例")
    config.addinivalue_line("markers", "login:标记只运行登录用例")
    config.addinivalue_line("markers", "logout:标记只运行退出用例")
    config.addinivalue_line("markers", "success:标记只运行成功用例")
    config.addinivalue_line("markers", "failed:标记只运行失败用例")
  • 方式二:创建pytest.ini文件,在文件中注册:
[pytest]
markers =
    smoke:smoke case
    login:login case
    logout:logout case
    success:success case
    failed:failed case

addopts = --strict

“addopts = --strict” 参数来严格规范 mark 标记的使用,当使用未注册的 mark 标记时,pytest会直接报错。

pytest.ini文件文件的更多用法,我们后面专门拿出一节课来介绍。

3.【组合运行用例】

其实当我们运行的时候,也可以指定多个标签。

  1. 使用 -m 参数运行标记的测试用例;
  2. -m 参数支持 and、or 、not 等表达式;

终端运行:

# 运行登陆功能但是不运行登陆失败的测试用例
pytest -m "login and not failed" test_demo.py
# 运行登出功能但是不运行登出成功的测试用例
pytest -m "logout and not success" test_demo.py
# 运行登陆和登出的用例
pytest -m "login or logout" test_demo.py




https://www.xamrdz.com/lan/5jy1961061.html

相关文章: