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

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

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的一个约定。assertEqualassertTrue是断言方法,用于验证预期结果与实际结果是否一致。

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_addtest_subtract。每个测试函数都以test_开头,这是pytest的一个约定。assert语句用于验证预期结果与实际结果是否一致。如果assert语句失败,测试将被视为失败。

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

复制代码

bash复制代码

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

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

相关推荐
曲幽14 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
代码匠心15 小时前
AI 自动编程:一句话设计高颜值博客
前端·ai·ai编程·claude
_AaronWong16 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
cxxcode16 小时前
I/O 多路复用:从浏览器到 Linux 内核
前端
用户54330814419416 小时前
AI 时代,前端逆向的门槛已经低到离谱 — 以 Upwork 为例
前端
JarvanMo16 小时前
Flutter 版本的 material_ui 已经上架 pub.dev 啦!快来抢先体验吧。
前端
恋猫de小郭17 小时前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
哀木17 小时前
给自己整一个 claude code,解锁编程新姿势
前端
程序员鱼皮17 小时前
GitHub 关注突破 2w,我总结了 10 个涨星涨粉技巧!
前端·后端·github
UrbanJazzerati17 小时前
Vue3 父子组件通信完全指南
前端·面试