Пример #1
0
def main():
    serializer = DefaultSerializer()
    request_envelope = serializer.deserialize(request.data, RequestEnvelope)
    response_envelope = SKILL.invoke(request_envelope=request_envelope,
                                     context=None)

    return jsonify(serializer.serialize(response_envelope))
Пример #2
0
def response_from_dict(response_dict) -> ResponseEnvelope:
    """
    Deserialize a response dictionary to a Response object
    Args:
        response_dict(dict): The response dictionary
    Returns: The deserialized response
    """
    serializer = DefaultSerializer()
    response_json = json.dumps(serializer.serialize(response_dict))
    return serializer.deserialize(response_json, ResponseEnvelope)
Пример #3
0
def operator_intent_handler(handler_input: HandlerInput):
    op = get_slot_value(handler_input, "operand")
    stack = DZ.deserialize(
        handler_input.attributes_manager.session_attributes["stack"],
        'list[float]')
    handler_input.attributes_manager.session_attributes[
        "stack"] = DZ.serialize([despatch[op](stack)])

    text = f"Operator intent, {op}"
    handler_input.response_builder.speak(text).set_card(
        SimpleCard("Calculator", text)).set_should_end_session(False)
    return handler_input.response_builder.response
Пример #4
0
def send_request(endpoint_url: str,
                 request_envelope: RequestEnvelope) -> ResponseEnvelope:
    """Sends a request to the endpoint and returns the response."""
    serializer = DefaultSerializer()
    r = requests.post(
        endpoint_url,
        json=serializer.serialize(request_envelope),
    )
    response_envelope = serializer.deserialize(payload=r.text,
                                               obj_type=ResponseEnvelope)

    return response_envelope
    def test_primitive_obj_deserialization_raising_type_error(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(side_effect=TypeError())

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = "test"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialized primitive type which raises TypeError incorrectly"
    def test_primitive_obj_deserialization_raising_unicode_exception(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(
            side_effect=UnicodeEncodeError('hitchhiker', u"", 42, 43, 'the universe and everything else'))

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = u"√"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == u"\u221a", \
                "Default Serializer deserialized primitive type which raises UnicodeEncodeError incorrectly"
Пример #7
0
def operand_intent_handler(handler_input: HandlerInput):
    val = float(get_slot_value(handler_input, "operand"))
    stack = []
    try:
        stack = DZ.deserialize(
            handler_input.attributes_manager.session_attributes['stack'],
            'List[float]')
    except:
        pass
    stack.append(val)
    handler_input.attributes_manager.session_attributes[
        'stack'] = DZ.serialize(stack)
    text = f"Operand intent, {val}"

    handler_input.response_builder.speak(text).set_card(
        SimpleCard("Calculator", text)).set_should_end_session(False)
    return handler_input.response_builder.response
class TestDeserialization(unittest.TestCase):
    def setUp(self):
        self.test_serializer = DefaultSerializer()

    def test_none_obj_deserialization(self):
        test_payload = None
        test_obj_type = str
        assert self.test_serializer.deserialize(
            test_payload, test_obj_type) is None, \
            "Default Serializer deserialized None object incorrectly"

    def test_str_obj_deserialization(self):
        test_payload = "test"
        test_obj_type = str
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialized string object incorrectly"

    def test_unicode_obj_deserialization(self):
        test_payload = u"√"
        test_obj_type = unicode_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == u"\u221a", \
                "Default Serializer deserialized unicode string object incorrectly"

    def test_int_obj_deserialization(self):
        test_payload = 123
        test_obj_type = int
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialized int object incorrectly"

    def test_long_obj_deserialization(self):
        test_payload = 123
        test_obj_type = long_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == long_type(test_payload), \
                "Default Serializer deserialized long object incorrectly"

    def test_primitive_obj_deserialization_raising_unicode_exception(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(
            side_effect=UnicodeEncodeError('hitchhiker', u"", 42, 43, 'the universe and everything else'))

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = u"√"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == u"\u221a", \
                "Default Serializer deserialized primitive type which raises UnicodeEncodeError incorrectly"

    def test_primitive_obj_deserialization_raising_type_error(self):
        test_serializer = DefaultSerializer()
        mocked_primitive_type = mock.Mock(side_effect=TypeError())

        test_serializer.PRIMITIVE_TYPES = [mocked_primitive_type]

        test_payload = "test"
        test_obj_type = mocked_primitive_type
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialized primitive type which raises TypeError incorrectly"

    def test_primitive_obj_deserialization_raising_value_error(self):
        test_payload = "test"
        test_obj_type = int

        with self.assertRaises(SerializationException) as exc:
            with patch("json.loads") as mock_json_loader:
                mock_json_loader.return_value = test_payload
                self.test_serializer.deserialize(test_payload, test_obj_type)

        assert "Failed to parse test into 'int' object" in str(exc.exception), \
            "Default Serializer didn't throw SerializationException when invalid primitive type is deserialized"

    def test_datetime_obj_serialization(self):
        # payload in iso8601 format
        test_payload = "2018-01-01T10:20:30"
        test_obj_type = datetime.datetime

        expected_obj = datetime.datetime(2018, 1, 1, 10, 20, 30)
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(test_payload, test_obj_type) == expected_obj, \
                "Default Serializer deserialized datetime object incorrectly"

    def test_date_obj_serialization(self):
        # payload in iso8601 format
        test_payload = "2018-01-01"
        test_obj_type = datetime.date

        expected_obj = datetime.date(2018, 1, 1)
        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(test_payload, test_obj_type) == expected_obj, \
                "Default Serializer deserialized date object incorrectly"

    def test_datetime_obj_deserialization_raising_value_error(self):
        test_payload = "abc-wx-yzT25:80:90"
        test_obj_type = datetime.datetime

        with self.assertRaises(SerializationException) as exc:
            with patch("json.loads") as mock_json_loader:
                mock_json_loader.return_value = test_payload
                self.test_serializer.deserialize(test_payload, test_obj_type)

        assert "Failed to parse abc-wx-yzT25:80:90 into 'datetime' object" in str(exc.exception), \
            "Default Serializer didn't throw SerializationException when invalid datetime type is deserialized"

    def test_datetime_obj_deserialization_raising_import_error(self):
        test_payload = "abc-wx-yzT25:80:90"
        test_obj_type = datetime.datetime

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            with mock.patch('dateutil.parser.parse') as parse_class:
                parse_class.side_effect = ImportError
                assert self.test_serializer.deserialize(
                    test_payload, test_obj_type) == test_payload, \
                    "Default Serializer didn't return datetime correctly for import errors"
                parse_class.assert_called_once_with(test_payload)

    def test_obj_type_deserialization(self):
        test_payload = "test"
        test_obj_type = object

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, \
                "Default Serializer deserialization of object returned other than the object itself"

    def test_native_type_mapping_deserialization(self):
        test_payload = "test"
        test_obj_type = "str"

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, (
                "Default Serializer deserialization of object with object_type of string class under native mapping "
                "not deserialized correctly")

    def test_polymorphic_list_obj_deserialization(self):
        test_payload = ["test", 123, "2018-01-01T10:20:30"]
        test_obj_type = "list[str, long, datetime]"

        deserialized_datetime_obj = datetime.datetime(2018, 1, 1, 10, 20, 30)
        expected_obj = ["test", 123, deserialized_datetime_obj]

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized list containing poly type object incorrectly")

    def test_similar_list_obj_deserialization(self):
        test_payload = ["test", "test1", "2018-01-01T10:20:30"]
        test_obj_type = "list[str]"
        expected_obj = ["test", "test1", "2018-01-01T10:20:30"]

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized list object containing similar type objects incorrectly")

    def test_dict_obj_deserialization(self):
        test_payload = {
            "test_key": ["test_val_1", "test_val_2"],
            "test_date_str": ["2018-01-01T10:20:30"]
        }
        test_obj_type = "dict(str, list[str])"

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, (
                "Default Serializer deserialized dict object incorrectly")

    def test_model_obj_deserialization(self):
        test_payload = {
            "var1": "test",
            "var2Time": "2018-01-01T10:20:30",
            "var3Object": {
                "var4Int": 123
            },
            "var6Enum": "ENUM_VAL_1"
        }
        test_obj_type = data.ModelTestObject1
        expected_datetime_obj = datetime.datetime(2018, 1, 1, 10, 20, 30)
        expected_sub_obj = data.ModelTestObject2(int_var=123)
        expected_enum_obj = data.ModelEnumObject("ENUM_VAL_1")
        expected_obj = data.ModelTestObject1(
            str_var="test", datetime_var=expected_datetime_obj, obj_var=expected_sub_obj, enum_var=expected_enum_obj)

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized model object incorrectly")

    def test_model_obj_with_additional_params_in_payload_deserialization(self):
        test_payload = {
            "var4Int": 123,
            "add_param_1": "Test"
        }
        test_obj_type = data.ModelTestObject2
        expected_obj = data.ModelTestObject2(int_var=123)
        expected_obj.add_param_1 = "Test"

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized model object incorrectly when payload has additional parameters")

    def test_invalid_model_obj_deserialization(self):
        test_payload = {
            "var_1": "some value"
        }
        test_obj_type = data.InvalidModelObject

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == test_payload, (
                "Default Serializer didn't provide payload back when an invalid model object type "
                "(without attribute map and swagger type dict) is passed")

    def test_invalid_model_obj_type_deserialization(self):
        test_payload = {
            "var_1": "some value"
        }
        test_obj_type = "InvalidModelObject"

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            with self.assertRaises(SerializationException) as exc:
                self.test_serializer.deserialize(test_payload, test_obj_type)

            assert "Unable to resolve class {} from installed modules".format(test_obj_type) in str(exc.exception), (
                "Default Serializer didn't throw SerializationException when deserialization is called with invalid "
                "object type")

    def test_invalid_json_deserialization(self):
        test_payload = {
            "var_1": "some value"
        }
        test_obj_type = "str"

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.side_effect = Exception
            with self.assertRaises(SerializationException) as exc:
                self.test_serializer.deserialize(test_payload, test_obj_type)

        assert "Couldn't parse response body" in str(exc.exception), \
            "Default Serializer didn't throw SerializationException when invalid json is deserialized"

    def test_parent_model_obj_with_discriminator_deserialization(self):
        test_payload = {
            "ChildType": 'ChildType1',
            "var1": "Some string",
            "var3Object": {
                "var4Int": 123
            },
            "testVar": "test string"
        }
        test_obj_type = data.ModelAbstractParentObject
        expected_sub_obj = data.ModelTestObject2(int_var=123)
        expected_obj = data.ModelChildObject1(
            str_var="Some string", obj_var=expected_sub_obj, test_var="test string")

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized model object incorrectly when object type is parent class "
                "with discriminator")

    def test_child_discriminator_model_obj_deserialization(self):
        test_payload = {
            "ChildType": 'ChildType2',
            "var1": "Some string",
            "var3Object": {
                "var4Int": 123
            },
            "testIntVar": 456
        }
        test_obj_type = data.ModelChildObject2
        expected_sub_obj = data.ModelTestObject2(int_var=123)
        expected_obj = data.ModelChildObject2(
            str_var="Some string", obj_var=expected_sub_obj, test_int_var=456)

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            assert self.test_serializer.deserialize(
                test_payload, test_obj_type) == expected_obj, (
                "Default Serializer deserialized model object incorrectly when object type is parent class "
                "with discriminator")

    def test_parent_model_obj_with_invalid_discriminator_deserialization(self):
        test_payload = {
            "ChildType": 'InvalidType',
            "var1": "Some string",
            "var3Object": {
                "var4Int": 123
            },
            "testVar": "test string"
        }
        test_obj_type = data.ModelAbstractParentObject

        with patch("json.loads") as mock_json_loader:
            mock_json_loader.return_value = test_payload
            with self.assertRaises(SerializationException) as exc:
                self.test_serializer.deserialize(test_payload, test_obj_type)

            assert "Couldn't resolve object by discriminator type" in str(exc.exception), (
                "Default Serializer didn't throw SerializationException when deserialization is called with invalid "
                "discriminator type in payload and parent model")