前言
httprunner 2.x 版本是可以支持 jsonpath 提取器,但有個小bug一直未得到解決,會出現報錯:ResponseObject does not have attribute: parsed_body
遇到問題
使用jsonpath提取器,提取返回結果,校驗結果的時候,部分代碼示例如下
validate:
- eq: [status_code, 200]
- eq: [headers.Content-Type, application/json]
- eq: [$.code, [0]]
運行會出現報錯:
Traceback (most recent call last):
AttributeError: 'Response' object has no attribute 'parsed_body'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
httprunner.exceptions.ParamsError: ResponseObject does not have attribute: parsed_body
報錯原因是ResponseObject 找不到 parsed_body 屬性,這是框架本身的一個小BUG,但是這個框架作者一直沒去維護更新,作者想主推3.x版本了,也就不再維護了。
github上已經有多個人提過issue了。https://github.com/httprunner/httprunner/issues/908
找到 response.py 下的這段代碼
def _extract_field_with_jsonpath(self, field):
"""
JSONPath Docs: https://goessner.net/articles/JsonPath/
For example, response body like below:
{
"code": 200,
"data": {
"items": [{
"id": 1,
"name": "Bob"
},
{
"id": 2,
"name": "James"
}
]
},
"message": "success"
}
:param field: Jsonpath expression, e.g. 1)$.code 2) $..items.*.id
:return: A list that extracted from json repsonse example. 1) [200] 2) [1, 2]
"""
result = jsonpath.jsonpath(self.parsed_body(), field)
if result:
return result
else:
raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field))
修復bug
報錯的原因是這句 result = jsonpath.jsonpath(parsed_body(), field)
有個parsed_body()
方法寫的莫名其妙的,在ResponseObject 里面並沒有定義此方法。
jsonpath 第一個參數應該傳一個json()解析后的對象,可以修改成 self.json就行了。
修改前
result = jsonpath.jsonpath(self.parsed_body(), field)
修改后
result = jsonpath.jsonpath(self.json, field)
由於jsonpath 提取的結果返回的是list, 如:1) [200] 2) [1, 2],我們平常大部分情況都是直接取值,不需要提取多個,於是return結果的時候,可以直接取值[0]
修改后
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
result = jsonpath.jsonpath(self.json, field)
if result:
return result[0]
else:
raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field))
jsonpath 提取和校驗
jsonpath 提取返回結果,提取出匹配到的第一個值, 校驗結果也一樣
# 作者-上海悠悠 QQ交流群:717225969
# blog地址 https://www.cnblogs.com/yoyoketang/
extract:
code: $.code
validate:
- eq: [status_code, 200]
- eq: [headers.Content-Type, application/json]
- eq: [$.code, 0]
- eq: ["$code", 0]
查看報告
jsonpath語法還不會的可以看這篇
https://www.cnblogs.com/yoyoketang/p/13216829.html
https://www.cnblogs.com/yoyoketang/p/14305895.html