Exemplo n.º 1
0
    def test_deployments_execute(self):
        execute_response = Execution({'status': 'started'})
        get_execution_response = Execution({
            'status': 'terminated',
            'workflow_id': 'mock_wf',
            'deployment_id': 'deployment-id',
            'blueprint_id': 'blueprint-id',
            'error': '',
            'id': 'id',
            'created_at': datetime.datetime.now(),
            'parameters': {}
        })
        success_event = {
            'event_type': 'workflow_succeeded',
            'type': 'foo',
            'timestamp': '12345678',
            'message': {
                'text': 'workflow execution succeeded'
            },
            'context': {
                'deployment_id': 'deployment-id'
            }
        }
        get_events_response = ([success_event], 1)

        self.client.executions.start = MagicMock(
            return_value=execute_response
        )
        self.client.executions.get = MagicMock(
            return_value=get_execution_response
        )
        self.client.events.get = MagicMock(return_value=get_events_response)
        cli_runner.run_cli('cfy executions start '
                           '-d a-deployment-id -w install')
Exemplo n.º 2
0
    def _assert_ex(self,
                   cli_cmd,
                   err_str_segment,
                   possible_solutions=None):

        def _assert():
            self.assertIn(err_str_segment, str(ex))
            if possible_solutions:
                if hasattr(ex, 'possible_solutions'):
                    self.assertEqual(ex.possible_solutions,
                                     possible_solutions)
                else:
                    self.fail('Exception should have '
                              'declared possible solutions')

        try:
            cli_runner.run_cli(cli_cmd)
            self.fail('Expected error {0} was not raised for command {1}'
                      .format(err_str_segment, cli_cmd))
        except SystemExit as ex:
            _assert()
        except exceptions.CloudifyCliError as ex:
            _assert()
        except exceptions.CloudifyValidationError as ex:
            _assert()
        except CloudifyClientError as ex:
            _assert()
        except ValueError as ex:
            _assert()
        except IOError as ex:
            _assert()
        except ImportError as ex:
            _assert()
Exemplo n.º 3
0
    def test_deployment_create(self):

        deployment = deployments.Deployment({'deployment_id': 'deployment_id'})

        self.client.deployments.create = MagicMock(return_value=deployment)
        cli_runner.run_cli('cfy deployments create -b '
                           'a-blueprint-id -d deployment')
 def test_dep_update_archive_loc_and_bp_path_parameters_exclusion(self):
     with self.assertRaises(SystemExit) as sys_exit:
         cli_runner.run_cli(
             'cfy deployments update -l '
             '{0}/helloworld/blueprint.tar.gz -p {0}/helloworld/'
             'blueprint.yaml -d my_deployment'.format(BLUEPRINTS_DIR))
         self.assertNotEquals(sys_exit.exception.code, 0)
Exemplo n.º 5
0
 def test_plugins_delete_force(self):
     for flag in ['--force', '-f']:
         mock = MagicMock()
         self.client.plugins.delete = mock
         cli_runner.run_cli('cfy plugins delete -p a-plugin-id {0}'
                            .format(flag))
         mock.assert_called_once_with(plugin_id='a-plugin-id', force=True)
Exemplo n.º 6
0
 def test_status_command_from_inner_dir(self):
     self._create_cosmo_wd_settings()
     cwd = utils.get_cwd()
     new_dir = os.path.join(cwd, 'test_command_from_inner_dir')
     os.mkdir(new_dir)
     utils.get_cwd = lambda: new_dir
     cli_runner.run_cli('cfy status')
Exemplo n.º 7
0
    def test_deployments_execute(self):
        execute_response = Execution({'status': 'terminated'})
        get_execution_response = Execution({
            'status':
            'terminated',
            'workflow_id':
            'mock_wf',
            'deployment_id':
            'deployment-id',
            'blueprint_id':
            'blueprint-id',
            'error':
            '',
            'id':
            id,
            'created_at':
            datetime.datetime.now(),
            'parameters': {}
        })

        self.client.executions.start = MagicMock(return_value=execute_response)
        self.client.executions.get = MagicMock(
            return_value=get_execution_response)
        self.client.events.get = MagicMock(return_value=([], 0))
        cli_runner.run_cli('cfy executions start '
                           '-d a-deployment-id -w install')
Exemplo n.º 8
0
 def test_init_implicit_provider_name(self):
     # the actual provider name
     # is 'cloudify_mock_provider_with_cloudify_prefix'
     cli_runner.run_cli('cfy init -p mock_provider_with_cloudify_prefix -v')
     self.assertEquals(
         'cloudify_mock_provider_with_cloudify_prefix',
         self._read_cosmo_wd_settings().get_provider())
Exemplo n.º 9
0
 def test_status_no_management_server_defined(self):
     # running a command which requires a target management server without
     # first calling "cfy use" or providing a target server explicitly
     cli_runner.run_cli('cfy init')
     self._assert_ex('cfy status',
                     'Must either first run `cfy use` or explicitly '
                     'provide a manager IP')
Exemplo n.º 10
0
    def test_deployments_execute(self):
        execute_response = Execution({"status": "started"})
        get_execution_response = Execution(
            {
                "status": "terminated",
                "workflow_id": "mock_wf",
                "deployment_id": "deployment-id",
                "blueprint_id": "blueprint-id",
                "error": "",
                "id": "id",
                "created_at": datetime.datetime.now(),
                "parameters": {},
            }
        )
        success_event = {
            "event_type": "workflow_succeeded",
            "type": "foo",
            "timestamp": "12345678",
            "message": {"text": "workflow execution succeeded"},
            "context": {"deployment_id": "deployment-id"},
        }
        get_events_response = MockListResponse([success_event], 1)

        self.client.executions.start = MagicMock(return_value=execute_response)
        self.client.executions.get = MagicMock(return_value=get_execution_response)
        self.client.events.list = MagicMock(return_value=get_events_response)
        cli_runner.run_cli("cfy executions start " "-d a-deployment-id -w install")
Exemplo n.º 11
0
    def test_recover_without_snapshot_flag(self, *_):
        cli_runner.run_cli('cfy init')

        # recovery command should not fail because there
        # is no snapshot flag
        self._assert_ex('cfy recover -f',
                        'This action requires a valid snapshot path.')
Exemplo n.º 12
0
    def test_parser_config_passes_expected_values(self, install_mock):

        install_command = 'cfy install'

        cli_runner.run_cli(install_command)

        install_command_arguments = \
            install_mock.call_args_list[0][1]

        expected_install_command_arguments = \
            {'blueprint_path': None,
             'blueprint_id': None,
             'validate_blueprint': False,
             'archive_location': None,
             'blueprint_filename': None,
             'deployment_id': None,
             'inputs': None,
             'workflow_id': None,
             'parameters': None,
             'allow_custom_parameters': False,
             'timeout': DEFAULT_TIMEOUT,
             'include_logs': False,
             'auto_generate_ids': False,
             'json': False
             }

        self.assertEqual(install_command_arguments,
                         expected_install_command_arguments)
Exemplo n.º 13
0
    def test_deployments_outputs(self):

        outputs = deployments.DeploymentOutputs({"deployment_id": "dep1", "outputs": {"port": 8080}})
        deployment = deployments.Deployment({"outputs": {"port": {"description": "Webserver port.", "value": "..."}}})
        self.client.deployments.get = MagicMock(return_value=deployment)
        self.client.deployments.outputs.get = MagicMock(return_value=outputs)
        cli_runner.run_cli("cfy deployments outputs -d dep1")
Exemplo n.º 14
0
 def test_init_existing_provider_config_no_overwrite(self):
     cli_runner.run_cli('cfy init -p mock_provider -v')
     os.remove(
         os.path.join(utils.get_cwd(), CLOUDIFY_WD_SETTINGS_DIRECTORY_NAME,
                      CLOUDIFY_WD_SETTINGS_FILE_NAME))
     self._assert_ex('cfy init -p mock_provider',
                     'already contains a provider configuration file')
Exemplo n.º 15
0
    def test_bootstrap(self):

        provider_context = {}
        provider_name = None

        def mock_create_context(_name, _context):
            global provider_context
            provider_context = _context
            global provider_name
            provider_name = _name

        def mock_get_context(_include=None):
            global provider_name
            global provider_context
            return {
                'name': provider_name,
                'context': provider_context
            }

        self.client.manager.create_context = mock_create_context
        self.client.manager.get_context = mock_get_context

        cli_runner.run_cli(
            'cfy init -p cloudify_mock_provider_with_cloudify_prefix'
        )
        cli_runner.run_cli('cfy bootstrap')

        context = self.client.manager.get_context()

        # see provision @cloudify_mock_provider_with_cloudify_prefix.py
        self.assertEquals('cloudify_mock_provider_with_cloudify_prefix',
                          context['name'])
        self.assertEquals('value', context['context']['key'])
Exemplo n.º 16
0
    def test_auto_generate_ids_generates_suffixed_ids_in_upload_mode(
            self,
            blueprints_upload_mock,
            deployments_create_mock,
            *_):

        upload_mode_command = 'cfy install -b bid -d did -g'

        tmp_blueprint_path = os.path.join(self.original_utils_get_cwd(),
                                          DEFAULT_BLUEPRINT_PATH)

        # create a tmp file representing a blueprint to upload
        open(tmp_blueprint_path, 'w+').close()

        cli_runner.run_cli(upload_mode_command)

        blueprints_upload_blueprint_id_argument = \
            blueprints_upload_mock.call_args_list[0][0][1]

        deployments_create_deployment_id_argument = \
            deployments_create_mock.call_args_list[0][0][1]

        self.assertTrue(blueprints_upload_blueprint_id_argument
                        .startswith('bid_'))
        self.assertTrue(deployments_create_deployment_id_argument
                        .startswith('did_'))
Exemplo n.º 17
0
 def test_use_command(self):
     self.client.manager.get_status = MagicMock()
     self.client.manager.get_context = MagicMock(return_value={"name": "name", "context": {}})
     self._create_cosmo_wd_settings()
     cli_runner.run_cli("cfy use -t 127.0.0.1")
     cwds = self._read_cosmo_wd_settings()
     self.assertEquals("127.0.0.1", cwds.get_management_server())
Exemplo n.º 18
0
 def assert_method_called(self, cli_command, module, function_name, kwargs):
     with patch.object(module, function_name) as mock:
         try:
             cli_runner.run_cli(cli_command)
         except BaseException as e:
             self.logger.info(e.message)
         mock.assert_called_with(**kwargs)
Exemplo n.º 19
0
 def test_list_sort_default(self):
     for r in self.resources_types:
         self._set_mock_list(
             r, parser_config()["commands"][r]["sub_commands"]["list"]["arguments"]["-s,--sort-by"]["default"]
         )
         cli_runner.run_cli("cfy {0} list".format(r))
     self.assertEqual(len(self.resources_types), self.count_mock_calls)
Exemplo n.º 20
0
    def test_executions_start_custom_parameters(self,
                                                executions_start_mock,
                                                *_):
        # 'blueprints archive location mode' is used to prevent from dealing
        # with the fact that 'upload mode' needs the blueprint_path argument
        # to lead to an existing file
        command = \
            'cfy install --archive-location {0} ' \
            '-w {1} ' \
            '-d {2} ' \
            '--timeout {3} ' \
            '--parameters {4} ' \
            '--allow-custom-parameters ' \
            '--include-logs ' \
            '--json' \
            .format(SAMPLE_ARCHIVE_PATH,
                    STUB_WORKFLOW,
                    STUB_DEPLOYMENT_ID,
                    STUB_TIMEOUT,
                    STUB_PARAMETERS
                    )

        cli_runner.run_cli(command)

        executions_start_mock.assert_called_with(
            workflow_id=STUB_WORKFLOW,
            deployment_id=STUB_DEPLOYMENT_ID,
            force=False,
            timeout=STUB_TIMEOUT,
            allow_custom_parameters=True,
            include_logs=True,
            parameters=[STUB_PARAMETERS],
            json=True
        )
Exemplo n.º 21
0
 def test_recover_no_force(self):
     self.client.manager.get_status = MagicMock()
     self.client.manager.get_context = MagicMock(return_value={"name": "mock_provider", "context": {"key": "value"}})
     self.client.deployments.list = MagicMock(return_value=[])
     cli_runner.run_cli("cfy init")
     cli_runner.run_cli("cfy use -t 10.0.0.1")
     self._assert_ex("cfy recover", "This action requires additional confirmation.")
Exemplo n.º 22
0
    def test_blueprints_upload_custom_arguments(self,
                                                blueprints_upload_mock,
                                                *_):
        command = \
            'cfy install -p {0} -b {1} --validate'\
            .format(SAMPLE_BLUEPRINT_PATH,
                    STUB_BLUEPRINT_ID)

        cli_runner.run_cli(command)

        blueprint_path_argument_from_upload = \
            blueprints_upload_mock.call_args_list[0][0][0]
        blueprint_id_argument_from_upload = \
            blueprints_upload_mock.call_args_list[0][0][1]
        validate_argument_from_upload = \
            blueprints_upload_mock.call_args_list[0][0][2]

        self.assertEqual(
            [blueprint_path_argument_from_upload.name,
             blueprint_id_argument_from_upload,
             validate_argument_from_upload],

            [SAMPLE_BLUEPRINT_PATH,
             STUB_BLUEPRINT_ID,
             True]
        )
Exemplo n.º 23
0
    def test_blueprint_is_deleted(self, blueprints_delete_mock, *_):

        uninstall_command = 'cfy uninstall -d did'

        cli_runner.run_cli(uninstall_command)

        self.assertTrue(blueprints_delete_mock.called)
Exemplo n.º 24
0
 def test_executions_start_json(self, get_events_logger_mock):
     execution = execution_mock('started')
     self.client.executions.start = MagicMock(return_value=execution)
     with patch('cloudify_cli.commands.executions.wait_for_execution',
                return_value=execution):
         cli_runner.run_cli('cfy executions start -w mock_wf -d dep --json')
     get_events_logger_mock.assert_called_with(True)
Exemplo n.º 25
0
    def _test_using_import_resolver(self,
                                    command,
                                    blueprint_path,
                                    mocked_module,
                                    mock_get_resolver):
        cli_runner.run_cli('cfy init -r')

        # create an import resolver
        parameters = {
            'rules':
                [{'rule1prefix': 'rule1replacement'}]
        }
        resolver = DefaultImportResolver(**parameters)
        # set the return value of mock_get_resolver -
        # this is the resolver we expect to be passed to
        # the parse_from_path method.
        mock_get_resolver.return_value = resolver

        # run the cli command and check that
        # parse_from_path was called with the expected resolver
        cli_command = 'cfy {0} -p {1}'.format(command, blueprint_path)
        kwargs = {
            'dsl_file_path': blueprint_path,
            'resolver': resolver,
            'validate_version': True
        }
        self.assert_method_called(
            cli_command, mocked_module, 'parse_from_path', kwargs=kwargs)
Exemplo n.º 26
0
    def test_deployments_delete_arguments(self, deployments_delete_mock, *_):

        uninstall_command = 'cfy uninstall -d did'

        cli_runner.run_cli(uninstall_command)

        deployments_delete_mock.assert_called_with('did',
                                                   ignore_live_nodes=False)
Exemplo n.º 27
0
 def test_init_existing_provider_config_no_overwrite(self):
     cli_runner.run_cli('cfy init -p mock_provider -v')
     os.remove(os.path.join(utils.get_cwd(),
                            CLOUDIFY_WD_SETTINGS_DIRECTORY_NAME,
                            CLOUDIFY_WD_SETTINGS_FILE_NAME))
     self._assert_ex(
         'cfy init -p mock_provider',
         'already contains a provider configuration file')
Exemplo n.º 28
0
 def test_status_command_from_inner_dir(self):
     self.client.manager.get_status = MagicMock()
     self._create_cosmo_wd_settings()
     cwd = utils.get_cwd()
     new_dir = os.path.join(cwd, 'test_command_from_inner_dir')
     os.mkdir(new_dir)
     utils.get_cwd = lambda: new_dir
     cli_runner.run_cli('cfy status')
Exemplo n.º 29
0
 def _test_events(self, flag=''):
     self.client.executions.get = self._mock_executions_get
     self.client.events.list = self._mock_events_list
     stdout = StringIO()
     with patch('sys.stdout', stdout):
         cli_runner.run_cli(
             'cfy events list --execution-id execution-id {}'.format(flag))
     return stdout.getvalue()
Exemplo n.º 30
0
    def test_install_plugins(self):

        blueprint_path = "{0}/local/blueprint_with_plugins.yaml".format(BLUEPRINTS_DIR)
        try:
            cli_runner.run_cli("cfy local install-plugins -p {0}".format(blueprint_path))
        except CommandExecutionException as e:
            # Expected pip install to start
            self.assertIn("pip install -r /tmp/requirements_", e.message)
Exemplo n.º 31
0
 def test_use_command_no_prior_init(self):
     self.client.manager.get_status = MagicMock()
     self.client.manager.get_context = MagicMock(return_value={
         'name': 'name',
         'context': {}
     })
     cli_runner.run_cli('cfy use -t 127.0.0.1')
     cwds = self._read_cosmo_wd_settings()
     self.assertEquals('127.0.0.1', cwds.get_management_server())
Exemplo n.º 32
0
 def test_plugins_upload(self):
     self.client.plugins.upload = MagicMock()
     plugin_dest = os.path.join(tempfile.gettempdir(), 'plugin.tar.gz')
     try:
         self.make_sample_plugin(plugin_dest)
         cli_runner.run_cli('cfy plugins upload -p '
                            '{0}'.format(plugin_dest))
     finally:
         shutil.rmtree(plugin_dest, ignore_errors=True)
Exemplo n.º 33
0
    def test_deployment_create(self):

        deployment = deployments.Deployment({
            'deployment_id': 'deployment_id'
        })

        self.client.deployments.create = MagicMock(return_value=deployment)
        cli_runner.run_cli('cfy deployments create -b '
                           'a-blueprint-id -d deployment')
Exemplo n.º 34
0
 def test_blueprint_validate_definitions_version_false(self):
     with open(utils.get_configuration_path()) as f:
         config = yaml.safe_load(f.read())
     with open(utils.get_configuration_path(), "w") as f:
         config["validate_definitions_version"] = False
         f.write(yaml.safe_dump(config))
     cli_runner.run_cli(
         "cfy blueprints validate " "-p {0}/local/blueprint_validate_definitions_version.yaml".format(BLUEPRINTS_DIR)
     )
Exemplo n.º 35
0
 def test_plugins_upload(self):
     self.client.plugins.upload = MagicMock()
     plugin_dest = os.path.join(tempfile.gettempdir(), 'plugin.tar.gz')
     try:
         self.make_sample_plugin(plugin_dest)
         cli_runner.run_cli('cfy plugins upload -p '
                            '{0}'.format(plugin_dest))
     finally:
         shutil.rmtree(plugin_dest, ignore_errors=True)
Exemplo n.º 36
0
 def test_activate_maintenance_with_wait(self):
     with patch('cloudify_rest_client.maintenance.'
                'MaintenanceModeClient.status',
                new=mock_activated_status):
         with patch('time.sleep') as sleep_mock:
             cli_runner.run_cli('cfy maintenance-mode activate --wait')
             cli_runner.run_cli('cfy maintenance-mode '
                                'activate --wait --timeout 20')
             sleep_mock.assert_has_calls([call(5), call(5)])
Exemplo n.º 37
0
    def test_blueprint_inputs(self):

        BLUEPRINT_ID = 'a-blueprint-id'
        NAME = 'test_input'
        TYPE = 'string'
        DESCRIPTION = 'Test input.'

        BLUEPRINT = {
            'plan': {
                'inputs': {
                    NAME: {
                        'type': TYPE,
                        'description': DESCRIPTION
                        # field 'default' intentionally omitted
                    }
                }
            }
        }

        assertEqual = self.assertEqual

        class RestClientMock(object):
            class BlueprintsClientMock(object):
                def __init__(self, blueprint_id, blueprint):
                    self.blueprint_id = blueprint_id
                    self.blueprint = blueprint

                def get(self, blueprint_id):
                    assertEqual(blueprint_id, self.blueprint_id)
                    return self.blueprint

            def __init__(self, blueprint_id, blueprint):
                self.blueprints = self.BlueprintsClientMock(
                    blueprint_id, blueprint)

        def get_rest_client_mock(*args, **kwargs):
            return RestClientMock(BLUEPRINT_ID, BLUEPRINT)

        def table_mock(fields, data, *args, **kwargs):
            self.assertEqual(len(data), 1)
            input = data[0]
            self.assertIn('name', input)
            self.assertIn('type', input)
            self.assertIn('default', input)
            self.assertIn('description', input)

            self.assertEqual(input['name'], NAME)
            self.assertEqual(input['type'], TYPE)
            self.assertEqual(input['default'], '-')
            self.assertEqual(input['description'], DESCRIPTION)

        with patch('cloudify_cli.utils.get_rest_client',
                   get_rest_client_mock),\
                patch('cloudify_cli.utils.table', table_mock):
            cli_runner.run_cli(
                'cfy blueprints inputs -b {0}'.format(BLUEPRINT_ID))
Exemplo n.º 38
0
    def test_blueprint_inputs(self):

        BLUEPRINT_ID = 'a-blueprint-id'
        NAME = 'test_input'
        TYPE = 'string'
        DESCRIPTION = 'Test input.'

        BLUEPRINT = {
            'plan': {
                'inputs': {
                    NAME: {
                        'type': TYPE,
                        'description': DESCRIPTION
                        # field 'default' intentionally omitted
                    }
                }
            }
        }

        assertEqual = self.assertEqual

        class RestClientMock(object):
            class BlueprintsClientMock(object):
                def __init__(self, blueprint_id, blueprint):
                    self.blueprint_id = blueprint_id
                    self.blueprint = blueprint

                def get(self, blueprint_id):
                    assertEqual(blueprint_id, self.blueprint_id)
                    return self.blueprint

            def __init__(self, blueprint_id, blueprint):
                self.blueprints = self.BlueprintsClientMock(blueprint_id,
                                                            blueprint)

        def get_rest_client_mock(*args, **kwargs):
            return RestClientMock(BLUEPRINT_ID, BLUEPRINT)

        def table_mock(fields, data, *args, **kwargs):
            self.assertEqual(len(data), 1)
            input = data[0]
            self.assertIn('name', input)
            self.assertIn('type', input)
            self.assertIn('default', input)
            self.assertIn('description', input)

            self.assertEqual(input['name'], NAME)
            self.assertEqual(input['type'], TYPE)
            self.assertEqual(input['default'], '-')
            self.assertEqual(input['description'], DESCRIPTION)

        with patch('cloudify_cli.utils.get_rest_client',
                   get_rest_client_mock),\
                patch('cloudify_cli.utils.table', table_mock):
            cli_runner.run_cli('cfy blueprints inputs -b {0}'
                               .format(BLUEPRINT_ID))
Exemplo n.º 39
0
 def test_recover_from_different_directory_than_bootstrap(self, *_):
     cli_runner.run_cli('cfy init')
     # recovery command should not fail because we do not have a manager
     # key path in the local context, and the environment variable is not
     # set
     self._assert_ex('cfy recover -f',
                     'Cannot perform recovery. manager key file not found. '
                     'Set the manager private key path via the '
                     'CLOUDIFY_MANAGER_PRIVATE_KEY_PATH environment '
                     'variable')
Exemplo n.º 40
0
    def test_install_plugins(self):

        blueprint_path = '{0}/local/blueprint_with_plugins.yaml'\
            .format(BLUEPRINTS_DIR)
        try:
            cli_runner.run_cli(
                'cfy local install-plugins -p {0}'.format(blueprint_path))
        except CommandExecutionException as e:
            # Expected pip install to start
            self.assertIn('pip install -r /tmp/requirements_', e.message)
Exemplo n.º 41
0
 def test_blueprint_validate_definitions_version_false(self):
     with open(utils.get_configuration_path()) as f:
         config = yaml.safe_load(f.read())
     with open(utils.get_configuration_path(), 'w') as f:
         config['validate_definitions_version'] = False
         f.write(yaml.safe_dump(config))
     cli_runner.run_cli(
         'cfy blueprints validate '
         '-p {0}/local/blueprint_validate_definitions_version.yaml'.format(
             BLUEPRINTS_DIR))
Exemplo n.º 42
0
    def test_install_command_default_init_arguments(self, local_init_mock, *_):

        local_install_command = 'cfy local install'
        cli_runner.run_cli(local_install_command)

        local_init_mock.assert_called_with(
            blueprint_path=DEFAULT_BLUEPRINT_PATH,
            inputs=None,
            install_plugins=False
            )
Exemplo n.º 43
0
 def test_get_resolver(self):
     cli_runner.run_cli('cfy init -r')
     resolver_configuration = create_resolver_configuration(
         implementation='mock implementation', parameters='mock parameters')
     update_config_file(resolver_configuration=resolver_configuration)
     with mock.patch('dsl_parser.utils.create_import_resolver') as \
             mock_create_import_resolver:
         utils.get_import_resolver()
         mock_create_import_resolver.assert_called_once_with(
             resolver_configuration[IMPORT_RESOLVER_KEY])
Exemplo n.º 44
0
    def test_teardown_no_management_ip_in_context_right_directory(
            self, mock_load_env, mock_teardown):  # NOQA
        cli_runner.run_cli('cfy init')

        with update_wd_settings() as wd:
            wd.set_provider_context({})

        cli_runner.run_cli('cfy teardown -f')
        mock_teardown.assert_called_once_with()
        mock_load_env.assert_called_once_with()
Exemplo n.º 45
0
 def test_recover_no_force(self):
     self.client.manager.get_status = MagicMock()
     self.client.manager.get_context = MagicMock(
         return_value={'name': 'mock_provider', 'context': {'key': 'value'}}
     )
     self.client.deployments.list = MagicMock(return_value=[])
     cli_runner.run_cli('cfy init')
     cli_runner.run_cli('cfy use -t 10.0.0.1')
     self._assert_ex('cfy recover',
                     'This action requires additional confirmation.')
Exemplo n.º 46
0
 def test_get_custom_resolver(self):
     cli_runner.run_cli('cfy init -r')
     parameters = {'param': 'custom-parameter'}
     custom_resolver_class_path = "%s:%s" % (
         CustomImportResolver.__module__, CustomImportResolver.__name__)
     import_resolver_config = create_resolver_configuration(
         implementation=custom_resolver_class_path, parameters=parameters)
     update_config_file(resolver_configuration=import_resolver_config)
     resolver = utils.get_import_resolver()
     self.assertEqual(type(resolver), CustomImportResolver)
     self.assertEqual(resolver.param, 'custom-parameter')
Exemplo n.º 47
0
 def test_teardown_has_existing_deployments_dont_ignore_deployments(self):
     self.client.manager.get_status = MagicMock()
     self.client.deployments.list = MagicMock(return_value=[{}])
     self.client.manager.get_context = MagicMock(return_value={
         'name': 'mock_provider',
         'context': {
             'key': 'value'
         }
     })
     cli_runner.run_cli('cfy init')
     cli_runner.run_cli('cfy use -t 10.0.0.1')
     self._assert_ex('cfy teardown -f', 'has existing deployments')
Exemplo n.º 48
0
    def test_bootstrap_no_validations_install_plugins(self):

        cli_runner.run_cli('cfy init')
        blueprint_path = '{0}/local/{1}.yaml' \
            .format(BLUEPRINTS_DIR,
                    'blueprint_with_plugins')
        self.assert_method_called(
            cli_command='cfy bootstrap --skip-validations '
            '--install-plugins -p {0}'.format(blueprint_path),
            module=common,
            function_name='install_blueprint_plugins',
            kwargs={'blueprint_path': blueprint_path})
Exemplo n.º 49
0
 def test_install_agent(self):
     blueprint_path = '{0}/local/install-agent-blueprint.yaml' \
         .format(BLUEPRINTS_DIR)
     try:
         cli_runner.run_cli('cfy local init -p {0}'.format(blueprint_path))
         self.fail('ValueError was expected')
     except ValueError as e:
         self.assertIn(
             "'install_agent': true is not supported "
             "(it is True by default) "
             "when executing local workflows. "
             "The 'install_agent' property must be set to false "
             "for each node of type {0}.".format(HOST_TYPE), e.message)
Exemplo n.º 50
0
 def test_recover_from_different_directory_than_bootstrap(self, *_):
     cli_runner.run_cli('cfy init')
     # recovery command should not fail because we do not have a manager
     # key path in the local context, and the environment variable is not
     # set
     fake_snapshot_path = os.path.join(TEST_WORK_DIR, 'sn.zip')
     open(fake_snapshot_path, 'w').close()
     self._assert_ex(
         'cfy recover -f -s {0}'.format(fake_snapshot_path),
         'Cannot perform recovery. manager key file not found. '
         'Set the manager private key path via the '
         'CLOUDIFY_MANAGER_PRIVATE_KEY_PATH environment '
         'variable')
Exemplo n.º 51
0
    def test_plugin_get(self):
        self.client.plugins.get = MagicMock(
            return_value=Plugin({
                'id': 'id',
                'package_name': 'dummy',
                'package_version': '1.2',
                'supported_platform': 'any',
                'distribution_release': 'trusty',
                'distribution': 'ubuntu',
                'uploaded_at': 'now'
            }))

        cli_runner.run_cli('cfy plugins get -p some_id')
Exemplo n.º 52
0
    def _local_init(self,
                    inputs=None,
                    blueprint='blueprint',
                    install_plugins=False):

        blueprint_path = '{0}/local/{1}.yaml'.format(BLUEPRINTS_DIR, blueprint)
        flags = '--install-plugins' if install_plugins else ''
        command = 'cfy local init {0} -p {1}'.format(flags, blueprint_path)
        if inputs:
            inputs_path = os.path.join(TEST_WORK_DIR, 'temp_inputs.json')
            with open(inputs_path, 'w') as f:
                f.write(json.dumps(inputs))
            command = '{0} -i {1}'.format(command, inputs_path)
        cli_runner.run_cli(command)
Exemplo n.º 53
0
    def test_recover_from_same_directory_as_bootstrap(self, *_):
        cli_runner.run_cli('cfy init')

        # mock bootstrap behavior by setting the management key path
        # in the local context
        key_path = os.path.join(TEST_WORK_DIR, 'key.pem')
        open(key_path, 'w').close()

        with update_wd_settings() as wd:
            wd.set_management_key(key_path)
            wd.set_provider_context({})

        # now run recovery and make sure no exception was raised
        cli_runner.run_cli('cfy recover -f -s {0}'.format(key_path))
Exemplo n.º 54
0
    def setUp(self):

        self.test_dir = os.path.join('/tmp', 'cloudify-cli-unit-tests')
        os.makedirs(self.test_dir)
        test_workdir = tempfile.mkdtemp(dir=self.test_dir)
        utils.get_cwd = lambda: test_workdir
        os.chdir(test_workdir)

        cli_runner.run_cli('cfy init -r')

        os.environ[constants.CLOUDIFY_USERNAME_ENV] = 'test_username'
        os.environ[constants.CLOUDIFY_PASSWORD_ENV] = 'test_password'
        os.environ[constants.CLOUDIFY_SSL_TRUST_ALL] = TRUST_ALL
        os.environ[constants.CLOUDIFY_SSL_CERT] = CERT_PATH
Exemplo n.º 55
0
    def test_recover_from_different_directory_than_bootstrap_with_env_variable(self, *_):  # NOQA
        cli_runner.run_cli('cfy init')

        key_path = os.path.join(TEST_WORK_DIR, 'key.pem')
        open(key_path, 'w').close()

        # mock provider context
        with update_wd_settings() as wd:
            wd.set_provider_context({})

        try:
            os.environ['CLOUDIFY_MANAGER_PRIVATE_KEY_PATH'] = key_path
            cli_runner.run_cli('cfy recover -f')
        finally:
            del os.environ['CLOUDIFY_MANAGER_PRIVATE_KEY_PATH']
Exemplo n.º 56
0
    def test_executions_get(self):

        execution = Execution({
            'status': 'terminated',
            'workflow_id': 'mock_wf',
            'deployment_id': 'deployment-id',
            'blueprint_id': 'blueprint-id',
            'error': '',
            'id': uuid4(),
            'created_at': datetime.datetime.now(),
            'parameters': {}
        })

        self.client.executions.get = MagicMock(return_value=execution)
        cli_runner.run_cli('cfy executions get -e execution-id')
Exemplo n.º 57
0
    def test_recover_from_same_directory_as_bootstrap_missing_key(self, *_):
        cli_runner.run_cli('cfy init')

        # mock bootstrap behavior by setting the management key path
        # in the local context. however, don't actually create the key file
        key_path = os.path.join(TEST_WORK_DIR, 'key.pem')

        with update_wd_settings() as wd:
            wd.set_management_key(key_path)
            wd.set_provider_context({})

        # recovery command should not fail because the key file specified in
        # the context file does not exist
        self._assert_ex('cfy recover -f',
                        'Cannot perform recovery. manager key '
                        'file does not exist')
Exemplo n.º 58
0
    def test_recover_no_force(self):
        self.client.manager.get_status = MagicMock()
        self.client.manager.get_context = MagicMock(return_value={
            'name': 'mock_provider',
            'context': {
                'key': 'value'
            }
        })
        fake_snapshot_path = os.path.join(TEST_WORK_DIR, 'sn.zip')
        open(fake_snapshot_path, 'w').close()

        self.client.deployments.list = MagicMock(return_value=[])
        cli_runner.run_cli('cfy init')
        cli_runner.run_cli('cfy use -t 10.0.0.1')
        self._assert_ex('cfy recover -s {0}'.format(fake_snapshot_path),
                        'This action requires additional confirmation.')
Exemplo n.º 59
0
    def test_teardown_manager_down_dont_ignore_deployments(self):
        self.client.manager.get_status = MagicMock()

        def raise_client_error():
            raise CloudifyClientError('CloudifyClientError')

        self.client.deployments.list = raise_client_error
        self.client.manager.get_context = MagicMock(return_value={
            'name': 'mock_provider',
            'context': {
                'key': 'value'
            }
        })
        cli_runner.run_cli('cfy init')
        cli_runner.run_cli('cfy use -t 10.0.0.1')
        self._assert_ex('cfy teardown -f', 'The Manager server may be down')