使用python反射,实现pytest读取yaml并发送请求

pytest + yaml

yaml

yaml 复制代码
- feature: 用户模块
  story: 登录
  title: 添加用户
  request:
    method: POST
    url: /system/user/list
    headers: null
    params: null
  validate: null

read_yaml_all

python 复制代码
def read_yaml_all(path):
    with open(path, 'r', encoding='utf-8') as f:
        value = yaml.safe_load(f)
        return value

dataclass.py

python 复制代码
from dataclasses import dataclass


@dataclass
class CaseInfo:
    feature: str
    story: str
    title: str
    request: dict
    validate: dict


def verify_yaml(case_info: dict):
    """
    通过解包的方式,校验yaml格式是否正确
    :param case_info:
    :return:
    """
    try:
        case = CaseInfo(**case_info)
        return case
    except Exception:
        raise Exception("YAML测试用例不符合规范!")

test_yaml_class.py

python 复制代码
from pathlib import Path

import pytest

from lib import read_yaml_all, verify_yaml


class TestYamlCases:
    pass


def create_case_by_yaml(yaml_path):
    # 读取yaml
    @pytest.mark.parametrize('case', read_yaml_all(yaml_path))
    def yaml_function(self, session, case):
        """
        :param self: TestYamlCases类对象
        :param session: 夹具
        :param case: 参数化
        :return:
        """
        # 校验yaml格式是否与数据类字段一致
        case_info = verify_yaml(case)
        # 发送请求
        session.request(**case_info.request)
    # return方法与def平级,切记
    return yaml_function


test_case_yaml_paths = Path(__file__).parent
case_yaml_list = test_case_yaml_paths.glob("**/*.yaml")

for yaml_file in case_yaml_list:
    print(yaml_file)
    print(yaml_file.stem)
    # python 反射,通过反射的方式将pytest的测试用例传入TestYamlCases中
    setattr(TestYamlCases, "test_" + yaml_file.stem, create_case_by_yaml(yaml_file))

成功

相关推荐
BK贝壳12 小时前
bool-hybrid-array 的 GPU_opt 与 cjx:一个没显卡就报错的开关,一个把 800 字压到 96 字节的编码
python
BD_Marathon16 小时前
安装Jupyter notebook
ide·python·jupyter
Zlzxzw16 小时前
End-to-End Autonomous Generation of Human Assembly Plans
python
Wellijohn17 小时前
2000 个请求、30% 失败率:我把 Python 批量并发的限流和重试参数算了一遍
后端·python·性能优化
Logintern0919 小时前
deep agents 多智能体模式——规划与委派
python·langchain
2601_9679801120 小时前
Python 办公自动化合集 ⑰:Excel自动计算——总和/平均分/最大值
python·pycharm·办公自动化·数据处理·excel自动计算
databook1 天前
时间序列预测,模型换了一圈为什么没变好
python·数据分析
reasonsummer1 天前
【教学类-07-17】20261119大3班破译电话号码HTML实际操作(添加“跳过按钮”和“返回按钮”在底部、增加“自编题目+解题”部分)
python·html
2601_967980111 天前
Python闭包(Closure)详解
python·作用域·装饰器·函数式编程·闭包
AI创界者1 天前
ComfyUI 进阶实战:MiniMax-H3 视频人物脸部替换工作流全解析(对比 Face 5.5 实测与避坑指南)
人工智能·python·aigc