Esempio n. 1
0
    def test_delete_environment(self):
        """Test that environment deletion results in the correct rpc call."""
        self._set_policy_rules({'delete_environment': '@'})
        self.expect_policy_check('delete_environment',
                                 {'environment_id': '12345'})

        fake_now = timeutils.utcnow()
        expected = dict(id='12345',
                        name='my-env',
                        version=0,
                        networking={},
                        created=fake_now,
                        updated=fake_now,
                        tenant_id=self.tenant,
                        description={
                            'Objects': {
                                '?': {
                                    'id': '12345'
                                }
                            },
                            'Attributes': {}
                        })
        e = models.Environment(**expected)
        test_utils.save_models(e)

        req = self._delete('/environments/12345')
        result = req.get_response(self.api)

        # Should this be expected behavior?
        self.assertEqual('', result.body)
        self.assertEqual(200, result.status_code)
Esempio n. 2
0
    def test_get_result(self, _):
        """Result of task with given id and environment id is returned."""
        now = timeutils.utcnow()
        expected_environment_id = 'test_environment'
        expected_task_id = 'test_task'
        expected_result = {'test_result': 'test_result'}

        environment = models.Environment(
            id=expected_environment_id,
            name='test_environment', created=now, updated=now,
            tenant_id=self.tenant
        )

        task = models.Task(
            id=expected_task_id,
            started=now,
            finished=now,
            result=expected_result,
            environment_id=expected_environment_id
        )

        test_utils.save_models(environment, task)

        request = self._get(
            '/environments/{environment_id}/actions/{task_id}'
            .format(environment_id=expected_environment_id,
                    task_id=expected_task_id),
        )

        response = request.get_response(self.api)

        self.assertEqual(200, response.status_code)
        self.assertEqual(expected_result, response.json)
Esempio n. 3
0
    def create(environment_params, tenant_id):
        #tagging environment by tenant_id for later checks
        """Creates environment with specified params, in particular - name

           :param environment_params: Dict, e.g. {'name': 'env-name'}
           :param tenant_id: Tenant Id
           :return: Created Environment
        """

        objects = {
            '?': {
                'id': uuidutils.generate_uuid(),
            }
        }
        objects.update(environment_params)
        objects.update(
            EnvironmentServices.generate_default_networks(objects['name']))
        objects['?']['type'] = 'io.murano.Environment'
        environment_params['tenant_id'] = tenant_id

        data = {'Objects': objects, 'Attributes': []}

        environment = models.Environment()
        environment.update(environment_params)

        unit = db_session.get_session()
        with unit.begin():
            unit.add(environment)

        #saving environment as Json to itself
        environment.update({'description': data})
        environment.save(unit)

        return environment
Esempio n. 4
0
    def test_execute_action_with_invalid_session_version(self, mocked_function,
                                                         _):
        """Test whether validate session function throws error."""
        self._set_policy_rules(
            {'execute_action': '@'}
        )

        fake_now = timeutils.utcnow()
        expected = dict(
            id='12345',
            name='my-env',
            version=0,
            created=fake_now,
            updated=fake_now,
            tenant_id=self.tenant,
            description={
                'Objects': {
                    '?': {'id': '12345',
                          '_actions': {
                              'actionsID_action': {
                                  'enabled': True,
                                  'name': 'Testaction'
                              }
                          }}
                },
                'Attributes': {}
            }
        )
        environment = models.Environment(**expected)
        test_utils.save_models(environment)
        req = self._post('/environments/12345/actions/actionID_action', b'{}')

        mocked_function.return_value = False
        self.assertRaises(exc.HTTPForbidden, self.controller.execute,
                          req, '12345', 'actionsID_action', {})
Esempio n. 5
0
    def setUp(self):
        super(TestEnvironmentServices, self).setUp()
        self.environment = models.Environment(name='test_environment',
                                              tenant_id='test_tenant_id',
                                              version=LATEST_VERSION)

        self.env_services = environments.EnvironmentServices()
    def setUp(self):
        super(TestInstanceReporter, self).setUp()

        self.environment = models.Environment(name='test_environment',
                                              tenant_id='test_tenant_id',
                                              version=LATEST_VERSION)

        self.addCleanup(mock.patch.stopall)
Esempio n. 7
0
    def test_update_environment(self):
        """Check that environment rename works."""
        self._set_policy_rules({
            'show_environment': '@',
            'update_environment': '@'
        })
        self.expect_policy_check('update_environment',
                                 {'environment_id': '12345'})

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        expected = dict(id='12345',
                        name='my-env',
                        version=0,
                        description_text='',
                        created=fake_now,
                        updated=fake_now,
                        tenant_id=self.tenant,
                        description={
                            'Objects': {
                                '?': {
                                    'id': '12345'
                                }
                            },
                            'Attributes': []
                        })
        e = models.Environment(**expected)
        test_utils.save_models(e)

        fake_now = timeutils.utcnow()
        timeutils.utcnow.override_time = fake_now

        del expected['description']
        expected['services'] = []
        expected['status'] = 'ready'
        expected['name'] = 'renamed_env'
        expected['updated'] = fake_now

        body = {'name': 'renamed_env'}
        req = self._put('/environments/12345', jsonutils.dump_as_bytes(body))
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)

        self.expect_policy_check('show_environment',
                                 {'environment_id': '12345'})
        req = self._get('/environments/12345')
        result = req.get_response(self.api)
        self.assertEqual(200, result.status_code)

        expected['created'] = timeutils.isotime(expected['created'])[:-1]
        expected['updated'] = timeutils.isotime(expected['updated'])[:-1]
        expected['acquired_by'] = None

        self.assertEqual(expected, jsonutils.loads(result.body))
Esempio n. 8
0
 def _create_fake_environment(self, env_name='my-env', env_id='123'):
     fake_now = timeutils.utcnow()
     expected = dict(id=env_id,
                     name=env_name,
                     version=0,
                     created=fake_now,
                     updated=fake_now,
                     tenant_id=self.tenant,
                     description={
                         'Objects': {
                             '?': {
                                 'id': '{0}'.format(env_id)
                             }
                         },
                         'Attributes': {}
                     })
     e = models.Environment(**expected)
     test_utils.save_models(e)
Esempio n. 9
0
    def test_get_result_not_found(self, _):
        """If task does not exists, it should be handled correctly
        and API should return 404.
        """
        expected_environment_id = 'test_environment'

        environment = models.Environment(id=expected_environment_id,
                                         name='test_environment',
                                         tenant_id=self.tenant)
        test_utils.save_models(environment)

        request = self._get(
            '/environments/{environment_id}/actions/{task_id}'.format(
                environment_id=expected_environment_id,
                task_id='not_existent_task_id'), )

        response = request.get_response(self.api)

        self.assertEqual(response.status_code, 404)
Esempio n. 10
0
    def create(environment_params, context):
        # tagging environment by tenant_id for later checks
        """Creates environment with specified params, in particular - name

           :param environment_params: Dict, e.g. {'name': 'env-name'}
           :param context: request context to get the tenant id and the token
           :return: Created Environment
        """
        objects = {
            '?': {
                'id': uuidutils.generate_uuid(),
            }
        }
        network_driver = EnvironmentServices.get_network_driver(context)
        objects.update(environment_params)
        if not objects.get('defaultNetworks'):
            objects['defaultNetworks'] = \
                EnvironmentServices.generate_default_networks(objects['name'],
                                                              network_driver)
        objects['?']['type'] = 'io.murano.Environment'
        objects['?']['metadata'] = {}

        data = {
            'Objects': objects,
            'Attributes': [],
            'project_id': context.tenant,
            'user_id': context.user
        }

        environment_params['tenant_id'] = context.tenant
        environment = models.Environment()
        environment.update(environment_params)

        unit = db_session.get_session()
        with unit.begin():
            unit.add(environment)

        # saving environment as Json to itself
        environment.update({'description': data})
        environment.save(unit)

        return environment
Esempio n. 11
0
    def test_environment_ready_if_last_session_deployed_after_failed(self):
        """Test environment ready status

        If last session was deployed successfully and other session
        was failed - environment must have status "ready".

        Bug: #1413260
        """
        OLD_VERSION = 0
        LATEST_VERSION = 1

        session = db_session.get_session()

        environment = models.Environment(
            name='test_environment', tenant_id='test_tenant_id',
            version=LATEST_VERSION
        )
        session.add(environment)

        now = timeutils.utcnow()

        session_1 = models.Session(
            environment=environment, user_id='test_user_id_1',
            version=OLD_VERSION,
            state=states.SessionState.DEPLOY_FAILURE,
            updated=now, description={}
        )
        session_2 = models.Session(
            environment=environment, user_id='test_user_id_2',
            version=LATEST_VERSION,
            state=states.SessionState.DEPLOYED,
            updated=now + dt.timedelta(minutes=1), description={}
        )
        session.add_all([session_1, session_2])
        session.flush()

        expected_status = states.EnvironmentStatus.READY
        actual_status = environments.EnvironmentServices.get_status(
            environment.id
        )

        self.assertEqual(expected_status, actual_status)
Esempio n. 12
0
    def test_execute_action_with_session_in_deleting_state(self, _):
        """Test whether session in deleting state throws error."""
        self._set_policy_rules(
            {'execute_action': '@'}
        )

        fake_now = timeutils.utcnow()
        expected = dict(
            id='12345',
            name='my-env',
            version=0,
            created=fake_now,
            updated=fake_now,
            tenant_id=self.tenant,
            description={
                'Objects': {
                    '?': {'id': '12345',
                          '_actions': {
                              'actionsID_action': {
                                  'enabled': True,
                                  'name': 'Testaction'
                              }
                          }}
                },
                'Attributes': {}
            }
        )
        environment = models.Environment(**expected)
        test_utils.save_models(environment)
        req = self._post('/environments/12345/actions/actionID_action', b'{}')
        user_id = req.context.user

        self._create_session_with_state(environment, user_id,
                                        states.SessionState.DELETING)
        self.assertRaises(exc.HTTPForbidden, self.controller.execute,
                          req, '12345', 'actionsID_action', {})
Esempio n. 13
0
    def setUp(self):
        super(TestManage, self).setUp()

        session = db_session.get_session()
        # Create environment.
        self.test_environment = models.Environment(name=b'test_environment',
                                                   tenant_id=b'test_tenant_id',
                                                   version=1)
        # Create categories.
        self.test_categories = [
            models.Category(name=b'test_category_1'),
            models.Category(name=b'test_category_2')
        ]
        # Create tags.
        self.test_tags = [
            models.Tag(name=b'test_tag_1'),
            models.Tag(name=b'test_tag_2')
        ]
        # Add environment, categories and tags to DB.
        with session.begin():
            session.add(self.test_environment)
            session.add_all(self.test_categories)
            session.add_all(self.test_tags)
        # Create package.
        self.test_package = models.Package(
            fully_qualified_name=b'test_fqn',
            name=b'test_name',
            logo=b'test_logo',
            supplier_logo=b'test_supplier_logo',
            type=b'test_type',
            description=b'test_desc',
            is_public=True,
            archive=b'test_archive',
            ui_definition=b'test_ui_definition',
            categories=self.test_categories,
            tags=self.test_tags,
            owner_id=self.test_environment.tenant_id,
        )
        # Add the package to the DB.
        with session.begin():
            session.add(self.test_package)
        # Create class definitions and assign their FKs to test_package.id.
        self.test_class_definitions = [
            models.Class(name=b'test_class_definition_1',
                         package_id=self.test_package.id),
            models.Class(name=b'test_class_definition_2',
                         package_id=self.test_package.id)
        ]
        # Add the class definitions to the DB and update the FK reference for
        # test_package.class_definitions.
        with session.begin():
            session.add_all(self.test_class_definitions)
            self.test_package.class_definitions = self.test_class_definitions
            session.add(self.test_package)
        # Create mock object that resembles loaded package from
        # load_utils.load_from_dir
        self.mock_loaded_package = mock.MagicMock(
            full_name=self.test_package.fully_qualified_name,
            display_name=self.test_package.name,
            package_type=self.test_package.type,
            author=self.test_package.author,
            supplier=self.test_package.supplier,
            description=self.test_package.description,
            tags=[tag.name for tag in self.test_package.tags],
            classes=[cls.name for cls in self.test_package.class_definitions],
            logo=self.test_package.logo,
            supplier_logo=self.test_package.supplier_logo,
            ui=self.test_package.ui_definition,
            blob=self.test_package.archive)
Esempio n. 14
0
    def test_execute_action(self, mock_policy_check):
        """Test that action execution results in the correct rpc call."""
        self._set_policy_rules(
            {'execute_action': '@'}
        )

        fake_now = timeutils.utcnow()
        expected = dict(
            id='12345',
            name='my-env',
            version=0,
            created=fake_now,
            updated=fake_now,
            tenant_id=self.tenant,
            description={
                'Objects': {
                    '?': {'id': '12345',
                          '_actions': {
                              'actionsID_action': {
                                  'enabled': True,
                                  'name': 'Testaction'
                              }
                          }}
                },
                'Attributes': {}
            }
        )
        e = models.Environment(**expected)
        test_utils.save_models(e)

        rpc_task = {
            'action': {
                'args': '{}',
                'method': 'Testaction',
                'object_id': '12345'
            },
            'project_id': self.tenant,
            'user_id': self.user,
            'model': {
                'Attributes': {},
                'Objects': {
                    'applications': [],
                    '?': {
                        '_actions': {
                            'actionsID_action': {
                                'enabled': True,
                                'name': 'Testaction'
                            }
                        },
                        'id': '12345'
                    }
                }
            },
            'token': None,
            'id': '12345'
        }

        req = self._post('/environments/12345/actions/actionID_action', b'{}')
        result = self.controller.execute(req, '12345', 'actionsID_action',
                                         '{}')

        self.mock_engine_rpc.handle_task.assert_called_once_with(rpc_task)

        self.assertIn('task_id', result)
Esempio n. 15
0
    def test_report_env_stats(self, mock_notifier):
        now = timeutils.utcnow()
        later = now + dt.timedelta(minutes=1)

        session = db_session.get_session()

        environment1 = models.Environment(
            name='test_environment1', tenant_id='test_tenant_id1',
            version=2, id='test_env_id_1',
            created=now,
            updated=later,
            description={
                'Objects': {
                    'applications': ['app1'],
                    'services': ['service1']
                }
            }
        )
        environment2 = models.Environment(
            name='test_environment2', tenant_id='test_tenant_id2',
            version=1, id='test_env_id_2',
            created=now,
            updated=later,
            description={
                'Objects': {
                    'applications': ['app2'],
                    'services': ['service3']
                }
            }
        )
        environment3 = models.Environment(
            name='test_environment3', tenant_id='test_tenant_id2',
            version=1, id='test_env_id_3',
            created=now,
            updated=later,
            description={}
        )

        session_1 = models.Session(
            environment=environment1, user_id='test_user_id',
            description={},
            state=states.SessionState.DEPLOYED,
            version=1
        )

        session_2 = models.Session(
            environment=environment2, user_id='test_user_id',
            description={},
            state=states.SessionState.DEPLOYED,
            version=0
        )

        session_3 = models.Session(
            environment=environment3, user_id='test_user_id',
            description={},
            state=states.SessionState.DEPLOY_FAILURE,
            version=1
        )

        task_1 = models.Task(
            id='task_id_1',
            environment=environment1,
            description={},
            created=now,
            started=now,
            updated=later,
            finished=later
        )

        task_2 = models.Task(
            id='task_id_2',
            environment=environment2,
            description={},
            created=now,
            started=now,
            updated=later,
            finished=later
        )

        task_3 = models.Task(
            id='task_id_3',
            environment=environment3,
            description={},
            created=now,
            started=now,
            updated=later,
            finished=later
        )

        status_1 = models.Status(
            id='status_id_1',
            task_id='task_id_1',
            text='Deployed',
            level='info'
        )

        status_2 = models.Status(
            id='status_id_2',
            task_id='task_id_2',
            text='Deployed',
            level='info'
        )

        status_3 = models.Status(
            id='status_id_3',
            task_id='task_id_3',
            text='Something was wrong',
            level='error'
        )

        session.add_all([environment1, environment2, environment3])
        session.add_all([session_1, session_2, session_3])
        session.add_all([task_1, task_2, task_3])
        session.add_all([status_1, status_2, status_3])

        session.flush()

        self.service.report_env_stats()

        self.assertEqual(mock_notifier.call_count, 2)

        dict_env_1 = {'version': 2,
                      'updated': later,
                      'tenant_id': u'test_tenant_id1',
                      'created': now,
                      'description_text': u'',
                      'status': 'ready',
                      'id': u'test_env_id_1',
                      'name': u'test_environment1'}

        dict_env_2 = {'version': 1,
                      'updated': later,
                      'tenant_id': u'test_tenant_id2',
                      'created': now,
                      'description_text': u'',
                      'status': 'ready',
                      'id': u'test_env_id_2',
                      'name': u'test_environment2'}

        calls = [mock.call('environment.exists', dict_env_1),
                 mock.call('environment.exists', dict_env_2)]

        mock_notifier.assert_has_calls(calls)