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()

运行结果:

相关推荐
测试19983 小时前
Jmeter性能压测:TPS与QPS
自动化测试·软件测试·python·jmeter·测试用例·压力测试·性能测试
我的xiaodoujiao4 小时前
API 接口自动化测试详细图文教程学习系列25--继续处理testCase中的数据
python·学习·测试工具·pytest
孙高飞8 小时前
从0开始学AI测试系列-工具篇
人工智能·自动化·测试用例
人形贴片机1 天前
低温车间防静电桌垫:低温环境真的会影响电阻测试仪测量吗?
测试用例
xiaobai1781 天前
pytest+playwright实现UI自动化(4)-上夹具fixture
ui·自动化·pytest·playwright
弹简特1 天前
【接口自动化】02-Pytest固件fixture核心机制与Allure企业级报告实战
自动化·pytest·测试
弹简特3 天前
【接口自动化】01-pytest详解、pytest执行逻辑、pytest参数、配置文件和pytest标记
自动化·pytest
香辣西红柿炒蛋3 天前
pytest框架介绍
python·pytest
kft13144 天前
04 — AI 测试用例生成与评审实战
人工智能·测试用例