def test_authenticator_auth_error(self):
     """
     Fail if keys are not provided.
     """
     with pytest.raises(KeyError):
         auth = IBMCloudFoundryAuthenticator("url", {"cf_api": "apikey"})
         auth.get_token()
 def test_authenticator_auth_error(self):
     """
     Fail if keys are not provided.
     """
     # call authenticator constructor without an api key in the options dict
     with pytest.raises(KeyError):
         auth = IBMCloudFoundryAuthenticator({}, {}, "url")
         auth.get_token()
 def test_authenticator_token_error(self, post, get):
     """
     Fail if token isn't returned.
     """
     get.return_value = give_response(200, {"authorization_endpoint": "test an end"})
     post.return_value = give_response(404, {
         "token_type": "say",
         "access_token": "melon"
     })
     with pytest.raises(ValueError):
         auth = IBMCloudFoundryAuthenticator("url", {"cf_api_apikey": "apikey"})
         auth.get_token()
 def test_authenticator_success(self, post, get):
     """
     Test that in event of success all get's processed as expected.
     """
     get.return_value = give_response(200, {"authorization_endpoint": "test an end"})
     post.return_value = give_response(200, {
         "token_type": "say",
         "access_token": "melon"
     })
     auth = IBMCloudFoundryAuthenticator("url", {"cf_api_apikey": "apikey"})
     auth.get_token()
     assert auth.get_headers() == {"Authorization": "say melon"}
    def test_authenticator_details_error(self, rc):
        """
        If details won't be returned fail.
        """
        getResp = give_response(404, {"authorization_endpoint": "test an end"})
        postResp = give_response(200, {
            "token_type": "say",
            "access_token": "melon"
        })

        rc.side_effect = [getResp, postResp]

        with pytest.raises(ValueError):
            auth = IBMCloudFoundryAuthenticator({}, {"cf_api_apikey": "apikey"}, "url")
            auth.get_token()
    def test_authenticator_token_error(self, rc):
        """
        Fail if token isn't returned.
        """
        getResp = give_response(200, {"authorization_endpoint": "test an end"})
        postResp = give_response(404, {
            "token_type": "say",
            "access_token": "melon"
        })

        # the test is makes a GET request followed by a POST request for authentication
        # create an iterable of responses accordingly
        rc.side_effect = [getResp, postResp]

        with pytest.raises(ValueError):
            auth = IBMCloudFoundryAuthenticator({}, {"cf_api_apikey": "apikey"}, "url")
            auth.get_token()
    def test_authenticator_success(self, rc):
        """
        Test that in event of success all get's processed as expected.
        """

        getResp = give_response(200, {"authorization_endpoint": "test an end"})
        postResp = give_response(200, {
            "token_type": "say",
            "access_token": "melon"
        })

        # set the side effect for the mock object
        # each time the mock is called, it will return the next item in the list
        # when authenticating, RequestsCommon makes calls in this order: GET, POST, GET, POST
        # hence the order of the list
        rc.side_effect = [getResp, postResp, getResp, postResp]

        auth = IBMCloudFoundryAuthenticator({}, {"cf_api_apikey": "apikey"}, "/url")
        auth.get_token()
        assert auth.get_headers() == {"Authorization": "say melon"}
    def _fn_cloud_foundry_create_app_function(self, event, *args, **kwargs):
        """Function: Creates and deploys a cloud foundry applications from the specified parameters/docker files."""
        try:
            # Get the function parameters:
            application_name = kwargs.get("fn_cloud_foundry_applications",
                                          None)  # text
            space_guid = kwargs.get("fn_cloud_foundry_space_guid",
                                    None)  # text
            additional_parameters = kwargs.get(
                "fn_cloud_foundry_additional_parameters_json", None)  # text

            if space_guid is None or application_name is None:
                raise ValueError(
                    "Both fn_cloud_foundry_applications and fn_cloud_foundry_space_guid "
                    "have to be defined.")

            if additional_parameters is None:
                additional_parameters = {}
            else:
                additional_parameters = json.loads(additional_parameters)

            log = logging.getLogger(__name__)
            log.info("fn_cloud_foundry_applications: %s", application_name)
            log.info("fn_cloud_foundry_space_guid: %s", space_guid)
            log.info("fn_cloud_foundry_additional_parameters_json: %s",
                     additional_parameters)
            log.info("Params: {}".format(additional_parameters))

            authenticator = IBMCloudFoundryAuthenticator(
                self.opts, self.options, self.base_url)
            yield StatusMessage("Authenticated into Cloud Foundry")
            cf_service = IBMCloudFoundryAPI(self.opts, self.options,
                                            self.base_url, authenticator)

            values = {
                "space_guid": space_guid,
                "name": application_name,
                "username": self.cf_api_username,
                "password": self.cf_api_password
            }
            additional_parameters.update(
                values
            )  # so values overwrite additional params, not the other way
            values = additional_parameters

            results = cf_service.create_app(values)
            log.info("Result: %s", results)
            yield StatusMessage("Done.")
            self._add_keys(results)
            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(str(e))
Beispiel #9
0
    def _fn_cloud_foundry_manage_applications_function(self, event, *args,
                                                       **kwargs):
        """Function: Performs a specified action on the chosen Cloud Foundry applications."""
        try:
            # Get the function parameters:
            action_name = self.get_select_param(
                kwargs.get("fn_cloud_foundry_action"))
            application_names = kwargs.get("fn_cloud_foundry_applications",
                                           None)  # text
            additional_parameters = kwargs.get(
                "fn_cloud_foundry_additional_parameters_json", None)  # text

            if action_name is None or application_names is None:
                raise ValueError(
                    "Both fn_cloud_foundry_action and fn_cloud_foundry_applications have to be defined."
                )

            if additional_parameters is None:
                additional_parameters = {}
            else:
                import json
                additional_parameters = json.loads(additional_parameters)

            log = logging.getLogger(__name__)
            log.info("fn_cloud_foundry_action: %s", action_name)
            log.info("fn_cloud_foundry_applications: %s", application_names)
            log.info("fn_cloud_foundry_additional_parameters_json: %s",
                     additional_parameters)

            yield StatusMessage("Starting.")

            application_names = [
                x.strip() for x in application_names.split(",")
            ]

            authenticator = IBMCloudFoundryAuthenticator(
                self.base_url, self.options)
            yield StatusMessage("Authenticated into Cloud Foundry")
            cf_service = IBMCloudFoundryAPI(self.base_url, authenticator)
            results = cf_service.run_application_command(
                application_names, action_name, additional_parameters)

            log.info("Result: %s", results)
            yield StatusMessage("Done.")
            self._add_keys(results)
            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception as e:
            yield FunctionError(str(e))