在自动化用例中,我们经常会看到有人提问,上一个接口的返回的结果,如何取出来给到下个接口的入参。
我们用 extract 关键字提取接口的返回结果(需要更新v1.0.2版本)。
举个例子
用个post请求http://httpbin.org/post
POST http://httpbin.org/post HTTP/1.1
User-Agent: Fiddler
Host: httpbin.org
Content-Length: 0
HTTP/1.1 200 OK
Date: Thu, 24 Nov 2022 06:18:03 GMT
Content-Type: application/json
Content-Length: 320
Connection: keep-alive
Server: gunicorn/19.9.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Content-Length": "0",
"Host": "httpbin.org",
"User-Agent": "Fiddler",
"X-Amzn-Trace-Id": "Root=1-637f0c9a-23b419f4180f6b843ba941af"
},
"json": null,
"origin": "66.112.216.24",
"url": "http://httpbin.org/post"
}
比如我需要提取返回接口里面的url参数,那么我们用extract 关键字
test_demo.yml 文件示例
config:
name: post示例
teststeps:
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: test
password: "123456"
extract:
url: body.url
validate:
- eq: [status_code, 200]
- eq: [headers.Server, gunicorn/19.9.0]
- eq: [$..username, test]
- eq: [body.json.username, test]
上一个接口提取到了url 变量,接下来在下个接口中引用${url}
config:
name: post示例
teststeps:
-
name: post
request:
method: POST
url: http://httpbin.org/post
json:
username: test
password: "123456"
extract:
url: body.url
validate:
- eq: [status_code, 200]
- eq: [headers.Server, gunicorn/19.9.0]
- eq: [$..username, test]
- eq: [body.json.username, test]
-
name: post
request:
method: GET
url: http://httpbin.org/get
headers:
url: ${url}
validate:
- eq: [status_code, 200]
于是看到请求报文中引用成功
GET http://httpbin.org/get HTTP/1.1
Host: httpbin.org
User-Agent: python-requests/2.28.1
Accept-Encoding: gzip, deflate, br
Accept: */*
Connection: keep-alive
url: http://httpbin.org/post
我们在上一篇提到不能在yaml中对返回值重新二次取值。, 这也是一些同学提到的问题,对于提取的结果,我想继续取值,比如他是一个字符串,在python中可以用切片取值
那么,在yaml 中如何实现?
我重新设计的这个框架中,就可以支持python语法,直接用切片取值
headers:
url: ${url[:4]}
请求报文
GET http://httpbin.org/get HTTP/1.1
Host: httpbin.org
User-Agent: python-requests/2.28.1
Accept-Encoding: gzip, deflate, br
Accept: */*
Connection: keep-alive
url: http
校验方式延续了httprunner的校验语法,可以支持response取值对象:status_code, url, ok, headers, cookies, text, json, encoding
其中返回的是json格式,那么可以支持
如果返回的不是json格式,那么可以用正则取值
更多功能持续开发中…大家有好的建议想法也欢迎提出, 微信交流联系wx:283340479