我有一个 django Rest API 端点登录,它采用 json 对象形式的用户名和密码,如下所示。
{
username: email,
password: password,
}
并返回一个包含 token 的 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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="9ce4e5e6dcf9f1fdf5f0b2fff3f1" rel="noreferrer noopener nofollow">[email protected]</a>",
"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": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="08707172486d65696164266b6765" rel="noreferrer noopener nofollow">[email protected]</a>",
"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
,或类似的东西。
关于python - 使用行为进行 API 端点测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50819491/