예제 #1
0
 def test_prepare_response_invalid_response_json(self):
     json_as_string = "Not a json string"
     try:
         ActionUtility.prepare_response("The value of ${a.b.3} in ${a.b.d.0} is ${a.b.c}", json_as_string)
         assert False
     except HttpActionFailure as e:
         assert str(e) == 'Could not find value for keys in response'
예제 #2
0
 def test_prepare_response_string_empty_request_output(self):
     json1 = json.dumps("{}")
     try:
         ActionUtility.prepare_response("The value of ${a.b.3} in ${a.b.d.0} is ${a.b.e}", json1)
         assert False
     except HttpActionFailure:
         assert True
예제 #3
0
 def test_get_http_action_no_bot(self):
     try:
         ActionUtility.get_http_action_config(bot=None,
                                              action_name="http_action")
         assert False
     except HttpActionFailure as ex:
         assert str(ex) == "Bot name and action name are required"
예제 #4
0
 def test_prepare_request_empty_slot(self):
     slots = {
         "bot": "demo_bot",
         "http_action_config": "http_action_name",
         "param2": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     http_action_config_params = [
         HttpActionRequestBody(key="param1", value="value1"),
         HttpActionRequestBody(key="param3",
                               value="",
                               parameter_type="slot")
     ]
     tracker = Tracker(sender_id="sender1",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=None,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     try:
         ActionUtility.prepare_request(
             tracker=tracker,
             http_action_config_params=http_action_config_params)
         assert False
     except HttpActionFailure as ex:
         assert str(ex) == ("Coudn't find value for key param3 from slot")
예제 #5
0
    def test_prepare_response(self):
        json1 = json.dumps({
            "a": {
                "b": {
                    "3": 2,
                    "43": 30,
                    "c": [],
                    "d": ['red', 'buggy', 'bumpers'],
                }
            }
        })
        response = ActionUtility.prepare_response("The value of ${a.b.3} in ${a.b.d.0} is ${a.b.c}", json1)
        assert response == 'The value of 2 in red is []'

        json2 = json.dumps({
            "data": [
                {"a": {
                    "b": {
                        "43": 30,
                        "c": [],
                        "d": ['red', 'buggy', 'bumpers'],
                    }}},
                {"a": {
                    "b": {
                        "43": 5,
                        "c": [1, 2],
                        "d": ['buggy', 'bumpers'],
                    }}}
            ]
        })
        response = ActionUtility.prepare_response("The value of ${data.0.a} in ${data.0.a.b} is ${data.0.a.b.d}", json2)
        assert response == 'The value of {"b": {"43": 30, "c": [], "d": ["red", "buggy", "bumpers"]}} in {"43": 30, "c": [], "d": ["red", "buggy", "bumpers"]} is [\'red\', \'buggy\', \'bumpers\']'
예제 #6
0
 def test_get_http_action_invalid_db_url(self):
     disconnect()
     try:
         ActionUtility.get_http_action_config("mongodb://localhost:8000/test", "bot", "http_action")
         assert False
     except HttpActionFailure:
         assert True
예제 #7
0
 def test_get_http_action_no_http_action(self):
     try:
         ActionUtility.get_http_action_config(db_url=pytest.db_url,
                                              bot="bot",
                                              action_name=None)
         assert False
     except HttpActionFailure as ex:
         assert str(
             ex) == "Database url, bot name and action name are required"
예제 #8
0
    def validate(self, clean=True):
        from kairon.action_server.actions import ActionUtility

        if ActionUtility.is_empty(self.key):
            raise ValidationError(
                "key in http action parameters cannot be empty")
        if self.parameter_type == "slot" and ActionUtility.is_empty(
                self.value):
            raise ValueError("Provide name of the slot as value")
예제 #9
0
    def test_execute_http_request_delete_no_auth_token(self):
        http_url = 'http://localhost:8080/mock'
        resp_msg = "Data updated successfully"
        request_params = {
            'data': 'test_data',
            'test_class': [{
                'key': 'value'
            }, {
                'key2': 'value2'
            }]
        }

        responses.add(method=responses.DELETE,
                      url=http_url,
                      body=resp_msg,
                      status=200,
                      match=[responses.json_params_matcher(request_params)])

        response = ActionUtility.execute_http_request(
            auth_token=None,
            http_url=http_url,
            request_method=responses.DELETE,
            request_body=request_params)
        assert response
        assert response == resp_msg
        assert 'Authorization' not in responses.calls[0].request.headers
예제 #10
0
    def test_execute_http_request_post_with_auth_token(self):
        http_url = 'http://localhost:8080/mock'
        auth_token = "bearer jkhfhkujsfsfslfhjsfhkjsfhskhfksj"
        resp_msg = "Data added successfully"
        request_params = {
            'data': 'test_data',
            'test_class': [{
                'key': 'value'
            }, {
                'key2': 'value2'
            }]
        }

        responses.add(method=responses.POST,
                      url=http_url,
                      body=resp_msg,
                      status=200,
                      match=[responses.json_params_matcher(request_params)])

        response = ActionUtility.execute_http_request(
            auth_token=auth_token,
            http_url=http_url,
            request_method=responses.POST,
            request_body=request_params)
        assert response
        assert response == resp_msg
        assert responses.calls[0].request.headers[
            'Authorization'] == auth_token
예제 #11
0
    def test_execute_http_request_getWith_auth_token(self):
        http_url = 'http://localhost:8080/mock'
        # file deepcode ignore HardcodedNonCryptoSecret: Random string for testing
        auth_token = "bearer jkhfhkujsfsfslfhjsfhkjsfhskhfksj"

        responses.add(method=responses.GET,
                      url=http_url,
                      json={
                          'data': 'test_data',
                          'test_class': [{
                              'key': 'value'
                          }, {
                              'key2': 'value2'
                          }]
                      },
                      status=200)

        response = ActionUtility.execute_http_request(
            auth_token=auth_token,
            http_url=http_url,
            request_method=responses.GET)
        assert response
        assert response['data'] == 'test_data'
        assert len(response['test_class']) == 2
        assert response['test_class'][1]['key2'] == 'value2'
        assert responses.calls[0].request.headers[
            'Authorization'] == auth_token
예제 #12
0
    def test_get_http_action_config(self):
        http_params = [HttpActionRequestBody(key="key1", value="value1", parameter_type="slot"),
                       HttpActionRequestBody(key="key2", value="value2")]
        expected = HttpActionConfig(
            auth_token="bearer kjflksjflksajfljsdflinlsufisnflisjbjsdalibvs",
            action_name="http_action",
            response="json",
            http_url="http://test.com",
            request_method="GET",
            params_list=http_params,
            bot="bot",
            user="******"
        ).save().to_mongo().to_dict()

        actual = ActionUtility.get_http_action_config("bot", "http_action")
        assert actual is not None
        assert expected['auth_token'] == actual['auth_token']
        assert expected['action_name'] == actual['action_name']
        assert expected['response'] == actual['response']
        assert expected['http_url'] == actual['http_url']
        assert expected['request_method'] == actual['request_method']
        assert expected['params_list'] is not None
        assert expected['params_list'][0]['key'] == actual['params_list'][0]['key']
        assert expected['params_list'][0]['value'] == actual['params_list'][0]['value']
        assert expected['params_list'][0]['parameter_type'] == actual['params_list'][0]['parameter_type']
        assert expected['params_list'][1]['key'] == actual['params_list'][1]['key']
        assert expected['params_list'][1]['value'] == actual['params_list'][1]['value']
        assert expected['params_list'][1]['parameter_type'] == actual['params_list'][1]['parameter_type']
        assert actual['status']
예제 #13
0
 def test_prepare_request(self):
     slots = {
         "bot": "demo_bot",
         "http_action_config": "http_action_name",
         "slot_name": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     http_action_config_params = [
         HttpActionRequestBody(key="param1", value="value1"),
         HttpActionRequestBody(key="param2",
                               value="slot_name",
                               parameter_type="slot")
     ]
     tracker = Tracker(sender_id="sender1",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=None,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     actual_request_body = ActionUtility.prepare_request(
         tracker=tracker,
         http_action_config_params=http_action_config_params)
     assert actual_request_body
     assert actual_request_body['param1'] == 'value1'
     assert actual_request_body['param2'] == 'param2value'
예제 #14
0
 def test_prepare_request_sender_id(self):
     slots = {
         "bot": "demo_bot",
         "http_action_config": "http_action_name",
         "param2": "param2value"
     }
     events = [{"event1": "hello"}, {"event2": "how are you"}]
     http_action_config_params = [
         HttpActionRequestBody(key="param1", value="value1"),
         HttpActionRequestBody(key="user_id",
                               value="",
                               parameter_type="sender_id")
     ]
     tracker = Tracker(sender_id="*****@*****.**",
                       slots=slots,
                       events=events,
                       paused=False,
                       latest_message=None,
                       followup_action=None,
                       active_loop=None,
                       latest_action_name=None)
     request_params = ActionUtility.prepare_request(
         tracker=tracker,
         http_action_config_params=http_action_config_params)
     assert request_params['param1'] == "value1"
     assert request_params['user_id'] == "*****@*****.**"
예제 #15
0
 def test_prepare_response_key_not_present(self):
     json1 = json.dumps({
         "a": {
             "b": {
                 "3": 2,
                 "43": 30,
                 "c": [],
                 "d": ['red', 'buggy', 'bumpers'],
             }
         }
     })
     try:
         ActionUtility.prepare_response("The value of ${a.b.3} in ${a.b.d.0} is ${a.b.e}", json1)
         assert False
     except HttpActionFailure:
         assert True
예제 #16
0
    def test_get_http_action_no_request_body(self):
        http_params = []
        HttpActionConfig(
            auth_token="bearer kjflksjflksajfljsdflinlsufisnflisjbjsdalibvs",
            action_name="http_action",
            response="json",
            http_url="http://test.com",
            request_method="GET",
            params_list=http_params,
            bot="bot",
            user="******").save().to_mongo().to_dict()

        try:
            ActionUtility.get_http_action_config("bot", "http_action1")
            assert False
        except HttpActionFailure as ex:
            assert str(ex).__contains__("No HTTP action found for bot")
예제 #17
0
 def test_retrieve_value_from_response_invalid_key(self):
     keys = ["d.e.f", 'g.h']
     resp_msg = {
         "a": {
             "b": {
                 "3": 2,
                 "43": 30,
                 "c": [],
                 "d": ['red', 'buggy', 'bumpers'],
             }
         }
     }
     try:
         ActionUtility.retrieve_value_from_response(keys, resp_msg)
         assert False
     except HttpActionFailure as e:
         assert str(e) == 'Unable to retrieve value for key from HTTP response: \'d\''
예제 #18
0
    def validate(self, clean=True):
        from kairon.action_server.actions import ActionUtility

        if self.parameter_type == "value" and ActionUtility.is_empty(
                self.value):
            raise ValidationError(
                "Either value for the key should be given or parameter_type should be set to slot"
            )
예제 #19
0
    def test_get_http_action_invalid_http_action(self):
        http_params = [HttpActionRequestBody(key="key1", value="value1", parameter_type="slot"),
                       HttpActionRequestBody(key="key2", value="value2")]
        HttpActionConfig(
            auth_token="bearer kjflksjflksajfljsdflinlsufisnflisjbjsdalibvs",
            action_name="http_action",
            response="json",
            http_url="http://test.com",
            request_method="GET",
            params_list=http_params,
            bot="bot",
            user="******"
        ).save().to_mongo().to_dict()

        try:
            ActionUtility.get_http_action_config(pytest.db_url, "bot", "http_action1")
            assert False
        except HttpActionFailure as ex:
            assert str(ex).__contains__("No HTTP action found for bot")
예제 #20
0
 def test_prepare_request_no_request_params(self):
     slots = {"bot": "demo_bot", "http_action_config": "http_action_name", "param2": "param2value"}
     events: List[Dict] = None
     http_action_config_params: List[HttpActionRequestBody] = None
     tracker = Tracker(sender_id="sender1", slots=slots, events=events, paused=False, latest_message=None,
                       followup_action=None, active_loop=None, latest_action_name=None)
     actual_request_body = ActionUtility.prepare_request(tracker=tracker,
                                                         http_action_config_params=http_action_config_params)
     #  deepcode ignore C1801: empty request body for http request with no request body params
     assert len(actual_request_body) == 0
예제 #21
0
 def test_prepare_response_string_response(self):
     json1 = json.dumps({
         "a": {
             "b": {
                 "3": 2,
                 "43": 30,
                 "c": [],
                 "d": ['red', 'buggy', 'bumpers'],
             }
         }
     })
     response = ActionUtility.prepare_response("The value of red is 0", json1)
     assert response == "The value of red is 0"
예제 #22
0
 def test_prepare_response_string_empty_response_string(self):
     json1 = json.dumps({
         "a": {
             "b": {
                 "3": 2,
                 "43": 30,
                 "c": [],
                 "d": ['red', 'buggy', 'bumpers'],
             }
         }
     })
     response = ActionUtility.prepare_response("", json1)
     assert response == '{"a": {"b": {"3": 2, "43": 30, "c": [], "d": ["red", "buggy", "bumpers"]}}}'
예제 #23
0
    def test_execute_http_request_get_no_auth_token(self):
        http_url = 'http://localhost:8080/mock'
        responses.add(
            method=responses.GET,
            url=http_url,
            json={'data': 'test_data', 'test_class': [{'key': 'value'}, {'key2': 'value2'}]},
            status=200
        )

        response = ActionUtility.execute_http_request(auth_token=None, http_url=http_url,
                                                      request_method=responses.GET)
        assert response
        assert response['data'] == 'test_data'
        assert len(response['test_class']) == 2
        assert response['test_class'][1]['key2'] == 'value2'
        assert 'Authorization' not in responses.calls[0].request.headers
예제 #24
0
    def test_execute_http_request_delete_with_auth_token_no_request_body(self):
        http_url = 'http://localhost:8080/mock'
        auth_token = "bearer jkhfhkujsfsfslfhjsfhkjsfhskhfksj"
        resp_msg = "Data deleted successfully"

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

        response = ActionUtility.execute_http_request(auth_token=auth_token, http_url=http_url,
                                                      request_method=responses.DELETE, request_body=None)
        assert response
        assert response == resp_msg
        assert responses.calls[0].request.headers['Authorization'] == auth_token
예제 #25
0
 def test_retrieve_value_from_response(self):
     keys = ["a.b.3", 'a.b']
     resp_msg = {
         "a": {
             "b": {
                 "3": 2,
                 "43": 30,
                 "c": [],
                 "d": ['red', 'buggy', 'bumpers'],
             }
         }
     }
     key_values = ActionUtility.retrieve_value_from_response(keys, resp_msg)
     assert key_values is not None
     assert key_values['${a.b.3}'] == 2
     assert key_values['${a.b}'] is not None
     assert key_values['${a.b}']['3'] == 2
     assert key_values['${a.b}']['d'][0] == 'red'
예제 #26
0
 def test_prepare_response_as_string_and_expected_as_none(self):
     response = ActionUtility.prepare_response(
         "The value of 2 in red is []", None)
     assert response == 'The value of 2 in red is []'
예제 #27
0
 def test_prepare_response_as_json_and_expected_as_plain_string(self):
     json_as_string = "Not a json string"
     response = ActionUtility.prepare_response(
         "The value of 2 in red is []", json_as_string)
     assert response == 'The value of 2 in red is []'
예제 #28
0
 def test_is_empty(self):
     assert ActionUtility.is_empty("")
     assert ActionUtility.is_empty("  ")
     assert ActionUtility.is_empty(None)
     assert not ActionUtility.is_empty("None")
예제 #29
0
 def test_attach_response(self):
     output = ActionUtility.attach_response("I want $${RESPONSE}",
                                            {"dollars": "51"})
     assert output == 'I want ${\'dollars\': \'51\'}'
예제 #30
0
 def test_attach_response_int(self):
     output = ActionUtility.attach_response("I want $${RESPONSE}", 51)
     assert output == 'I want $51'