def test_setattr_path(): assert getattr_path(setattr_path(Struct(a=0), 'a', 1), 'a') == 1 assert getattr_path(setattr_path(Struct(a=Struct(b=0)), 'a__b', 2), 'a__b') == 2 with pytest.raises(AttributeError): setattr_path(Struct(a=1), 'a__b', 1)
def apply(self, instance): """ Write the new values specified in the form into the instance specified. """ assert self.is_valid() for field in self.fields: if not field.editable: field.value = field.initial field.value_list = field.initial_list if field.attr is not None: if field.value is not None: setattr_path(instance, field.attr, field.value) else: setattr_path(instance, field.attr, field.value_list)
def test_getattr_path_and_setattr_path(): class Baz(object): def __init__(self): self.quux = 3 class Bar(object): def __init__(self): self.baz = Baz() class Foo(object): def __init__(self): self.bar = Bar() foo = Foo() assert getattr_path(foo, 'bar__baz__quux') == 3 setattr_path(foo, 'bar__baz__quux', 7) assert getattr_path(foo, 'bar__baz__quux') == 7 setattr_path(foo, 'bar__baz', None) assert getattr_path(foo, 'bar__baz__quux') is None setattr_path(foo, 'bar', None) assert foo.bar is None
def test_getattr_path_and_setattr_path(): class Baz(object): def __init__(self): self.quux = 3 class Bar(object): def __init__(self): self.baz = Baz() class Foo(object): def __init__(self): self.bar = Bar() foo = Foo() assert 3 == getattr_path(foo, 'bar__baz__quux') setattr_path(foo, 'bar__baz__quux', 7) assert 7 == getattr_path(foo, 'bar__baz__quux') setattr_path(foo, 'bar__baz', None) assert None is getattr_path(foo, 'bar__baz__quux') setattr_path(foo, 'bar', None) assert None is foo.bar
def default_write_to_instance(field, instance, value): setattr_path(instance, field.attr, value)