Python自动化测试
·
目录
1. 使用 unittest 标准库
Python 自带的测试框架,适合简单项目,语法类似 JUnit。
# test_math.py
import unittest
def add(a, b):
return a + b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
self.assertNotEqual(add(0, 0), 1)
def test_type_error(self):
with self.assertRaises(TypeError):
add("2", 3)
if __name__ == '__main__':
unittest.main()
运行测试:
python -m unittest test_math.py
2. 使用 pytest 框架
更现代、灵活的框架,支持插件和简洁语法。
安装:
pip install pytest
示例测试文件 (test_calculator.py):
def multiply(a, b):
return a * b
def test_multiply():
assert multiply(3, 4) == 12
def test_string_multiplication():
assert multiply("a", 3) == "aaa"
运行测试:
pytest test_calculator.py -v # -v 显示详细输出
3. 高级功能与插件
(1) 参数化测试
用 @pytest.mark.parametrize 简化多组输入测试:
import pytest
def divide(a, b):
return a / b
@pytest.mark.parametrize("a, b, expected", [
(6, 3, 2),
(10, 2, 5),
(0, 1, 0)
])
def test_divide_valid(a, b, expected):
assert divide(a, b) == expected
def test_divide_by_zero():
with pytest.raises(ZeroDivisionError):
divide(10, 0)
(2) 使用 Fixture 共享资源
import pytest
@pytest.fixture
def database_connection():
conn = create_db_connection() # 假设的初始化函数
yield conn
conn.close() # 测试后清理
def test_query_users(database_connection):
users = database_connection.query("SELECT * FROM users")
assert len(users) >= 1
4. Mock 外部依赖
使用 unittest.mock 或 pytest-mock 隔离测试。
from unittest.mock import Mock
def send_http_request(url):
# 假设的 HTTP 请求函数
pass
def test_http_request(mocker):
mock_request = mocker.patch('__main__.send_http_request')
mock_request.return_value = {"status": 200}
response = send_http_request("https://api.example.com")
assert response["status"] == 200
mock_request.assert_called_once_with("https://api.example.com")
5. 测试覆盖率
使用 coverage 或 pytest-cov 检查代码覆盖。
安装:
pip install pytest-cov
运行测试并生成报告:
pytest --cov=my_module tests/ --cov-report=html
生成的 HTML 报告会展示未覆盖的代码行。
6. 集成到 CI/CD
在 GitHub Actions 中配置 Python 测试:
name: Python Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: pip install -r requirements.txt
- name: Run Tests
run: pytest --cov=myapp tests/
7. 测试报告生成
(1) 生成 JUnit 格式报告
pytest --junitxml=report.xml
(2) 使用 Allure 报告
pip install allure-pytest
pytest --alluredir=./allure-results
allure serve ./allure-results # 本地查看报告
8. 性能测试
使用 timeit 或 pytest-benchmark 进行基准测试。
示例:
def test_sort_performance(benchmark):
data = [3, 1, 4, 1, 5, 9, 2, 6]
benchmark(sorted, data) # 测试 sorted() 的性能
9. 常见测试场景
| 测试类型 | 示例代码/工具 |
|---|---|
| API 接口测试 | 使用 requests + pytest |
| 数据库测试 | 结合 SQLAlchemy 和事务回滚 |
| CLI 工具测试 | 使用 subprocess 捕获命令行输出 |
| Web UI 测试 | 集成 Selenium 或 Playwright |
| 异步代码测试 | 使用 pytest-asyncio |
总结
- 简单项目:优先使用
unittest(无需额外依赖) - 复杂项目:选择
pytest(插件丰富、语法简洁) - 关键场景:结合 Mock、覆盖率、性能测试工具
- 自动化流程:将测试集成到 CI/CD 中(如 GitHub Actions)
通过合理选择工具,Python 自动化测试可以覆盖从单元测试到端到端(E2E)测试的全流程。
更多推荐


所有评论(0)