def test_thing_from_obj_kwargs(): t = Thing(x=1, y=2) x = Thing.from_object(t, x=3, z='abc') assert x == {'x': 3, 'y': 2, 'z': 'abc'}
def test_thing_from_obj_noop(): t = Thing(x=1, y=2) x = Thing.from_object(t) assert x is t
def test_thing_path(): t = Thing(a=1, b=2) tt = Thing(t=t, c=3) assert tt.t.a == 1 assert tt.t.b == 2 assert tt.c == 3 assert tt['t.a'] == 1 assert tt['t.b'] == 2 assert tt['c'] == 3
def test_thing_from_obj(): f = Thing.from_object assert f(1) == 1 assert f((1, 2)) == (1, 2) assert f([1, 2]) == [1, 2] assert f(dict(a=1, b=2)) == Thing(a=1, b=2) assert f(dict(sub=dict(a=1, b=2), c=3)) == Thing(sub=Thing(a=1, b=2), c=3)
def test_thing_from_obj_kwargs_only(): t = None x = Thing.from_object(t, x=3, z='abc') assert x == {'x': 3, 'z': 'abc'}
def test_thing(): t = Thing(a=1, b=2) assert t.a == 1 assert t.b == 2 assert t['a'] == 1 assert t['b'] == 2
def test_thing_raises_attributeerror(): t = Thing(a=1, b=2) with pytest.raises(AttributeError): x = t.c with pytest.raises(AttributeError): y = t.a.b
def test_thing_raises_keyerror(): t = Thing(a=1, b=2) with pytest.raises(KeyError): x = t['c'] with pytest.raises(KeyError): y = t['a.b']
def test_yaml_dump(): # Keys are deliberately not in alphabetical order data = Thing(b=2, a=1) out = io.StringIO() yaml_dump(data, stream=out) result = out.getvalue() assert result == """b: 2\na: 1\n"""
""" Demonstrate some awkward cases. """ from rjgtoys.thing import Thing data = Thing.from_object({ 'a.b': 1, 'c': { 'd.e': 2 }, 'f.g': { 'h': 3 } }) assert data['a.b'] == 1 try: assert data.a.b == 1 except AttributeError: print("You can't 'split' a dotted item name and use it as two attributes") # The search for a point to 'split' an attribute path is not exhaustive: # These work: assert data['c']['d.e'] == 2
town=data['result']['value']['address']['town'])) def print_attrs(data): print("The {type} called {name} lives in {town}".format( type=data.result.value.type, name=data.result.value.name, town=data.result.value.address.town)) # The raw data can be printed: print("Print raw data...") print_items(data) try: print_attrs(data) except AttributeError: print("The raw data does not support attribute access") # Convert to a Thing... print("Now convert...") data = Thing.from_object(data) print_items(data) print_attrs(data)