百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Python3+pytest+allure接口自动化测试框架搭建

myzbx 2025-03-20 16:59 12 浏览

项目结构

安装依赖

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

相关推荐

Django零基础速成指南:快速打造带用户系统的博客平台

#python##服务器##API##编程##学习#不是所有教程都值得你花时间!这篇实战指南将用5分钟带你解锁Django核心技能,手把手教你从零搭建一个具备用户注册登录、文章管理功能的完整...

iOS 17.0 Bootstrap 1.2.9 半越狱来啦!更新两点

这款Bootstrap半越狱工具终于更新,离上一次更新已相隔很久,现在推出1.2.9版本,主要为内置两点功能进行更新,也是提升半越狱的稳定性。如果你正在使用这款半越狱工具的,建议你更新。注意!...

iOS 16.x Bootstrap 1.2.3 发布,支持运行清理工具

本文主要讲Bootstrap半越狱工具更新相关内容。如果你是iOS16.0至16.6.1和17.0系统的,想体验半越狱的果粉,请继续往下看。--知识点科普--Bootstrap...

SpringBoot整合工作流引擎Acticiti系统,适用于ERP、OA系统

今日推荐:SpringBoot整合工作流引擎Acticiti的源码推荐理由:1、SpringBoot整合工作流引擎Acticiti系统2、实现了三级权限结构3、持久层使用了mybatis框架4、流程包...

SpringCloud自定义Bootstrap配置指南

在SpringCloud中自定义Bootstrap配置需要以下步骤,以确保在应用启动的早期阶段加载自定义配置:1.添加依赖(针对新版本SpringCloud)从SpringCloud2020...

Python使用Dash开发网页应用(三)(python网页开发教程)

PlotlyDash开发Web应用示例一个好的网页设计通常都需要编写css甚至js来定制前端内容,例如非常流行的bootstrap框架。我们既然想使用Dash来搭建web应用,很大的一个原因是不熟悉...

Oxygen XML Editor 27.1 中的新功能

OxygenXMLEditor27.1版是面向内容作者、开发者、合作者和出版商的行业领先工具包的增量版本。在27.1版本中,AIPositronAssistant得到了增强,包括用于...

【LLM-多模态】Mini-Gemini:挖掘多模态视觉语言模型的潜力

一、结论写在前面论文提出了Mini-Gemini,一个精简而强大的多模态VLM框架。Mini-Gemini的本质在于通过战略性框架设计、丰富的数据质量和扩展的功能范围,发掘VLM的潜在能力。其核心是补...

谐云课堂 | 一文详解分布式改造理论与实战

01微服务与分布式什么是分布式?首先,我们对上图提到的部分关键词进行讲解。单体,是指一个进程完成全部的后端处理;水平拆分,是同一个后端多环境部署,他们都处理相同的内容,使用反向代理来均衡负载,这种也叫...

基于Abaqus的手动挡换挡机构可靠性仿真

手动挡,也称手动变速器,英文全称为Manualtransmission,简称MT,即用手拨动换挡操纵总成才能改变变速器内的齿轮啮合位置,改变传动比,从而达到变速的目的。家用轿车主要采用软轴连接的换挡...

【pytorch】目标检测:彻底搞懂YOLOv5详解

YOLOv5是GlennJocher等人研发,它是Ultralytics公司的开源项目。YOLOv5根据参数量分为了n、s、m、l、x五种类型,其参数量依次上升,当然了其效果也是越来越好。从2020...

超实用!50个非常实用的PS快捷键命令大全分享

今天,给大家介绍50个非常实用的快捷键命令大全,大家伙都是设计师,关于软件使用那是越快越好啊。一、常用的热键组合1、图层混合模式快捷键:正常(Shift+Option+N),正片叠底(Shif...

Pohtoshop中深藏不露的小技巧(科目一考试技巧记忆口诀看完必过)

邢帅教育ps教程为大家总结了一些Pohtoshop中深藏不露的小技巧,可以帮助到大家在设计时减少不必要的麻烦,提高工作效率哦~~~1.设置网格线保持像素完美不在1:1分辨率下也能保持像素完美,可以...

Ganglia监控安装总结(监控安装工作总结)

一、ganglia简介:Ganglia是一个跨平台可扩展的,高性能计算系统下的分布式监控系统,如集群和网格。它是基于分层设计,它使用广泛的技术,如XML数据代表,便携数据传输,RRDtool用于数据...

谁说Adobe XD做不出好看的设计?那是你没搞懂这些功能

AdobeXD的美化栏具有将设计视图美化的功能,它能使界面设计和原型设计更漂亮、更吸引眼球。美化栏的7个功能包括竖线布局设计、横线布局设计、重复网格、图形大小和位置设置、响应式调整大小、文字美化以及...