python - 使用 pytest 时 API POST 调用抛出 401 错误
问题描述
我正在执行 API 测试并使用 pytest 框架。测试一直失败,出现 401 错误。无法弄清楚是什么问题。
这是代码:
import requests
import json,jsonpath
import urllib3
import constants
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# variables
dumpFile = "somepath"
url = "someUrl"
headers = {'Authorization' : constants.consts['siteToken'],
'accept':'application/json',
'content-type':'application/json'}
#siteToken = 'Bearer jwt token'
# read json input file
input_file = open("json file path", 'r')
json_input = input_file.read()
request_json = json.loads(json_input)
# make POST request with JSON Input Body
r = requests.post(url, request_json, headers=headers)
# Verification of the response
assert r.status_code == 200
def test_json_result():
# fetch header from response
print(r.headers.get("Date"))
# parse response to JSON Format
response_json = json.loads(r.text)
# validate response using Json Path
name = jsonpath.jsonpath(response_json, 'name')
print(name)
解决方案
我通过输入 json=your_payload 解决了这个问题。
import requests
import json,jsonpath
import urllib3
import constants
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# variables
dumpFile = "somepath"
url = "someUrl"
headers = {'Authorization' : constants.consts['siteToken'],
'accept':'application/json',
'content-type':'application/json'}
#siteToken = 'Bearer jwt token'
# read json input file
input_file = open("json file path", 'r')
json_input = input_file.read()
request_json = json.loads(json_input)
def test_json_result():
# make POST request with JSON Input Body
r = requests.post(url, json=request_json, headers=headers)
# Verification of the response
assert r.status_code == 200
# fetch header from response
print(r.headers.get("Date"))
# parse response to JSON Format
response_json = json.loads(r.text)
# validate response using Json Path
name = jsonpath.jsonpath(response_json, 'name')
print(name)
推荐阅读
- java - Sonarqube 问题 - 将此“尝试”更改为资源尝试。如何处理条件资源?
- arrays - 如何在swift 5中将所有元素从自定义对象收集到数组中
- javascript - 我的异步组件渲染了两次,并且期望即使使用 await 也不会等待第二次?
- node.js - MongoDB 排序/加权$或聚合查询
- html - 基于所选滑块图像的自定义页面 html
- angular - 在动态 mat-table 中添加静态行
- asp.net-mvc - 如何将我的 List 转换为 IEnumerable?
- python - 了解 Numpy rot90 轴
- swift - NSFetchRequest 返回错误的 .count 值
- python - 如何使用 for 循环打印先前函数完成的操作?