自动化测试框架pytest
时间: 2025-05-29 15:53:00 浏览: 14
### Pytest 自动化测试框架使用指南
#### 什么是 pytest?
Pytest 是一种功能强大且易于使用的 Python 测试框架,它能够帮助开发者更高效地编写和执行测试脚本[^1]。其核心优势在于简化了测试过程中的复杂操作,并提供了丰富的插件生态系统来扩展功能。
---
#### 安装 pytest
要开始使用 pytest,首先需要安装该库。可以通过 pip 工具完成安装:
```bash
pip install pytest
```
---
#### 基础概念
- **测试文件命名规则**:pytest 默认识别以 `test_` 开头或 `_test` 结尾的文件作为测试文件[^2]。
- **测试函数/方法命名规则**:测试函数应以 `test_` 开始;类名则需以 `Test` 开头,且不应包含父类继承(除非必要)。
---
#### 示例代码
以下是一个完整的 pytest 测试案例演示如何定义并运行多个测试用例:
##### 文件结构
假设有一个名为 `calculator.py` 的模块用于实现加法运算逻辑:
```python
# calculator.py
def add(a, b):
return a + b
```
对应的测试文件如下所示:
```python
# test_calculator.py
import pytest
from calculator import add
class TestCalculator:
def test_add_positive_numbers(self):
result = add(1, 2)
assert result == 3, f"Incorrect addition result: {result}" # 断言验证结果是否正确[^4]
def test_add_negative_numbers(self):
result = add(-1, -2)
assert result == -3, f"Incorrect addition result: {result}"
if __name__ == "__main__":
pytest.main()
```
运行此测试文件的方式有两种:
1. 执行整个目录下的所有测试文件:
```bash
pytest
```
2. 针对单个文件运行测试:
```bash
pytest test_calculator.py
```
---
#### 参数化测试
为了减少冗余代码量,pytest 提供了参数化的机制,允许一次性定义多种输入条件及其预期输出值。以下是基于前面例子改进后的版本:
```python
@pytest.mark.parametrize(
"a,b,expected",
[
(1, 2, 3),
(-1, -2, -3),
(0, 0, 0),
],
)
def test_add_parametrized(a, b, expected):
result = add(a, b)
assert result == expected, f"Expected {expected}, but got {result}"
```
这样可以显著提升测试效率与可维护性。
---
#### 固定装置(Fixtures)
固定装置是 pytest 中非常重要的特性之一,主要用于提供共享资源给不同测试用例使用。例如登录状态、数据库连接等情境都可通过 fixtures 实现复用。
下面展示了一个简单示例说明如何创建 fixture 并将其应用于多个测试用例之中:
```python
@pytest.fixture(scope="module")
def setup():
print("\nSetup called before any tests.")
yield {"username": "admin", "password": "secret"}
print("\nTeardown after all tests.")
class TestLoginFixtureUsage:
def test_login_with_fixture(self, setup):
user_info = setup
assert user_info["username"] == "admin"
def test_another_test_case_using_same_setup(self, setup):
pass # 可继续添加更多依赖于同一setup数据的测试逻辑
```
此处的关键点在于通过 `@pytest.fixture()` 装饰器声明一个 fixture 函数,在需要的地方传入即可调用对应的数据准备流程[^3]。
---
#### 总结
Pytest 不仅能极大地方便日常开发过程中单元测试工作的开展,而且还能促进团队协作时保持高质量交付成果的能力。掌握好它的基本语法以及高级特性的运用技巧将会成为每位工程师不可或缺的一项技能。
---
阅读全文
相关推荐

















