httprunner+JSONPath支持属性和索引多重过滤

 

原生的Httprunner2.5.7 ,的Jsonpath似乎被屏蔽了,
通过重写,打开后,如下

 def _extract_field_with_jsonpath(self, field):
    if result: # TODO return result[0] if len(result) == 1 else result else: raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field))

后续又发现 不能支持属性过滤和索引同时使用,这就有点不友好了,毕竟返回数据多时,还是想做多重过滤的,如下

$..book[?(@.title=="Moby Dick")][1].price 过滤所有title为Moby Dick的书籍 数组中第二个的price

 

查了下,发现是Jsonpath本身不支持,那就只能再优化,

将一个混合提取分隔为多段,原数据,使用第一段提取完成后,将取出的数据再做为源数据进入第二段提取,以此类推,

基本实现了 过滤+索引的混合提取;

如下

    def _extract_field_with_jsonpath(self, field):
        split_lst = re.findall('.+?\[(\d)\]', field)
        ex_lst = re.split('\[\d\]', field)
        if ex_lst and '@' in field: # add 支持 属性过滤后取索引
            import copy
            result = copy.deepcopy(self.json)
            for i, per_ex in enumerate(ex_lst):
                if not per_ex.startswith('$.'):
                    per_ex = f'$.{per_ex}'
                result = jsonpath.jsonpath(result, per_ex)
                if i != len(ex_lst) - 1:
                    result = result[int(split_lst[i])]
        else:
            result = jsonpath.jsonpath(self.json, field)
        if result:  # TODO
            return result[0] if len(result) == 1 else result
        else:
            raise exceptions.ExtractFailure("\tjsonpath {} get nothing\n".format(field))

 

posted on 2022-01-22 15:55  旧楚布衣  阅读(235)  评论(0编辑  收藏  举报