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 wrapper(*args, **kwargs): httpretty.enable() fun(*args, **kwargs) httpretty.disable() httpretty.reset()
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 testPostJsonFromFile(self): """ Test that we are able to send json data through a file :return: """ def request_callback(request, url, headers): data = json.loads(request.body.decode()) if "title" in data and "body" in data and "userId" in data: return 200, headers, "all key received from URL %s" % url return 400, headers, "server did not receive all keys from URL %s" % url httpretty.enable() httpretty.register_uri(httpretty.POST, self.test_url, body=request_callback) parameters = { "url": self.test_url, "method": "POST", "data_from_file": "brain/neurons/uri/tests/data_post_test.json", "headers": { "Content-Type": 'application/json' } } with mock.patch.object(NeuronModule, 'say', return_value=None) as mock_method: uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.status_code, 200)
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_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 testPostJson(self): """ Test that we are able to send json data directly from the data variable :return: """ def request_callback(request, url, headers): data = json.loads(request.body.decode()) if "title" in data and "body" in data and "userId" in data: return 200, headers, "all key received from URL %s" % url return 400, headers, "server did not receive all keys from URL %s" % url httpretty.enable() httpretty.register_uri(httpretty.POST, self.test_url, body=request_callback) parameters = { "url": self.test_url, "method": "POST", "data": "{\"id\": 1,\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}", "headers": { "Content-Type": 'application/json' } } with mock.patch.object(NeuronModule, 'say', return_value=None) as mock_method: uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.status_code, 200)
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_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_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')
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_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 test_restores_files(test_repo): organisation = "hmrc-digital" httpretty.enable(allow_net_connect=False) httpretty.reset() with_packages(organisation) with_package_metadata(organisation) with_package_file_metadata(organisation) with_create_packages(organisation) with_file_upload(organisation) restore( username="******", token="hdiasjnhd", organisation=organisation, repositories=[TEST_REPO], ) assert len(package_created_requests(httpretty, organisation)) == 2 assert_package_created( httpretty, organisation, { "name": "fake_package_3", "licenses": ["Apache-2.0"], "vcs_url": "https://github.com/hmrc/fake_package_3", "desc": "a description", "labels": ["something"], "website_url": "example.com", "issue_tracker_url": "example.com", "github_repo": "hmrc/vat-registration", "github_release_notes_file": "README.md", }, ) assert_package_created( httpretty, organisation, { "name": "fake_package_4", "licenses": ["Apache-2.0"], "vcs_url": "https://github.com/hmrc", "desc": None, "labels": None, "website_url": None, "issue_tracker_url": None, "github_repo": None, "github_release_notes_file": None, }, ) uploads = file_uploaded_requests(httpretty) assert len(uploads) == 3 assert (any( x.path == "/api/v1/content/hmrc-digital/repo-to-check/fake_package_4/0.0.1/this/is/my/path/foo.txt?publish=1&override=1" for x in uploads)) assert uploads[0].body == b"this is a test file" assert (any( x.path == "/api/v1/content/hmrc-digital/repo-to-check/fake_package_2/0.0.1/this/is/my/path/foo.txt?publish=1&override=1" for x in uploads)) assert uploads[1].body == b"this is a test file"
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 projects(self, users, flights): httpretty.enable() httpretty.register_uri( httpretty.POST, "http://container-geoserver:8080/geoserver/rest/workspaces", "") p1 = users[0].user_projects.create(name="proj1") p1.flights.add(flights[0]) return p1,
def setup_class(self): super().setup_class( self ) # HACK: Required to get the FLightsMixin setup_class code to trigger httpretty.enable() httpretty.register_uri( httpretty.POST, "http://container-geoserver:8080/geoserver/rest/workspaces", "")
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 testGetRaw(self): expected_content = 'raw line' httpretty.enable() httpretty.register_uri(httpretty.GET, self.test_url, body=expected_content) parameters = {"url": self.test_url} uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.content, expected_content)
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_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_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_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_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_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_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_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 testPatch(self): expected_content = '{"voice": "nico"}' httpretty.enable() httpretty.register_uri(httpretty.PATCH, self.test_url, body=expected_content) parameters = {"url": self.test_url, "method": "PATCH"} uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.text, expected_content)
def testHead(self): expected_content = '{"voice": "nico"}' httpretty.enable() httpretty.register_uri(httpretty.HEAD, self.test_url, body=expected_content) parameters = {"url": self.test_url, "method": "HEAD"} uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.status_code, 200)
def testGet(self): expected_content = '{"voice": "nico"}' httpretty.enable() httpretty.register_uri(httpretty.GET, self.test_url, body=expected_content) parameters = {"url": self.test_url} uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.text, expected_content)
def testGetRaw(self): expected_content = b'raw line' httpretty.enable() httpretty.register_uri(httpretty.GET, self.test_url, body=expected_content) parameters = { "url": self.test_url } with mock.patch.object(NeuronModule, 'say', return_value=None) as mock_method: uri_neuron = Uri(**parameters) self.assertEqual(uri_neuron.content, expected_content)
def flights(self, users): httpretty.enable() httpretty.register_uri(httpretty.POST, "http://container-nodeodm:3000/task/new/init") httpretty.register_uri( httpretty.POST, re.compile(r"http://container-webhook-adapter:8080/register/.+")) f1 = users[0].flight_set.create(name="flight1", date=datetime.now()) f1.camera = Camera.REDEDGE.name f1.save() return f1,
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_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_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_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_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 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_duckling_entity_extractor(component_builder): httpretty.register_uri( httpretty.POST, "http://localhost:8000/parse", body="""[{"body":"Today","start":0,"value":{"values":[{ "value":"2018-11-13T00:00:00.000-08:00","grain":"day", "type":"value"}],"value":"2018-11-13T00:00:00.000-08:00", "grain":"day","type":"value"},"end":5, "dim":"time","latent":false},{"body":"the 5th","start":9, "value":{"values":[{ "value":"2018-12-05T00:00:00.000-08:00","grain":"day", "type":"value"}, {"value":"2019-01-05T00:00:00.000-08:00","grain":"day", "type":"value"}, {"value":"2019-02-05T00:00:00.000-08:00","grain":"day", "type":"value"}], "value":"2018-12-05T00:00:00.000-08:00","grain":"day", "type":"value"},"end":16,"dim":"time", "latent":false},{"body":"5th of May","start":13,"value":{ "values":[{ "value":"2019-05-05T00:00:00.000-07:00","grain":"day", "type":"value"}, {"value":"2020-05-05T00:00:00.000-07:00","grain":"day", "type":"value"}, {"value":"2021-05-05T00:00:00.000-07:00","grain":"day", "type":"value"}], "value":"2019-05-05T00:00:00.000-07:00","grain":"day", "type":"value"},"end":23,"dim":"time", "latent":false},{"body":"tomorrow","start":37,"value":{ "values":[{ "value":"2018-11-14T00:00:00.000-08:00","grain":"day", "type":"value"}], "value":"2018-11-14T00:00:00.000-08:00","grain":"day", "type":"value"},"end":45,"dim":"time", "latent":false}]""" ) httpretty.enable() _config = RasaNLUModelConfig( {"pipeline": [{"name": "DucklingHTTPExtractor"}]} ) _config.set_component_attr(0, dimensions=["time"], timezone="UTC", url="http://localhost:8000") duckling = component_builder.create_component(_config.for_component(0), _config) message = Message("Today is the 5th of May. Let us meet tomorrow.") duckling.process(message) entities = message.get("entities") assert len(entities) == 4 # Test duckling with a defined date httpretty.register_uri( httpretty.POST, "http://localhost:8000/parse", body="""[{"body":"tomorrow","start":12,"value":{"values":[{ "value":"2013-10-13T00:00:00.000Z","grain":"day", "type":"value"}],"value":"2013-10-13T00:00:00.000Z", "grain":"day","type":"value"},"end":20, "dim":"time","latent":false}]""" ) # 1381536182 == 2013/10/12 02:03:02 message = Message("Let us meet tomorrow.", time="1381536182") duckling.process(message) entities = message.get("entities") assert len(entities) == 1 assert entities[0]["text"] == "tomorrow" assert entities[0]["value"] == "2013-10-13T00:00:00.000Z" # Test dimension filtering includes only specified dimensions _config = RasaNLUModelConfig( {"pipeline": [{"name": "DucklingHTTPExtractor"}]} ) _config.set_component_attr(0, dimensions=["number"], url="http://localhost:8000") ducklingNumber = component_builder.create_component( _config.for_component(0), _config) httpretty.register_uri( httpretty.POST, "http://localhost:8000/parse", body="""[{"body":"Yesterday","start":0,"value":{"values":[{ "value":"2019-02-28T00:00:00.000+01:00","grain":"day", "type":"value"}],"value":"2019-02-28T00:00:00.000+01:00", "grain":"day","type":"value"},"end":9,"dim":"time"}, {"body":"5","start":21,"value":{"value":5,"type":"value"}, "end":22,"dim":"number"}]""" ) message = Message("Yesterday there were 5 people in a room") ducklingNumber.process(message) entities = message.get("entities") assert len(entities) == 1 assert entities[0]["text"] == "5" assert entities[0]["value"] == 5
def setUp(self): httpretty.reset() httpretty.enable()
def httpretty(): httpretty_class.reset() httpretty_class.enable() httpretty_class.allow_net_connect = False yield httpretty_class httpretty_class.disable()