def test_slackbot_send_attachment_withtext(): from rasa_core.channels.slack import SlackBot httpretty.register_uri(httpretty.POST, 'https://slack.com/api/chat.postMessage', body='{"ok":true,"purpose":"Testing bots"}') httpretty.enable() bot = SlackBot("DummyToken", "General") text = "Sample text" attachment = json.dumps([{ "fallback": "Financial Advisor Summary", "color": "#36a64f", "author_name": "ABE", "title": "Financial Advisor Summary", "title_link": "http://tenfactorialrocks.com", "image_url": "https://r.com/cancel/r12", "thumb_url": "https://r.com/cancel/r12", "actions": [{ "type": "button", "text": "\ud83d\udcc8 Dashboard", "url": "https://r.com/cancel/r12", "style": "primary" }, { "type": "button", "text": "\ud83d\udccb XL", "url": "https://r.com/cancel/r12", "style": "danger" }, { "type": "button", "text": "\ud83d\udce7 E-Mail", "url": "https://r.com/cancel/r123", "style": "danger" }], "footer": "Powered by 1010rocks", "ts": 1531889719 }]) bot.send_attachment("ID", attachment, text) httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body == { 'channel': ['General'], 'as_user': ['True'], 'text': ['Sample text'], 'attachments': [attachment] }
def test_endpoint_config(): endpoint = EndpointConfig("https://abc.defg/", params={"A": "B"}, headers={"X-Powered-By": "Rasa"}, basic_auth={ "username": "******", "password": "******" }, token="mytoken", token_name="letoken") httpretty.register_uri(httpretty.POST, 'https://abc.defg/test', status=500, body='') httpretty.enable() endpoint.request("post", subpath="test", content_type="application/text", json={"c": "d"}, params={"P": "1"}) httpretty.disable() r = httpretty.latest_requests[-1] assert json.loads(str(r.body.decode("utf-8"))) == {"c": "d"} assert r.headers.get("X-Powered-By") == "Rasa" assert r.headers.get("Authorization") == "Basic dXNlcjpwYXNz" assert r.querystring.get("A") == ["B"] assert r.querystring.get("P") == ["1"] assert r.querystring.get("letoken") == ["mytoken"]
def test_remove_bookmark(self): _id = 2 * randrange(1, 500) httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a página funcionar httpretty.register_uri(httpretty.DELETE, 'http://example.com/bookmarks/%d' % _id, body=self.mock_api_content_delete_bookmark) httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/', body=self.mock_api_content_get_bookmarks) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) post_data = { "__operation": "__remove__", "__id": str(_id), "txtTitulo": "Alterado pelo dashboard", "txtUrl": "http://outra.url.com.br/" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(response.context_data['view'].user_message, 'Bookmark removido com sucesso')
def test_create_new_bookmark(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a página funcionar httpretty.register_uri( httpretty.POST, 'http://example.com/bookmarks/', body=self.mock_api_content_create_or_update_bookmark) httpretty.register_uri(httpretty.GET, 'http://example.com/bookmarks/', body=self.mock_api_content_get_bookmarks) httpretty.register_uri( httpretty.GET, 'http://example.com/user/', body= '{"id": 35, "name": "Mock User", "email": "*****@*****.**", "isAdmin": false}' ) post_data = { "txtTitulo": "Criado pelo dashboard", "txtUrl": "http://outra.url.com.br/" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(response.context_data['view'].user_message, 'Bookmark criado com sucesso')
def test_endpoint_config(): endpoint = EndpointConfig( "https://abc.defg/", params={"A": "B"}, headers={"X-Powered-By": "Rasa"}, basic_auth={"username": "******", "password": "******"}, token="mytoken", token_name="letoken" ) httpretty.register_uri( httpretty.POST, 'https://abc.defg/test', status=500, body='') httpretty.enable() endpoint.request("post", subpath="test", content_type="application/text", json={"c": "d"}, params={"P": "1"}) httpretty.disable() r = httpretty.latest_requests[-1] assert json.loads(str(r.body.decode("utf-8"))) == {"c": "d"} assert r.headers.get("X-Powered-By") == "Rasa" assert r.headers.get("Authorization") == "Basic dXNlcjpwYXNz" assert r.querystring.get("A") == ["B"] assert r.querystring.get("P") == ["1"] assert r.querystring.get("letoken") == ["mytoken"]
async def test_slackbot_send_image_url(): from rasa.core.channels.slack import SlackBot httpretty.register_uri( httpretty.POST, "https://slack.com/api/chat.postMessage", body='{"ok":true,"purpose":"Testing bots"}', ) httpretty.enable() bot = SlackBot("DummyToken", "General") url = "http://www.rasa.net" await bot.send_image_url("ID", url) httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body["as_user"] == ["True"] assert r.parsed_body["channel"] == ["General"] assert len(r.parsed_body["blocks"]) == 1 assert '"type": "image"' in r.parsed_body["blocks"][0] assert '"alt_text": "http://www.rasa.net"' in r.parsed_body["blocks"][0] assert '"image_url": "http://www.rasa.net"' in r.parsed_body["blocks"][0]
def test_create_user_password_does_not_match(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/users/', body=self.mock_api_login_or_create_user) httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = { "name": "Fulano de Tal", "email": "*****@*****.**", "password": "******", "confirm_password": "******" } response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() # Verifica se renderizou a página de login novamente self.assertEquals(response.status_code, 200) self.assertEquals(response.resolver_match.url_name, 'sign-in') self.assertEquals(response.context_data['view'].error_message, 'Senhas não conferem')
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'.format( mock_endpoint.url, sender_id) replace_url = '{}/conversations/{}/tracker/events'.format( mock_endpoint.url, sender_id) httpretty.register_uri(httpretty.GET, url, body=tracker_dump) httpretty.register_uri(httpretty.PUT, replace_url) httpretty.enable() online._undo_latest(sender_id, mock_endpoint) httpretty.disable() b = httpretty.latest_requests[-1].body.decode("utf-8") # this should be the events the online call send to the endpoint # these events should have the last utterance omitted replaced_evts = json.loads(b) assert len(replaced_evts) == 6 assert replaced_evts == evts[:6]
def test_telegram_channel(): # telegram channel will try to set a webhook, so we need to mock the api with mock.patch.object(sanic.Sanic, 'run', fake_sanic_run): httpretty.register_uri( httpretty.POST, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook', body='{"ok": true, "result": {}}') httpretty.enable() # START DOC INCLUDE from rasa.core.channels.telegram import TelegramInput from rasa.core.agent import Agent from rasa.core.interpreter import RegexInterpreter # load your trained agent agent = Agent.load(MODEL_PATH, interpreter=RegexInterpreter()) input_channel = TelegramInput( # you get this when setting up a bot access_token="123:YOUR_ACCESS_TOKEN", # this is your bots username verify="YOUR_TELEGRAM_BOT", # the url your bot should listen for messages webhook_url="YOUR_WEBHOOK_URL") s = agent.handle_channels([input_channel], 5004) # END DOC INCLUDE # the above marker marks the end of the code snipped included # in the docs routes_list = utils.list_routes(s) assert routes_list.get("telegram_webhook.health").startswith( "/webhooks/telegram") assert routes_list.get("telegram_webhook.message").startswith( "/webhooks/telegram/webhook") httpretty.disable()
def wrapper(*args, **kwargs): httpretty.enable() fun(*args, **kwargs) httpretty.disable() httpretty.reset()
def test_remote_action_logs_events(default_dispatcher_collecting, default_domain): tracker = DialogueStateTracker("default", default_domain.slots) endpoint = EndpointConfig("https://abc.defg/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"}]} httpretty.register_uri( httpretty.POST, 'https://abc.defg/webhooks/actions', body=json.dumps(response)) httpretty.enable() events = remote_action.run(default_dispatcher_collecting, tracker, default_domain) httpretty.disable() assert (httpretty.latest_requests[-1].path == "/webhooks/actions") b = httpretty.latest_requests[-1].body.decode("utf-8") assert json.loads(b) == { 'domain': default_domain.as_dict(), 'next_action': 'my_action', 'sender_id': 'default', 'tracker': { 'latest_message': { 'entities': [], 'intent': {}, 'text': 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"}]
def test_remote_action_logs_events(default_dispatcher_collecting, default_domain): tracker = DialogueStateTracker("default", default_domain.slots) endpoint = EndpointConfig("https://abc.defg/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"}]} httpretty.register_uri( httpretty.POST, 'https://abc.defg/webhooks/actions', body=json.dumps(response)) httpretty.enable() events = remote_action.run(default_dispatcher_collecting, tracker, default_domain) httpretty.disable() assert (httpretty.latest_requests[-1].path == "/webhooks/actions") b = httpretty.latest_requests[-1].body.decode("utf-8") assert json.loads(b) == { 'domain': default_domain.as_dict(), 'next_action': 'my_action', 'sender_id': 'default', 'tracker': { 'latest_message': { 'entities': [], 'intent': {}, 'text': None }, 'sender_id': 'default', 'paused': False, 'followup_action': 'action_listen', 'latest_event_time': None, 'slots': {'name': None}, 'events': [] } } 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"}]
def test_formbot_example(): sys.path.append("examples/formbot/") p = "examples/formbot/" stories = os.path.join(p, "data", "stories.md") endpoint = EndpointConfig("https://abc.defg/webhooks/actions") endpoints = AvailableEndpoints(action=endpoint) agent = train(os.path.join(p, "domain.yml"), stories, os.path.join(p, "models", "dialogue"), endpoints=endpoints, policy_config="rasa_core/default_config.yml") response = { 'events': [{ 'event': 'form', 'name': 'restaurant_form', 'timestamp': None }, { 'event': 'slot', 'timestamp': None, 'name': 'requested_slot', 'value': 'cuisine' }], 'responses': [{ 'template': 'utter_ask_cuisine' }] } httpretty.register_uri(httpretty.POST, 'https://abc.defg/webhooks/actions', body=json.dumps(response)) httpretty.enable() responses = agent.handle_text("/request_restaurant") httpretty.disable() assert responses[0]['text'] == 'what cuisine?' response = { "error": "Failed to validate slot cuisine with action restaurant_form", "action_name": "restaurant_form" } httpretty.register_uri(httpretty.POST, 'https://abc.defg/webhooks/actions', status=400, body=json.dumps(response)) httpretty.enable() responses = agent.handle_text("/chitchat") httpretty.disable() assert responses[0]['text'] == 'chitchat'
async def test_slackbot_send_attachment_withtext(): from rasa.core.channels.slack import SlackBot httpretty.register_uri( httpretty.POST, "https://slack.com/api/chat.postMessage", body='{"ok":true,"purpose":"Testing bots"}', ) httpretty.enable() bot = SlackBot("DummyToken", "General") kwargs = {"text": "Sample text"} attachment = { "fallback": "Financial Advisor Summary", "color": "#36a64f", "author_name": "ABE", "title": "Financial Advisor Summary", "title_link": "http://tenfactorialrocks.com", "image_url": "https://r.com/cancel/r12", "thumb_url": "https://r.com/cancel/r12", "actions": [ { "type": "button", "text": "\ud83d\udcc8 Dashboard", "url": "https://r.com/cancel/r12", "style": "primary", }, { "type": "button", "text": "\ud83d\udccb XL", "url": "https://r.com/cancel/r12", "style": "danger", }, { "type": "button", "text": "\ud83d\udce7 E-Mail", "url": "https://r.com/cancel/r123", "style": "danger", }, ], "footer": "Powered by 1010rocks", "ts": 1531889719, } await bot.send_attachment("ID", attachment, **kwargs) httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body == { "channel": ["General"], "as_user": ["True"], "text": ["Sample text"], "attachments": [json.dumps([attachment])], }
def test_get_bookmarks_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com erro httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/', status=400) self.assertEquals(self.bookmark_client.get_bookmarks(), []) httpretty.disable() httpretty.reset()
def test_home_status(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertEquals(response.status_code, 200)
def test_home_template(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertEquals(response.template_name, ['home.html'])
def test_login_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com erro - falha no login httpretty.register_uri(httpretty.POST, self.url + '/auth/', status=400) self.assertFalse( self.bookmark_client.login(user='******', password='******')) httpretty.disable() httpretty.reset()
def test_redirect_to_home(self): expected_url = reverse('home') httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() self.assertRedirects(response, expected_url)
def test_get_all_bookmarks_error(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/all/', body=self.mock_api_get_all_bookmarks) self.bookmark_client.token = 'TOKEN_FAKE_NOT_ADMIN' self.assertEquals(self.bookmark_client.get_all_bookmarks(), []) httpretty.disable() httpretty.reset()
def test_swbiodiversity_harvester(): httpretty.enable() httpretty.allow_net_connect = False config = SourceConfig.objects.get(label=('org.swbiodiversity')) url = config.harvester_kwargs['list_url'] harvester = config.get_harvester() httpretty.register_uri(httpretty.GET, url, body=main_page, content_type='text/html', match_querystring=True) collection = furl(url) collection.args['collid'] = 223 httpretty.register_uri(httpretty.GET, url + ';collid=(\d+)', body=collection_page, content_type='text/html', match_querystring=True) start = pendulum.utcnow() - timedelta(days=3) end = pendulum.utcnow() results = harvester.fetch_date_range(start, end) for result in results: assert result.identifier == collection.url assert "".join(result.datum.split()) == "".join(''' <div id="innertext"> <h1>SEINet - Arizona Chapter Collections </h1> <div> Select a collection to see full details. </div> <table style="margin:10px;"> <tr> <td> <h3> <a href="collprofiles.php?collid=223"> A. Michael Powell Herbarium </a> </h3> <div style="margin:10px;"> <div>Sample description</div> <div style="margin-top:5px;"> <b>Contact:</b> Test Author ([email protected]) </div> </div> </td> </tr> </table> </div> ''' "".split()) httpretty.disable()
def test_user_invalid(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/user/', body=self.mock_api_get_user) self.bookmark_client.token = 'ANOTHER_TOKEN' # Token inválido data = self.bookmark_client.get_user() httpretty.disable() httpretty.reset() self.assertEquals(data, {})
def test_login_success(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com token - sucesso no login httpretty.register_uri(httpretty.POST, self.url + '/auth/', body='{"token": "any content"}', content_type="application/json") self.assertTrue( self.bookmark_client.login(user='******', password='******')) httpretty.disable() httpretty.reset()
def test_home_has_bootstrap(self): httpretty.enable() httpretty.allow_net_connect = True httpretty.register_uri(httpretty.GET, 'http://example.com/user/', body=self.mock_api_get_user) response = self.client.get(self.url) httpretty.disable() httpretty.reset() html = response.content.decode('utf-8') self.assertIn('bootstrap.min.css', html) self.assertIn('bootstrap.min.js', html)
def test_delete_bookmark_error(self): _id = 2 * randrange( 1, 500) + 1 # Força número impar - É nossa flag para erro httpretty.enable() httpretty.allow_net_connect = False # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.DELETE, self.url + '/bookmarks/%d' % _id, body=self.mock_api_content_delete_bookmark) self.assertFalse(self.bookmark_client.delete_bookmark(_id)) httpretty.disable() httpretty.reset()
def test_request_prediction(mock_endpoint): sender_id = uuid.uuid4().hex url = '{}/conversations/{}/predict'.format(mock_endpoint.url, sender_id) httpretty.register_uri(httpretty.POST, url, body='{}') httpretty.enable() interactive.request_prediction(mock_endpoint, sender_id) httpretty.disable() b = httpretty.latest_requests[-1].body.decode("utf-8") assert b == ""
def test_login_session(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = {"username": "******", "password": "******"} response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() self.assertEquals(self.client.session['user'], 'FAKE_TOKEN')
def test_is_listening_for_messages(mock_endpoint): tracker_dump = utils.read_file("data/test_trackers/tracker_moodbot.json") sender_id = uuid.uuid4().hex url = '{}/conversations/{}/tracker'.format(mock_endpoint.url, sender_id) httpretty.register_uri(httpretty.GET, url, body=tracker_dump) httpretty.enable() is_listening = online.is_listening_for_message(sender_id, mock_endpoint) httpretty.disable() assert is_listening
def test_get_bookmarks(self): mock_content = [] qtd_bookmarks = randrange(2, 10) for _ in range(qtd_bookmarks): mock_content.append(self.get_fake_bookmark()) httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/bookmarks/', json.dumps(mock_content)) data = self.bookmark_client.get_bookmarks() self.assertEquals(len(data), qtd_bookmarks) httpretty.disable() httpretty.reset()
def test_new_bookmark_error(self): bookmark_title = "" bookmark_url = "" httpretty.enable() httpretty.allow_net_connect = False # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri( httpretty.POST, self.url + '/bookmarks/', body=self.mock_api_content_create_or_update_bookmark) self.assertFalse( self.bookmark_client.new_bookmark(bookmark_title, bookmark_url)) httpretty.disable() httpretty.reset()
def test_login_with_error(self): httpretty.enable() httpretty.allow_net_connect = True # Precisa para a chamada a /login funcionar # mock_api_content_create_bookmark irá retornar sucesso ou erro, dependendo dos parametros httpretty.register_uri(httpretty.POST, 'http://example.com/auth/', body=self.mock_api_login_or_create_user) # Dados habilitados para sucesso no mock post_data = {"username": "******", "password": "******"} response = self.client.post(self.url, post_data) httpretty.disable() httpretty.reset() # Verifica se renderizou a página de login novamente self.assertEquals(response.status_code, 200) self.assertEquals(response.resolver_match.url_name, 'login')
def test_user(self): httpretty.enable() httpretty.allow_net_connect = False # Mock responderá com sucesso httpretty.register_uri(httpretty.GET, self.url + '/user/', body=self.mock_api_get_user) self.bookmark_client.token = 'TOKEN_FAKE_GET_USER' # Token que o mock retorna sucesso data = self.bookmark_client.get_user() httpretty.disable() httpretty.reset() self.assertIn('id', data) self.assertIn('name', data) self.assertIn('email', data) self.assertIn('isAdmin', data)
def test_swbiodiversity_harvester(): httpretty.enable() httpretty.allow_net_connect = False config = SourceConfig.objects.get(label=('org.swbiodiversity')) url = config.harvester_kwargs['list_url'] harvester = config.get_harvester() httpretty.register_uri(httpretty.GET, url, body=main_page, content_type='text/html', match_querystring=True) collection = furl(url) collection.args['collid'] = 223 httpretty.register_uri(httpretty.GET, url + ';collid=(\d+)', body=collection_page, content_type='text/html', match_querystring=True) start = pendulum.utcnow() - timedelta(days=3) end = pendulum.utcnow() results = harvester.fetch_date_range(start, end) for result in results: assert result.identifier == collection.url assert "".join(result.datum.split()) == "".join(''' <div id="innertext"> <h1>SEINet - Arizona Chapter Collections </h1> <div> Select a collection to see full details. </div> <table style="margin:10px;"> <tr> <td> <h3> <a href="collprofiles.php?collid=223"> A. Michael Powell Herbarium </a> </h3> <div style="margin:10px;"> <div>Sample description</div> <div style="margin-top:5px;"> <b>Contact:</b> Test Author ([email protected]) </div> </div> </td> </tr> </table> </div> '''"".split()) httpretty.disable()
def test_slackbot_send_text(): from rasa_core.channels.slack import SlackBot httpretty.register_uri(httpretty.POST, 'https://slack.com/api/chat.postMessage', body='{"ok":true,"purpose":"Testing bots"}') httpretty.enable() bot = SlackBot("DummyToken", "General") bot.send_text_message("ID", "my message") httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body == {'as_user': ['True'], 'channel': ['General'], 'text': ['my message']}
def test_remote_action_runs(default_dispatcher_collecting, default_domain): tracker = DialogueStateTracker("default", default_domain.slots) endpoint = EndpointConfig("https://abc.defg/webhooks/actions") remote_action = action.RemoteAction("my_action", endpoint) httpretty.register_uri( httpretty.POST, 'https://abc.defg/webhooks/actions', body='{"events": [], "responses": []}') httpretty.enable() remote_action.run(default_dispatcher_collecting, tracker, default_domain) httpretty.disable() assert (httpretty.latest_requests[-1].path == "/webhooks/actions") b = httpretty.latest_requests[-1].body.decode("utf-8") assert json.loads(b) == { 'domain': default_domain.as_dict(), 'next_action': 'my_action', 'sender_id': 'default', 'tracker': { 'latest_message': { 'entities': [], 'intent': {}, 'text': None }, 'sender_id': 'default', 'paused': False, 'latest_event_time': None, 'followup_action': 'action_listen', 'slots': {'name': None}, 'events': [] } }
def test_slackbot_send_attachment_withtext(): from rasa_core.channels.slack import SlackBot httpretty.register_uri(httpretty.POST, 'https://slack.com/api/chat.postMessage', body='{"ok":true,"purpose":"Testing bots"}') httpretty.enable() bot = SlackBot("DummyToken", "General") text = "Sample text" attachment = json.dumps([{"fallback": "Financial Advisor Summary", "color": "#36a64f", "author_name": "ABE", "title": "Financial Advisor Summary", "title_link": "http://tenfactorialrocks.com", "image_url": "https://r.com/cancel/r12", "thumb_url": "https://r.com/cancel/r12", "actions": [{"type": "button", "text": "\ud83d\udcc8 Dashboard", "url": "https://r.com/cancel/r12", "style": "primary"}, {"type": "button", "text": "\ud83d\udccb XL", "url": "https://r.com/cancel/r12", "style": "danger"}, {"type": "button", "text": "\ud83d\udce7 E-Mail", "url": "https://r.com/cancel/r123", "style": "danger"}], "footer": "Powered by 1010rocks", "ts": 1531889719}]) bot.send_attachment("ID", attachment, text) httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body == {'channel': ['General'], 'as_user': ['True'], 'text': ['Sample text'], 'attachments': [attachment]}
def test_telegram_channel(): # telegram channel will try to set a webhook, so we need to mock the api httpretty.register_uri( httpretty.POST, 'https://api.telegram.org/bot123:YOUR_ACCESS_TOKEN/setWebhook', body='{"ok": true, "result": {}}') httpretty.enable() from rasa_core.channels.telegram import TelegramInput from rasa_core.agent import Agent from rasa_core.interpreter import RegexInterpreter # load your trained agent agent = Agent.load(MODEL_PATH, interpreter=RegexInterpreter()) input_channel = TelegramInput( # you get this when setting up a bot access_token="123:YOUR_ACCESS_TOKEN", # this is your bots username verify="YOUR_TELEGRAM_BOT", # the url your bot should listen for messages webhook_url="YOUR_WEBHOOK_URL" ) # set serve_forever=False if you want to keep the server running s = agent.handle_channels([input_channel], 5004, serve_forever=False) # END DOC INCLUDE # the above marker marks the end of the code snipped included # in the docs try: assert s.started routes_list = utils.list_routes(s.application) assert routes_list.get("/webhooks/telegram/").startswith( 'telegram_webhook.health') assert routes_list.get("/webhooks/telegram/webhook").startswith( 'telegram_webhook.message') finally: s.stop() httpretty.disable()
def test_remote_action_endpoint_responds_500(default_dispatcher_collecting, default_domain): tracker = DialogueStateTracker("default", default_domain.slots) endpoint = EndpointConfig("https://abc.defg/webhooks/actions") remote_action = action.RemoteAction("my_action", endpoint) httpretty.register_uri( httpretty.POST, 'https://abc.defg/webhooks/actions', status=500, body='') httpretty.enable() with pytest.raises(Exception) as execinfo: remote_action.run(default_dispatcher_collecting, tracker, default_domain) httpretty.disable() assert "Failed to execute custom action." in str(execinfo.value)
def test_slackbot_send_image_url(): from rasa_core.channels.slack import SlackBot httpretty.register_uri(httpretty.POST, 'https://slack.com/api/chat.postMessage', body='{"ok":true,"purpose":"Testing bots"}') httpretty.enable() bot = SlackBot("DummyToken", "General") url = json.dumps([{"URL": "http://www.rasa.net"}]) bot.send_image_url("ID", url) httpretty.disable() r = httpretty.latest_requests[-1] assert r.parsed_body['as_user'] == ['True'] assert r.parsed_body['channel'] == ['General'] assert len(r.parsed_body['attachments']) == 1 assert '"text": ""' in r.parsed_body['attachments'][0] assert '"image_url": "[{\\"URL\\": \\"http://www.rasa.net\\"}]"' \ in r.parsed_body['attachments'][0]
def test_console_input(): import rasa_core.channels.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(rasa_core.channels.console, text="Test Input"): httpretty.register_uri(httpretty.POST, 'https://abc.defg/webhooks/rest/webhook', body='') httpretty.enable() console.record_messages( server_url="https://abc.defg", max_message_limit=3) httpretty.disable() assert (httpretty.latest_requests[-1].path == "/webhooks/rest/webhook?stream=true&token=") b = httpretty.latest_requests[-1].body.decode("utf-8") assert json.loads(b) == {"message": "Test Input", "sender": "default"}
def httpretty(): httpretty_class.reset() httpretty_class.enable() httpretty_class.allow_net_connect = False yield httpretty_class httpretty_class.disable()
def tearDown(self): httpretty.disable()