Ejemplo n.º 1
0
    def test_depth(self):
        class LevelsGenerator(object):
            def __init__(self, levels):
                self._levels = levels

            def iteritems(self):
                if self._levels == 0:
                    return iter([])
                else:
                    return iter([(0, LevelsGenerator(self._levels - 1))])

        l4_obj = LevelsGenerator(4)

        json_l2 = {0: {0: '?'}}
        json_l3 = {0: {0: {0: '?'}}}
        json_l4 = {0: {0: {0: {0: '?'}}}}

        ret = jsonutils.to_primitive(l4_obj, max_depth=2)
        self.assertEqual(ret, json_l2)

        ret = jsonutils.to_primitive(l4_obj, max_depth=3)
        self.assertEqual(ret, json_l3)

        ret = jsonutils.to_primitive(l4_obj, max_depth=4)
        self.assertEqual(ret, json_l4)
Ejemplo n.º 2
0
    def test_depth(self):
        class LevelsGenerator(object):
            def __init__(self, levels):
                self._levels = levels

            def iteritems(self):
                if self._levels == 0:
                    return iter([])
                else:
                    return iter([(0, LevelsGenerator(self._levels - 1))])

        l4_obj = LevelsGenerator(4)

        json_l2 = {0: {0: '?'}}
        json_l3 = {0: {0: {0: '?'}}}
        json_l4 = {0: {0: {0: {0: '?'}}}}

        ret = jsonutils.to_primitive(l4_obj, max_depth=2)
        self.assertEqual(ret, json_l2)

        ret = jsonutils.to_primitive(l4_obj, max_depth=3)
        self.assertEqual(ret, json_l3)

        ret = jsonutils.to_primitive(l4_obj, max_depth=4)
        self.assertEqual(ret, json_l4)
Ejemplo n.º 3
0
    def test_instance(self):
        class MysteryClass(object):
            a = 10

            def __init__(self):
                self.b = 1

        x = MysteryClass()
        self.assertEqual(jsonutils.to_primitive(x, convert_instances=True),
                         dict(b=1))

        self.assertEqual(jsonutils.to_primitive(x), x)
Ejemplo n.º 4
0
    def test_instance(self):
        class MysteryClass(object):
            a = 10

            def __init__(self):
                self.b = 1

        x = MysteryClass()
        self.assertEqual(jsonutils.to_primitive(x, convert_instances=True),
                         dict(b=1))

        self.assertEqual(jsonutils.to_primitive(x), x)
Ejemplo n.º 5
0
    def test_iteritems_with_cycle(self):
        class IterItemsClass(object):
            def __init__(self):
                self.data = dict(a=1, b=2, c=3)
                self.index = 0

            def iteritems(self):
                return self.data.items()

        x = IterItemsClass()
        x2 = IterItemsClass()
        x.data['other'] = x2
        x2.data['other'] = x

        # If the cycle isn't caught, to_primitive() will eventually result in
        # an exception due to excessive recursion depth.
        jsonutils.to_primitive(x)
Ejemplo n.º 6
0
    def test_iteritems_with_cycle(self):
        class IterItemsClass(object):
            def __init__(self):
                self.data = dict(a=1, b=2, c=3)
                self.index = 0

            def iteritems(self):
                return self.data.items()

        x = IterItemsClass()
        x2 = IterItemsClass()
        x.data['other'] = x2
        x2.data['other'] = x

        # If the cycle isn't caught, to_primitive() will eventually result in
        # an exception due to excessive recursion depth.
        jsonutils.to_primitive(x)
Ejemplo n.º 7
0
 def test_nasties(self):
     def foo():
         pass
     x = [datetime, foo, dir]
     ret = jsonutils.to_primitive(x)
     self.assertEqual(len(ret), 3)
     self.assertTrue(ret[0].startswith(u"<module 'datetime' from "))
     self.assertTrue(ret[1].startswith('<function foo at 0x'))
     self.assertEqual(ret[2], '<built-in function dir>')
Ejemplo n.º 8
0
 def test_nasties(self):
     def foo():
         pass
     x = [datetime, foo, dir]
     ret = jsonutils.to_primitive(x)
     self.assertEqual(len(ret), 3)
     self.assertTrue(ret[0].startswith(u"<module 'datetime' from "))
     self.assertTrue(ret[1].startswith('<function foo at 0x'))
     self.assertEqual(ret[2], '<built-in function dir>')
Ejemplo n.º 9
0
def notify(context, publisher_id, event_type, priority, payload):
    """Sends a notification using the specified driver

    :param publisher_id: the source worker_type.host of the message
    :param event_type:   the literal type of event (ex. Instance Creation)
    :param priority:     patterned after the enumeration of Python logging
                         levels in the set (DEBUG, WARN, INFO, ERROR, CRITICAL)
    :param payload:       A python dictionary of attributes

    Outgoing message format includes the above parameters, and appends the
    following:

    message_id
      a UUID representing the id for this notification

    timestamp
      the GMT timestamp the notification was sent at

    The composite message will be constructed as a dictionary of the above
    attributes, which will then be sent via the transport mechanism defined
    by the driver.

    Message example::

        {'message_id': str(uuid.uuid4()),
         'publisher_id': 'compute.host1',
         'timestamp': timeutils.utcnow(),
         'priority': 'WARN',
         'event_type': 'compute.create_instance',
         'payload': {'instance_id': 12, ... }}

    """
    if priority not in log_levels:
        raise BadPriorityException(
            _('%s not in valid priorities') % priority)

    # Ensure everything is JSON serializable.
    payload = jsonutils.to_primitive(payload, convert_instances=True)

    msg = dict(message_id=str(uuid.uuid4()),
               publisher_id=publisher_id,
               event_type=event_type,
               priority=priority,
               payload=payload,
               timestamp=str(timeutils.utcnow()))

    for driver in _get_drivers():
        try:
            driver.notify(context, msg)
        except Exception as e:
            LOG.exception(_("Problem '%(e)s' attempting to "
                            "send to notification system. "
                            "Payload=%(payload)s")
                          % dict(e=e, payload=payload))
Ejemplo n.º 10
0
def notify(context, publisher_id, event_type, priority, payload):
    """Sends a notification using the specified driver

    :param publisher_id: the source worker_type.host of the message
    :param event_type:   the literal type of event (ex. Instance Creation)
    :param priority:     patterned after the enumeration of Python logging
                         levels in the set (DEBUG, WARN, INFO, ERROR, CRITICAL)
    :param payload:       A python dictionary of attributes

    Outgoing message format includes the above parameters, and appends the
    following:

    message_id
      a UUID representing the id for this notification

    timestamp
      the GMT timestamp the notification was sent at

    The composite message will be constructed as a dictionary of the above
    attributes, which will then be sent via the transport mechanism defined
    by the driver.

    Message example::

        {'message_id': str(uuid.uuid4()),
         'publisher_id': 'compute.host1',
         'timestamp': timeutils.utcnow(),
         'priority': 'WARN',
         'event_type': 'compute.create_instance',
         'payload': {'instance_id': 12, ... }}

    """
    if priority not in log_levels:
        raise BadPriorityException(
            _('%s not in valid priorities') % priority)

    # Ensure everything is JSON serializable.
    payload = jsonutils.to_primitive(payload, convert_instances=True)

    msg = dict(message_id=str(uuid.uuid4()),
               publisher_id=publisher_id,
               event_type=event_type,
               priority=priority,
               payload=payload,
               timestamp=str(timeutils.utcnow()))

    for driver in _get_drivers():
        try:
            driver.notify(context, msg)
        except Exception as e:
            LOG.exception(_("Problem '%(e)s' attempting to "
                            "send to notification system. "
                            "Payload=%(payload)s")
                          % dict(e=e, payload=payload))
Ejemplo n.º 11
0
    def test_iteritems(self):
        class IterItemsClass(object):
            def __init__(self):
                self.data = dict(a=1, b=2, c=3).items()
                self.index = 0

            def iteritems(self):
                return self.data

        x = IterItemsClass()
        p = jsonutils.to_primitive(x)
        self.assertEqual(p, {'a': 1, 'b': 2, 'c': 3})
Ejemplo n.º 12
0
    def test_iteritems(self):
        class IterItemsClass(object):
            def __init__(self):
                self.data = dict(a=1, b=2, c=3).items()
                self.index = 0

            def iteritems(self):
                return self.data

        x = IterItemsClass()
        p = jsonutils.to_primitive(x)
        self.assertEqual(p, {'a': 1, 'b': 2, 'c': 3})
Ejemplo n.º 13
0
 def test_nasties(self):
     def foo():
         pass
     x = [datetime, foo, dir]
     ret = jsonutils.to_primitive(x)
     self.assertEqual(len(ret), 3)
     self.assertTrue(ret[0].startswith(u"<module 'datetime' from "))
     if six.PY3:
         self.assertTrue(ret[1].startswith('<function '
                         'ToPrimitiveTestCase.test_nasties.<locals>.foo '
                         'at 0x'))
     else:
         self.assertTrue(ret[1].startswith('<function foo at 0x'))
     self.assertEqual(ret[2], '<built-in function dir>')
Ejemplo n.º 14
0
    def test_iter(self):
        class IterClass(object):
            def __init__(self):
                self.data = [1, 2, 3, 4, 5]
                self.index = 0

            def __iter__(self):
                return self

            def next(self):
                if self.index == len(self.data):
                    raise StopIteration
                self.index = self.index + 1
                return self.data[self.index - 1]

        x = IterClass()
        self.assertEqual(jsonutils.to_primitive(x), [1, 2, 3, 4, 5])
Ejemplo n.º 15
0
    def test_iter(self):
        class IterClass(object):
            def __init__(self):
                self.data = [1, 2, 3, 4, 5]
                self.index = 0

            def __iter__(self):
                return self

            def next(self):
                if self.index == len(self.data):
                    raise StopIteration
                self.index = self.index + 1
                return self.data[self.index - 1]

        x = IterClass()
        self.assertEqual(jsonutils.to_primitive(x), [1, 2, 3, 4, 5])
Ejemplo n.º 16
0
    def test_iteritems(self):
        class IterItemsClass(object):
            def __init__(self):
                self.data = dict(a=1, b=2, c=3).items()
                self.index = 0

            def __iter__(self):
                return self

            def next(self):
                if self.index == len(self.data):
                    raise StopIteration
                self.index = self.index + 1
                return self.data[self.index - 1]

        x = IterItemsClass()
        ordered = jsonutils.to_primitive(x)
        ordered.sort()
        self.assertEquals(ordered, [['a', 1], ['b', 2], ['c', 3]])
Ejemplo n.º 17
0
 def test_ipaddr(self):
     thing = {'ip_addr': netaddr.IPAddress('1.2.3.4')}
     ret = jsonutils.to_primitive(thing)
     self.assertEqual({'ip_addr': '1.2.3.4'}, ret)
Ejemplo n.º 18
0
 def test_typeerror(self):
     x = bytearray  # Class, not instance
     self.assertEqual(jsonutils.to_primitive(x), u"<type 'bytearray'>")
Ejemplo n.º 19
0
 def test_message_with_named_param(self):
     message_with_params = 'A message with params: %(param)s'
     msg = gettextutils.Message(message_with_params, 'test_domain')
     msg = msg % {'param': 'hello'}
     ret = jsonutils.to_primitive(msg)
     self.assertEqual(msg, ret)
Ejemplo n.º 20
0
 def test_ipaddr(self):
     thing = {'ip_addr': netaddr.IPAddress('1.2.3.4')}
     ret = jsonutils.to_primitive(thing)
     self.assertEqual({'ip_addr': '1.2.3.4'}, ret)
Ejemplo n.º 21
0
 def test_typeerror(self):
     x = bytearray  # Class, not instance
     self.assertEqual(jsonutils.to_primitive(x), u"<type 'bytearray'>")
Ejemplo n.º 22
0
 def test_datetime_preserve(self):
     x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7)
     self.assertEqual(jsonutils.to_primitive(x, convert_datetime=False), x)
Ejemplo n.º 23
0
 def test_dict(self):
     self.assertEqual(jsonutils.to_primitive(dict(a=1, b=2, c=3)),
                      dict(a=1, b=2, c=3))
Ejemplo n.º 24
0
 def test_empty_dict(self):
     self.assertEqual(jsonutils.to_primitive({}), {})
Ejemplo n.º 25
0
 def test_datetime_preserve(self):
     x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7)
     self.assertEqual(jsonutils.to_primitive(x, convert_datetime=False), x)
Ejemplo n.º 26
0
 def test_message_with_param(self):
     message_with_params = 'A message with param: %s'
     msg = gettextutils.Message(message_with_params, 'test_domain')
     msg = msg % 'test_domain'
     ret = jsonutils.to_primitive(msg)
     self.assertEqual(msg, ret)
Ejemplo n.º 27
0
 def test_tuple(self):
     self.assertEqual(jsonutils.to_primitive((1, 2, 3)), [1, 2, 3])
Ejemplo n.º 28
0
 def test_datetime(self):
     x = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
     self.assertEquals(jsonutils.to_primitive(x),
                       "0001-02-03 04:05:06.000007")
Ejemplo n.º 29
0
 def test_empty_list(self):
     self.assertEqual(jsonutils.to_primitive([]), [])
Ejemplo n.º 30
0
 def test_datetime(self):
     x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7)
     self.assertEqual(jsonutils.to_primitive(x),
                      '1920-02-03T04:05:06.000007')
Ejemplo n.º 31
0
 def test_list(self):
     self.assertEqual(jsonutils.to_primitive([1, 2, 3]), [1, 2, 3])
Ejemplo n.º 32
0
 def test_empty_dict(self):
     self.assertEqual(jsonutils.to_primitive({}), {})
Ejemplo n.º 33
0
 def test_empty_list(self):
     self.assertEqual(jsonutils.to_primitive([]), [])
Ejemplo n.º 34
0
 def test_DateTime(self):
     x = xmlrpclib.DateTime()
     x.decode("19710203T04:05:06")
     self.assertEqual(jsonutils.to_primitive(x),
                      '1971-02-03T04:05:06.000000')
Ejemplo n.º 35
0
 def test_dict(self):
     self.assertEqual(jsonutils.to_primitive(dict(a=1, b=2, c=3)),
                      dict(a=1, b=2, c=3))
Ejemplo n.º 36
0
 def test_message_with_param(self):
     message_with_params = 'A message with param: %s'
     msg = gettextutils.Message(message_with_params, domain='test_domain')
     msg = msg % 'test_domain'
     ret = jsonutils.to_primitive(msg)
     self.assertEqual(msg, ret)
Ejemplo n.º 37
0
 def test_datetime(self):
     x = datetime.datetime(1920, 2, 3, 4, 5, 6, 7)
     self.assertEqual(jsonutils.to_primitive(x),
                      '1920-02-03T04:05:06.000007')
Ejemplo n.º 38
0
 def test_message_with_named_param(self):
     message_with_params = 'A message with params: %(param)s'
     msg = gettextutils.Message(message_with_params, domain='test_domain')
     msg = msg % {'param': 'hello'}
     ret = jsonutils.to_primitive(msg)
     self.assertEqual(msg, ret)
Ejemplo n.º 39
0
 def test_DateTime(self):
     x = xmlrpclib.DateTime()
     x.decode("19710203T04:05:06")
     self.assertEqual(jsonutils.to_primitive(x),
                      '1971-02-03T04:05:06.000000')
Ejemplo n.º 40
0
 def serialize_entity(context, entity):
     return jsonutils.to_primitive(entity, convert_instances=True)
Ejemplo n.º 41
0
 def test_list(self):
     self.assertEqual(jsonutils.to_primitive([1, 2, 3]), [1, 2, 3])
Ejemplo n.º 42
0
 def test_tuple(self):
     self.assertEqual(jsonutils.to_primitive((1, 2, 3)), [1, 2, 3])