Coverage for ejpiaj/variable_extractor: 94%

# Coverage for ejpiaj/variable_extractor : 94%

## 36 statements 34 run 2 missing 0 excluded

Hot-keys on this page

r m x p toggle line displays

j k next/prev highlighted chunk

0 (zero) top of page

1 (one) first highlighted chunk

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | import re import json from .decorators import variable_extractor @variable_extractor('json') def json_variables_extractor(response, variables): """Extracts variables from json response.content. Variables path are written using 'dot' access and index access to lists f.i.: some.path.to.list.[0] [1].dict.access.later """ result = {} re_list = re.compile('^\[\d+\]$') # use 'dot' access to dictionary data = json.loads(response.content) for path, name in variables.items(): try: subdata = data for attr in path.split('.'): # support for list access [0] if re_list.match(attr): ind = int(attr[1:-1]) subdata = subdata[ind] else: subdata = subdata.get(attr) result[name] = subdata except: result[name] = None return result @variable_extractor('response') def response_variables_extractor(response, variables): result = {} re_list = re.compile('^\[\d+\]$') for path, name in variables.items(): try: subdata = response for attr in path.split('.'): # support for list access [0] if re_list.match(attr): ind = int(attr[1:-1]) subdata = subdata[ind] else: if isinstance(subdata, dict): subdata = subdata.get(attr) else: subdata = getattr(subdata, attr) result[name] = subdata except: result[name] = None return result