使用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))

成功

相关推荐
Csvn6 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵1 天前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent