Python自动化测试:unittest与pytest框架

在Python中,unittest和pytest都是常用的自动化测试框架。它们提供了编写测试用例、测试套件和执行测试的强大功能。

1. unittest框架

unittest是Python标准库的一部分,因此无需额外安装。它提供了丰富的断言方法,用于验证测试结果。

示例代码:
复制代码

python复制代码

|---|----------------------------------------------------|
| | import unittest |
| | |
| | class TestStringMethods(unittest.TestCase): |
| | |
| | def test_upper(self): |
| | self.assertEqual('foo'.upper(), 'FOO') |
| | |
| | def test_isalpha(self): |
| | self.assertTrue('foo'.isalpha()) |
| | self.assertFalse('foo123'.isalpha()) |
| | |
| | def test_split(self): |
| | s = 'hello world' |
| | self.assertEqual(s.split(), ['hello', 'world']) |
| | # 使用断言检查列表长度 |
| | with self.assertRaises(ValueError): |
| | s.split(maxsplit=1) |
| | |
| | if __name__ == '__main__': |
| | unittest.main() |

在这个示例中,我们定义了一个名为TestStringMethods的测试类,其中包含三个测试方法。每个测试方法都以test_开头,这是unittest的一个约定。assertEqual和assertTrue是断言方法,用于验证预期结果与实际结果是否一致。

2. pytest框架

pytest是一个更简洁、更易于使用的测试框架。它不需要继承任何基类或编写特定的测试方法。

示例代码:

首先,确保你已经安装了pytest:

复制代码

bash复制代码

|---|----------------------|
| | pip install pytest |

然后,创建一个名为test_example.py的测试文件,并编写以下代码:

复制代码

python复制代码

|---|-----------------------------------|
| | def add(x, y): |
| | return x + y |
| | |
| | def test_add(): |
| | assert add(1, 2) == 3 |
| | assert add(0, 0) == 0 |
| | with pytest.raises(TypeError): |
| | add(1, '2') |
| | |
| | def test_subtract(): |
| | assert add(5, -3) == 2 |

在这个示例中,我们定义了一个简单的add函数,然后创建了两个测试函数test_add和test_subtract。每个测试函数都以test_开头,这是pytest的一个约定。assert语句用于验证预期结果与实际结果是否一致。如果assert语句失败,测试将被视为失败。

要运行这些测试,请在命令行中导航到包含测试文件的目录,并执行以下命令:

复制代码

bash复制代码

|---|----------|
| | pytest |

pytest将自动查找并执行所有以test_开头的函数。如果所有测试都通过,则不会显示任何输出。如果有测试失败,pytest`将显示失败的详细信息。

相关推荐
鬓戈6 小时前
Volta:解决 nvm「不能同时存在多个 Node 版本」的痛点
前端
nvd116 小时前
# 从 192 秒到 13 秒:Apache Flink 批处理极速调优实战记录
大数据·flink·apache
東隅已逝,桑榆非晚6 小时前
c++模板进阶
开发语言·c++·笔记·学习
吴声子夜歌6 小时前
Nginx应用与运维——Nginx Web服务应用实战(HTTP增强协议服务器的搭建)
运维·前端·nginx
Omics Pro6 小时前
计算虚拟扰动:网络毒理+虚拟敲除
数据库·人工智能·算法·机器学习·自然语言处理
老歌老听老掉牙10 小时前
空间曲线数据的拼接与几何变换分析
python·曲线
Cc.Y10 小时前
Java零基础入门:字符串深度掌握——从基础API到StringBuilder性能优化
java·开发语言·性能优化
weixin_7503302311 小时前
AI获客工具选型:从技术架构看中小企业效率提升方案
大数据·人工智能·架构·ai获客
mpp00712 小时前
36氪《2026 中国 AI Agent 行业发展报告》:当 Agent 进入「交付」主战场
大数据·人工智能
databook14 小时前
使用 SciPy 库进行时间序列分析
python·数据分析·scipy