httprunner2.X踩坑指南
問題一、
2.X的版本有個bug:執行jsonpath會報錯:AttributeError: 'Response' object has no attribute 'parsed_body'
需要手動修復:https://blog.51cto.com/u_15249893/2950450
原因是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)
1.
修改後
result = jsonpath.jsonpath(self.json, field)
問題二、
requests.exceptions.InvalidHeader: Value for header {loginPatientId: ['17058']} must be of type str or bytes, not <class 'list'>
如上報錯時因為我在header中傳值時使用的欄位值是我在上個介面用jsonpath匹配的數值,
根據原始碼中response.py下def _extract_field_with_jsonpath(self, field)方法中描述:
: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]
返回值是個list,所以我這個報錯就是因為header中的傳引數值型別出錯了導致的
修改程式碼
result = jsonpath.jsonpath(self.parsed_body(), field)
if result:
return result
改為
result = jsonpath.jsonpath(self.parsed_body(), field)
if result:
return "".join(result)
這樣就返回str型別的值了,問題解決