目录

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

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

pytest + yaml

yaml

  • feature: 用户模块 story: 登录 title: 添加用户 request: method: POST url: /system/user/list headers: null params: null validate: null

read_yaml_all

def read_yaml_all(path): with open(path, ‘r’, encoding=‘utf-8’) as f: value = yaml.safe_load(f) return value

dataclass.py

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

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

成功

https://i-blog.csdnimg.cn/direct/d25935893cdb48f7b7c7aec0881c97c6.png