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类型的值了,问题解决

 

posted @ 2022-02-24 22:34  头大点怎么了  阅读(110)  评论(0)    收藏  举报