我有一个 django rest API 端点登录,它采用 json 对象形式的用户名和密码,如下所示。
{
username: email,
password: password,
}
并返回一个包含token的json对象
{
token : 0234jh324234j2hiy342
}
现在我想在 behave 中编写一个测试。我有以下功能文件。
Feature: Login User
By providing different credentials we check if our login API end point is working as expected or not
Scenario: Login User by Providing Authentication Credentials
Given I provide user authentication credentials
Then I must get a reponse with status code 200 and a jSon object with token
下面是我的auth.py文件
from behave import *
import requests
import json
@given('I have user authentication credentials')
def set_impl(context):
url = 'https://example.com/v1/login'
headers = {'content-type': 'application/json'}
body = {
"username": "xyz@email.com",
"password": "abcdef123",
}
@when('I make an http post call')
def step_impl(context):
context.res = requests.post(url, data=json.dumps(body), headers=headers)
@then('I must get a reponse with status code 200 and a jSon object with token')
def step_impl(context):
assert context.res.status == 200
我无法从@when 装饰器中的@given 装饰器访问url、 header 和正文。我如何检查 json 以响应我预期的 json。
请您参考如下方法:
根据@KlausD. 的建议,您应该将变量添加到行为的context 对象中。我已经编辑了您的代码,将您的变量添加为 context 对象的属性。
from behave import *
import requests
import json
@given('I have user authentication credentials')
def set_impl(context):
context.url = 'https://example.com/v1/login'
context.headers = {'content-type': 'application/json'}
context.body = {
"username": "xyz@email.com",
"password": "abcdef123",
}
@when('I make an http post call')
def step_impl(context):
context.res = requests.post(context.url, data=json.dumps(context.body), headers=context.headers)
@then('I must get a reponse with status code 200 and a jSon object with token')
def step_impl(context):
assert context.res.status == 200
至于根据预期的 JSON 检查响应中的 JSON...
检查
requests包的response对象here了解如何获取response对象的属性。通过
open()打开您自己期望的 JSON 文件,获取与token键对应的值,然后执行assert expectedToken = = responseToken,或类似的东西。
