httprunner 3.x学习19 - 从返回头部headers取值Content-Type (报错已解决:Bad jmespath expression: Unknown token '-')
前言
httprunner 3.x 取值是用 jmespath 表达式,当从头部取值Content-Type时,有特殊字符 -,会报错
jmespath.exceptions.LexerError: Bad jmespath expression: Unknown token '-': headers.Content-Type
使用示例
从返回的headers提取Content-Type内容
from httprunner import HttpRunner, Config, Step, RunRequest
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
class TestLoginV4Case(HttpRunner):
config = Config("登录v4用例").base_url("http://127.0.0.1:80")
teststeps = [
Step(RunRequest("step-login")
.post("/api/v1/login")
.with_json({"username": "test", "password": "123456"})
.validate()
.assert_equal("status_code", 200)
.assert_equal('headers.Content-Type', 'application/json')
)
]
返回的 response 内容
================== response details ==================
status_code : 200
headers : {
"Date": "Tue, 17 Aug 2021 10:54:10 GMT",
"Server": "WSGIServer/0.2 CPython/3.6.8",
"Content-Type": "application/json",
"Vary": "Accept, Cookie",
"Allow": "POST, OPTIONS",
"X-Frame-Options": "SAMEORIGIN",
"Content-Length": "109"
}
cookies : {}
encoding : utf-8
content_type : application/json
body : {
"code": 0,
"msg": "login success!",
"username": "test",
"token": "607d2bea6a652b05f3e3d201e7328e2bb4026173"
}
运行的时候会报错
expression: headers.Content-Type
data: {'status_code': 200,
'headers': {'Date': 'Tue, 17 Aug 2021 10:54:10 GMT', 'Server': 'WSGIServer/0.2 CPython/3.6.8', 'Content-Type': 'application/json', 'Vary': 'Accept, Cookie', 'Allow': 'POST, OPTIONS', 'X-Frame-Options': 'SAMEORIGIN', 'Content-Length': '109'},
'cookies': {},
'body': {'code': 0, 'msg': 'login success!', 'username': 'test', 'token': '607d2bea6a652b05f3e3d201e7328e2bb4026173'}}
exception: Bad jmespath expression: Unknown token '-':
headers.Content-Type
解决办法
因为headers.Content-Type有特殊字符-,jmespath处理特殊字符可以用引号包起来headers.\"Content-Type\"
.validate()
.assert_equal("status_code", 200)
.assert_equal('headers.\"Content-Type\"', 'application/json')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2018-08-17 pytest文档14-函数传参和fixture传参数request