Ejemplo n.º 1
0
    def test_parsing_nested_elements(self):
        class Test9one(ResponseElement):
            Nest = Element()
            Zoom = Element()

        class Test9Result(ResponseElement):
            Item = Element(Test9one)

        text = """<Test9Response><Test9Result>
                  <Item>
                        <Foo>Bar</Foo>
                        <Nest>
                            <Zip>Zap</Zip>
                            <Zam>Zoo</Zam>
                        </Nest>
                        <Bif>Bam</Bif>
                  </Item>
                  </Test9Result></Test9Response>"""
        obj = self.check_issue(Test9Result, text)
        Item = obj._result.Item
        useful = lambda x: not x[0].startswith('_')
        nest = dict(filter(useful, Item.Nest.__dict__.items()))
        self.assertEqual(nest, dict(Zip='Zap', Zam='Zoo'))
        useful = lambda x: not x[0].startswith('_') and not x[0] == 'Nest'
        item = dict(filter(useful, Item.__dict__.items()))
        self.assertEqual(item, dict(Foo='Bar', Bif='Bam', Zoom=None))
Ejemplo n.º 2
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if 1 != len(filter(hasgroup, groups)):
         message = " OR ".join(["+".join(g) for g in groups])
         message = "{0} requires {1} argument(s)" "".format(getattr(func, "action", "Method"), message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 3
0
    def test_parsing_nested_elements(self):
        class Test9one(ResponseElement):
            Nest = Element()
            Zoom = Element()

        class Test9Result(ResponseElement):
            Item = Element(Test9one)

        text = b"""<Test9Response><Test9Result>
                  <Item>
                        <Foo>Bar</Foo>
                        <Nest>
                            <Zip>Zap</Zip>
                            <Zam>Zoo</Zam>
                        </Nest>
                        <Bif>Bam</Bif>
                  </Item>
                  </Test9Result></Test9Response>"""
        obj = self.check_issue(Test9Result, text)
        Item = obj._result.Item
        useful = lambda x: not x[0].startswith('_')
        nest = dict(filter(useful, Item.Nest.__dict__.items()))
        self.assertEqual(nest, dict(Zip='Zap', Zam='Zoo'))
        useful = lambda x: not x[0].startswith('_') and not x[0] == 'Nest'
        item = dict(filter(useful, Item.__dict__.items()))
        self.assertEqual(item, dict(Foo='Bar', Bif='Bam', Zoom=None))
Ejemplo n.º 4
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if 1 != len(filter(hasgroup, groups)):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires {1} argument(s)" \
                   "".format(getattr(func, 'action', 'Method'), message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 5
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if field in kw and 1 > len(filter(hasgroup, groups)):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} argument {1} requires {2}" \
                   "".format(func.action, field, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 6
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if len(filter(hasgroup, groups)) not in (0, 1):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires either {1}" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 7
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if len(filter(hasgroup, groups)) not in (0, 1):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires either {1}" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 8
0
 def wrapper(*args, **kw):
     hasgroup = lambda x: len(x) == len(filter(kw.has_key, x))
     if field in kw and 1 > len(filter(hasgroup, groups)):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} argument {1} requires {2}" \
                   "".format(func.action, field, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 9
0
Archivo: model.py Proyecto: 10sr/hue
    def __init__(cls, name, bases, dict):
        super(ModelMeta, cls).__init__(name, bases, dict)
        # Make sure this is a subclass of Model - mainly copied from django ModelBase (thanks!)
        cls.__sub_classes__ = []

        # Do a delayed import to prevent possible circular import errors.
        from boto.sdb.db.manager import get_manager

        try:
            if filter(lambda b: issubclass(b, Model), bases):
                for base in bases:
                    base.__sub_classes__.append(cls)
                cls._manager = get_manager(cls)
                # look for all of the Properties and set their names
                for key in dict.keys():
                    if isinstance(dict[key], Property):
                        property = dict[key]
                        property.__property_config__(cls, key)
                prop_names = []
                props = cls.properties()
                for prop in props:
                    if not prop.__class__.__name__.startswith('_'):
                        prop_names.append(prop.name)
                setattr(cls, '_prop_names', prop_names)
        except NameError:
            # 'Model' isn't defined yet, meaning we're looking at our own
            # Model class, defined below.
            pass
Ejemplo n.º 10
0
    def __init__(cls, name, bases, dict):
        super(ModelMeta, cls).__init__(name, bases, dict)
        # Make sure this is a subclass of Model - mainly copied from django ModelBase (thanks!)
        cls.__sub_classes__ = []

        # Do a delayed import to prevent possible circular import errors.
        from boto.sdb.db.manager import get_manager

        try:
            if filter(lambda b: issubclass(b, Model), bases):
                for base in bases:
                    base.__sub_classes__.append(cls)
                cls._manager = get_manager(cls)
                # look for all of the Properties and set their names
                for key in dict.keys():
                    if isinstance(dict[key], Property):
                        property = dict[key]
                        property.__property_config__(cls, key)
                prop_names = []
                props = cls.properties()
                for prop in props:
                    if not prop.__class__.__name__.startswith('_'):
                        prop_names.append(prop.name)
                setattr(cls, '_prop_names', prop_names)
        except NameError:
            # 'Model' isn't defined yet, meaning we're looking at our own
            # Model class, defined below.
            pass
Ejemplo n.º 11
0
 def wrapper(self, *args, **kw):
     for field in filter(kw.has_key, fields):
         amount = kw.pop(field)
         kw[field + '.Value'] = getattr(amount, 'Value', str(amount))
         kw[field + '.CurrencyCode'] = getattr(amount, 'CurrencyCode',
                                               self.currencycode)
     return func(self, *args, **kw)
Ejemplo n.º 12
0
 def requires(*args, **kw):
     hasgroup = lambda group: all(key in kw for key in group)
     if 1 != len(list(filter(hasgroup, groups))):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires {1} argument(s)" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 13
0
 def wrapper(*args, **kw):
     hasgroup = lambda group: all(key in kw for key in group)
     if len(list(filter(hasgroup, groups))) not in (0, 1):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires either {1}" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 14
0
 def requires(*args, **kw):
     hasgroup = lambda group: all(key in kw for key in group)
     if 1 != len(list(filter(hasgroup, groups))):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires {1} argument(s)" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 15
0
 def wrapper(*args, **kw):
     hasgroup = lambda group: all(key in kw for key in group)
     if len(list(filter(hasgroup, groups))) not in (0, 1):
         message = ' OR '.join(['+'.join(g) for g in groups])
         message = "{0} requires either {1}" \
                   "".format(func.action, message)
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 16
0
 def __repr__(self):
     render = lambda pair: '{0!s}: {1!r}'.format(*pair)
     do_show = lambda pair: not pair[0].startswith('_')
     attrs = filter(do_show, self.__dict__.items())
     name = self.__class__.__name__
     if name.startswith('JIT_'):
         name = '^{0}^'.format(self._name or '')
     return '{0}{1!r}({2})'.format(name, self.copy(),
                                   ', '.join(map(render, attrs)))
Ejemplo n.º 17
0
Archivo: response.py Proyecto: 10sr/hue
 def __repr__(self):
     render = lambda pair: '{0!s}: {1!r}'.format(*pair)
     do_show = lambda pair: not pair[0].startswith('_')
     attrs = filter(do_show, self.__dict__.items())
     name = self.__class__.__name__
     if name.startswith('JIT_'):
         name = '^{0}^'.format(self._name or '')
     return '{0}{1!r}({2})'.format(
         name, self.copy(), ', '.join(map(render, attrs)))
Ejemplo n.º 18
0
    def _declared(self, op, **kw):
        def inherit(obj):
            result = {}
            for cls in getattr(obj, '__bases__', ()):
                result.update(inherit(cls))
            result.update(obj.__dict__)
            return result

        scope = inherit(self.__class__)
        scope.update(self.__dict__)
        declared = lambda attr: isinstance(attr[1], DeclarativeType)
        for name, node in filter(declared, scope.items()):
            getattr(node, op)(self, name, parentname=self._name, **kw)
Ejemplo n.º 19
0
Archivo: response.py Proyecto: 10sr/hue
    def _declared(self, op, **kw):
        def inherit(obj):
            result = {}
            for cls in getattr(obj, '__bases__', ()):
                result.update(inherit(cls))
            result.update(obj.__dict__)
            return result

        scope = inherit(self.__class__)
        scope.update(self.__dict__)
        declared = lambda attr: isinstance(attr[1], DeclarativeType)
        for name, node in filter(declared, scope.items()):
            getattr(node, op)(self, name, parentname=self._name, **kw)
Ejemplo n.º 20
0
 def _encode_n(self, attr):
     try:
         if isinstance(attr, float) and not hasattr(Decimal, 'from_float'):
             # python2.6 does not support creating Decimals directly
             # from floats so we have to do this ourself.
             n = str(float_to_decimal(attr))
         else:
             n = str(DYNAMODB_CONTEXT.create_decimal(attr))
         if list(filter(lambda x: x in n, ('Infinity', 'NaN'))):
             raise TypeError('Infinity and NaN not supported')
         return n
     except (TypeError, DecimalException) as e:
         msg = '{0} numeric for `{1}`\n{2}'.format(
             e.__class__.__name__, attr, str(e) or '')
     raise DynamoDBNumberError(msg)
Ejemplo n.º 21
0
 def list_orders(self, request, response, **kw):
     """Returns a list of orders created or updated during a time
        frame that you specify.
     """
     toggle = set(('FulfillmentChannel.Channel.1',
                   'OrderStatus.Status.1', 'PaymentMethod.1',
                   'LastUpdatedAfter', 'LastUpdatedBefore'))
     for do, dont in {
         'BuyerEmail': toggle.union(['SellerOrderId']),
         'SellerOrderId': toggle.union(['BuyerEmail']),
     }.items():
         if do in kw and filter(kw.has_key, dont):
             message = "Don't include {0} when specifying " \
                       "{1}".format(' or '.join(dont), do)
             raise AssertionError(message)
     return self._post_request(request, kw, response)
Ejemplo n.º 22
0
 def list_orders(self, request, response, **kw):
     """Returns a list of orders created or updated during a time
        frame that you specify.
     """
     toggle = set(
         ('FulfillmentChannel.Channel.1', 'OrderStatus.Status.1',
          'PaymentMethod.1', 'LastUpdatedAfter', 'LastUpdatedBefore'))
     for do, dont in {
             'BuyerEmail': toggle.union(['SellerOrderId']),
             'SellerOrderId': toggle.union(['BuyerEmail']),
     }.items():
         if do in kw and filter(kw.has_key, dont):
             message = "Don't include {0} when specifying " \
                       "{1}".format(' or '.join(dont), do)
             raise AssertionError(message)
     return self._post_request(request, kw, response)
Ejemplo n.º 23
0
 def wrapper(*args, **kw):
     members = kwargs.get('members', False)
     for field in filter(kw.has_key, fields):
         destructure_object(kw.pop(field), kw, field, members=members)
     return func(*args, **kw)
Ejemplo n.º 24
0
    def test_parsing_nested_lists(self):
        class Test7Result(ResponseElement):
            Item = MemberList(Nest=MemberList(),
                              List=ElementList(Simple=SimpleList()))

        text = b"""<Test7Response><Test7Result>
                  <Item>
                        <member>
                            <Value>One</Value>
                            <Nest>
                                <member><Data>2</Data></member>
                                <member><Data>4</Data></member>
                                <member><Data>6</Data></member>
                            </Nest>
                        </member>
                        <member>
                            <Value>Two</Value>
                            <Nest>
                                <member><Data>1</Data></member>
                                <member><Data>3</Data></member>
                                <member><Data>5</Data></member>
                            </Nest>
                            <List>
                                <Simple>4</Simple>
                                <Simple>5</Simple>
                                <Simple>6</Simple>
                            </List>
                            <List>
                                <Simple>7</Simple>
                                <Simple>8</Simple>
                                <Simple>9</Simple>
                            </List>
                        </member>
                        <member>
                            <Value>Six</Value>
                            <List>
                                <Complex>Foo</Complex>
                                <Simple>1</Simple>
                                <Simple>2</Simple>
                                <Simple>3</Simple>
                            </List>
                            <List>
                                <Complex>Bar</Complex>
                            </List>
                        </member>
                  </Item>
                  </Test7Result></Test7Response>"""
        obj = self.check_issue(Test7Result, text)
        item = obj._result.Item
        self.assertEqual(len(item), 3)
        nests = [z.Nest for z in filter(lambda x: x.Nest, item)]
        self.assertSequenceEqual(
            [[y.Data for y in nest] for nest in nests],
            [[u'2', u'4', u'6'], [u'1', u'3', u'5']],
        )
        self.assertSequenceEqual(
            [element.Simple for element in item[1].List],
            [[u'4', u'5', u'6'], [u'7', u'8', u'9']],
        )
        self.assertSequenceEqual(
            item[-1].List[0].Simple,
            ['1', '2', '3'],
        )
        self.assertEqual(item[-1].List[1].Simple, [])
        self.assertSequenceEqual(
            [e.Value for e in obj._result.Item],
            ['One', 'Two', 'Six'],
        )
Ejemplo n.º 25
0
 def wrapper(self, *args, **kw):
     for field in filter(kw.has_key, fields):
         amount = kw.pop(field)
         kw[field + ".Value"] = getattr(amount, "Value", str(amount))
         kw[field + ".CurrencyCode"] = getattr(amount, "CurrencyCode", self.currencycode)
     return func(self, *args, **kw)
Ejemplo n.º 26
0
 def __repr__(self):
     render = lambda pair: '{!s}: {!r}'.format(*pair)
     do_show = lambda pair: not pair[0].startswith('_')
     attrs = filter(do_show, self.__dict__.items())
     return '{0}({1})'.format(self.__class__.__name__,
                            ', '.join(map(render, attrs)))
Ejemplo n.º 27
0
    def test_parsing_nested_lists(self):
        class Test7Result(ResponseElement):
            Item = MemberList(Nest=MemberList(),
                              List=ElementList(Simple=SimpleList()))

        text = """<Test7Response><Test7Result>
                  <Item>
                        <member>
                            <Value>One</Value>
                            <Nest>
                                <member><Data>2</Data></member>
                                <member><Data>4</Data></member>
                                <member><Data>6</Data></member>
                            </Nest>
                        </member>
                        <member>
                            <Value>Two</Value>
                            <Nest>
                                <member><Data>1</Data></member>
                                <member><Data>3</Data></member>
                                <member><Data>5</Data></member>
                            </Nest>
                            <List>
                                <Simple>4</Simple>
                                <Simple>5</Simple>
                                <Simple>6</Simple>
                            </List>
                            <List>
                                <Simple>7</Simple>
                                <Simple>8</Simple>
                                <Simple>9</Simple>
                            </List>
                        </member>
                        <member>
                            <Value>Six</Value>
                            <List>
                                <Complex>Foo</Complex>
                                <Simple>1</Simple>
                                <Simple>2</Simple>
                                <Simple>3</Simple>
                            </List>
                            <List>
                                <Complex>Bar</Complex>
                            </List>
                        </member>
                  </Item>
                  </Test7Result></Test7Response>"""
        obj = self.check_issue(Test7Result, text)
        item = obj._result.Item
        self.assertEqual(len(item), 3)
        nests = [z.Nest for z in filter(lambda x: x.Nest, item)]
        self.assertSequenceEqual(
            [[y.Data for y in nest] for nest in nests],
            [[u'2', u'4', u'6'], [u'1', u'3', u'5']],
        )
        self.assertSequenceEqual(
            [element.Simple for element in item[1].List],
            [[u'4', u'5', u'6'], [u'7', u'8', u'9']],
        )
        self.assertSequenceEqual(
            item[-1].List[0].Simple,
            ['1', '2', '3'],
        )
        self.assertEqual(item[-1].List[1].Simple, [])
        self.assertSequenceEqual(
            [e.Value for e in obj._result.Item],
            ['One', 'Two', 'Six'],
        )
Ejemplo n.º 28
0
Archivo: response.py Proyecto: 10sr/hue
 def __repr__(self):
     render = lambda pair: '{!s}: {!r}'.format(*pair)
     do_show = lambda pair: not pair[0].startswith('_')
     attrs = filter(do_show, self.__dict__.items())
     return '{0}({1})'.format(self.__class__.__name__,
                            ', '.join(map(render, attrs)))
Ejemplo n.º 29
0
 def wrapper(*args, **kw):
     members = kwargs.get('members', False)
     for field in filter(lambda i: i in kw, fields):
         destructure_object(kw.pop(field), kw, field, members=members)
     return func(*args, **kw)
Ejemplo n.º 30
0
 def wrapper(*args, **kw):
     if not filter(kw.has_key, fields):
         message = "{0} requires at least one of {1} argument(s)" \
                   "".format(func.action, ', '.join(fields))
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 31
0
 def wrapper(*args, **kw):
     if not filter(kw.has_key, fields):
         message = "{0} requires at least one of {1} argument(s)" \
                   "".format(func.action, ', '.join(fields))
         raise KeyError(message)
     return func(*args, **kw)
Ejemplo n.º 32
0
Archivo: response.py Proyecto: 10sr/hue
 def __repr__(self):
     values = [getattr(self, key, None) for key in self._dimensions]
     values = filter(None, values)
     return 'x'.join(map('{0.Value:0.2f}{0[Units]}'.format, values))
Ejemplo n.º 33
0
 def __repr__(self):
     values = [getattr(self, key, None) for key in self._dimensions]
     values = filter(None, values)
     return 'x'.join(map('{0.Value:0.2f}{0[Units]}'.format, values))