Python 测试开发教程
测试开发
单元测试
unittest 框架
unittest 是 Python 的标准测试框架,提供了一套完整的测试工具。
核心概念:
- TestCase:测试用例类,包含具体的测试方法
- setUp/tearDown:测试前后的准备和清理工作
- assertions:断言方法,用于验证结果
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import unittest
class Calculator:
def add(self, a, b):
return a + b
class TestCalculator(unittest.TestCase):
def setUp(self):
self.calc = Calculator()
def test_add(self):
result = self.calc.add(3, 5)
self.assertEqual(result, 8)
def tearDown(self):
pass
if __name__ == '__main__':
unittest.main()
pytest 使用
pytest 是 Python 最流行的第三方测试框架,提供更简洁的语法和强大的功能。
主要特点:
- 简单的断言语法
- 自动发现测试用例
- 丰富的插件生态
示例代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# test_calculator.py
import pytest
def test_addition():
assert 1 + 1 == 2
def test_zero():
assert 1 + 0 == 1
@pytest.mark.parametrize("a,b,expected", [
(3, 5, 8),
(-1, 1, 0),
(0, 0, 0),
])
def test_add_params(a, b, expected):
assert a + b == expected
测试用例设计
测试用例设计原则:
- 单一职责:每个测试用例只测试一个功能点
- 完整性:覆盖正常流程和异常情况
- 独立性:测试用例之间互不影响
- 可重复性:多次运行结果一致
常见测试场景:
- 边界值测试
- 等价类划分
- 错误输入处理
- 特殊情况测试
测试夹具(Fixtures)
测试夹具用于提供测试所需的预置条件和环境。
pytest fixtures 示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import pytest
@pytest.fixture
def database():
# 设置测试数据库
db = Database()
db.connect()
yield db
# 清理操作
db.disconnect()
def test_database_query(database):
result = database.query("SELECT * FROM users")
assert len(result) > 0
参数化测试
参数化测试允许用不同的参数运行相同的测试代码。
pytest 参数化示例:
1
2
3
4
5
6
7
8
9
10
import pytest
@pytest.mark.parametrize("input,expected", [
("hello", 5),
("python", 6),
("", 0),
("测试", 2)
])
def test_string_length(input, expected):
assert len(input) == expected
测试覆盖率
coverage 工具
coverage.py 是 Python 代码覆盖率统计的标准工具。
安装和基本使用:
1
2
3
4
pip install coverage
coverage run -m pytest
coverage report
coverage html # 生成HTML报告
代码覆盖率分析
覆盖率类型:
- 语句覆盖率:执行到的代码行数百分比
- 分支覆盖率:条件分支的覆盖情况
- 路径覆盖率:代码执行路径的覆盖情况
配置文件 (.coveragerc) 示例:
1
2
3
4
5
6
7
8
9
[run]
source = myproject
omit = */tests/*
[report]
exclude_lines =
pragma: no cover
def __repr__
raise NotImplementedError
测试报告生成
pytest-html 报告生成:
1
2
pip install pytest-html
pytest --html=report.html --self-contained-html
覆盖率报告解读:
- Missing:未覆盖的代码行
- Stmts:语句总数
- Miss:未覆盖的语句数
- Cover:覆盖率百分比
最佳实践:
- 设置最低覆盖率要求
- 定期生成覆盖率报告
- 重点关注核心业务逻辑的覆盖
- 将覆盖率检查集成到 CI/CD 流程
补充说明
- 测试命名规范
- 测试文件名应以
test_
开头 - 测试类名应以
Test
开头 - 测试方法名应以
test_
开头
- 测试文件名应以
- 测试执行顺序
- 测试用例应该保持独立性
- 不要依赖测试执行顺序
- 使用 fixtures 管理测试依赖
- 调试技巧
- 使用
pytest -v
查看详细输出 - 使用
pytest -k "pattern"
选择特定测试 - 使用
pytest --pdb
在失败时进入调试器
- 使用
- 持续集成建议
- 在代码提交前运行测试
- 配置自动化测试流程
- 设置覆盖率阈值
- 生成测试报告并归档