我有一个django rest API端点登录,它以json对象的形式获取用户名和密码,如下所示。
{
username: email,
password: password,
}
并返回包含标记
的json对象{
token : 0234jh324234j2hiy342
}
现在我想在行为中写一个测试。我有以下功能文件。
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 decorator中的@given装饰器访问url,header和body。我如何检查json以回应我预期的json。
答案 0 :(得分:1)
Per @ 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
或类似的事情。