Pytest测试用例执行跳过的3种方式

文章目录

  • 1.前言
  • [2.使用 @pytest.mark.skip 标记无条件跳过](#2.使用 @pytest.mark.skip 标记无条件跳过)
  • [3.使用 @pytest.mark.skipif 标记根据条件跳过](#3.使用 @pytest.mark.skipif 标记根据条件跳过)
  • [4. 执行pytest.skip()方法跳过测试用例](#4. 执行pytest.skip()方法跳过测试用例)

1.前言

在实际场景中,我们可能某条测试用例没写完,代码执行时会报错,或者是在一些条件下不让某些测试用例去执行,这个时候我们就需要跳过一些测试用例的执行。

pytest中测试用例跳过有三种方式:

  1. @pytest.mark.skip
  2. @pytest.mark.skipif
  3. 执行pytest.skip()在测试函数内部动态跳过

2.使用 @pytest.mark.skip 标记无条件跳过

当你明确知道某个测试用例由于某些原因(如功能未实现、依赖环境不满足等)不能执行时,可以使用此标记。

示例:

python 复制代码
import pytest

def test_01():
    assert 1==1

@pytest.mark.skip(reason='测试用例无条件跳过')
def test_02():
    assert 2==2


if __name__ == '__main__':
    pytest.main()

运行结果:

3.使用 @pytest.mark.skipif 标记根据条件跳过

根据指定的条件来决定是否跳过测试用例,当条件为 True 时,测试用例会被跳过。

示例:

python 复制代码
import pytest


def test_01():
    assert 1==1

@pytest.mark.skip(reason='测试用例无条件跳过')
def test_02():
    assert 2==2

@pytest.mark.skipif(1==1,reason='条件为True时跳过')
def test_03():
    assert 3==3


if __name__ == '__main__':
    pytest.main()

4. 执行pytest.skip()方法跳过测试用例

在测试函数执行过程中,根据某些运行时的条件来决定是否跳过测试。

示例:

python 复制代码
import pytest


def test_01():
    assert 1==1

@pytest.mark.skip(reason='测试用例无条件跳过')
def test_02():
    assert 2==2

@pytest.mark.skipif(1==1,reason='条件为True时跳过')
def test_03():
    assert 3==3

def test_04():
    pytest.skip('执行测试用例时跳过')
    assert 4==4

if __name__ == '__main__':
    pytest.main()

运行结果:

相关推荐
Madison-No73 天前
pytest框架
pytest
TomEval4 天前
【测AI】第17篇:大模型评测方法论 —— LLM 怎么测?
人工智能·python·aigc·测试用例
TomEval5 天前
【测AI】第16篇:模型公平性与可解释性测试 — AI 的偏见与黑箱
人工智能·python·功能测试·ai·测试用例
川石课堂软件测试6 天前
涨薪技术|0到1学会性能测试第9课-HTTP响应统计
数据库·功能测试·网络协议·http·kubernetes·单元测试·测试用例
川石课堂软件测试7 天前
JMeter异步接口测试实战
数据库·python·jmeter·mysql·kubernetes·测试用例·prometheus
凛铄linshuo9 天前
分析业务流程什么时候适合断言?
python·pytest
凛铄linshuo10 天前
自动化测试:pytest第一个实例学习
学习·pytest
TomEval12 天前
【测AI】第12篇:NLP / CV / 语音 —— 三大 AI 方向速通
人工智能·python·自然语言处理·aigc·测试用例
墨云安全12 天前
AI 渗透测试是怎么实现的?2026 年大模型驱动测试用例生成的工程拆解
网络·人工智能·网络安全·渗透测试·测试用例
Helix25012 天前
Python单元测试实战:pytest框架从入门到企业级测试体系搭建指南
python·单元测试·实战·mock·pytest·测试覆盖率·fixture