14. 原生测试框架Unittest的skip、skipIf、skipUnless的使用

14. 原生测试框架Unittest的skip、skipIf、skipUnless的使用

一、跳过机制核心装饰器解析

1.1 装饰器功能对照表

装饰器 触发条件 典型应用场景
@skip 无条件跳过 维护中/未完成的测试用例
@skipIf 条件为True时跳过 环境依赖检查
@skipUnless 条件为False时跳过 平台特性验证

二、类级别跳过控制实现

2.1 全局跳过示例

python 复制代码
@skip  # 类装饰器
class A(unittest.TestCase):
    def test_a1(self):
        self.assertEqual(1, 2)  # 不会执行
        
    @skip  # 方法装饰器(冗余设置)
    def test_a2(self): ...      # 不会执行
执行特征:

Runner TestCase 发现测试类 检测到类级@skip 标记所有方法为跳过 不执行任何方法 Runner TestCase


三、条件跳过深度解析

3.1 环境条件检测

python 复制代码
@skipIf(name != 'nt', '非Windows系统跳过')  # 检查操作系统
class B(unittest.TestCase):
    @skipIf(version_info[0] < 3, 'Python3以下版本跳过')
    def test_b1(self): ...  # 当Python主版本<3时跳过
    
    @skipUnless('win' in platform, '非Windows平台跳过') 
    def test_b2(self): ...  # 当平台不包含win时跳过

3.2 条件表达式组成

表达式 检测目标 返回值逻辑
name != 'nt' 操作系统类型 Windows返回False
version_info[0] < 3 Python主版本号 3.x版本返回False
'win' in platform 平台信息字符串 含win返回True

四、执行流程控制逻辑

4.1 装饰器优先级规则

类装饰器 方法装饰器 父类装饰器 子类装饰器 skipUnless skipIf skip 具体条件装饰器

4.2 多层控制示例

python 复制代码
@skipIf(condition1, '')  # 第一层过滤
class MyTest(unittest.TestCase):
    @skipUnless(condition2, '')  # 第二层过滤
    def test_case(self): ...
执行判定流程:
  1. 检查类级别条件condition1
  2. 通过后检查方法级别condition2
  3. 双重条件均满足时执行测试

五、最佳实践指南

5.1 跳过的正确用法

python 复制代码
# 推荐写法
@skipIf(not has_feature('ocr'), '缺少OCR模块支持')  
def test_image_recognition(): ...

# 不推荐写法
if not has_feature('ocr'):
    pass  # 会标记为成功而非跳过
else:
    def test_image_recognition(): ...

5.2 报告输出优化

python 复制代码
@skipUnless(
    platform.system() == 'Darwin',
    '要求MacOS系统 | 当前系统: {}'.format(platform.system())
)

输出示例:
SKIP: 要求MacOS系统 | 当前系统: Linux


六、高级应用场景

6.1 动态跳过机制

python 复制代码
def skip_on_exception(func):
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            raise unittest.SkipTest(f"预检失败: {str(e)}")
    return wrapper

@skip_on_exception
def test_database(): ...

6.2 跨模块条件复用

python 复制代码
# common.py
WIN_ONLY = skipUnless(platform.system() == 'Windows', '仅限Windows')

# test_module.py
@WIN_ONLY
def test_windows_feature(): ...

七、完整代码

python 复制代码
"""
Python :3.13.3
Selenium: 4.31.0

test_module_1.py
"""

import unittest
from unittest import skip, skipIf, skipUnless
from os import name
from sys import version_info, platform


# @skip
class A(unittest.TestCase):

    def test_a1(self):
        self.assertEqual(1, 2)

    @skip
    def test_a2(self):
        ...


@skipIf(name != 'nt', '')
class B(unittest.TestCase):

    @skipIf(version_info[0] < 3, '')
    def test_b1(self):
        ...

    @skipUnless('win' in platform, '')
    def test_b2(self):
        ...

「小贴士」 :点击头像→【关注】按钮,获取更多软件测试的晋升认知不迷路! 🚀

相关推荐
SunnyDays101117 分钟前
Python 实现 HTML 转 Word 和 PDF
python·html转word·html转pdf·html转docx·html转doc
跟橙姐学代码1 小时前
Python异常处理:告别程序崩溃,让代码更优雅!
前端·python·ipython
蓝纹绿茶1 小时前
Python程序使用了Ffmpeg,结束程序后,文件夹中仍然生成音频、视频文件
python·ubuntu·ffmpeg·音视频
mahuifa1 小时前
OpenCV 开发 -- 图像基本处理
人工智能·python·opencv·计算机视觉
一个java开发2 小时前
distributed.client.Client 用户可调用函数分析
大数据·python
eqwaak02 小时前
Matplotlib 动态显示详解:技术深度与创新思考
网络·python·网络协议·tcp/ip·语言模型·matplotlib
007php0072 小时前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
CodeCraft Studio2 小时前
Excel处理控件Aspose.Cells教程:使用 Python 将 Pandas DataFrame 转换为 Excel
python·json·excel·pandas·csv·aspose·dataframe
flashlight_hi3 小时前
LeetCode 分类刷题:2563. 统计公平数对的数目
python·算法·leetcode
java1234_小锋3 小时前
Scikit-learn Python机器学习 - 特征预处理 - 归一化 (Normalization):MinMaxScaler
python·机器学习·scikit-learn