Skip to content

Commit

Permalink
Merge pull request #17 from salute-developers/fix/as_is_to_message
Browse files Browse the repository at this point in the history
Fix/as is to message
  • Loading branch information
dangerink authored May 18, 2022
2 parents 03b91fa + cc3ff2c commit f119a52
Show file tree
Hide file tree
Showing 8 changed files with 67 additions and 83 deletions.
13 changes: 5 additions & 8 deletions core/basic_models/actions/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

class Command:
def __init__(self, name=None, params=None, action_id=None, request_type=None, request_data=None, loader=None,
need_payload_wrap=True):
need_payload_wrap=True, need_message_name=True):
"""
Initialize Command instance with params
Expand All @@ -22,14 +22,11 @@ def __init__(self, name=None, params=None, action_id=None, request_type=None, re
self.request_data = request_data or {}
self.loader = loader or "json.dumps"
self.need_payload_wrap = need_payload_wrap
self.need_message_name = need_message_name

@property
def raw(self):
message = {"messageName": self.name, "action_id": self.action_id}
message = {k: v for k, v in message.items() if v is not None}

if self.need_payload_wrap:
message["payload"] = self.payload
else:
message.update(self.payload)
message = {"payload": self.payload} if self.need_payload_wrap else self.payload
if self.need_message_name:
message["messageName"] = self.name
return message
7 changes: 4 additions & 3 deletions core/basic_models/actions/push_action.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
from core.basic_models.actions.command import Command
from core.basic_models.actions.string_actions import StringAction
from core.text_preprocessing.base import BaseTextPreprocessingResult
from core.unified_template.unified_template import UnifiedTemplate
from core.utils.pickle_copy import pickle_deepcopy
from core.utils.utils import deep_update_dict
from scenarios.user.user_model import User
from smart_kit.request.kafka_request import SmartKitKafkaRequest

PUSH_NOTIFY = "PUSH_NOTIFY"


class PushAction(StringAction):
"""
Expand Down Expand Up @@ -51,6 +51,7 @@ class PushAction(StringAction):
def __init__(self, items: Dict[str, Any], id: Optional[str] = None):
self.surface = items.get("surface", self.COMPANION)
items["nodes"] = items.get("content") or {}
items["command"] = PUSH_NOTIFY
super().__init__(items, id)
self.default_request_data_template = self._get_template_tree(self.DEFAULT_REQUEST_DATA)
self.request_data_template = self._get_template_tree(self.request_data) if self.request_data else None
Expand All @@ -73,6 +74,6 @@ def run(self, user: User, text_preprocessing_result: BaseTextPreprocessingResult
}
requests_data = self._render_request_data(params)
commands = [Command(self.command, command_params, self.id, request_type=self.request_type,
request_data=requests_data, need_payload_wrap=False)]
request_data=requests_data, need_payload_wrap=False, need_message_name=False)]
return commands

Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,11 @@
from smart_kit.message.smartapp_to_message import SmartAppToMessage


class SmartAppPushToMessage(SmartAppToMessage):
class AsIsToMessage(SmartAppToMessage):

@lazy
def as_dict(self):
self.incoming_message: SmartAppFromMessage
fields = {
"projectId": self.payload.get("project_id"),
"clientId": self.incoming_message.sub,
"surface": self.payload.get("surface"),
"content": self.payload.get("content"),
}
fields = self.command.raw
fields.update(self.root_nodes)
return fields

4 changes: 2 additions & 2 deletions smart_kit/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@
PreprocessingMessagesDescription
from smart_kit.action.http import HTTPRequestAction
from smart_kit.message.get_to_message import to_messages
from smart_kit.message.smart_app_push_message import SmartAppPushToMessage
from smart_kit.message.as_is_to_message import AsIsToMessage
from smart_kit.request.kafka_request import SmartKitKafkaRequest

from core.db_adapter.aioredis_sentinel_adapter import AIORedisSentinelAdapter
Expand Down Expand Up @@ -406,4 +406,4 @@ def init_classifiers(self):
classifiers["skip"] = SkipClassifier

def init_message_handlers(self):
to_messages[PUSH_NOTIFY] = SmartAppPushToMessage
to_messages[PUSH_NOTIFY] = AsIsToMessage
2 changes: 1 addition & 1 deletion smart_kit/start_points/main_loop_kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from core.basic_models.actions.command import Command
from smart_kit.compatibility.commands import combine_commands
from smart_kit.message.get_to_message import get_to_message
from smart_kit.message.smart_app_push_message import SmartAppPushToMessage
from smart_kit.message.as_is_to_message import SmartAppPushToMessage
from smart_kit.message.smartapp_to_message import SmartAppToMessage
from smart_kit.names import message_names
from smart_kit.request.kafka_request import SmartKitKafkaRequest
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# coding: utf-8
import json
import unittest
import uuid
from unittest.mock import Mock, MagicMock
Expand Down Expand Up @@ -337,7 +338,7 @@ def test_push_action(self):
user.parametrizer = MockSimpleParametrizer(user, {"data": params})
user.settings = settings
command = action.run(user=user, text_preprocessing_result=None)[0]
self.assertEqual(command.payload, expected)
self.assertEqual(command.raw, expected)
# проверяем наличие кастомных хэдеров для сервиса пушей
self.assertTrue(SmartKitKafkaRequest.KAFKA_EXTRA_HEADERS in command.request_data)
headers = command.request_data.get(SmartKitKafkaRequest.KAFKA_EXTRA_HEADERS)
Expand Down Expand Up @@ -553,20 +554,20 @@ def test_typical_answer(self):
}
}
}
exp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'Ivan Ivanov', 'items': [{'bubble': {'text': 'Text2'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}"
exp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'items': [{'bubble': {'text': 'Text1'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}"
exp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'Ivan Ivanov', 'items': [{'bubble': {'text': 'Text2'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}, sort_keys=True)
exp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'items': [{'bubble': {'text': 'Text1'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}, sort_keys=True)
expect_arr = [exp1, exp2]

nexp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'Ivan Ivanov', 'items': [{'bubble': {'text': 'Text1'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}"
nexp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'items': [{'bubble': {'text': 'Text2'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}"
nexp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'Ivan Ivanov', 'items': [{'bubble': {'text': 'Text1'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}, sort_keys=True)
nexp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'items': [{'bubble': {'text': 'Text2'}}, {'card': {'type': 'simple_list', 'header': '1 доллар США ', 'items': [{'title': 'Купить', 'body': '67.73 RUR'}, {'title': 'Продать', 'body': '64.56 RUR'}], 'footer': 'Ivan Ivanov Сбербанк Онлайн на сегодня 17:53 при обмене до 1000 USD'}}], 'suggestions': {'buttons': [{'title': 'Отделения', 'action': {'text': 'Где ближайщие отделения сбера?', 'type': 'text'}}]}}}, sort_keys=True)
not_expect_arr = [nexp1, nexp2]

for i in range(10):
action = SDKAnswer(items)
result = action.run(user, None)
self.assertEqual("ANSWER_TO_USER", result[0].name)
self.assertTrue(str(result[0].raw) in expect_arr)
self.assertFalse(str(result[0].raw) in not_expect_arr)
self.assertTrue(json.dumps(result[0].raw, sort_keys=True) in expect_arr)
self.assertFalse(json.dumps(result[0].raw, sort_keys=True) in not_expect_arr)


def test_typical_answer_without_items(self):
Expand All @@ -580,14 +581,14 @@ def test_typical_answer_without_items(self):
"pronounceText": ["pronounceText1", "pronounceText2"],
}
}
exp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1'}}"
exp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText2'}}"
exp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1'}}, sort_keys=True)
exp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText2'}}, sort_keys=True)
exp_list = [exp1, exp2]
for i in range(10):
action = SDKAnswer(items)
result = action.run(user, None)
self.assertEqual("ANSWER_TO_USER", result[0].name)
self.assertTrue(str(result[0].raw) in exp_list)
self.assertTrue(json.dumps((result[0].raw), sort_keys=True) in exp_list)

def test_typical_answer_without_nodes(self):
user = PicklableMock()
Expand Down Expand Up @@ -616,19 +617,19 @@ def test_typical_answer_without_nodes(self):
]
}
}
exp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'Ivan Ivanov', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит1', 'action': {'text': 'кредит', 'type': 'text'}}]}}}"
exp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'отделения2', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит2', 'action': {'text': 'кредит', 'type': 'text'}}]}}}"
exp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'Ivan Ivanov', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит1', 'action': {'text': 'кредит', 'type': 'text'}}]}}}, sort_keys=True)
exp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'отделения2', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит2', 'action': {'text': 'кредит', 'type': 'text'}}]}}}, sort_keys=True)
expect_arr = [exp1, exp2]

nexp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'Ivan Ivanov', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит2', 'action': {'text': 'кредит', 'type': 'text'}}]}}}"
nexp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'отделения2', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит1', 'action': {'text': 'кредит', 'type': 'text'}}]}}}"
nexp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'Ivan Ivanov', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит2', 'action': {'text': 'кредит', 'type': 'text'}}]}}}, sort_keys=True)
nexp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'pronounceText1', 'suggestions': {'buttons': [{'title': 'отделения2', 'action': {'text': 'отделения', 'type': 'text'}}, {'title': 'кредит1', 'action': {'text': 'кредит', 'type': 'text'}}]}}}, sort_keys=True)
not_expect_arr = [nexp1, nexp2]
for i in range(10):
action = SDKAnswer(items)
result = action.run(user, None)
self.assertEqual("ANSWER_TO_USER", result[0].name)
self.assertTrue(str(result[0].raw) in expect_arr)
self.assertFalse(str(result[0].raw) in not_expect_arr)
self.assertTrue(json.dumps((result[0].raw), sort_keys=True) in expect_arr)
self.assertFalse(json.dumps((result[0].raw), sort_keys=True) in not_expect_arr)


class SDKRandomAnswer(unittest.TestCase):
Expand Down Expand Up @@ -713,13 +714,13 @@ def test_SDKItemAnswer_full(self):
}
]
}
exp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'items': [{'bubble': {'text': 't2', 'markdown': False}}, {'card': {'cards_params': 'a lot of params'}}], 'suggestions': {'buttons': [{'title': 'p2', 'action': {'text': 't2', 'type': 'text'}}, {'title': 'p2', 'action': {'text': 't2', 'type': 'text'}}, {'title': 'p2', 'action': {'deep_link': 'www.ww.w', 'type': 'deep_link'}}]}, 'pronounceText': 'p2'}}"
exp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'items': [{'bubble': {'text': 'Ivan Ivanov', 'markdown': False}}, {'card': {'cards_params': 'a lot of params'}}], 'suggestions': {'buttons': [{'title': 'p1', 'action': {'text': 'Ivan Ivanov', 'type': 'text'}}, {'title': 'p1', 'action': {'text': 'Ivan Ivanov', 'type': 'text'}}, {'title': 'p1', 'action': {'deep_link': 'www.ww.w', 'type': 'deep_link'}}]}, 'pronounceText': 'p1'}}"
exp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'items': [{'bubble': {'text': 't2', 'markdown': False}}, {'card': {'cards_params': 'a lot of params'}}], 'suggestions': {'buttons': [{'title': 'p2', 'action': {'text': 't2', 'type': 'text'}}, {'title': 'p2', 'action': {'text': 't2', 'type': 'text'}}, {'title': 'p2', 'action': {'deep_link': 'www.ww.w', 'type': 'deep_link'}}]}, 'pronounceText': 'p2'}}, sort_keys=True)
exp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'items': [{'bubble': {'text': 'Ivan Ivanov', 'markdown': False}}, {'card': {'cards_params': 'a lot of params'}}], 'suggestions': {'buttons': [{'title': 'p1', 'action': {'text': 'Ivan Ivanov', 'type': 'text'}}, {'title': 'p1', 'action': {'text': 'Ivan Ivanov', 'type': 'text'}}, {'title': 'p1', 'action': {'deep_link': 'www.ww.w', 'type': 'deep_link'}}]}, 'pronounceText': 'p1'}}, sort_keys=True)

action = SDKAnswerToUser(items)
for i in range(3):
result = action.run(user, None)
self.assertTrue(str(result[0].raw) in [exp1, exp2])
self.assertTrue(json.dumps(result[0].raw, sort_keys=True) in [exp1, exp2])

def test_SDKItemAnswer_root(self):

Expand Down Expand Up @@ -762,13 +763,13 @@ def test_SDKItemAnswer_root(self):
},
]
}
exp1 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'p1'}}"
exp2 = "{'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'p2'}}"
exp1 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'p1'}}, sort_keys=True)
exp2 = json.dumps({'messageName': 'ANSWER_TO_USER', 'payload': {'pronounceText': 'p2'}}, sort_keys=True)

action = SDKAnswerToUser(items)
for i in range(3):
result = action.run(user, None)
self.assertTrue(str(result[0].raw) in [exp1, exp2])
self.assertTrue(json.dumps(result[0].raw, sort_keys=True) in [exp1, exp2])

def test_SDKItemAnswer_simple(self):

Expand Down
30 changes: 30 additions & 0 deletions tests/smart_kit_tests/message/test_as_is_to_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# coding: utf-8
import json
import unittest
from unittest.mock import Mock

from smart_kit.message.as_is_to_message import AsIsToMessage


class TestAsIsTooMessage(unittest.TestCase):
def setUp(self):
self.command_ = Mock()
self.request_ = Mock()
self.message_ = Mock()
self.command_.loader = "json.dumps"
self.request_.header = "json"
self.command_.payload = {}
self.command_.root_nodes = {}
self.command_.raw = {
"content": {"test_param": ""},
"surface": "some_surface",
"project_id": "project_id",
}
self.message_.sub = 'sub'

def test_as_is_to_message_as_dict(self):
obj = AsIsToMessage(self.command_, self.message_, self.request_)
self.assertEqual(obj.as_dict, {
"content": {"test_param": ""},
"surface": "some_surface",
"project_id": "project_id"})
Loading

0 comments on commit f119a52

Please sign in to comment.