测试开发
单元测试
unittest 框架
unittest 是 Python 的标准测试框架,提供了一套完整的测试工具。
核心概念:
-
-
setUp/tearDown:测试前后的准备和清理工作
-
示例代码:
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()
5pytest 使用
pytest 是 Python 最流行的第三方测试框架,提供更简洁的语法和强大的功能。
主要特点:
示例代码:
# 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 示例:
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 参数化示例:
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 代码覆盖率统计的标准工具。
安装和基本使用:
pip install coverage
coverage run -m pytest
coverage report
coverage html # 生成HTML报告
代码覆盖率分析
覆盖率类型:
-
-
-
配置文件 (.coveragerc) 示例:
[run]
source = myproject
omit = */tests/*
[report]
exclude_lines =
pragma: no cover
def __repr__
raise NotImplementedError
测试报告生成
pytest-html 报告生成: