快速上手¶
环境依赖¶
pytest-yaml-sanmu 的使用环境为: python >=3.12和 pytest>=8.2
具体依赖如下:
python>=3.12
pytest>=8.2
pyyaml~=6.0
pyyaml-include~=1.3.1
安装插件¶
警告
注意: pytest-yaml-sanmu
和 pytest-yaml
存在冲突,只能 二选一 进行安装
pip install pytest-yaml-sanmu -U
添加配置¶
鉴于yaml文件应用广泛,为了避免误操作,本插件需要配置后才会启用。
具体来说:
在根目录创建
pytest.ini
写入下面这些内容
# pytest.ini
[pytest]
# 执行yaml用例
yaml_run_case = true
使用插件¶
1. 创建用例¶
创建yaml文件用例,每一个用例包含三个字段:
备注
注意:文件名必须是 test_
开头,以此和非用例的yaml进行区分
name:必填 ,字符串格式,用来说明用例名称
mark:选填,列表,用来说明标记
steps:必填 ,列表格式,用来说明用例步骤
例如:
# test_api.yaml
name: fetch baidu # Each test case has a name
steps: # Each test case has multiple steps
- request: # steps 1: send request
method: get
url: https://www.baidu.com
- response: # steps 2: assert response
status_code: 200
text: "*baidu*"
2. 创建钩子¶
插件在执行yaml用例时,会解析 steps
中的内容,并依次传递给钩子
pytest_yaml_run_step()
。
所以,创建钩子,即可得到每一个具体步骤,并根据步骤内容完成相应的动作。
备注
注意:钩子应该返回True,以便后续的同名钩子不再执行
# conftest.py
import requests
import responses_validator
def pytest_yaml_run_step(item):
step = item.current_step
request = step.get('request')
response = step.get('response')
if request:
print(f'url={request["url"]}')
item.resp = requests.request(**request)
if response:
responses_validator.validator(item.resp, **response)
return True
3. 执行用例¶
启动pytest框架即可加载和执行YAML用例
(.venv) ~/pytest-yaml-demo>pytest
================== test session starts ==================
platform win32 -- Python 3.12.2, pytest-8.2.2, pluggy-1.5.0
rootdir: ~/pytest-yaml-demo
configfile: pytest.ini
plugins: allure-pytest-2.13.5, yaml-0.3.0.dev3
collected 1 item
test_api.yaml . [100%]
================== 1 passed in 0.22s ==================
下一步¶
现在你已经可以用pytest执行yaml文件用例了,
接下来,可以继续学习在yaml文件中使用mark、fixture、数据驱动、变量、函数等内容。
此外,也可以在yaml文件中使用其他的pytest插件(通常是mark 或fixture的方式)