Python+Pytest+Allure+Jenkins+Gitee自动化测试框架
一、框架整体架构
1. 技术栈分工
- Python:测试脚本开发语言
- Pytest:测试用例管理和执行引擎
- Allure:测试报告生成与展示
- Jenkins:持续集成和任务调度
- Gitee:代码版本管理和触发机制
2. 数据流向
Gitee代码提交 → Jenkins触发构建 → Pytest执行用例 →
生成Allure结果 → Jenkins收集报告 → 团队查看分析
二、详细搭建步骤
1. 环境准备
Python环境配置
# 创建虚拟环境
python -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
# 安装核心依赖
pip install pytest allure-pytest pytest-html requests selenium pytest-xdist
Allure命令行工具安装
# Mac
brew install allure
# Windows
scoop install allure
# Linux
sudo apt-add-repository ppa:qameta/allure
sudo apt-get update
sudo apt-get install allure
2. 项目结构设计
automation_framework/
├── .gitignore
├── README.md
├── requirements.txt
├── conftest.py
├── pytest.ini
├── run.py
├── cases/
│ ├── __init__.py
│ ├── test_api/
│ ├── test_web/
│ └── test_mobile/
├── common/
│ ├── __init__.py
│ ├── logger.py
│ ├── assert.py
│ └── utils.py
├── config/
│ ├── __init__.py
│ ├── config.yaml
│ └── env.py
├── data/
│ ├── test_data.json
│ └── users.csv
├── page_objects/ # Page Object模式
│ ├── web/
│ └── mobile/
└── reports/
├── allure/
└── html/
3. 核心配置文件
pytest.ini配置
[pytest]
addopts = -v --alluredir=./reports/allure_results --clean-alluredir
markers =
smoke: smoke test
regression: regression test
testpaths = ./cases
python_files = test_*.py
python_classes = Test*
python_functions = test_*
conftest.py示例
import pytest
from selenium import webdriver
@pytest.fixture(scope="session")
def browser():
driver = webdriver.Chrome()
yield driver
driver.quit()
@pytest.fixture
def api_client():
return APIClient(config.API_URL)
4. Jenkins详细配置
安装必要插件
- Allure Plugin
- Gitee Plugin
- Email Extension Plugin
- Build Timestamp Plugin
任务配置步骤
- 新建自由风格项目
- 源码管理选择Git,填写Gitee仓库地址
- 添加构建触发器:
- Gitee webhook触发
- 定时构建(如H/15 * * * *)
- 添加构建步骤:
# Execute shell
source venv/bin/activate
pip install -r requirements.txt
pytest cases/ --alluredir=reports/allure_results
- 添加后构建操作:
- Allure Report:Path=reports/allure_results
- Editable Email Notification:配置邮件通知
5. Gitee Webhook配置
- 进入仓库 → 管理 → WebHooks
- 添加WebHook:
- URL: http:///gitee-project/
- 触发事件: Push Events
- Secret: 与Jenkins中配置一致
三、框架核心功能实现
1. 测试用例编写示例
API测试示例
# cases/test_api/test_user_api.py
import pytest
class TestUserAPI:
@pytest.mark.smoke
def test_create_user(self, api_client):
resp = api_client.post("/users", data={"name": "test"})
assert resp.status_code == 201
assert resp.json()["name"] == "test"
Web UI测试示例
# cases/test_web/test_login.py
from page_objects.web.login_page import LoginPage
@pytest.mark.usefixtures("browser")
class TestLogin:
def test_admin_login(self, browser):
login_page = LoginPage(browser)
dashboard = login_page.login("admin", "admin123")
assert dashboard.is_displayed()
2. Allure增强用法
添加测试步骤
import allure
@allure.step("用户登录操作")
def login(username, password):
# 登录实现
def test_login():
with allure.step("输入用户名"):
# 操作代码
with allure.step("输入密码"):
# 操作代码
添加附件
def test_error_handling(browser):
try:
# 测试操作
except Exception as e:
allure.attach(browser.get_screenshot_as_png(),
name="失败截图",
attachment_type=allure.attachment_type.PNG)
raise
3. Jenkins流水线脚本
Jenkinsfile示例
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git url: 'https://gitee.com/your/repo.git', branch: 'main'
}
}
stage('Test') {
steps {
sh '''
python -m venv venv
. venv/bin/activate
pip install -r requirements.txt
pytest --alluredir=reports/allure_results
'''
}
}
stage('Report') {
steps {
allure includeProperties: false,
jdk: '',
results: [[path: 'reports/allure_results']]
}
}
}
post {
always {
emailext body: '${DEFAULT_CONTENT}',
subject: '${DEFAULT_SUBJECT}',
to: 'team@example.com'
}
}
}
四、高级配置与优化
1. 分布式测试执行
# 安装
pip install pytest-xdist
# 执行命令
pytest -n 4 # 使用4个worker并行执行
2. 失败重试机制
# pytest.ini
[pytest]
addopts = --reruns 3 --reruns-delay 2
3. 多环境配置
# config/env.py
import os
ENV = os.getenv("TEST_ENV", "dev")
configs = {
"dev": {
"base_url": "http://dev.example.com",
"db": "dev_db"
},
"test": {
"base_url": "http://test.example.com",
"db": "test_db"
}
}
current_config = configs[ENV]
4. 自动生成测试数据
# common/test_data.py
from faker import Faker
fake = Faker()
def generate_user():
return {
"name": fake.name(),
"email": fake.email(),
"address": fake.address()
}
五、常见问题解决方案
1. Allure报告无数据
- 原因:未正确生成结果文件
- 解决:
# 确保执行时添加--alluredir参数 pytest --alluredir=reports/allure_results # 生成报告 allure serve reports/allure_results
2. Jenkins无法触发构建
- 检查:
- Gitee Webhook配置的URL是否正确
- Jenkins是否安装了Gitee插件
- 网络是否互通(特别是内网环境)
3. 浏览器自动化不稳定
- 优化方案:
# 使用显式等待 from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def wait_element(driver, locator, timeout=10): return WebDriverWait(driver, timeout).until( EC.presence_of_element_located(locator)
六、维护与扩展建议
- 目录结构规范:保持统一的项目结构
- 命名约定:
- 测试文件:test__.py
- 测试类:Test
- 测试方法:test_
- 版本控制:
- 使用.gitignore排除临时文件
- 提交有意义的commit信息
- 文档补充:
- 在README中记录框架使用方法
- 为复杂功能添加注释
通过以上完整配置,您可以建立一个功能完善的企业级自动化测试框架。该框架具有以下特点:
- 完整的CI/CD集成能力
- 专业的测试报告系统
- 灵活的测试用例管理
- 高效的并行执行能力
- 便捷的团队协作支持