yaml结合数据驱动编写测试用例
文章中示例源码获取地址:https://github.com/wmm0165/auditcenter_190912
1.yaml格式介绍
基本格式
k: v(:后必须有空格)
减号-表示列表 - desc: 机构列表 api: /api/v1/zoneForReport method: get data: - test1 - test2 params: keyword: null headers: Content-Type: application/json assert_code: 200 等价于: [{'desc': '机构列表', 'api': '/api/v1/zoneForReport', 'method': 'get', 'data': ['test1', 'test2'], 'params': {'keyword': None}, 'headers': {'Content-Type': 'application/json'}, 'assert_code': 200}]
-分隔多个测试用例 - desc: 机构列表 api: /api/v1/zoneForReport method: get data: - test1 - test2 params: keyword: null headers: Content-Type: application/json assert_code: 200 - desc: 门诊科室列表 api: /api/v1/deptForReport method: get data: null params: type: 1 keyword: null headers: Content-Type: application/json assert_code: 200 等价于: [{'desc': '机构列表', 'api': '/api/v1/zoneForReport', 'method': 'get', 'data': ['test1', 'test2'], 'params': {'keyword': None}, 'headers': {'Content-Type': 'application/json'}, 'assert_code': 200}, {'desc': '门诊科室列表', 'api': '/api/v1/deptForReport', 'method': 'get', 'data': None, 'params': {'type': 1, 'keyword': None}, 'headers': {'Content-Type': 'application/json'}, 'assert_code': 200}]
2.读取yaml文件
import yaml import os from config.config import YAML_PATH class HandleYaml: def __init__(self): pass def read_yaml(self, filename): with open(os.path.join(YAML_PATH, filename), 'r', encoding='utf8') as f: file_content = yaml.load(f, Loader=yaml.FullLoader) datas = [tuple(i.values())[1::] for i in file_content] print(file_content) return datas
3.使用pytest进行数据驱动
import pytest from common.request import HttpRequest from common.handle_yaml import HandleYaml requ = HttpRequest() hy = HandleYaml() datas = hy.read_yaml('auditcenter.yaml') print(datas) auditcenter_url = 'http://10.1.1.89:9999/auditcenter' @pytest.mark.parametrize("api,method,data,params,headers,assert_code", datas) def test_single_api(api, method, data, params, headers, assert_code): res = requ.req(auditcenter_url + api, method, data, params, headers) assert res.json()['code'] == str(assert_code)
踩坑是成长最快的方式