Skip to content

Commit

Permalink
Now any object implementing the dict interface can be used
Browse files Browse the repository at this point in the history
as a dict value for the Embedded field.

refs #18
  • Loading branch information
jaimegildesagredo committed Jan 29, 2014
1 parent 7ae5184 commit 38bd6d0
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
4 changes: 3 additions & 1 deletion booby/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ class User(Model):
is_active = Boolean(default=False)
"""

import collections

from booby import validators as builtin_validators


Expand Down Expand Up @@ -144,7 +146,7 @@ def __init__(self, model, *args, **kwargs):
self.model = model

def __set__(self, instance, value):
if isinstance(value, dict):
if isinstance(value, collections.MutableMapping):
value = self.model(**value)

super(Embedded, self).__set__(instance, value)
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/test_fields.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-

from __future__ import unicode_literals
import collections

from expects import expect
from ._helpers import Spy, stub_validator
Expand Down Expand Up @@ -97,6 +98,13 @@ def callback():

expect(callback).to.raise_error(errors.FieldError, 'foo')

def test_when_set_field_value_with_mutable_mapping_then_value_is_model_instance_with_dict_values(self):
self.group.admin = MyDict(name='foo', email='[email protected]')

expect(self.group.admin).to.be.an(User)
expect(self.group.admin).to.have.properties(
name='foo', email='[email protected]')

def test_when_set_field_value_with_not_dict_object_then_value_is_given_object(self):
user = User(name='foo', email='[email protected]')
self.group.admin = user
Expand Down Expand Up @@ -193,3 +201,23 @@ def test_when_embedded_model_validates_then_does_not_raise(self):

def setup(self):
self.field = fields.Embedded(User)


class MyDict(collections.MutableMapping):
def __init__(self, **kwargs):
self._store = kwargs

def __getitem__(self, key):
return self._store[key]

def __setitem__(self, key, value):
pass

def __delitem__(self, key):
pass

def __len__(self):
pass

def __iter__(self):
return iter(self._store)

0 comments on commit 38bd6d0

Please sign in to comment.