pytest 现学现用(三)

接下来就是鉴权接口的测试。
先封装httpx的发送发送请求:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 小橙子的爸比 (279453094@qq.com)
# @Version        : 1.0
# @Update Time    : 2025/1/3 下午5:59
# @File           : httpx_request.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
import httpx
from config.env_config import EnvInfo
from db.database_factory import DatabaseFactory
from utils.nb_logger import httpx_log as log


def get_sotre_token():
    rds = DatabaseFactory().get_db_instance("redis").db_getter()
    redis_key = EnvInfo.USER_NAME + "-" + EnvInfo.TEST_ENV_TAG + "-" + EnvInfo.REDIS_STORE_TOKEN_KEY
    token = rds.get(redis_key)
    if not token:
        raise ValueError("token不存在")
    return token


class HttpxRequest:
    def __init__(self, token=get_sotre_token()):
        auth_token = {"Authorization": f"Bearer {token}"}
        self.headers = EnvInfo().stitching_headers(update_data=auth_token)
        self.client = httpx.Client(headers=self.headers)

    def get(self, uri, pargrams=None):
        """封装get请求"""

        url = EnvInfo().stitching_url(uri)
        resp = self.client.get(url, params=pargrams)
        self.client.close()
        return resp

    def post(self, uri, data=None, files_path=None, file_name=None):
        """封装post请求
        :files_path :上传文件的绝对路径
        :file_name :上传文件的文件名

        """
        files = None
        url = EnvInfo().stitching_url(uri)
        if files_path is not None:
            files = {'upload-file': (files_path, open(file_name, 'rb'), 'application/vnd.ms-excel')}
        with self.client as client:
            resp = self.client.post(url, headers=self.headers, json=data, files=files)
            log.info(f"POST请求:{url}")
            # log.info(f"POST请求头消息:{self.headers}")
            log.info(f"POST请求参数:{data}")
            log.info(f"POST响应参数:{resp.text}")
        return resp

需要鉴权的接口,头消息需要有"Authorization",由session级的fixture负责存入redis,这里直接由函数get_sotre_token去获取,获取不到就抛出异常。然后我们看下具体的鉴权接口的用例。还是通过@pytest.mark.abnormity,@pytest.mark.smock两个标签来区分冒烟用例和异常场景用例,数据驱动由yaml文件提供。
使用的标签需要再pytest.ini里配置:

[pytest]
;addopts = --alluredir ./allure-results --capture=no --tb=long
addopts = --alluredir ./allure-results --cache-clear --capture=no --tb=long

markers =
    smock: basic case tag
    abnormity: request data usally has some mistake

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : 小橙子的爸比 (279453094@qq.com)
# @Version        : 1.0
# @Update Time    : 2025/1/4 下午7:42
# @File           : test_enterprise.py
# @IDE            : PyCharm
# @Desc           : 文件描述信息
import os

import allure
import pytest
from config.env_config import TestDataYamlFileName, ApiUri, TableName
from project_config import settings
from utils.tools import YamlTool
from utils.httpx_request import HttpxRequest
from utils.smarthub_crud import SmarthubCRUD

yml = YamlTool(os.path.join(settings.system.DATA_PATH, TestDataYamlFileName.ENTERPRISE_YML))
print(os.path.join(settings.system.DATA_PATH, TestDataYamlFileName.ENTERPRISE_YML))
test_datas = yml.read_yaml()


@allure.feature("SMARTHUB接口测试")
@allure.story("企业接口测试")
@allure.testcase("正确参数可以创建企业")
@pytest.mark.smock
@pytest.mark.parametrize("enterprise_info", test_datas['enterprise_create']['enterprise_info'])
def test_add_enterprise(enterprise_info):
    # 动态标题
    allure.dynamic.title(enterprise_info['title'])
    resp = HttpxRequest().post(uri=ApiUri.ENTERPRISE_URI, data=enterprise_info['data'])
    assert resp.status_code == 201
    # 创建数据接口,增加数据库入库检查
    v_where = f"where name='{enterprise_info['data']['name']}'"
    sql = SmarthubCRUD.make_sql(table_name=TableName.ENTERPRISE,v_where=v_where)
    query_res = SmarthubCRUD().execute_smarthub_qurry_sql(sql)
    assert len(query_res) > 0, f"新增企业数据未入库,企业名称:{enterprise_info['data']['name']}"
    assert resp.status_code == 201


@allure.feature("SMARTHUB接口测试")
@allure.story("企业接口测试")
@allure.testcase("错误参数,无法创建企业")
@pytest.mark.abnormity
@pytest.mark.parametrize("enterprise_info", test_datas['enterprise_create']['enterprise_info_error'])
def test_add_enterprise_error(enterprise_info):
    # 动态标题
    allure.dynamic.title(enterprise_info['title'])
    resp = HttpxRequest().post(uri=ApiUri.ENTERPRISE_URI, data=enterprise_info['data'])
    assert resp.status_code == 422
	# 创建数据接口,增加数据库入库检查
    v_where = f"where name='{enterprise_info['data']['name']}'"
    sql = SmarthubCRUD.make_sql(table_name=TableName.ENTERPRISE,v_where=v_where)
    query_res = SmarthubCRUD().execute_smarthub_qurry_sql(sql)
    assert len(query_res) > 0, f"新增企业数据(异常数据)入库,企业名称:{enterprise_info['data']['name']}"

现在就要考虑用例的后置脚本了,很烦哟。按理说,自动化测试用例要求独立性,但是后置脚本我没法完全从数据纬度去恢复测试环境,关联表太多,从数据库去恢复测试数据状态不现实(对我来说),备份数据库也是一个方法,将预置测试数据都造好后就将数据库备份起来,然后清理redis里的缓存。每次测试前就先恢复一次数据库。但是我的测试对象,每张卡跨月会自动续订套餐,备份数据库的方式就会导致数据缺失。目前我暂时通过一些接口去恢复数据。头疼!!!

该数据集通过合成方式模拟了多种发动机在运行过程中的传感器监测数据,旨在构建一个用于机械系统故障检测的基准资源,特别适用于汽车领域的诊断分析。数据按固定时间间隔采集,涵盖了发动机性能指标、异常状态以及工作模式等多维度信息。 时间戳:数据类型为日期时间,记录了每个数据点的采集时刻。序列起始于2024年12月24日10:00,并以5分钟为间隔持续生成,体现了对发动机运行状态的连续监测。 温度(摄氏度):以浮点数形式记录发动机的温度读数。其数值范围通常处于60至120摄氏度之间,反映了发动机在常规工况下的典型温度区间。 转速(转/分钟):以浮点数表示发动机曲轴的旋转速度。该参数在1000至4000转/分钟的范围内随机生成,符合多数发动机在正常运转时的转速特征。 燃油效率(公里/升):浮点型变量,用于衡量发动机的燃料利用效能,即每升燃料所能支持的行驶里程。其取值范围设定在15至30公里/升之间。 振动_X、振动_Y、振动_Z:这个浮点数列分别记录了发动机在维空间坐标系中各轴向的振动强度。测量值标准化至0到1的标度,较高的数值通常暗示存在异常振动,可能与潜在的机械故障相关。 扭矩(牛·米):以浮点数表征发动机输出的旋转力矩,数值区间为50至200牛·米,体现了发动机的负载能力。 功率输出(千瓦):浮点型变量,描述发动机单位时间内做功的速率,取值范围为20至100千瓦。 故障状态:整型分类变量,用于标识发动机的异常程度,共分为四个等级:0代表正常状态,1表示轻微故障,2对应中等故障,3指示严重故障。该列作为分类任务的目标变量,支持基于传感器数据预测故障等级。 运行模式:字符串类型变量,描述发动机当前的工作状态,主要包括:怠速(发动机运转但无负载)、巡航(发动机在常规负载下平稳运行)、重载(发动机承受高负荷或高压工况)。 数据集整体包含1000条记录,每条记录对应特定时刻的发动机性能快照。其中故障状态涵盖从正常到严重故障的四级分类,有助于训练模型实现故障预测与诊断。所有数据均为合成生成,旨在模拟真实的发动机性能变化与典型故障场景,所包含的温度、转速、燃油效率、振动、扭矩及功率输出等关键传感指标,均为影响发动机故障判定的重要因素。 资源来源于网络分享,仅用于学习交流使用,请勿用于商业,如有侵权请联系我删除!
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值