Exemplo n.º 1
0
def test_dictlike():
    class Base(object):
        properties = Properties({'def': 456}, abc=123)

    props = Base.properties
    assert sorted(props.items()) == [('abc', 123), ('def', 456)]

    assert sorted(props.keys()) == ['abc', 'def']
    assert sorted(iterkeys(props)) == ['abc', 'def']

    assert sorted(props.values()) == [123, 456]
    assert sorted(itervalues(props)) == [123, 456]

    assert props.get('abc') == 123
    assert props.get('abc', 'blah') == 123
    assert props.get('blah', 'default') == 'default'
    assert props.get('blah') is None

    assert_raises(NotImplementedError, props.popitem)

    assert 'abc' in props
    assert 'ghi' not in props

    assert props == {'abc': 123, 'def': 456}
    assert props != {'ghi': 789}

    assert props
    props.clear()
    assert not props

    assert repr(props) == '{}'
Exemplo n.º 2
0
    def set(self, value):
        """.. TODO:: doc set()"""
        self.raw = value
        pairs = to_pairs(value)
        self._reset()

        seen = set()
        converted = True
        for key, value in pairs:
            if not self.may_contain(key):
                raise KeyError('%s %r schema does not allow key %r' %
                               (type(self).__name__, self.name, key))
            converted &= self[key].set(value)
            seen.add(key)
        required = set(iterkeys(self))
        if seen != required:
            missing = required - seen
            raise TypeError(
                'all keys required for a set() operation, missing %s.' %
                (','.join(repr(key) for key in missing)))
        element_set.send(self, adapted=converted)
        return converted
Exemplo n.º 3
0
    def set(self, value):
        """.. TODO:: doc set()"""
        self.raw = value
        pairs = to_pairs(value)
        self._reset()

        seen = set()
        converted = True
        for key, value in pairs:
            if not self.may_contain(key):
                raise KeyError(
                    '%s %r schema does not allow key %r' % (
                        type(self).__name__, self.name, key))
            converted &= self[key].set(value)
            seen.add(key)
        required = set(iterkeys(self))
        if seen != required:
            missing = required - seen
            raise TypeError(
                'all keys required for a set() operation, missing %s.' % (
                    ','.join(repr(key) for key in missing)))
        element_set.send(self, adapted=converted)
        return converted
Exemplo n.º 4
0
 def clear(self):
     frame = self._base_frame
     for key in iterkeys(self):
         frame[key] = Deleted
Exemplo n.º 5
0
 def __contains__(self, key):
     return key in iterkeys(self)
Exemplo n.º 6
0
 def keys(self):
     return list(iterkeys(self))
Exemplo n.º 7
0
 def is_empty(self):
     for _ in iterkeys(self):
         return False
     return True
Exemplo n.º 8
0
    def set_by_object(self, obj, include=None, omit=None, rename=None):
        """Set fields with an object's attributes.

        :param obj: any object
        :param include: optional, an iterable of attribute names to pull from
            *obj*, if present on the object.  Only these attributes will be
            included.
        :param omit: optional, an iterable of attribute names to ignore on
            **obj**.  All other attributes matching a named field on the
            mapping will be included.
        :param rename: optional, a mapping of attribute-to-field name
            transformations.  Attributes specified in the mapping will be
            included regardless of *include* or *omit*.

        *include* and *omit* are mutually exclusive.

        Sets fields on *self*, using as many attributes as possible from
        *obj*.  Object attributes that do not correspond to field names are
        ignored.

        Mapping instances have two corresponding methods useful for
        round-tripping values in and out of your domain objects.

        .. testsetup::

          # FIXME
          from flatland import Schema, String
          class UserForm(Schema):
              login = String
              password = String
              verify_password = String

          class User(object):
              def __init__(self, login=None, password=None):
                  self.login = login
                  self.password = password

        :meth:`update_object` performs the inverse of :meth:`set_object`, and
        :meth:`slice` is useful for constructing new objects.

        .. doctest::

          >>> user = User('biff', 'secret')
          >>> form = UserForm()
          >>> form.set_by_object(user)
          >>> form['login'].value
          u'biff'
          >>> form['password'] = u'new-password'
          >>> form.update_object(user, omit=['verify_password'])
          >>> user.password
          u'new-password'
          >>> user_keywords = form.slice(omit=['verify_password'], key=str)
          >>> sorted(user_keywords.keys())
          ['login', 'password']
          >>> new_user = User(**user_keywords)

        """
        fields = set(iterkeys(self))
        attributes = fields.copy()
        if rename:
            rename = list(to_pairs(rename))
            attributes.update(key for key, value in rename
                              if value in attributes)
        if omit:
            omit = list(omit)
            attributes.difference_update(omit)

        possible = ((attr, getattr(obj, attr)) for attr in sorted(attributes)
                    if hasattr(obj, attr))

        sliced = keyslice_pairs(possible,
                                include=include,
                                omit=omit,
                                rename=rename)
        final = dict((key, value) for key, value in sliced if key in fields)
        self.set(final)
Exemplo n.º 9
0
 def is_empty(self):
     for _ in iterkeys(self):
         return False
     return True
Exemplo n.º 10
0
    def set_by_object(self, obj, include=None, omit=None, rename=None):
        """Set fields with an object's attributes.

        :param obj: any object
        :param include: optional, an iterable of attribute names to pull from
            *obj*, if present on the object.  Only these attributes will be
            included.
        :param omit: optional, an iterable of attribute names to ignore on
            **obj**.  All other attributes matching a named field on the
            mapping will be included.
        :param rename: optional, a mapping of attribute-to-field name
            transformations.  Attributes specified in the mapping will be
            included regardless of *include* or *omit*.

        *include* and *omit* are mutually exclusive.

        Sets fields on *self*, using as many attributes as possible from
        *obj*.  Object attributes that do not correspond to field names are
        ignored.

        Mapping instances have two corresponding methods useful for
        round-tripping values in and out of your domain objects.

        .. testsetup::

          # FIXME
          from flatland import Schema, String
          class UserForm(Schema):
              login = String
              password = String
              verify_password = String

          class User(object):
              def __init__(self, login=None, password=None):
                  self.login = login
                  self.password = password

        :meth:`update_object` performs the inverse of :meth:`set_object`, and
        :meth:`slice` is useful for constructing new objects.

        .. doctest::

          >>> user = User('biff', 'secret')
          >>> form = UserForm()
          >>> form.set_by_object(user)
          >>> form['login'].value
          u'biff'
          >>> form['password'] = u'new-password'
          >>> form.update_object(user, omit=['verify_password'])
          >>> user.password
          u'new-password'
          >>> user_keywords = form.slice(omit=['verify_password'], key=str)
          >>> sorted(user_keywords.keys())
          ['login', 'password']
          >>> new_user = User(**user_keywords)

        """
        fields = set(iterkeys(self))
        attributes = fields.copy()
        if rename:
            rename = list(to_pairs(rename))
            attributes.update(key for key, value in rename
                                  if value in attributes)
        if omit:
            omit = list(omit)
            attributes.difference_update(omit)

        possible = ((attr, getattr(obj, attr))
                    for attr in sorted(attributes)
                    if hasattr(obj, attr))

        sliced = keyslice_pairs(possible, include=include,
                                omit=omit, rename=rename)
        final = dict((key, value)
                     for key, value in sliced
                     if key in fields)
        self.set(final)
Exemplo n.º 11
0
 def clear(self):
     frame = self._base_frame
     for key in iterkeys(self):
         frame[key] = Deleted
Exemplo n.º 12
0
 def __contains__(self, key):
     return key in iterkeys(self)
Exemplo n.º 13
0
 def keys(self):
     return list(iterkeys(self))