def test_inspect(): # test repr assert repr(Inspect()) == '<INSPECT>' target = {'a': {'b': 'c'}} import pdb # test breakpoint assert Inspect(breakpoint=True).breakpoint == pdb.set_trace with pytest.raises(TypeError): Inspect(breakpoint='lol') tracker = [] spec = { 'a': Inspect('a.b', echo=False, breakpoint=lambda: tracker.append(True)) } glom(target, spec) assert len(tracker) == 1 # test post_mortem assert Inspect(post_mortem=True).post_mortem == pdb.post_mortem with pytest.raises(TypeError): Inspect(post_mortem='lol') tracker = [] spec = { 'a': Inspect('nope.nope', post_mortem=lambda: tracker.append(True)) } assert glom(target, spec, default='default') == 'default' assert len(tracker) == 1
def test_initial_integration(): class Example(object): pass example = Example() subexample = Example() subexample.name = 'good_name' example.mapping = {'key': subexample} val = { 'a': { 'b': 'c' }, # basic dictionary nesting 'example': example, # basic object 'd': { 'e': ['f'], # list in dictionary 'g': 'h' }, 'i': [{ 'j': 'k', 'l': 'm' }], # list of dictionaries 'n': 'o' } spec = { 'a': (Inspect(recursive=True), 'a', 'b'), # inspect just prints here 'name': 'example.mapping.key.name', # test object access 'e': 'd.e', # d.e[0] or d.e: (callable to fetch 0) 'i': ( 'i', [{ 'j': 'j' }] ), # TODO: support True for cases when the value should simply be mapped into the field name? 'n': ('n', lambda n: n.upper()), 'p': Coalesce('xxx', 'yyy', default='zzz') } ret = glom(val, spec) print('in: ', val) print('got:', ret) expected = { 'a': 'c', 'name': 'good_name', 'e': ['f'], 'i': [{ 'j': 'k' }], 'n': 'O', 'p': 'zzz' } print('exp:', expected) assert ret == expected
def glom_cli(target, spec, indent, debug, inspect): """Command-line interface to the glom library, providing nested data access and data restructuring with the power of Python. """ if debug or inspect: stdin_open = not sys.stdin.closed spec = Inspect(spec, echo=inspect, recursive=inspect, breakpoint=inspect and stdin_open, post_mortem=debug and stdin_open) try: result = glom(target, spec) except GlomError as ge: print('%s: %s' % (ge.__class__.__name__, ge)) return 1 if not indent: indent = None print(json.dumps(result, indent=indent, sort_keys=True)) return