Python3+pytest+allure接口自动化测试框架搭建
myzbx 2025-03-20 16:59 53 浏览
项目结构
安装依赖
pip install pytest requests pytest-html pytest-xdist jsonpath
核心代码实现
配置文件 (config/config.py)
class Config:
# 环境配置
BASE_URL = "https://api.example.com"
TIMEOUT = 10
# 测试账号
USERNAME = "test_user"
PASSWORD = "test_password"
# 日志配置
LOG_LEVEL = "INFO"
API客户端 (api/client.py)
import requests
import json
import logging
from config.config import Config
class APIClient:
def __init__(self):
self.base_url = Config.BASE_URL
self.session = requests.Session()
self.timeout = Config.TIMEOUT
def get(self, url, params=None, headers=None):
return self._request("GET", url, params=params, headers=headers)
def post(self, url, data=None, json=None, headers=None):
return self._request("POST", url, data=data, json=json, headers=headers)
def put(self, url, data=None, json=None, headers=None):
return self._request("PUT", url, data=data, json=json, headers=headers)
def delete(self, url, headers=None):
return self._request("DELETE", url, headers=headers)
def _request(self, method, url, **kwargs):
full_url = self.base_url + url
logging.info(f"Request: {method} {full_url}")
if "headers" not in kwargs or kwargs["headers"] is None:
kwargs["headers"] = {"Content-Type": "application/json"}
if "timeout" not in kwargs:
kwargs["timeout"] = self.timeout
try:
response = self.session.request(method, full_url, **kwargs)
logging.info(f"Response status: {response.status_code}")
return response
except Exception as e:
logging.error(f"Request error: {e}")
raise
测试用例 (tests/test_api.py)
import pytest
import json
from api.client import APIClient
class TestAPI:
@pytest.fixture(scope="class")
def api_client(self):
return APIClient()
def test_get_users(self, api_client):
"""测试获取用户列表接口"""
response = api_client.get("/users")
assert response.status_code == 200
data = response.json()
assert "data" in data
assert isinstance(data["data"], list)
def test_create_user(self, api_client):
"""测试创建用户接口"""
user_data = {
"name": "测试用户",
"email": "test@example.com",
"password": "password123"
}
response = api_client.post("/users", json=user_data)
assert response.status_code == 201
data = response.json()
assert data["name"] == user_data["name"]
assert data["email"] == user_data["email"]
def test_update_user(self, api_client):
"""测试更新用户接口"""
# 假设我们已经知道用户ID为1
user_id = 1
update_data = {"name": "更新名称"}
response = api_client.put(f"/users/{user_id}", json=update_data)
assert response.status_code == 200
data = response.json()
assert data["name"] == update_data["name"]
pytest配置 (conftest.py)
import pytest
import logging
import os
from datetime import datetime
# 设置日志
def setup_logging():
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = f"{log_dir}/test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
def pytest_configure(config):
setup_logging()
@pytest.fixture(scope="session", autouse=True)
def setup_teardown():
# 测试前置操作
logging.info("测试开始")
yield
# 测试后置操作
logging.info("测试结束")
测试运行脚本 (run.py)
import pytest
import argparse
import os
from datetime import datetime
def run_tests():
parser = argparse.ArgumentParser(description="运行API自动化测试")
parser.add_argument("--html", action="store_true", help="生成HTML报告")
parser.add_argument("--parallel", action="store_true", help="并行运行测试")
args = parser.parse_args()
# 创建报告目录
report_dir = "reports"
if not os.path.exists(report_dir):
os.makedirs(report_dir)
# 构建pytest参数
pytest_args = ["-v", "tests/"]
if args.html:
report_file = f"{report_dir}/report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
pytest_args.extend(["--html", report_file, "--self-contained-html"])
if args.parallel:
pytest_args.extend(["-n", "auto"])
# 运行测试
pytest.main(pytest_args)
if __name__ == "__main__":
run_tests()
执行测试
# 普通执行
python run.py
# 生成HTML报告
python run.py --html
# 并行执行测试
python run.py --parallel
# 同时生成报告和并行执行
python run.py --html --parallel
添加Allure报告
更新依赖
pip install pytest requests pytest-html pytest-xdist jsonpath allure-pytest
安装Allure命令行工具Windows
scoop install allure
更新测试用例 (tests/test_api.py)
import pytest
import json
import allure
from api.client import APIClient
@allure.epic("API测试")
@allure.feature("用户管理接口")
class TestAPI:
@pytest.fixture(scope="class")
def api_client(self):
return APIClient()
@allure.story("获取用户列表")
@allure.title("测试获取所有用户")
@allure.severity(allure.severity_level.NORMAL)
def test_get_users(self, api_client):
"""测试获取用户列表接口"""
with allure.step("发送GET请求到/users"):
response = api_client.get("/users")
with allure.step("验证响应状态码"):
assert response.status_code == 200
with allure.step("验证响应数据结构"):
data = response.json()
assert "data" in data
assert isinstance(data["data"], list)
allure.attach(json.dumps(data, indent=2),
"响应数据",
allure.attachment_type.JSON)
@allure.story("创建新用户")
@allure.title("测试创建用户功能")
@allure.severity(allure.severity_level.CRITICAL)
def test_create_user(self, api_client):
"""测试创建用户接口"""
user_data = {
"name": "测试用户",
"email": "test@example.com",
"password": "password123"
}
allure.attach(json.dumps(user_data, indent=2),
"请求数据",
allure.attachment_type.JSON)
with allure.step("发送POST请求到/users"):
response = api_client.post("/users", json=user_data)
with allure.step("验证响应状态码"):
assert response.status_code == 201
with allure.step("验证创建的用户数据"):
data = response.json()
assert data["name"] == user_data["name"]
assert data["email"] == user_data["email"]
allure.attach(json.dumps(data, indent=2),
"响应数据",
allure.attachment_type.JSON)
@allure.story("更新用户")
@allure.title("测试更新用户信息")
@allure.severity(allure.severity_level.HIGH)
def test_update_user(self, api_client):
"""测试更新用户接口"""
# 假设我们已经知道用户ID为1
user_id = 1
update_data = {"name": "更新名称"}
allure.attach(json.dumps(update_data, indent=2),
"请求数据",
allure.attachment_type.JSON)
with allure.step(f"发送PUT请求到/users/{user_id}"):
response = api_client.put(f"/users/{user_id}", json=update_data)
with allure.step("验证响应状态码"):
assert response.status_code == 200
with allure.step("验证更新后的用户数据"):
data = response.json()
assert data["name"] == update_data["name"]
allure.attach(json.dumps(data, indent=2),
"响应数据",
allure.attachment_type.JSON)
更新API客户端 (api/client.py)
import requests
import json
import logging
import allure
from config.config import Config
class APIClient:
def __init__(self):
self.base_url = Config.BASE_URL
self.session = requests.Session()
self.timeout = Config.TIMEOUT
def get(self, url, params=None, headers=None):
return self._request("GET", url, params=params, headers=headers)
def post(self, url, data=None, json=None, headers=None):
return self._request("POST", url, data=data, json=json, headers=headers)
def put(self, url, data=None, json=None, headers=None):
return self._request("PUT", url, data=data, json=json, headers=headers)
def delete(self, url, headers=None):
return self._request("DELETE", url, headers=headers)
def _request(self, method, url, **kwargs):
full_url = self.base_url + url
logging.info(f"Request: {method} {full_url}")
# 记录请求信息到Allure
if "json" in kwargs and kwargs["json"] is not None:
allure.attach(json.dumps(kwargs["json"], indent=2, ensure_ascii=False),
f"{method} {url} - Request Body",
allure.attachment_type.JSON)
elif "data" in kwargs and kwargs["data"] is not None:
allure.attach(str(kwargs["data"]),
f"{method} {url} - Request Body",
allure.attachment_type.TEXT)
if "headers" not in kwargs or kwargs["headers"] is None:
kwargs["headers"] = {"Content-Type": "application/json"}
if "timeout" not in kwargs:
kwargs["timeout"] = self.timeout
try:
response = self.session.request(method, full_url, **kwargs)
logging.info(f"Response status: {response.status_code}")
# 记录响应信息到Allure
try:
response_body = response.json()
allure.attach(json.dumps(response_body, indent=2, ensure_ascii=False),
f"{method} {url} - Response Body",
allure.attachment_type.JSON)
except:
allure.attach(response.text,
f"{method} {url} - Response Body",
allure.attachment_type.TEXT)
return response
except Exception as e:
logging.error(f"Request error: {e}")
allure.attach(str(e),
f"{method} {url} - Exception",
allure.attachment_type.TEXT)
raise
更新conftest.py
import pytest
import logging
import os
import allure
from datetime import datetime
# 设置日志
def setup_logging():
log_dir = "logs"
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_file = f"{log_dir}/test_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log"
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler()
]
)
return log_file
def pytest_configure(config):
log_file = setup_logging()
# 添加环境信息到Allure报告
allure.environment(
python_version=platform.python_version(),
pytest_version=pytest.__version__,
platform=platform.system(),
host=Config.BASE_URL
)
@pytest.fixture(scope="session", autouse=True)
def setup_teardown():
# 测试前置操作
logging.info("测试开始")
yield
# 测试后置操作
logging.info("测试结束")
# 添加钩子函数记录测试结果
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
if report.when == "call":
if report.failed:
# 失败时捕获页面截图或其他信息
allure.attach(
f"测试用例: {item.function.__name__} 失败",
"失败信息",
allure.attachment_type.TEXT
)
更新运行脚本 (run.py)
import pytest
import argparse
import os
import shutil
import subprocess
from datetime import datetime
def run_tests():
parser = argparse.ArgumentParser(description="运行API自动化测试")
parser.add_argument("--html", action="store_true", help="生成HTML报告")
parser.add_argument("--allure", action="store_true", help="生成Allure报告")
parser.add_argument("--parallel", action="store_true", help="并行运行测试")
parser.add_argument("--clean", action="store_true", help="清理报告目录")
args = parser.parse_args()
# 创建报告目录
report_dir = "reports"
allure_result_dir = "allure-results"
allure_report_dir = f"{report_dir}/allure-report"
if args.clean:
if os.path.exists(report_dir):
shutil.rmtree(report_dir)
if os.path.exists(allure_result_dir):
shutil.rmtree(allure_result_dir)
if not os.path.exists(report_dir):
os.makedirs(report_dir)
# 构建pytest参数
pytest_args = ["-v", "tests/"]
if args.html:
report_file = f"{report_dir}/report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html"
pytest_args.extend(["--html", report_file, "--self-contained-html"])
if args.allure:
pytest_args.extend(["--alluredir", allure_result_dir])
if args.parallel:
pytest_args.extend(["-n", "auto"])
# 运行测试
pytest.main(pytest_args)
# 生成Allure报告
if args.allure:
# 创建Allure报告目录
if not os.path.exists(allure_report_dir):
os.makedirs(allure_report_dir)
print("正在生成Allure报告...")
try:
subprocess.run(["allure", "generate", allure_result_dir, "-o", allure_report_dir, "--clean"], check=True)
print(f"Allure报告已生成: {os.path.abspath(allure_report_dir)}")
# 打开Allure报告
print("正在打开Allure报告...")
subprocess.run(["allure", "open", allure_report_dir], check=True)
except subprocess.CalledProcessError as e:
print(f"生成Allure报告失败: {e}")
except FileNotFoundError:
print("未找到allure命令,请确保Allure已正确安装")
if __name__ == "__main__":
run_tests()
添加缺少的导入到conftest.py中
import platform
from config.config import Config
执行测试并生成Allure报告
# 清理历史报告并生成Allure报告
python run.py --allure --clean
# 同时生成HTML和Allure报告
python run.py --html --allure
# 并行执行测试并生成Allure报告
python run.py --allure --parallel
相关推荐
- 砌体植筋拉拔试验检验值到底是6.0KN,还是10.2KN,如何计算确定
-
砌体拉结筋植筋养护完成后,需对所植钢筋进行拉拔试验,以检验植筋的锚固强度是否满足设计要求。检测时,按照一定的抽样比例进行拉拔试验。根据《混凝土结构后锚固技术规程》JGJ145-2013,以同品种、同...
- 柴油机功率如何计算?计算柴油机功率需要哪些参数?
-
在汽车领域,对于柴油机功率的计算是一项重要的工作,它有助于我们更好地了解柴油机的性能和适用场景。下面我们就来详细探讨一下柴油机功率的计算方法以及所需的参数。首先,我们要了解计算柴油机功率常用的公式。在...
- 变压器短路阻抗的作用和计算方法(变压器短路阻抗的作用和计算方法是什么)
-
变压器短路阻抗的作用和计算方法短路阻抗是在负载试验中测量的一项数据,它是二次侧短接并流过额定电流时,一次侧施加的电压与额定电压的的百分数。那么测量变压器的短路阻抗有什么意义呢?其实变压器的阻抗电压乃是...
- 9.35m层高高支模支撑架计算书(支模架多高属于高支模)
-
某工厂新扩建的建筑面积为1989.2m^2,建筑物总体分为2层,但局部为4层。建筑物檐高19.4m,建筑物总高23m。建筑物呈长方形设置,长度为48.20m,宽度为23.88m,结构形式为框架结构...
- 吊篮(悬挂装置前梁加长)安全复核计算书
-
吊篮(悬挂装置前梁加长)安全复核计算书一种超常规搭设的高处作业吊篮,因使用要求将吊篮悬挂装置前梁加长设置,本计算书针对这种工况的校核,以作参考。计算依据:1、《高处作业吊篮》GB/T19155-...
- 电功率计算公式精编汇总(电功率计算视频讲解)
-
一、电功率计算公式:1在纯直流电路中:P=UIP=I2RP=U2/R式中:P---电功率(W),U---电压(V),I----电流(A),R---电阻(Ω)。2在单相交流电路中:P=UIcosφ...
- 灌注桩承载力检测方法及步骤(灌注桩承载力不够怎么办)
-
检测灌注桩的承载力是确保基础工程安全可靠的关键环节,检测结果的精细能准确为我们提供可靠的数据,让我们能准确判断桩基础的承载力,方便后续施工安排,同样也能让我们根据数据分辨出有问题桩基,采取可靠有效的措...
- 很哇塞的体积计算方法:向量叉乘 很哇塞的体积计算方法
-
高中数学必看:向量叉乘,体积的神。大家都知道a、b的向量是什么意思,但是a、b的向量又是什么?很多同学都不知道,向量的向量在高中阶段非常有用,虽然它是大学的知识,在高中阶段可以干两件事。·第一件事,表...
- 施工升降机基础(设置在地库顶板回顶)计算书
-
施工升降机基础(设置在地库顶板回顶)计算书计算依据:1、《施工现场设施安全设计计算手册》谢建民编著2、《建筑地基基础设计规范》GB50007-20113、《混凝土结构设计标准》GB/T50010-2...
- 剪力墙水平钢筋根数如何计算?(剪力墙水平钢筋绑扎搭接规范)
-
剪力墙水平钢筋根数的计算需综合考虑墙高、起步距离、间距及构造要求等因素,具体步骤如下及依据:1.基本计算公式水平钢筋根数计算公式为:根数=(墙高-起步距离)/间距(墙高-起步距离)/间距...
- 直流电路常用计算公式(直流电路常用计算公式有哪些)
-
1、电阻导体阻碍电流通过的能力叫做电阻,用字母R表示,单位欧(Ω)。R=ρl/s式中R-导体的电阻,欧(Ω);ρ-导体的电阻率,欧·米(Ω·m);l-导体的长度,米(m);s-导体的截面积,平方米(m...
- 电气主电路图的绘制特点(电气原理图主电路)
-
1、电气主电路图中的电气设备、元件,如电源进线、变压器、隔离开关、断路器、熔断器、避雷器等都垂直绘制,而母线则水平绘制。电气主电路图除特殊情况外,几乎无一例外地画成单线图,并以母线为核心将各个项目(如...
- 中考总复习:物理专题 功和机械能 (功的计算、功率、动能、势能)
-
中考物理专题:功与机械能解析一、力学中的功——能量转化的桥梁功是力对物体能量变化的量度,需满足两要素:作用在物体上的力、物体沿力方向移动距离。例如推箱子时,若箱子未移动,推力不做功;若箱子滑动,推力做...
- 40亿QQ号,不超过1G内存,如何去重?
-
分享一道网上很火的面试题:40亿QQ号,不超过1G的内存,如何去重?这是一个非常经典的海量数据去重问题,并且做了内存限制,最多只能1GB,本文跟大家探讨一下~~一、常规思路我们日常开发中,如果谈到去重...
- 填充墙体拉结筋植筋深度、孔径、拉拔试验承载力计算!
-
今天分享下植筋间距及保护层要求:根据JGJ145-2013混凝土后锚固技术规程要求植筋与混凝土结构边缘不应小于5mm,植筋为两根及以上时水平间距为不应小于5d(d为钢筋直径)。根据混凝土结构后锚固技...
- 一周热门
- 最近发表
- 标签列表
-
- HTML 简介 (30)
- HTML 响应式设计 (31)
- HTML URL 编码 (32)
- HTML Web 服务器 (31)
- HTML 表单属性 (32)
- HTML 音频 (31)
- HTML5 支持 (33)
- HTML API (36)
- HTML 总结 (32)
- HTML 全局属性 (32)
- HTML 事件 (31)
- HTML 画布 (32)
- HTTP 方法 (30)
- 键盘快捷键 (30)
- CSS 语法 (35)
- CSS 轮廓宽度 (31)
- CSS 谷歌字体 (33)
- CSS 链接 (31)
- CSS 定位 (31)
- CSS 图片库 (32)
- CSS 图像精灵 (31)
- SVG 文本 (32)
- 时钟启动 (33)
- HTML 游戏 (34)
- JS Loop For (32)