pytest.mark简介

pytest.markpytest 框架中的一个功能,它允许你标记测试函数或类,这样你就可以在运行测试时选择性地执行它们。使用标记,你可以实现以下功能:

  1. 条件执行:你可以根据标记来决定哪些测试应该被执行。
  2. 分组:可以将测试分为不同的组,比如按功能、重要性或速度分组。
  3. 参数化 :可以使用 pytest.mark.parametrize 装饰器来为测试函数提供多个参数集。
  4. 跳过测试 :使用 pytest.mark.skippytest.mark.skipif 可以跳过某些测试。
  5. 预计失败 :使用 pytest.mark.xfail 可以标记预计会失败的测试。

以下是一些 pytest.mark 的常见用法:

跳过测试

复制代码
import pytest

@pytest.mark.skip(reason="not implemented yet")
def test_feature_not_implemented():
    ...

条件性跳过

复制代码
import pytest

@pytest.mark.skipif(sys.platform == 'win32', reason="does not run on Windows")
def test_linux_only_feature():
    ...

预计失败

python

复制代码
import pytest

@pytest.mark.xfail(reason="bug 123")
def test_feature_with_bug():
    ...

参数化测试

复制代码
import pytest

@pytest.mark.parametrize("input,expected", [("3+5", 8), ("2+4", 6)])
def test_add(input, expected):
    assert eval(input) == expected

选择性执行

假设你有一个标记 smoke,你可以通过命令行运行所有带有这个标记的测试:

复制代码
pytest -m smoke

标记测试函数:

复制代码
@pytest.mark.smoke
def test_important_feature():
    ...

通过这种方式,pytest.mark 提供了强大的测试组织和管理能力,使得测试更加灵活和可控。

相关推荐
努力搬砖的咸鱼1 天前
AI Agent测试全景图:它到底改变了什么
人工智能·python·ai·集成测试·pytest·agent·ai编程
X1A0RAN2 天前
自动化流水线提效·微观篇:pytest 执行顺序优化
自动化·pytest
久久学姐10 天前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
小白上线*^_^*10 天前
Pytest 自动化测试框架速通指南(二)
软件测试·pytest·python测试框架·ai测试基础
Logintern0911 天前
pytest的AST 断言重写
pytest
Tinyfacture12 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest
ji_shuke14 天前
从零深入:基于 Playwright + Pytest + Allure 的企业级 Web 端到端自动化测试框架实战
前端·自动化测试·docker·jenkins·pytest·allure·playwright
祉猷并茂,雯华若锦15 天前
Selenium+Pytest自动化测试框架实战
selenium·测试工具·pytest
祉猷并茂,雯华若锦17 天前
Pytest+Selenium自动化测试:失败自动截图集成Allure报告
selenium·测试工具·pytest
我的xiaodoujiao20 天前
API 接口自动化测试详细图文教程学习系列32--Allure测试报告2
python·学习·测试工具·pytest