def test_functional(self):
     response = self.client.get('/auth/login/appsfuel/')
     self.assertEqual(response.status_code, 302)
     location = urlparse(response['Location'])
     self.assertEqual(location.hostname, 'app.appsfuel.com')
     self.assertEqual(location.path, '/content/permission')
     qs = parse_qs(location.query)
     self.assertEqual(qs.keys(), ['state', 'redirect_uri', 'response_type', 'client_id'])
     self.assertTrue(qs['redirect_uri'][0].startswith('http://testserver/auth/complete/appsfuel/?redirect_state='))
     self.assertEqual(qs['response_type'][0], 'code')
     self.assertEqual(qs['client_id'][0], settings.APPSFUEL_CLIENT_ID)
     httpretty.register_uri(
         method=httpretty.POST,
         uri='https://api.appsfuel.com/v1/live/oauth/token',
         body='{"status" : "ok", "access_token" : "<access-token>",  "expire_in" : 28800}',
         content_type="application/json",
     )
     httpretty.register_uri(
         method=httpretty.GET,
         uri='https://api.appsfuel.com/v1/live/user?access_token=%3Caccess-token%3E',
         body='{"user_id": "<user-id>", "is_paid": false, "status":"ok", "display_name": "Im A Test", "email": "*****@*****.**"}',
         content_type="application/json",
     )
     response = self.client.get(qs['redirect_uri'][0] + '&code=imareqtoken')
     self.assertEqual(len(httpretty.latest_requests), 2)
     self.assertEqual(parse_qs(httpretty.latest_requests[0].body).keys(), ['client_secret', 'code', 'redirect_uri', 'client_id', 'grant_type'])
     self.assertEqual(httpretty.latest_requests[1].body, '')
     self.assertEqual(response.status_code, 302)
     self.assertEqual(response['Location'], 'http://testserver/accounts/profile/')
     user = get_user_model().objects.get()
     self.assertEqual(user.username, 'test')
     self.assertEqual(user.first_name, 'Im A Test')
     self.assertEqual(user.last_name, '')
     self.assertEqual(user.email, '*****@*****.**')
Exemplo n.º 2
0
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"]
Exemplo n.º 3
0
 def __enter__(self):
     hr_core.POTENTIAL_HTTP_PORTS.add(
         8081)  # FIXME should depend on self.expected_requests
     # noinspection PyProtectedMember
     self.old_httpretty_entries = httpretty._entries.copy(
     )  # FIXME accessing private properties of httpretty
     for request in self.expected_requests:
         httpretty.register_uri(**request)
Exemplo n.º 4
0
 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", "")
Exemplo n.º 6
0
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"}]
Exemplo n.º 7
0
 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_redmine_failure(self, logger_mock):
        httpretty.register_uri(httpretty.PUT, re.compile("http://example.com/issues/(\d+).json"),
                               status=500,
                               body='Sorry, we are unavailable')
        response = self.client.post(data=self.valid_data)

        assert response.status_code == 200, response.data
        assert response.data == 'ERROR', response.data
        logger_mock.error.assert_called_with('Redmine update failed: [500] Sorry, we are unavailable')
Exemplo n.º 9
0
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'
Exemplo n.º 10
0
def test_slackbot_send_attachment_only():
    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")
    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 Download XL",
            "url": "https://r.com/cancel/r12",
            "style": "danger"
        }, {
            "type": "button",
            "text": "\ud83d\udce7 E-Mail",
            "url": "https://r.com/cancel/r12",
            "style": "danger"
        }],
        "footer":
        "Powered by 1010rocks",
        "ts":
        1531889719
    }])
    bot.send_attachment("ID", attachment)

    httpretty.disable()

    r = httpretty.latest_requests[-1]

    assert r.parsed_body == {
        'channel': ['General'],
        'as_user': ['True'],
        'attachments': [attachment]
    }
Exemplo n.º 11
0
def with_file_upload(organisation):
    httpretty.register_uri(
        httpretty.PUT,
        re.compile(
            f"https://bintray.com/api/v1/content/{organisation}/{TEST_REPO}/.*"
        ),  # ?publish=1&override=1
        status=200,
        body="{}",
    )
Exemplo n.º 12
0
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])],
    }
Exemplo n.º 13
0
 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)
Exemplo n.º 14
0
 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'])
Exemplo n.º 15
0
 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()
Exemplo n.º 16
0
 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()
Exemplo n.º 17
0
    def test_get_postcode(self):
        body = {"Test": "Data"}
        httpretty.register_uri(
            httpretty.GET,
            OPEN_POSTCODE_GET.format(postcode=self.test_postcode),
            body=dumps(body))

        postcode = get_postcode(self.test_postcode)

        self.assertEqual(body, postcode)
Exemplo n.º 18
0
    def test_get_postcode_exception(self):
        httpretty.register_uri(
            httpretty.GET,
            OPEN_POSTCODE_GET.format(postcode=self.test_postcode),
            status=500,
            body="")

        with self.assertRaises(ServiceError) as e:
            get_postcode(self.test_postcode)
            self.assertEqual(e.service, SERVICE_NAME)
Exemplo n.º 19
0
def with_create_packages(organisation):
    httpretty.register_uri(
        httpretty.POST,
        f"https://bintray.com/api/v1/packages/{organisation}/{TEST_REPO}",
        status=201,
        adding_headers={
            "Content-Type": "application/json",
        },
        body=json.dumps({}),
    )
Exemplo n.º 20
0
    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)
Exemplo n.º 21
0
    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)
Exemplo n.º 22
0
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()
Exemplo n.º 23
0
 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,
Exemplo n.º 24
0
 def test_upload_images_admin(self, c, users, flights, fs):
     self._auth(c, users[2])
     httpretty.register_uri(
         httpretty.POST, "http://container-nodeodm:3000/task/new/upload/" +
         str(flights[0].uuid), "")
     httpretty.register_uri(
         httpretty.POST, "http://container-nodeodm:3000/task/new/commit/" +
         str(flights[0].uuid), "")
     resp = c.post(reverse('upload_files', kwargs={"uuid":
                                                   flights[0].uuid}))
     assert resp.status_code == 200
Exemplo n.º 25
0
    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)
Exemplo n.º 26
0
    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)
Exemplo n.º 27
0
 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)
Exemplo n.º 28
0
 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()
Exemplo n.º 29
0
    def test_get_postcode_not_found(self):
        the_message = "the message"
        httpretty.register_uri(
            httpretty.GET,
            OPEN_POSTCODE_GET.format(postcode=self.test_postcode),
            status=404,
            body='{{"error": "{msg}"}}'.format(msg=the_message))

        with self.assertRaises(ValueError) as e:
            get_postcode(self.test_postcode)
            self.assertEqual(str(e), the_message)
Exemplo n.º 30
0
 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()
Exemplo n.º 31
0
 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()
Exemplo n.º 32
0
 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)
Exemplo n.º 33
0
 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_api_calls_to_redmine(self):
        httpretty.register_uri(httpretty.PUT, re.compile("http://example.com/issues/(\d+).json"), status=200)

        response = self.client.post(data=self.valid_data)

        assert response.status_code == 200, response.data
        assert response.data == 'OK', response.data
        assert len(httpretty.latest_requests) == 2

        assert httpretty.latest_requests[-2].path == '/issues/777.json'
        json_post = json.loads(httpretty.latest_requests[-2].body)
        assert json_post['issue']['notes'] == 'Deployed on TestServer at 2006-04-07 22:13:13 in release \"42\":http://jenkins_url/jobs/2/'

        assert httpretty.last_request.path == '/issues/123.json'
        json_post = json.loads(httpretty.last_request.body)
        assert json_post['issue']['notes'] == 'Deployed on TestServer at 2006-04-07 22:13:13 in release \"42\":http://jenkins_url/jobs/2/'
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_client_sent_data(self):
        httpretty.register_uri(httpretty.POST, "http://releasedate-server/", body='OK')
        ci.cli('http://releasedate-server/', '/path/to/my/repo/')
        check_against = {
            'build_number': ['42'],
            'build_tag': ['jenkins-myjob-42'],
            'previous_tag': ['jenkins-myjob-41'],
            'job_url': ['http://jenkins_url/jobs/42/'],
            'repo': ['/path/to/my/repo/'],
        }

        self.assertBodyQueryString(**check_against)

        output = ci.cli('http://releasedate-server/', '/path/to/my/repo/', 'myserver')
        assert 'OK' in output
        check_against['instance'] = ['myserver']
        self.assertBodyQueryString(**check_against)
Exemplo n.º 37
0
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']}
Exemplo n.º 38
0
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': []
        }
    }
Exemplo n.º 39
0
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]}
Exemplo n.º 40
0
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()
Exemplo n.º 41
0
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)
Exemplo n.º 42
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"}
Exemplo n.º 43
0
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]
Exemplo n.º 44
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