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

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

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

项目结构

安装依赖

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

相关推荐

Luminati代理动态IP教程指南配置代理VMLogin中文版反指纹浏览器

介绍如何使用在VMLogin中文版设置Luminati代理。首先下载VMLogin中文版反指纹浏览器(https://cn.vmlogin.com)对于刚接触Luminati动态ip的朋友,是不是不懂...

文档中图形及子图形的处理(word中的图形对象有何特点)

【分享成果,随喜正能量】走得越远,见识越多,认识的人越多,你就越能体会到,人这一辈子,你真的在意的,同时又在意你的人,就那么几个,这几个人,就是你全部的世界。三两知己,爱人在侧,父母康健,听起来平淡无...

Python爬虫破解滑动验证码教程(python绕过滑动验证码)

破解滑动验证码通常需要结合图像识别和模拟人类操作,以下是分步骤的解决方案:1.分析验证码类型缺口识别型:背景图带缺口,滑块图带凸块轨迹验证型:除了位置还需模拟人类移动轨迹2.获取验证码图片方法一:...

「教程」5 分钟带你入门 kivy(新手kp教学)

原创:星安果AirPythonkivy语言通过编写界面UI,然后利用Python定义一些业务逻辑,可以移植很多功能模块到移动端直接执行。下面对kivy常见用法做一个汇总。1、什么是...

比呀比: Fossil Estate Canvas EW 男式复古邮差包 $70.99

Fossil是一个来自美国的全球性生活时尚品牌,始建于1984年,专注于时尚配件,是第一个将手表的价值与款式完美结合的美国品牌,如今Fossil已跃身成为美国最受欢迎的品牌之一。这款FossilE...

智能教学:如何在网上授课(网上授课怎么弄)

摘要:因为担心传统课堂可能会传播冠状病毒,许多大学已经开始在网上授课。耶鲁-新加坡国立大学的讲师凯瑟琳·谢伊·桑格(CatherineSheaSanger)解释了如何快速而有效地做到这一点。当新型冠...

wxPython库教程系列之图片:托盘图标和图片缩放、移动

1概要:=====1.1托盘图标设置1.2普通图片显示:原图显示,缩放显示,窗口与图片大小相互适应。1.3按钮图片设置1.4移动图片和zoom菜单按钮联动设置2托盘图标:========2...

UE4渲染目标开发教程(ue4渲染效果图质量怎么样)

渲染目标(RenderTarget)是你可以在运行时写入的纹理。在引擎方面,它们存储基础颜色、法线和环境光遮蔽等信息。在用户方面,渲染目标主要用作一种辅助相机。你可以将场景捕捉指向某物并将图像存储到...

比呀比: Fossil 化石 Canvas NS 男士复古帆布斜挎包 $57.59

FossilCanvasNS男士复古帆布斜挎包,尺寸约为26.5*11*33厘米。采用100%纯棉帆布面料,融合了休闲与百搭的外形,在经典的款型呈现复古质感。内设1个拉链袋,2个搭扣数码产品袋和...

比呀比: Timberland 添柏岚 Canvas Cord Case 帆布旅行手包 $5.99

Timberland添柏岚这款耐用帆布旅行手包,虽然一眼过去,觉得不咋地,但是品牌和质量还是妥妥滴,非常适合装一些零零碎碎的小东西,便于携带,多色可选,重点是价格更是感动价啊。目前这款包在6pm报价...

提炼文章/知识资料,两键转换成小红书图片

现在AI的功能已经越来越强大了,通过AI可以提高我们不少工作效率。刚好前几天做了一个几乎“一气呵成”,把长文章转成小红书卡片的流程Demo,分享给大家。之前发过两篇利用AI把长文章转成小红书图片...

python海龟绘图turtle(一):画布和窗体

海龟绘图(turtle)是python的一个有趣的内置模块,是python语言的标准库之一,是入门级的图形绘制函数库。海龟绘图(turtle)可以根据编写的控制指令(代码),让一个小“海龟”在屏幕上来...

在文档中添加画布及图片(word中如何添加画布)

【分享成果,随喜正能量】宁可正而不足,不可邪而有余。相识满天下,知心能几人。书七成,戏三分,牛皮灯影胡编成。布施不如还债,修福不如避祸。勿以恶小而为之,勿以善小而不为。。《VBA之Word应用》,是我...

知识管理神器 Obsidian,终于有了白板功能!

沙牛提示阅读本文需要3分钟,Obsidian白板功能来了!如果你喜欢本文,就分享给你的小伙伴!01白板继双链笔记之后,这一年,白板类工具开始火了起来。顾名思义,白板类工具,它给了你一张无限尺寸...

虚拟背景第一弹!教你如何在家中优雅地“学在交大”!

交大将于3月2日正式开始线上教学(3月1日举行线上教学第一课|视频直播课)目前正处于网课试课阶段交大在线课程教学以ZOOM、Canvas等作为主平台平台的虚拟背景功能可以具特别的环境效果更好地沉浸课堂...