Esempio n. 1
0
    async def test_validate_yes_no(self):
        """
        Tests that yes no slots validate correctly
        """
        form = HealthCheckForm()
        for slot in [
                "symptoms_fever",
                "symptoms_cough",
                "symptoms_sore_throat",
                "symptoms_difficulty_breathing",
                "symptoms_taste_smell",
                "tracing",
        ]:
            tracker = self.get_tracker_for_text_slot_with_message(slot, "yes")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "yes"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(slot, "no")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "no"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(
                slot, "Invalid")
            dispatcher = CollectingDispatcher()
            events = await form.validate(dispatcher, tracker, {})
            assert events == [
                SlotSet(slot, None),
            ]
            [message] = dispatcher.messages
            assert message["template"] == "utter_incorrect_selection"
Esempio n. 2
0
    async def test_validate_yes_no_maybe(self):
        """
        Tests that yes no maybe slots validate correctly
        """
        form = HealthCheckForm()
        for slot in ["exposure"]:
            tracker = self.get_tracker_for_text_slot_with_message(slot, "yes")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "yes"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(slot, "no")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "no"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(
                slot, "not sure")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "not sure"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(
                slot, "Invalid")
            dispatcher = CollectingDispatcher()
            events = await form.validate(dispatcher, tracker, {})
            assert events == [
                SlotSet(slot, None),
            ]
            [message] = dispatcher.messages
            assert message["template"] == "utter_incorrect_selection"
Esempio n. 3
0
    async def test_validate_yes_no(self):
        """
        Tests that yes no slots validate correctly
        """
        form = HealthCheckProfileForm()
        for slot in [
                "medical_condition_obesity",
                "medical_condition_diabetes",
                "medical_condition_hypertension",
                "medical_condition_cardio",
        ]:
            tracker = self.get_tracker_for_text_slot_with_message(slot, "yes")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "yes"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(slot, "no")
            events = await form.validate(CollectingDispatcher(), tracker, {})
            assert events == [
                SlotSet(slot, "no"),
            ]

            tracker = self.get_tracker_for_text_slot_with_message(
                slot, "Invalid")
            dispatcher = CollectingDispatcher()
            events = await form.validate(dispatcher, tracker, {})
            assert events == [
                SlotSet(slot, None),
            ]
            [message] = dispatcher.messages
            assert message["template"] == "utter_incorrect_selection"
Esempio n. 4
0
def test_extract_requested_slot_from_entity_with_intent():
    """Test extraction of a slot value from entity with the different name
    and certain intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {
                "some_slot": self.from_entity(
                    entity="some_entity", intent="some_intent"
                )
            }

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "intent": {"name": "some_intent", "confidence": 1.0},
            "entities": [{"entity": "some_entity", "value": "some_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(
        CollectingDispatcher(), tracker, "some_slot", {}
    )
    # check that the value was extracted for correct intent
    assert slot_values == {"some_slot": "some_value"}

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "intent": {"name": "some_other_intent", "confidence": 1.0},
            "entities": [{"entity": "some_entity", "value": "some_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(
        CollectingDispatcher(), tracker, "some_slot", {}
    )
    # check that the value was not extracted for incorrect intent
    assert slot_values == {}
Esempio n. 5
0
def test_extract_other_slots_with_intent():
    """Test extraction of other not requested slots values
    from entities with the same names
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def slot_mappings(self):
            return {
                "some_other_slot": self.from_entity(
                    entity="some_other_slot", intent="some_intent"
                )
            }

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "intent": {"name": "some_other_intent", "confidence": 1.0},
            "entities": [{"entity": "some_other_slot", "value": "some_other_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted for non requested slot
    assert slot_values == {}

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {
            "intent": {"name": "some_intent", "confidence": 1.0},
            "entities": [{"entity": "some_other_slot", "value": "some_other_value"}],
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_other_slots(CollectingDispatcher(), tracker, {})
    # check that the value was extracted only for non requested slot
    assert slot_values == {"some_other_slot": "some_other_value"}
Esempio n. 6
0
def test_extract_requested_slot_from_text_with_not_intent():
    """Test extraction of a slot value from text with certain intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_text(not_intent="some_intent")}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "text": "some_text",
            "intent": {
                "name": "some_intent",
                "confidence": 1.0
            }
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was extracted for correct intent
    assert slot_values == {}

    tracker = Tracker(
        "default",
        {"requested_slot": "some_slot"},
        {
            "text": "some_text",
            "intent": {
                "name": "some_other_intent",
                "confidence": 1.0
            },
        },
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    # check that the value was not extracted for incorrect intent
    assert slot_values == {"some_slot": "some_text"}
Esempio n. 7
0
 async def test_run_no_bot(self):
     slots = {
         "bot": None,
         "http_action_config_http_action": "new_http_action",
         "param2": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     dispatcher: CollectingDispatcher = CollectingDispatcher()
     latest_message = {
         'text': 'get intents',
         'intent_ranking': [{
             'name': 'http_action'
         }]
     }
     tracker = Tracker(sender_id="sender2",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=latest_message,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     domain: Dict[Text, Any] = None
     actual: List[Dict[Text, Any]] = await HttpAction().run(
         dispatcher, tracker, domain)
     assert actual is not None
     assert str(actual[0]['name']) == 'KAIRON_ACTION_RESPONSE'
     assert str(
         actual[0]['value']) == 'I have failed to process your request'
     log = HttpActionLog.objects(sender="sender2", status="FAILURE").get()
     assert log[
         'exception'] == 'Bot id and HTTP action configuration name not found in slot'
Esempio n. 8
0
    async def test_run_with_get_placeholder_vs_string_response(
            self, monkeypatch):
        action = HttpActionConfig(
            auth_token="",
            action_name=
            "test_run_with_get_string_http_response_placeholder_required",
            response="The value of ${a.b.3} in ${a.b.d.0} is ${a.b.d}",
            http_url="http://localhost:8080/mock",
            request_method="GET",
            params_list=None,
            bot="5f50fd0a56b698ca10d35d2e",
            user="******")

        def _get_action(*arge, **kwargs):
            return action.to_mongo().to_dict()

        monkeypatch.setattr(ActionUtility, "get_http_action_config",
                            _get_action)
        http_url = 'http://localhost:8082/mock'
        resp_msg = "This is string http response"

        responses.start()
        responses.add(
            method=responses.GET,
            url=http_url,
            body=resp_msg,
            status=200,
        )

        slots = {
            "bot":
            "5f50fd0a56b698ca10d35d2e",
            "http_action_config_test_run":
            "test_run_with_get_string_http_response_placeholder_required"
        }
        events = [{"event1": "hello"}, {"event2": "how are you"}]
        dispatcher: CollectingDispatcher = CollectingDispatcher()
        latest_message = {
            'text': 'get intents',
            'intent_ranking': [{
                'name': 'test_run'
            }]
        }
        tracker = Tracker(sender_id="sender1",
                          slots=slots,
                          events=events,
                          paused=False,
                          latest_message=latest_message,
                          followup_action=None,
                          active_loop=None,
                          latest_action_name=None)
        domain: Dict[Text, Any] = None
        action.save().to_mongo().to_dict()
        actual: List[Dict[Text, Any]] = await HttpAction().run(
            dispatcher, tracker, domain)
        responses.stop()
        assert actual is not None
        assert str(actual[0]['name']) == 'KAIRON_ACTION_RESPONSE'
        assert str(
            actual[0]['value']) == 'I have failed to process your request'
 def test_validate_university(self):
     form = HealthCheckProfileForm()
     tracker = Tracker(
         "27820001001",
         {"destination_province": "ec"},
         {},
         [],
         False,
         None,
         {},
         "action_listen",
     )
     dispatcher = CollectingDispatcher()
     response = form.validate_university("afda", dispatcher, tracker, {})
     self.assertEqual(
         response,
         {
             "university": "afda",
             "university_list": "\n".join(
                 [
                     "*1.* AFDA",
                     "*2.* STADIO AFDA",
                     "*3.* Ikhala",
                     "*4.* MANCOSA",
                     "*5.* Damelin",
                 ]
             ),
         },
     )
Esempio n. 10
0
    def test_run_with_post(self):
        # request_params = {'data': 'test_data', 'test_class': [{'key': 'value'}, {'key2': 'value2'}]}
        # request_params = [HttpActionRequestBody(key='data', value="test_data"),
        #                   HttpActionRequestBody(key='test_class', value=[{'key': 'value'}, {'key2': 'value2'}])]
        http_url = 'http://localhost:8080/mock'
        resp_msg = "5000"
        responses.add(
            method=responses.POST,
            url=http_url,
            body=resp_msg,
            status=200,
        )

        slots = {"bot": "5f50fd0a56b698ca10d35d2e", "http_action_config": "test_run_with_post"}
        events = [{"event1": "hello"}, {"event2": "how are you"}]
        dispatcher: CollectingDispatcher = CollectingDispatcher()
        tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=None,
                          followup_action=None, active_form=None, latest_action_name=None)
        domain: Dict[Text, Any] = None
        HttpActionConfig(
            auth_token="",
            action_name="test_run_with_post",
            response="Data added successfully, id:${RESPONSE}",
            http_url="http://localhost:8080/mock",
            request_method="POST",
            params_list=None,
            bot="5f50fd0a56b698ca10d35d2e",
            user="******"
        ).save().to_mongo().to_dict()
        actual: List[Dict[Text, Any]] = HttpAction().run(dispatcher, tracker, domain)
        assert actual is not None
        assert actual[0]['name'] == 'Data added successfully, id:5000'
Esempio n. 11
0
 def test_run_invalid_http_action(self):
     slots = {
         "bot": "5f50fd0a56b698ca10d35d2e",
         "http_action_config": "test_run_invalid_http_action",
         "param2": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     HttpActionConfig(
         auth_token="bearer kjflksjflksajfljsdflinlsufisnflisjbjsdalibvs",
         action_name="test_run_invalid_http_action1",
         response="json",
         http_url="http://www.google.com",
         request_method="GET",
         params_list=None,
         bot="5f50fd0a56b698ca10d35d2e",
         user="******").save()
     dispatcher: CollectingDispatcher = CollectingDispatcher()
     tracker = Tracker(sender_id="sender1",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=None,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     domain: Dict[Text, Any] = None
     HttpAction().run(dispatcher, tracker, domain)
     str(dispatcher.messages[0]['text']).__contains__(
         "I have failed to process your request: No HTTP action found for bot"
     )
Esempio n. 12
0
async def test_deprecated_helper_style():
    # noinspection PyAbstractClass
    # This method tests the old style of returning values instead of {'slot':'value'}
    # dicts, and can be removed if we officially stop supporting the deprecated style.
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate_some_slot(self, value, dispatcher, tracker, domain):
            if value == "some_value":
                return "validated_value"

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_value"},
        {"entities": [{"entity": "some_slot", "value": "some_value"}]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    events = await form.validate(CollectingDispatcher(), tracker, {})

    # check that some_slot gets validated correctly
    assert events == [SlotSet("some_slot", "validated_value")]
Esempio n. 13
0
def test_abstract_action():
    dispatcher = CollectingDispatcher()
    tracker = Tracker("test", {}, {}, [], False, None, {}, "listen")
    domain = {}

    events = CustomAction().run(dispatcher, tracker, domain)
    assert events == [SlotSet("test", "test")]
Esempio n. 14
0
    async def generic_action(self, request):
        action_name = request.get("next_action")
        if action_name:
            _LOGGER.debug("Received request to run '{}'".format(action_name))

            tracker_json = request.get("tracker")
            domain = request.get("domain", {})
            tracker = Tracker.from_dict(tracker_json)
            dispatcher = CollectingDispatcher()

            if action_name.endswith("_form"):
                intent_id = action_name[:-5]
                intent = await self.asm.memory.get(
                    self.config['skill-id'] + "_intents", intent_id)
                gfa = GenericFormAction()
                gfa.set_name(action_name)
                gfa.set_intent(intent)
                gfa.set_domain(domain)
                gfa.set_memory(self.asm.memory)
                events = gfa.run(dispatcher, tracker, domain)

            if not events:
                # make sure the action did not just return `None`...
                events = []

            validated_events = self.validate_events(events, action_name)
            _LOGGER.debug("Finished running '{}'".format(action_name))
        else:
            _LOGGER.warning("Received an action call without an action.")

        return {"events": validated_events, "responses": dispatcher.messages}
Esempio n. 15
0
    async def test_run_no_connection(self, monkeypatch):
        action = HttpActionConfig(
            auth_token="",
            action_name="test_run_with_post",
            response="This should be response",
            http_url="http://localhost:8085/mock",
            request_method="GET",
            params_list=None,
            bot="5f50fd0a56b698ca10d35d2e",
            user="******"
        )

        def _get_action(*arge, **kwargs):
            return action.to_mongo().to_dict()

        monkeypatch.setattr(ActionUtility, "get_http_action_config", _get_action)
        slots = {"bot": "5f50fd0a56b698ca10d35d2e", "http_action_config_test_run": "test_run_with_post"}
        events = [{"event1": "hello"}, {"event2": "how are you"}]
        dispatcher: CollectingDispatcher = CollectingDispatcher()
        latest_message = {'text': 'get intents', 'intent_ranking': [{'name': 'test_run'}]}
        tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=latest_message,
                          followup_action=None, active_loop=None, latest_action_name=None)
        domain: Dict[Text, Any] = None
        action.save()
        actual: List[Dict[Text, Any]] = await HttpAction().run(dispatcher, tracker, domain)
        assert actual is not None
        assert str(actual[0]['name']) == 'KAIRON_ACTION_RESPONSE'
        assert str(actual[0]['value']).__contains__('I have failed to process your request')
Esempio n. 16
0
 async def test_run_invalid_http_action(self, mock_get_http_action_exception):
     slots = {"bot": "5f50fd0a56b698ca10d35d2e", "http_action_config_http_action": "test_run_invalid_http_action",
              "param2": "param2value"}
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     latest_message = {'text': 'get intents', 'intent_ranking': [{'name': 'http_action'}]}
     HttpActionConfig(
         auth_token="bearer kjflksjflksajfljsdflinlsufisnflisjbjsdalibvs",
         action_name="test_run_invalid_http_action1",
         response="json",
         http_url="http://www.google.com",
         request_method="GET",
         params_list=None,
         bot="5f50fd0a56b698ca10d35d2e",
         user="******"
     ).save()
     dispatcher: CollectingDispatcher = CollectingDispatcher()
     tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=latest_message,
                       followup_action=None, active_loop=None, latest_action_name=None)
     domain: Dict[Text, Any] = None
     await HttpAction().run(dispatcher, tracker, domain)
     str(dispatcher.messages[0]['text']).__contains__(
         "I have failed to process your request: No HTTP action found for bot")
     log = HttpActionLog.objects(sender="sender1",
                                 bot="5f50fd0a56b698ca10d35d2e",
                                 status="FAILURE").get()
     assert log['exception'].__contains__('No HTTP action found for bot')
Esempio n. 17
0
    async def process_actions(self, action_call):
        from rasa_sdk.interfaces import Tracker

        action_name = action_call.get("next_action")
        if action_name and action_name.strip():
            logger.debug(f"Received request to run '{action_name}'")

            tracker_json = action_call["tracker"]
            domain = action_call.get("domain", {})
            tracker = Tracker.from_dict(tracker_json)
            dispatcher = CollectingDispatcher()

            events = await ActionProcessor.process_action(
                dispatcher, tracker, domain, action_name)

            if not events:
                events = []

            validated_events = ActionExecutor.validate_events(
                events, action_name)
            logger.debug(f"Finished running '{action_name}'")
            return ActionExecutor._create_api_response(validated_events,
                                                       dispatcher.messages)

        logger.warning("Received an action call without an action.")
        return None
Esempio n. 18
0
    async def test_happy_path(self, mock_datetime, mock_session_factory):
        reminder_mock = _mock_reminder(mock_session_factory, DEFAULT_PHONE_NUMBER)
        mock_datetime.utcnow.return_value = DEFAULT_NOW

        tracker = _create_tracker()
        dispatcher = CollectingDispatcher()

        with patch.dict("os.environ", ENV):
            await ActionSendDailyCheckInReminder().run(dispatcher, tracker, {})

        self.assertEqual(len(dispatcher.messages), 1)
        message = dispatcher.messages[0]

        self.assertEqual(message["template"], "utter_checkin_reminder")
        self.assertEqual(message["first_name"], DEFAULT_FIRST_NAME)
        self.assertEqual(
            message["check_in_url"],
            CHECKIN_URL_PATTERN.format(
                language=DEFAULT_LANGUAGE, reminder_id=DEFAULT_REMINDER_ID_HASH
            ),
        )

        self.assertEqual(reminder_mock.last_reminded_at, DEFAULT_NOW)
        mock_session_factory.return_value.commit.assert_called()
        mock_session_factory.return_value.close.assert_called()
Esempio n. 19
0
 def test_run_no_connection(self):
     slots = {
         "bot": "5f50fd0a56b698ca10d35d2e",
         "http_action_config_test_run": "test_run_with_post"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     dispatcher: CollectingDispatcher = CollectingDispatcher()
     latest_message = {
         'text': 'get intents',
         'intent_ranking': [{
             'name': 'test_run'
         }]
     }
     tracker = Tracker(sender_id="sender1",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=latest_message,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     domain: Dict[Text, Any] = None
     HttpActionConfig(auth_token="",
                      action_name="test_run_with_post",
                      response="This should be response",
                      http_url="http://localhost:8080/mock",
                      request_method="GET",
                      params_list=None,
                      bot="5f50fd0a56b698ca10d35d2e",
                      user="******").save()
     actual: List[Dict[Text,
                       Any]] = HttpAction().run(dispatcher, tracker, domain)
     assert actual is not None
     assert str(actual[0]['name']).__contains__(
         'I have failed to process your request')
Esempio n. 20
0
 async def test_run_no_http_action(self):
     slots = {
         "bot": "jhgfsjgfausyfgus",
         "http_action_config_http_action": None,
         "param2": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     dispatcher: CollectingDispatcher = CollectingDispatcher()
     latest_message = {
         'text': 'get intents',
         'intent_ranking': [{
             'name': 'http_action'
         }]
     }
     tracker = Tracker(sender_id="sender1",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=latest_message,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     domain: Dict[Text, Any] = None
     actual: List[Dict[Text, Any]] = await HttpAction().run(
         dispatcher, tracker, domain)
     assert actual is not None
     assert str(actual[0]['name']) == 'KAIRON_ACTION_RESPONSE'
     assert str(
         actual[0]['value']) == 'I have failed to process your request'
Esempio n. 21
0
async def test_validate_on_activation_with_other_action_after_user_utterance():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        async def submit(self, _dispatcher, _tracker, _domain):
            return []

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {},
        {"entities": [{"entity": "some_other_slot", "value": "some_other_value"}]},
        [],
        False,
        None,
        {},
        "some_action",
    )
    dispatcher = CollectingDispatcher()
    events = await form.run(dispatcher=dispatcher, tracker=tracker, domain=None)
    # check that the form was activated and validation was performed
    assert events == [
        ActiveLoop("some_form"),
        SlotSet("some_other_slot", "some_other_value"),
        SlotSet(REQUESTED_SLOT, "some_slot"),
    ]
Esempio n. 22
0
def test_extract_requested_slot_from_entity_no_intent():
    """Test extraction of a slot value from entity with the different name
    and any intent
    """

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_entity(entity="some_entity")}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {"entities": [{
            "entity": "some_entity",
            "value": "some_value"
        }]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    assert slot_values == {"some_slot": "some_value"}
Esempio n. 23
0
async def test_form_validation_without_validate_function():
    form = TestFormValidationAction()

    # tracker with active form
    tracker = Tracker(
        "default",
        {},
        {},
        [
            SlotSet("slot1", "correct_value"),
            SlotSet("slot2", "incorrect_value"),
            SlotSet("slot3", "some_value"),
        ],
        False,
        None,
        {"name": "some_form", "is_interrupted": False, "rejected": False},
        "action_listen",
    )

    dispatcher = CollectingDispatcher()
    with pytest.warns(UserWarning):
        events = await form.run(dispatcher=dispatcher, tracker=tracker, domain=None)
        assert events == [
            SlotSet("slot3", "some_value"),
            SlotSet("slot2", None),
            SlotSet("slot1", "validated_value"),
        ]
 def test_additional_details_copied(self):
     """
     Should copy over the name details when exiting
     """
     action = ActionExit()
     dispatcher = CollectingDispatcher()
     events = action.run(
         dispatcher,
         Tracker(
             "27820001001",
             {
                 "first_name": "test first",
                 "last_name": "test last",
                 "destination": "campus",
                 "reason": "student",
             },
             {},
             [],
             False,
             None,
             {},
             "action_listen",
         ),
         {},
     )
     self.assertIn(SlotSet("first_name", "test first"), events)
     self.assertIn(SlotSet("last_name", "test last"), events)
     self.assertIn(SlotSet("destination", "campus"), events)
     self.assertIn(SlotSet("reason", "student"), events)
Esempio n. 25
0
    async def test_validate_location_google_places(self):
        """
        If there's are google places API credentials, then do a lookup
        """
        base.actions.actions.config.GOOGLE_PLACES_API_KEY = "test_key"
        form = HealthCheckProfileForm()
        form.places_lookup = utils.AsyncMock()
        form.places_lookup.return_value = {
            "formatted_address": "Cape Town, South Africa",
            "geometry": {
                "location": {
                    "lat": 1.23,
                    "lng": 4.56
                }
            },
        }

        tracker = self.get_tracker_for_text_slot_with_message(
            "location",
            "Cape Town",
        )

        events = await form.validate(CollectingDispatcher(), tracker, {})
        assert events == [
            SlotSet("location", "Cape Town, South Africa"),
            SlotSet("city_location_coords", "+01.23+004.56/"),
        ]

        base.actions.actions.config.GOOGLE_PLACES_API_KEY = None
Esempio n. 26
0
    def test_run_with_get_placeholder_vs_string_response(self):
        http_url = 'http://localhost:8080/mock'
        resp_msg = "This is string http response"
        responses.add(
            method=responses.GET,
            url=http_url,
            body=resp_msg,
            status=200,
        )

        slots = {"bot": "5f50fd0a56b698ca10d35d2e",
                 "http_action_config": "test_run_with_get_string_http_response_placeholder_required"}
        events = [{"event1": "hello"}, {"event2": "how are you"}]
        dispatcher: CollectingDispatcher = CollectingDispatcher()
        tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=None,
                          followup_action=None, active_form=None, latest_action_name=None)
        domain: Dict[Text, Any] = None
        HttpActionConfig(
            auth_token="",
            action_name="test_run_with_get_string_http_response_placeholder_required",
            response="The value of ${a.b.3} in ${a.b.d.0} is ${a.b.d}",
            http_url="http://localhost:8080/mock",
            request_method="GET",
            params_list=None,
            bot="5f50fd0a56b698ca10d35d2e",
            user="******"
        ).save().to_mongo().to_dict()
        actual: List[Dict[Text, Any]] = HttpAction().run(dispatcher, tracker, domain)
        assert actual is not None
        assert str(
            actual[0]['name']) == 'I have failed to process your request: Could not find value for keys in response'
Esempio n. 27
0
async def test_validate_extracted_no_requested():
    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        @staticmethod
        def required_slots(_tracker):
            return ["some_slot", "some_other_slot"]

        def validate_some_slot(self, value, dispatcher, tracker, domain):
            if value == "some_value":
                return {"some_slot": "validated_value"}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: None},
        {"entities": [{
            "entity": "some_slot",
            "value": "some_value"
        }]},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    events = await form.validate(CollectingDispatcher(), tracker, {})

    # check that some_slot gets validated correctly
    assert events == [SlotSet("some_slot", "validated_value")]
Esempio n. 28
0
    async def test_validate_location_google_places_error(self):
        """
        Errors should be retried 3 times
        """
        base.actions.actions.config.GOOGLE_PLACES_API_KEY = "test_key"
        form = HealthCheckProfileForm()
        form.places_lookup = utils.AsyncMock()
        form.places_lookup.side_effect = Exception()

        tracker = self.get_tracker_for_text_slot_with_message(
            "location",
            "Cape Town",
        )

        dispatcher = CollectingDispatcher()
        events = await form.validate(dispatcher, tracker, {})
        assert events == [
            SlotSet("location", None),
        ]

        [message] = dispatcher.messages
        assert message["template"] == "utter_incorrect_location"

        assert form.places_lookup.call_count == 3

        base.actions.actions.config.GOOGLE_PLACES_API_KEY = None
Esempio n. 29
0
def test_extract_requested_slot_from_text_no_intent():
    """Test extraction of a slot value from text with any intent"""

    # noinspection PyAbstractClass
    class CustomFormAction(FormAction):
        def name(self):
            return "some_form"

        def slot_mappings(self):
            return {"some_slot": self.from_text()}

    form = CustomFormAction()

    tracker = Tracker(
        "default",
        {REQUESTED_SLOT: "some_slot"},
        {"text": "some_text"},
        [],
        False,
        None,
        {},
        "action_listen",
    )

    slot_values = form.extract_requested_slot(CollectingDispatcher(), tracker,
                                              {})
    assert slot_values == {"some_slot": "some_text"}
 def test_send_risk_to_user_minor(self, dt):
     """
     The message to the user should not include the name
     as it was not captured in the case of minors
     """
     form = HealthCheckForm()
     dispatcher = CollectingDispatcher()
     dt.now.return_value = datetime(
         2020, 1, 2, 3, 4, 5, tzinfo=timezone(timedelta(hours=2))
     )
     tracker = Tracker(
         "27820001001",
         {"destination": "campus", "reason": "student"},
         {},
         [],
         False,
         None,
         {},
         "action_listen",
     )
     form.send_risk_to_user(dispatcher, "low", tracker)
     [msg] = dispatcher.messages
     self.assertEqual(msg["template"], "utter_risk_low")
     self.assertEqual(msg["name"], "Not captured")
     self.assertEqual(msg["issued"], "January 2, 2020, 3:04 AM")
     self.assertEqual(msg["expired"], "January 3, 2020, 3:04 AM")