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`将显示失败的详细信息。

相关推荐
比老马还六4 分钟前
Bipes-Blockly项目二次开发/Coze智能体(十)
前端·嵌入式
6 分钟前
Vue 3 组件封装与使用:保姆级教程
前端
星辰10 分钟前
深入浅出 Android AOA 协议:通信流程与设备切换附着机制解析
前端
恋猫de小郭28 分钟前
Amper 正式转正 Kotlin Toolchain ,Gradle 未来何去何从
android·前端·flutter
敲代码的彭于晏36 分钟前
Bean 生命周期完全图解:前端同学也能看懂的 Spring 核心机制
java·前端·后端
IT_陈寒42 分钟前
Redis内存飙升的锅,原来是我没搞懂这个过期策略
前端·人工智能·后端
云浪1 小时前
前端二进制数组完全指南:ArrayBuffer、TypedArray、DataView 一次讲透
前端·javascript
张风捷特烈1 小时前
Flutter 类库大揭秘#02 | path_provider 各平台实现
前端·flutter
铁皮饭盒2 小时前
26年bunjs, elysia+pg一把梭, redis都省了
前端·javascript·后端
花酒锄作田10 小时前
Pydantic校验配置文件
python