使用python+pytest+yaml写接口自动化,两个接口的关联不知道怎么实现。
例如:yaml文件的token如何使用extract的动态参数。



使用python+pytest+yaml写接口自动化,两个接口的关联不知道怎么实现。
例如:yaml文件的token如何使用extract的动态参数。



关注引自免费微信小程序:皆我百晓生
在使用pytest, pytest-bdd(用于BDD风格的测试)和yaml编写接口自动化时,可以通过提取一个接口响应中的动态参数(例如token),并将其作为后续接口调用的参数。以下是一个详细的步骤说明以及示例代码:
假设你有一个test_data.yaml文件,其中包含两个API接口信息,并且第一个接口返回的JSON数据中包含需要提取的token:
# test_data.yaml
---
first_api:
url: 'https://example.com/api/login'
method: POST
data:
username: user1
password: pass123
extract_token: "$.access_token"
second_api:
url: 'https://example.com/api/protected_resource'
method: GET
headers:
Authorization: "Bearer {{ token }}"
在pytest测试脚本中,你可以使用requests库来发送请求,并通过jsonpath-ng或pyjq等库从响应中提取token。
首先安装必要的库:
pip install pytest pytest-bdd requests jsonpath-ng
然后在pytest测试脚本中实现动态参数提取:
import yaml
import requests
from jsonpath_ng import jsonpath, parse
# 加载yaml配置文件
with open("test_data.yaml", "r") as f:
config = yaml.safe_load(f)
def get_token_from_response(response):
token_path = config["first_api"]["extract_token"]
jsonpath_expr = parse(token_path)
token_match = jsonpath_expr.find(response.json())
return token_match[0].value if token_match else None
def test_api_sequence(requests_mock):
# 发送第一个请求并获取token
first_response = requests.request(
config["first_api"]["method"],
config["first_api"]["url"],
json=config["first_api"].get("data", {}),
)
# 提取token
token = get_token_from_response(first_response)
# 将token注入到第二个请求的headers中
second_api_config = config["second_api"]
second_api_config["headers"]["Authorization"] = f"Bearer {token}"
# 发送第二个请求
second_response = requests.request(
second_api_config["method"],
second_api_config["url"],
headers=second_api_config["headers"],
)
# 这里添加对第二个接口响应的断言检查
请注意,上述示例中使用了requests_mock库进行模拟请求,实际场景中可能不需要此库,直接使用requests即可。此外,为了简化问题,我们没有展示如何将这个过程与pytest fixture 和 pytest-bdd 配合使用,但你可以扩展此示例,在不同的given-when-then步骤中执行请求并传递动态参数。