我正在使用 Tavern
在 python3
中测试我的 Web 服务器。 Tavern
是基于预定义的yaml
文件来测试服务。当向客户端响应自动生成的 id 值时,我有一个后端 API。如何测试自动生成的响应?如何将响应保存到变量并将其用于其他测试?
test_name: Test phonebook service
stages:
- name: Make sure we can create new contact
request:
url: http://localhost:8080/v2/contact
method: POST
json:
username: testUser
first_name: first
last_name: last
email: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9de9f8eee9ddf8f0fcf4f1b3fef2f0" rel="noreferrer noopener nofollow">[email protected]</a>
password: "123456"
phone: "111111"
response:
status_code: 200
body:
contact_id: # This is auto generated id from backend
如上面的示例,它向服务器发送 POST 请求,并期望响应中包含 200 状态代码。但我不知道如何检查 contact_id
这是后端生成的整数。
另外,我想将 contact_id
保存在变量中作为其他 API 的输入。
最佳答案
可以通过在响应中使用 save
来解决,例如:
response:
status_code: 200
headers:
content-type: application/json
save:
body:
contact_id: id
对于tavern >= 1.0 ,使用 json
而不是 body
:
response:
status_code: 200
headers:
content-type: application/json
save:
json:
contact_id: id
它将把响应 json 对象中的 id 值保存到名为 contact_id
的变量中。然后,您可以通过“{contact_id}”
引用该变量,如果您想将变量类型转换为“十进制整数”,则可以通过“{contact_id:d}”
引用该变量。
关于python - 如何将响应值保存到酒馆中的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57650726/