Пример #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')
Пример #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()
Пример #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)
Пример #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)
Пример #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')
Пример #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')
Пример #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())
Пример #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')
Пример #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")
Пример #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.')
Пример #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)
Пример #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")
Пример #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')
Пример #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'])
Пример #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_'))
Пример #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())
Пример #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)
Пример #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)
Пример #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
        )
Пример #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.")
Пример #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]
        )
Пример #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)
Пример #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)
Пример #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)
Пример #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)
Пример #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')
Пример #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')
Пример #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()
Пример #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)
Пример #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())
Пример #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)
Пример #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')
Пример #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)
     )
Пример #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)
Пример #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)])
Пример #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))
Пример #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))
Пример #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')
Пример #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)
Пример #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))
Пример #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
            )
Пример #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])
Пример #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()
Пример #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.')
Пример #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')
Пример #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')
Пример #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})
Пример #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)
Пример #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')
Пример #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')
Пример #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)
Пример #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))
Пример #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
Пример #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']
Пример #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')
Пример #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')
Пример #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.')
Пример #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')