예제 #1
0
async def test_callback_calls_endpoint():
    from rasa.core.channels.callback import CallbackOutput
    with aioresponses() as mocked:
        mocked.post("https://example.com/callback",
                    repeat=True,
                    headers={"Content-Type": "application/json"})

        output = CallbackOutput(EndpointConfig("https://example.com/callback"))

        await output.send_response("test-id", {
            "text": "Hi there!",
            "image": "https://example.com/image.jpg"
        })

        r = latest_request(mocked, "post", "https://example.com/callback")

        assert r

        image = r[-1].kwargs["json"]
        text = r[-2].kwargs["json"]

        assert image['recipient_id'] == "test-id"
        assert image['image'] == "https://example.com/image.jpg"

        assert text['recipient_id'] == "test-id"
        assert text['text'] == "Hi there!"
예제 #2
0
async def test_undo_latest_msg(mock_endpoint):
    tracker_dump = utils.read_file("data/test_trackers/tracker_moodbot.json")
    tracker_json = json.loads(tracker_dump)
    evts = tracker_json.get("events")

    sender_id = uuid.uuid4().hex

    url = '{}/conversations/{}/tracker?include_events=ALL'.format(
        mock_endpoint.url, sender_id)
    replace_url = '{}/conversations/{}/tracker/events'.format(
        mock_endpoint.url, sender_id)
    with aioresponses() as mocked:
        mocked.get(url, body=tracker_dump)
        mocked.put(replace_url)

        await interactive._undo_latest(sender_id, mock_endpoint)

        r = latest_request(mocked, 'put', replace_url)

        assert r

        # this should be the events the interactive call send to the endpoint
        # these events should have the last utterance omitted
        replaced_evts = json_of_latest_request(r)
        assert len(replaced_evts) == 6
        assert replaced_evts == evts[:6]
예제 #3
0
async def test_request_prediction(mock_endpoint):
    sender_id = uuid.uuid4().hex

    url = '{}/conversations/{}/predict'.format(mock_endpoint.url, sender_id)

    with aioresponses() as mocked:
        mocked.post(url, payload={})

        await interactive.request_prediction(mock_endpoint, sender_id)

        assert latest_request(mocked, 'post', url) is not None
예제 #4
0
async def test_print_history(mock_endpoint):
    tracker_dump = utils.read_file("data/test_trackers/tracker_moodbot.json")

    sender_id = uuid.uuid4().hex

    url = '{}/conversations/{}/tracker?include_events=AFTER_RESTART'.format(
        mock_endpoint.url, sender_id)
    with aioresponses() as mocked:
        mocked.get(url,
                   body=tracker_dump,
                   headers={"Accept": "application/json"})

        await interactive._print_history(sender_id, mock_endpoint)

        assert latest_request(mocked, 'get', url) is not None
예제 #5
0
async def test_remote_action_runs(default_dispatcher_collecting,
                                  default_domain):
    tracker = DialogueStateTracker("default", default_domain.slots)

    endpoint = EndpointConfig("https://example.com/webhooks/actions")
    remote_action = action.RemoteAction("my_action", endpoint)

    with aioresponses() as mocked:
        mocked.post('https://example.com/webhooks/actions',
                    payload={
                        "events": [],
                        "responses": []
                    })

        await remote_action.run(default_dispatcher_collecting, tracker,
                                default_domain)

        r = latest_request(mocked, 'post',
                           "https://example.com/webhooks/actions")

        assert r

        assert json_of_latest_request(r) == {
            'domain': default_domain.as_dict(),
            'next_action': 'my_action',
            'sender_id': 'default',
            'version': rasa.__version__,
            'tracker': {
                'latest_message': {
                    'entities': [],
                    'intent': {},
                    'text': None
                },
                'active_form': {},
                'latest_action_name': None,
                'sender_id': 'default',
                'paused': False,
                'latest_event_time': None,
                'followup_action': 'action_listen',
                'slots': {
                    'name': None
                },
                'events': [],
                'latest_input_channel': None
            }
        }
예제 #6
0
async def test_http_parsing():
    message = UserMessage('lunch?')

    endpoint = EndpointConfig('https://interpreter.com')
    with aioresponses() as mocked:
        mocked.post('https://interpreter.com/parse', repeat=True, status=200)

        inter = RasaNLUHttpInterpreter(endpoint=endpoint)
        try:
            await MessageProcessor(inter, None, None, None,
                                   None)._parse_message(message)
        except KeyError:
            pass  # logger looks for intent and entities, so we except

        r = latest_request(mocked, 'POST', "https://interpreter.com/parse")

        assert r
        assert json_of_latest_request(r)['message_id'] == message.message_id
예제 #7
0
async def test_send_message(mock_endpoint):
    sender_id = uuid.uuid4().hex

    url = '{}/conversations/{}/messages'.format(mock_endpoint.url, sender_id)
    with aioresponses() as mocked:
        mocked.post(url, payload={})

        await interactive.send_message(mock_endpoint, sender_id, "Hello")

        r = latest_request(mocked, 'post', url)

        assert r

        assert json_of_latest_request(r) == {
            "sender": "user",
            "message": "Hello",
            "parse_data": None
        }
예제 #8
0
async def test_endpoint_config():
    with aioresponses() as mocked:
        endpoint = EndpointConfig("https://example.com/",
                                  params={"A": "B"},
                                  headers={"X-Powered-By": "Rasa"},
                                  basic_auth={
                                      "username": "******",
                                      "password": "******"
                                  },
                                  token="mytoken",
                                  token_name="letoken",
                                  type="redis",
                                  port=6379,
                                  db=0,
                                  password="******",
                                  timeout=30000)

        mocked.post('https://example.com/test?A=B&P=1&letoken=mytoken',
                    payload={"ok": True},
                    repeat=True,
                    status=200)

        await endpoint.request("post",
                               subpath="test",
                               content_type="application/text",
                               json={"c": "d"},
                               params={"P": "1"})

        r = latest_request(mocked, 'post',
                           "https://example.com/test?A=B&P=1&letoken=mytoken")

        assert r

        assert json_of_latest_request(r) == {"c": "d"}
        assert r[-1].kwargs.get("params", {}).get("A") == "B"
        assert r[-1].kwargs.get("params", {}).get("P") == "1"
        assert r[-1].kwargs.get("params", {}).get("letoken") == "mytoken"

        # unfortunately, the mock library won't report any headers stored on
        # the session object, so we need to verify them separately
        async with endpoint.session() as s:
            assert s._default_headers.get("X-Powered-By") == "Rasa"
            assert s._default_auth.login == "user"
            assert s._default_auth.password == "pass"
예제 #9
0
async def test_http_interpreter():
    with aioresponses() as mocked:
        mocked.post("https://example.com/parse")

        endpoint = EndpointConfig('https://example.com')
        interpreter = RasaNLUHttpInterpreter(endpoint=endpoint)
        await interpreter.parse(text='message_text', message_id='1134')

        r = latest_request(
            mocked, "POST", "https://example.com/parse")

        query = json_of_latest_request(r)
        response = {'project': 'default',
                    'q': 'message_text',
                    'message_id': '1134',
                    'model': None,
                    'token': None}

        assert query == response
예제 #10
0
async def test_console_input():
    from rasa.core.channels import console

    # Overwrites the input() function and when someone else tries to read
    # something from the command line this function gets called.
    with utilities.mocked_cmd_input(console, text="Test Input"):
        with aioresponses() as mocked:
            mocked.post(
                'https://example.com/webhooks/rest/webhook?stream=true',
                repeat=True,
                payload={})

            await console.record_messages(server_url="https://example.com",
                                          max_message_limit=3)

            r = latest_request(
                mocked, 'POST',
                "https://example.com/webhooks/rest/webhook?stream=true")

            assert r

            b = json_of_latest_request(r)

            assert b == {"message": "Test Input", "sender": "default"}
예제 #11
0
async def test_remote_action_logs_events(default_dispatcher_collecting,
                                         default_domain):
    tracker = DialogueStateTracker("default", default_domain.slots)

    endpoint = EndpointConfig("https://example.com/webhooks/actions")
    remote_action = action.RemoteAction("my_action", endpoint)

    response = {
        "events": [{
            "event": "slot",
            "value": "rasa",
            "name": "name"
        }],
        "responses": [{
            "text": "test text",
            "buttons": [{
                "title": "cheap",
                "payload": "cheap"
            }]
        }, {
            "template": "utter_greet"
        }]
    }

    with aioresponses() as mocked:
        mocked.post('https://example.com/webhooks/actions', payload=response)

        events = await remote_action.run(default_dispatcher_collecting,
                                         tracker, default_domain)

        r = latest_request(mocked, 'post',
                           "https://example.com/webhooks/actions")
        assert r

        assert json_of_latest_request(r) == {
            'domain': default_domain.as_dict(),
            'next_action': 'my_action',
            'sender_id': 'default',
            'version': rasa.__version__,
            'tracker': {
                'latest_message': {
                    'entities': [],
                    'intent': {},
                    'text': None
                },
                'active_form': {},
                'latest_action_name': None,
                'sender_id': 'default',
                'paused': False,
                'followup_action': 'action_listen',
                'latest_event_time': None,
                'slots': {
                    'name': None
                },
                'events': [],
                'latest_input_channel': None
            }
        }

    assert events == [SlotSet("name", "rasa")]

    channel = default_dispatcher_collecting.output_channel
    assert channel.messages == [{
        "text":
        "test text",
        "recipient_id":
        "my-sender",
        "buttons": [{
            "title": "cheap",
            "payload": "cheap"
        }]
    }, {
        "text": "hey there None!",
        "recipient_id": "my-sender"
    }]