pytest用yaml文件编写测试用例流程详解
作者:爱学习de测试小白
前言
本篇来学习在pytest中使用yaml编写测试用例
项目结构
conftest.py
只需在 conftest.py 即可实现使用yaml编写测试用例
# -*- coding: utf-8 -*- import jsonpath import pytest import requests def pytest_collect_file(parent, file_path): if file_path.suffix == ".yaml" and file_path.name.startswith("test"): return YamlFile.from_parent(parent, path=file_path) class YamlFile(pytest.File): def collect(self): import yaml yml_raw = self.fspath.open(encoding='utf-8').read() print('yml_raw', yml_raw) yml_var = Template(yml_raw).safe_substitute(os.environ) raw = yaml.safe_load(yml_var) print('raw', raw) for yaml_case in raw: name = yaml_case["test"]["name"] values = yaml_case["test"] yield YamlItem.from_parent(self, name=name, spec=values) class YamlItem(pytest.Item): def __init__(self, name, parent, spec): super().__init__(name, parent) self.name = name self.values = spec self.request = self.values.get("request") self.validate = self.values.get("validate") self.s = requests.session() def values_render_variable(self, values): # 替换测试用例中的关联值 yaml_test = Template(json.dumps(values)).safe_substitute(os.environ) values = yaml.safe_load(yaml_test) print('values', values) return values def runtest(self): values = self.values_render_variable(self.values) print('values:', values) request_data = values["request"] response = self.s.request(**request_data) print("响应数据:", response.text) # 判断是否有extract提取参数,实现参数关联 if values.get("extract"): for key, value in values.get("extract").items(): os.environ[key] = jsonpath.jsonpath(response.json(), value)[0] print('key', key) print('value', jsonpath.jsonpath(response.json(), value)[0]) # 断言 print('validate:', self.validate) self.assert_response(response, self.validate) def assert_response(self, response, validate): """自定义断言""" for i in validate: if "eq" in i.keys(): yaml_result = i.get("eq")[0] actual_result = jsonpath.jsonpath(response.json(), yaml_result) expect_result = i.get("eq")[1] print("实际结果:%s" % actual_result[0]) print("期望结果:%s" % expect_result) assert actual_result[0] == expect_result
yaml文件
test_method.yaml
说明:
此yaml支持参数化
extract :提取关键字
- name: 后面引用变量的key值
- $.args.name:jsonpath 提取变量表达式
引用变量
- $name : $key
- test:
name: get case
request:
url: https://postman-echo.com/get
method: GET
headers:
Content-Type: application/json
User-Agent: python-requests/2.18.4
params:
name: DH
city: Beijing
extract:
name: $.args.name
validate:
- eq: [$.args.name, DH]
- eq: [$.args.city, Beijing]
- test:
name: post case
request:
url: https://postman-echo.com/post
method: POST
headers:
Content-Type: application/json
User-Agent: python-requests/2.18.4
json:
name: $name
city: Beijing
validate:
- eq: [$.json.name, DH]
- eq: [$.json.city, Beijing]
执行并查看结果
pytest -s -v
到此这篇关于pytest用yaml文件编写测试用例流程详解的文章就介绍到这了,更多相关pytest编写测试用例内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!