def test_nested_struct(): """adapted from use case""" import json def _json(spec): return Auto((json.loads, _str_json, Match(spec))) _str_json = Ref( 'json', Match( Or(And(dict, {Ref('json'): Ref('json')}), And(list, [Ref('json')]), And(type(u''), Auto(str)), object))) rule_spec = Match({ 'rule_id': Or('', Regex(r'\d+')), 'rule_name': str, 'effect': Or('approve', 'custom_approvers'), 'rule_approvers': _json([{ 'pk': int, 'level': int }]), 'rule_data': _json([ # list of condition-objects { Optional('value', 'null'): _json(Or(None, int, float, str, [int, float, str])), 'field': Auto(int), # id of row from FilterField 'operator': str, # corresponds to FilterOperator.display_name } ]), Optional('save_as_new', False): Or(str, bool), }) rule = dict(rule_id='1', rule_name='test rule', effect='approve', rule_approvers=json.dumps([{ 'pk': 2, 'level': 1 }]), rule_data=json.dumps([{ 'value': json.dumps([1, 2]), 'field': 2, 'operator': '>' }, { 'field': 2, 'operator': '==' }])) glom(rule, rule_spec) rule['save_as_new'] = 'true' glom(rule, rule_spec)
def test_cruddy_json(): _chk(Match({'int_id?': Auto((int, (M > 0)))}), {'int_id?': '1'}, {'int_id?': '-1'}) # embed a build squished_json = Match({ 'smooshed_json': Auto((json.loads, Match({'sub': Auto((json.loads, M == 1))}))) }) glom({'smooshed_json': json.dumps({'sub': json.dumps(1)})}, squished_json)
def default_if_none(sub_schema, default_factory): return Or( And(M == None, Auto(lambda t: default_factory())), sub_schema)
def as_type(sub_schema, typ): 'after checking sub_schema, pass the result to typ()' return And(sub_schema, Auto(typ))
def _json(spec): return Auto((json.loads, _str_json, Match(spec)))