zl程序教程

您现在的位置是:首页 >  IT要闻

当前栏目

pytest学习和使用11-Pytest如何使用自定义标记mark?

2023-03-07 09:42:13 时间

1 mark简介

  • pytest可自定义标记;
  • 把一个大项目自动化用例,划分多个模块,标明哪些是模块A用例,哪些是模块B的,运行代码时候指定mark名称运行就可以。

2 使用方法

@pytest.mark.自定义名称

3 实例

# -*- coding:utf-8 -*-
# 作者:NoamaNelson
# 日期:2022/11/18 
# 文件名称:test_mark.py
# 作用:自定义标记mark的使用
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson

import pytest

@pytest.mark.login
def test_login():
    print("用户登陆")

@pytest.mark.case_a
def test_case_a():
    print("执行用例a")

@pytest.mark.case_b
def test_case_b():
    print("执行用例b")

@pytest.mark.quit
def test_quit():
    print("用户退出")
  • 运行一个标记:
pytest -s -m login test_mark.py
collected 4 items / 3 deselected / 1 selected

test_mark.py 用户登陆
.
  • 运行多个标记:
pytest -s -m "login or case_a or case_b or quit" test_mark.py
collected 4 items

test_mark.py 用户登陆
.执行用例a
.执行用例b
.用户退出
.
  • 不运行某个标记,直接取反即可:
pytest -s -m "not quit" test_mark.py
collected 4 items / 1 deselected / 3 selected

test_mark.py 用户登陆
.执行用例a
.执行用例b
.

4 如何忽略警告?

  • 运行上述标记后,有很多警告信息,如下:
============================================== warnings summary ==============================================
test_mark.py:11
  F:\pytest_study\test_case\test_e\test_mark.py:11: PytestUnknownMarkWarning: Unknown pytest.mark.login - is th
is a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/s
table/mark.html
    @pytest.mark.login

test_mark.py:15
  F:\pytest_study\test_case\test_e\test_mark.py:15: PytestUnknownMarkWarning: Unknown pytest.mark.case_a - is t
his a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/
stable/mark.html
    @pytest.mark.case_a

test_mark.py:19
  F:\pytest_study\test_case\test_e\test_mark.py:19: PytestUnknownMarkWarning: Unknown pytest.mark.case_b - is t
his a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/
stable/mark.html
    @pytest.mark.case_b

test_mark.py:23
  F:\pytest_study\test_case\test_e\test_mark.py:23: PytestUnknownMarkWarning: Unknown pytest.mark.quit - is thi
s a typo?  You can register custom marks to avoid this warning - for details, see https://docs.pytest.org/en/st
able/mark.html
    @pytest.mark.quit

-- Docs: https://docs.pytest.org/en/stable/warnings.html
================================ 3 passed, 1 deselected, 4 warnings in 0.03s =================================
  • 那如何避免这些警告呢?
  • 我们需要创建一个pytest.ini文件,加上自定义mark;
  • 另外,pytest.ini需要和运行的测试用例同一个目录,或在根目录下作用于全局;
  • 后边再详细学习pytest.ini,先看下本文如何避免警告,我们在用例同级目录创建一个pytest.ini
    在这里插入图片描述
  • 并写入以下内容:
[pytest]
markers =
    login: 这是用户登陆功能
    case_a: 这是用例a
    case_b: 这是用例b
    quit: 这是用户退出功能
  • 再次运行标记,发现警告信息没有了:
pytest -s -m "login or case_a or case_b or quit" test_mark.py
collected 4 items

test_mark.py 用户登陆
.执行用例a
.执行用例b
.用户退出
.

============================================= 4 passed in 0.03s ==============================================