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):
        ...

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

相关推荐
AI探索者14 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者14 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh15 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅15 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽17 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时20 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python