Exemplo n.º 1
0
    def testDecodeUUIDInvalid(self):
        from uuid import UUID
        class Foo(messages.Message):
            bar = messages.UUIDField()

        with self.assertRaises(messages.DecodeError):
            to_url.decode_message(Foo, 'bar=bad')
Exemplo n.º 2
0
    def testDecodeDateTimeMsInteger(self):
        class MyMessage(messages.Message):
            a_datetime = messages.DateTimeMsIntegerField()

        m = to_url.decode_message(MyMessage, 'a_datetime=1349019110262')
        self.assertEquals(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)

        m = to_url.decode_message(MyMessage, 'a_datetime=1349019110262')
        self.assertEquals(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)
Exemplo n.º 3
0
    def testDecodeDateTimeIso8601(self):
        class MyMessage(messages.Message):
            a_datetime = messages.DateTimeISO8601Field()

        m = to_url.decode_message(MyMessage, 'a_datetime=2012-09-30T15:31:50.262000')
        self.assertEquals(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)

        m = to_url.decode_message(MyMessage, 'a_datetime=2012-09-30T15%3A31%3A50.262000')
        self.assertEquals(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)
Exemplo n.º 4
0
    def testDecodeDateTimeMsInteger(self):
        class MyMessage(messages.Message):
            a_datetime = messages.DateTimeMsIntegerField()

        m = to_url.decode_message(MyMessage, 'a_datetime=1349019110262')
        self.assertEqual(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)

        m = to_url.decode_message(MyMessage, 'a_datetime=1349019110262')
        self.assertEqual(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)
Exemplo n.º 5
0
    def testDecodeDateTimeIso8601(self):
        class MyMessage(messages.Message):
            a_datetime = messages.DateTimeISO8601Field()

        m = to_url.decode_message(MyMessage, 'a_datetime=2012-09-30T15:31:50.262000')
        self.assertEqual(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)

        m = to_url.decode_message(MyMessage, 'a_datetime=2012-09-30T15%3A31%3A50.262000')
        self.assertEqual(datetime(2012, 9, 30, 15, 31, 50, 262000), m.a_datetime)
Exemplo n.º 6
0
    def testDecodeUUID(self):
        from uuid import UUID
        class Foo(messages.Message):
            bar = messages.UUIDField()

        m = to_url.decode_message(Foo, 'bar=06335e84-2872-4914-8c5d-3ed07d2a2f16')
        self.assertEqual(UUID("06335e84-2872-4914-8c5d-3ed07d2a2f16"), m.bar)
Exemplo n.º 7
0
    def testProtourlencodeUnrecognizedField(self):
        """Test that unrecognized fields are saved and can be accessed."""

        class MyMessage(messages.Message):
            number = messages.IntegerField()

        decoded = to_url.decode_message(MyMessage,
                                                self.unexpected_tag_message)
        self.assertEquals(1, len(decoded.all_unrecognized_fields()))
        self.assertEquals('unexpected', decoded.all_unrecognized_fields()[0])
        # Unknown values set to a list of however many values had that name.
        self.assertEquals((['whatever'], messages.Variant.STRING),
                          decoded.get_unrecognized_field_info('unexpected'))

        repeated_unknown = urllib.urlencode([('repeated', 400),
                                             ('repeated', 'test'),
                                             ('repeated', '123.456')])
        decoded2 = to_url.decode_message(MyMessage, repeated_unknown)
        self.assertEquals((['400', 'test', '123.456'], messages.Variant.STRING),
                          decoded2.get_unrecognized_field_info('repeated'))
Exemplo n.º 8
0
    def testProtourlencodeUnrecognizedField(self):
        """Test that unrecognized fields are saved and can be accessed."""

        class MyMessage(messages.Message):
            number = messages.IntegerField()

        decoded = to_url.decode_message(MyMessage,
                                                self.unexpected_tag_message)
        self.assertEqual(1, len(decoded.all_unrecognized_fields()))
        self.assertEqual('unexpected', decoded.all_unrecognized_fields()[0])
        # Unknown values set to a list of however many values had that name.
        self.assertEqual((['whatever'], messages.Variant.STRING),
                          decoded.get_unrecognized_field_info('unexpected'))

        repeated_unknown = urlencode([('repeated', 400),
                                      ('repeated', 'test'),
                                      ('repeated', '123.456')])
        decoded2 = to_url.decode_message(MyMessage, repeated_unknown)
        self.assertEqual((['400', 'test', '123.456'], messages.Variant.STRING),
                          decoded2.get_unrecognized_field_info('repeated'))
Exemplo n.º 9
0
    def testParameterPrefix(self):
        """Test using the 'prefix' parameter to encode_message."""

        class MyMessage(messages.Message):
            number = messages.IntegerField()
            names = messages.StringField(repeated=True)

        message = MyMessage()
        message.number = 10
        message.names = [u'Fred', u'Lisa']

        encoded_message = to_url.encode_message(message, prefix='prefix-')
        self.assertEquals({'prefix-number': ['10'],
                           'prefix-names': ['Fred', 'Lisa']},
                          urlparse.parse_qs(encoded_message))

        self.assertEquals(message, to_url.decode_message(MyMessage,
                                                                 encoded_message,
                                                                 prefix='prefix-'))
Exemplo n.º 10
0
    def testParameterPrefix(self):
        """Test using the 'prefix' parameter to encode_message."""

        class MyMessage(messages.Message):
            number = messages.IntegerField()
            names = messages.StringField(repeated=True)

        message = MyMessage()
        message.number = 10
        message.names = [u'Fred', u'Lisa']

        encoded_message = to_url.encode_message(message, prefix='prefix-')
        self.assertEqual({'prefix-number': ['10'],
                           'prefix-names': ['Fred', 'Lisa']},
                          parse_qs(encoded_message))

        self.assertEqual(message, to_url.decode_message(MyMessage,
                                                                 encoded_message,
                                                                 prefix='prefix-'))
Exemplo n.º 11
0
    def test_encode_message_repeated_message_field(self):
        class Animal(messages.Message):
            name = messages.StringField()
            size = messages.IntegerField()

        class Animals(messages.Message):
            animals = messages.MessageField(Animal, repeated=True)
            number = messages.IntegerField()

        dog = Animal(name='dog', size=12)
        cat = Animal(name='cat', size=10)
        tmp = Animals(animals=[dog, cat], number=2)

        encoded_message = to_url.encode_message(tmp)
        self.assertEquals({'number': ['2'],
                           'animals-0.name': ['dog'],
                           'animals-0.size': ['12'],
                           'animals-1.name': ['cat'],
                           'animals-1.size': ['10']},
                          urlparse.parse_qs(encoded_message))

        self.assertEquals(tmp, to_url.decode_message(Animals, encoded_message))
Exemplo n.º 12
0
    def test_encode_message_repeated_message_field(self):
        class Animal(messages.Message):
            name = messages.StringField()
            size = messages.IntegerField()

        class Animals(messages.Message):
            animals = messages.MessageField(Animal, repeated=True)
            number = messages.IntegerField()

        dog = Animal(name='dog', size=12)
        cat = Animal(name='cÄt', size=10)
        tmp = Animals(animals=[dog, cat], number=2)

        encoded_message = to_url.encode_message(tmp)
        self.assertEqual({'number': ['2'],
                           'animals-0.name': ['dog'],
                           'animals-0.size': ['12'],
                           'animals-1.name': ['cÄt'],
                           'animals-1.size': ['10']},
                           parse_qs(encoded_message))

        self.assertEqual(tmp, to_url.decode_message(Animals, encoded_message))
Exemplo n.º 13
0
        def wrapper(*args, **kwargs):
            try:
                pj = to_json.JsonEncoder()

                # If we have a body message provided, this request must be json
                if body is not None:
                    request_content_type = request.headers.get(
                        'Content-Type', None)

                    if request_content_type is not None:
                        request_content_type = request_content_type.lower(
                        ).split(";")[0]

                    if request_content_type != "application/json" and not lenient:
                        raise exceptions.HTTPUnsupportedMediaType(
                            "Content type must be 'application/json'")

                for name, message_type in (query or {}).items():
                    try:
                        query_string = request.url[
                            len(request.base_url) +
                            1:] if len(request.url) > len(
                                request.base_url) + 1 else ''
                        m = to_url.decode_message(message_type, query_string)
                        kwargs[name] = m

                    except (ValueError, messages.Error) as error:
                        raise exceptions.HTTPBadRequest(
                            error.message or "Request JSON is invalid.")

                for name, message_type in (body or {}).items():
                    try:
                        m = pj.decode_message(message_type,
                                              request.get_data(as_text=True))
                        kwargs[name] = m

                    except ValueError:
                        raise exceptions.HTTPBadRequest(
                            "Request body is invalid.")
                    except messages.Error as error:
                        raise exceptions.HTTPBadRequest(str(error))

                # Everything is good. Call the actual handler method
                result = f(*args, **kwargs)

                response_code = None
                headers = {}
            except Exception as e:
                result = message_types.error_message_from_exception(e)

                headers = {}
                response_code = 500

                if hasattr(e, 'code'):
                    response_code = e.code

                # Log only errors
                if response_code < 200 or response_code > 404:
                    logging.exception(e)

            if type(result) != tuple:
                result = (result, )

            response = make_response()

            for val in result:
                if type(val) == int:
                    response_code = val
                elif type(val) == dict:
                    headers.update(val)
                elif isinstance(val, messages.Message):
                    response_code = response_code or 200
                    response.content_type = 'application/json'
                    response.set_data(pj.encode_message(val))

            if response_code:
                response.status_code = response_code

            for k, v in headers.items():
                response.headers[k] = v

            return response