Debian系统Python自动化测试如何进行
小樊
35
2025-11-23 08:08:56
Debian系统Python自动化测试实战指南
一 环境准备与项目初始化
- 更新系统并安装基础工具:sudo apt update && sudo apt install -y python3 python3-pip。
- 建议使用虚拟环境隔离依赖:python3 -m venv venv && source venv/bin/activate。
- 安装测试相关依赖:pip install -U pip;pip install pytest(如需覆盖率:pip install pytest-cov)。
- 准备依赖清单:pip freeze > requirements.txt,后续可用 pip install -r requirements.txt 一键还原。
- 推荐项目结构:
my_project/
├── src/(或 my_module/)
├── tests/
│ ├── init.py
│ └── test_*.py
├── requirements.txt
└── pytest.ini / tox.ini(可选)
二 编写与运行测试
- 使用内置 unittest 的最小示例(tests/test_math.py):
import unittest
def add(a, b): return a + b
class TestMath(unittest.TestCase):
def test_add(self): self.assertEqual(add(1, 2), 3)
运行:python -m unittest discover -s tests 或 python -m unittest tests.test_math。
- 使用 pytest 的最小示例(tests/test_math.py):
from src.math import add
def test_add(): assert add(1, 2) == 3
运行:pytest tests/ -v;查看覆盖率:pytest --cov=src --cov-report=term-missing。
- 常用运行与组织技巧:
- 测试发现:pytest 默认查找 test_*.py 或 *_test.py;unittest 使用 discover。
- 标记与选择:pytest -m slow 运行被 @pytest.mark.slow 标记的用例;pytest tests/test_math.py::test_add -v 精确运行。
- 并行与报告:pytest -n auto(需 pytest-xdist);生成 JUnit 报告:pytest --junitxml=report.xml。
三 集成与持续化
- 本地预提交/预推送钩子(.git/hooks/pre-commit):
#!/usr/bin/env bash
set -e
source venv/bin/activate
pytest tests/ --maxfail=1 || { echo “Tests failed”; exit 1; }
- Jenkins 流水线(Jenkinsfile 片段):
pipeline {
agent any
stages {
stage(‘Checkout’) { steps { git ‘https://github.com/example/my-python-app.git’ } }
stage(‘Install’) { steps { sh ‘python -m pip install --upgrade pip && pip install -r requirements.txt’ } }
stage(‘Test’) { steps { sh ‘pytest --junitxml=report.xml’ } }
stage(‘Archive’) { steps { junit ‘report.xml’ } }
}
}
- GitHub Actions(.github/workflows/ci.yml 片段):
name: Python CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: ‘3.11’ }
- run: pip install -r requirements.txt
- run: pytest --junitxml=report.xml
- uses: actions/upload-artifact@v4
with: { path: report.xml, name: pytest-report }
四 专项测试场景
- Web UI 自动化(Selenium):
- 安装:pip install selenium;浏览器驱动(如 geckodriver)放入 PATH。
- 示例:
from selenium import webdriver
def test_title():
driver = webdriver.Firefox()
try:
driver.get(“https://example.com”)
assert “Example” in driver.title
finally:
driver.quit()
- 打包与多版本测试(Debian 打包与 pybuild):
- 安装构建依赖:sudo apt-get install python3-all-dev python3-all-dbg python3-dev。
- 在 debian/rules 或构建流程中调用:pybuild --test,可结合 tox/stestr 做多版本矩阵测试。
- 性能与剖析:
- 基准测试(timeit):
import timeit
print(timeit.timeit(‘sum(range(1000))’, number=10000))
- CPU 剖析(cProfile):python -m cProfile -o profile.out app.py。
五 常见问题与最佳实践
- 使用虚拟环境隔离依赖,避免与系统包冲突;requirements.txt 与锁文件(如 requirements-dev.txt)分层管理。
- 始终在 CI 中运行测试并上传报告(JUnit XML),保证每次提交可验证。
- 为慢测、集成测打标记,日常开发用快速用例,CI 全量回归。
- 配置 pytest.ini 统一测试路径、标记与覆盖率;如 [pytest] testpaths=tests, integration。
- 对于 Debian 打包项目,优先用 pybuild 管理构建与测试,减少环境差异带来的不确定性。