Ejemplo n.º 1
0
def generic_deployment() -> Deployment:
    dep = Deployment()
    dep.deployment_id = str(uuid.uuid4())
    dep.state = InvocationState.SUCCESS
    # dep.label = 'deployment_label'
    dep.operation = OperationType.DEPLOY_FRESH
    dep.timestamp = timestamp_util.datetime_now_to_string()
    return dep
Ejemplo n.º 2
0
    def add_revision(self,
                     blueprint_id: uuid = None,
                     CSAR: FileStorage = None,
                     blueprint_path: Path = None,
                     revision_msg: str = None,
                     minor_to_increment: str = None):
        """
        saves blueprint into database. One of (CSAR, blueprint_path) must not be None. If blueprint_token is None,
        it is generated and returned together with version_id

        if minor_to_increment not None, minor version of tag will be incremented, else, major version (of all tags)
        will be incremented
        """
        token = blueprint_id or uuid.uuid4()
        path = Path(
            tempfile.mkdtemp()) if not blueprint_path else blueprint_path

        if CSAR is not None:
            workdir = Path(tempfile.mkdtemp())
            CSAR_path = workdir / Path(CSAR.filename)
            workdir.mkdir(parents=True, exist_ok=True)
            CSAR.save(CSAR_path.open('wb'))
            try:
                csar_to_blueprint(csar=CSAR_path, dst=path)
            except shutil.ReadError as e:
                logger.error(str(e))
                shutil.rmtree(str(workdir))
                return None, str(e)
            shutil.rmtree(str(workdir))
            try:
                validate_csar(path, raise_exceptions=True)
            except Exception as e:
                logger.error(str(e))
                shutil.rmtree(str(path))
                return None, str(e)

        elif blueprint_path is None:
            # both params cannot be None
            raise AttributeError('Both CSAR and blueprint path cannot be None')
        result = self.connection.save_CSAR(
            csar_path=path,
            csar_token=token,
            message=revision_msg,
            minor_to_increment=minor_to_increment)
        https_url = self.connection.get_repo_url(csar_token=token)
        users = self.connection.get_user_list(csar_token=token)
        if CSAR is not None:
            shutil.rmtree(str(path))

        return {
            'message': "Revision saved to GitDB",
            'blueprint_id': result['token'],
            'url': https_url,
            'commit_sha': result['commit_sha'],
            'version_id': result['version_tag'],
            'users': users,
            'timestamp': datetime_now_to_string()
        }, None
Ejemplo n.º 3
0
def generic_invocation():
    inv = Invocation()
    inv.state = InvocationState.PENDING
    inv.deployment_label = 'TestDeployment'
    inv.blueprint_id = str(uuid.uuid4())
    inv.deployment_id = str(uuid.uuid4())
    inv.version_id = 'v1.0'
    inv.operation = OperationType.DEPLOY_FRESH
    inv.timestamp_submission = timestamp_util.datetime_now_to_string()
    return inv
Ejemplo n.º 4
0
def generic_blueprint_meta() -> BlueprintVersion:
    blueprint_meta = BlueprintVersion()
    blueprint_meta.blueprint_id = str(uuid.uuid4())
    blueprint_meta.version_id = 'v1.0'
    blueprint_meta.blueprint_name = 'name'
    blueprint_meta.aadm_id = str(uuid.uuid4())
    blueprint_meta.username = '******'
    blueprint_meta.project_domain = 'project_domain'
    blueprint_meta.url = 'https://github.com/torvalds/linux'
    blueprint_meta.commit_sha = 'd7c5303fbc8ac874ae3e597a5a0d3707dc0230b4'
    blueprint_meta.timestamp = timestamp_util.datetime_now_to_string()
    return blueprint_meta
    def test_success(client, mocker, generic_blueprint_meta, patch_auth_wrapper):
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        blueprint_meta.deployments = [
            Deployment(
                str(uuid.uuid4()), InvocationState.SUCCESS,
                OperationType.DEPLOY_CONTINUE, timestamp_util.datetime_now_to_string()
            )]
        mocker.patch('opera.api.service.sqldb_service.PostgreSQL.get_blueprint_meta',
                     return_value=blueprint_meta.to_dict())
        mocker.patch('opera.api.service.csardb_service.GitDB.get_blueprint_user_list', return_value=[['foo'], None])

        resp = client.get(f"/blueprint/{uuid.uuid4()}/version/v1.0/meta")
        assert resp.status_code == 200
        assert_that(resp.json).contains(*[key for key in blueprint_meta.to_dict().keys() if key is not None])
 def test_success(self, client, mocker, patch_auth_wrapper):
     blueprints = [{
         "blueprint_id": '91df79b1-d78b-4cac-ae24-4edaf49c5030',
         "blueprint_name": 'TestBlueprint',
         "aadm_id": 'aadm_id',
         "username": '******',
         "project_domain": 'SODALITE',
         "timestamp": timestamp_util.datetime_now_to_string()
     }]
     mocker.patch(
         'opera.api.service.sqldb_service.PostgreSQL.get_blueprints_by_user_or_project',
         return_value=blueprints)
     resp = client.get(f"/blueprint?username=foo")
     assert_that(resp.status_code).is_equal_to(200)
     assert_that(len(resp.json)).is_equal_to(1)
     assert_that(resp.json).is_equal_to(blueprints)
def delete_blueprint_version(blueprint_id, version_id, force=None):
    """Delete version of blueprint.

    :param blueprint_id: Id of blueprint
    :type blueprint_id: 
    :param version_id: Id of blueprint version
    :type version_id: str
    :param force: force delete blueprint
    :type force: bool

    :rtype: Blueprint
    """
    if not force:
        if PostgreSQL.blueprint_used_in_deployment(blueprint_id, version_id):
            return "Cannot delete blueprint, deployment with this blueprint exists", 403

    repo_url, _ = CSAR_db.get_repo_url(blueprint_id)

    rows_affected, status_code = CSAR_db.delete_blueprint(
        blueprint_id, version_id)
    logger.debug(f"Rows affected, status_code: {rows_affected} {status_code}")

    if status_code == 200:
        PostgreSQL.delete_blueprint_meta(blueprint_id, version_id)
        PostgreSQL.save_git_transaction_data(
            blueprint_id=blueprint_id,
            version_id=version_id,
            revision_msg=f"Deleted a version of blueprint",
            job='delete',
            git_backend=str(CSAR_db.connection.git_connector),
            repo_url=repo_url)
        return BlueprintVersion(
            blueprint_id=blueprint_id,
            version_id=version_id,
            url=repo_url,
            timestamp=timestamp_util.datetime_now_to_string()), 200

    message = {
        200: 'Successfully removed',
        404: 'Blueprint version or blueprint not found',
        500: 'Server error'
    }

    return message[status_code], status_code
    def test_keys(self, client, mocker, patch_auth_wrapper):
        git_data = GitLog(
            blueprint_id=str(uuid.uuid4()),
            commit_sha="commit_sha",
            git_backend="MockConnector",
            job="update",
            repo_url="local",
            revision_msg="rev_msg",
            timestamp=timestamp_util.datetime_now_to_string(),
            version_id='v1.0'
        )
        mock_git_data = mocker.MagicMock(name='invoke', return_value=[git_data.to_dict()])
        mocker.patch('opera.api.service.sqldb_service.PostgreSQL.get_git_transaction_data', new=mock_git_data)

        resp = client.get(f"/blueprint/{git_data.blueprint_id}/git_history")
        assert resp.status_code == 200
        assert_that(resp.json).is_length(1)
        assert_that(resp.json[0]).contains_only(*git_data.to_dict().keys())
        mock_git_data.assert_called_with(git_data.blueprint_id)
 def test_no_blueprint(self, client, mocker, patch_db):
     # assert endpoint works even when blueprint is gone
     blueprint_id = uuid.uuid4()
     mocker.patch('opera.api.service.csardb_service.GitDB.version_exists', return_value=False)
     git_data = GitLog(
         blueprint_id=str(blueprint_id),
         commit_sha="commit_sha",
         git_backend="MockConnector",
         job="update",
         repo_url="local",
         revision_msg="rev_msg",
         timestamp=timestamp_util.datetime_now_to_string(),
         version_id='v1.0'
     )
     mocker.patch('opera.api.service.sqldb_service.PostgreSQL.get_git_transaction_data',
                  return_value=[git_data.to_dict()])
     blueprint_id = uuid.uuid4()
     resp = client.get(f"/blueprint/{blueprint_id}/git_history")
     assert resp.status_code == 200
    def test_success(self, client, csar_1, mocker):
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.save_blueprint_meta',
            return_value=True)
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.save_git_transaction_data'
        )
        mocker.patch('opera.api.controllers.security_controller.check_roles',
                     return_value=True)
        mocker.patch('opera.api.service.csardb_service.GitDB.add_revision',
                     return_value=({
                         'message':
                         "Revision saved to GitDB",
                         'blueprint_id':
                         uuid.uuid4(),
                         'url':
                         'https://google.com',
                         'commit_sha':
                         'commit_sha',
                         'version_id':
                         'v1.0',
                         'users': ['xopera'],
                         'timestamp':
                         timestamp_util.datetime_now_to_string()
                     }, None))
        revision_msg = 'Another blueprint'
        name = 'Test blueprint'
        aadm_id = str(uuid.uuid4())
        username = '******'
        project_domain = 'SODALITE'
        resp = client.post(
            f"/blueprint?revision_msg={revision_msg}&blueprint_name={name}&aadm_id={aadm_id}"
            f"&username={username}&project_domain={project_domain}",
            data=csar_1)
        assert_that(resp.status_code).is_equal_to(201)
        assert_that(resp.json).is_not_none().contains_only(
            'blueprint_id', 'version_id', 'blueprint_name', 'aadm_id', 'url',
            'project_domain', 'username', 'commit_sha', 'timestamp')
        uuid.UUID(resp.get_json()['blueprint_id'])

        assert_that(resp.get_json()['version_id']).is_equal_to('v1.0')

        validators.url(resp.get_json()['url'])
    def test_success(self, client, csar_1, mocker, patch_auth_wrapper):
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.save_blueprint_meta',
            return_value=True)
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.version_exists',
            return_value=True)
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.get_project_domain',
            return_value=None)
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.save_git_transaction_data'
        )
        mocker.patch('opera.api.service.csardb_service.GitDB.version_exists',
                     return_value=True)
        mocker.patch('opera.api.service.csardb_service.GitDB.add_revision',
                     return_value=({
                         'message':
                         "Revision saved to GitDB",
                         'blueprint_id':
                         uuid.uuid4(),
                         'url':
                         'https://google.com',
                         'commit_sha':
                         'commit_sha',
                         'version_id':
                         'v2.0',
                         'users': ['xopera'],
                         'timestamp':
                         timestamp_util.datetime_now_to_string()
                     }, None))

        # test new version
        resp2 = client.post(f"/blueprint/{uuid.uuid4()}", data=csar_1)
        assert_that(resp2.status_code).is_equal_to(201)
        assert_that(resp2.json).is_not_none().contains_only(
            'blueprint_id', 'url', 'version_id', 'commit_sha', 'timestamp')
        assert_that(resp2.json['version_id']).is_equal_to('v2.0')
Ejemplo n.º 12
0
 def save_opera_session_data(cls, deployment_id: uuid, tree: dict):
     """
     Saves .opera file tree to database
     """
     tree_str = json.dumps(tree)
     timestamp = timestamp_util.datetime_now_to_string()
     response = cls.execute(
         """insert into {} (deployment_id, timestamp, tree)
            values (%s, %s, %s)
            ON CONFLICT (deployment_id) DO UPDATE
                SET timestamp=excluded.timestamp,
                tree=excluded.tree;""".format(
             Settings.opera_session_data_table),
         (str(deployment_id), timestamp, tree_str))
     if response:
         logger.debug(
             f'Updated dot_opera_data for deployment_id={deployment_id} in PostgreSQL database'
         )
     else:
         logger.error(
             f'Failed to update dot_opera_data for deployment_id={deployment_id} in PostgreSQL database'
         )
     return response
 def test_project_data_saving_error(self, csar_1, client, mocker,
                                    patch_auth_wrapper):
     mocker.patch(
         'opera.api.service.sqldb_service.PostgreSQL.save_blueprint_meta',
         return_value=False)
     mocker.patch('opera.api.service.csardb_service.GitDB.add_revision',
                  return_value=({
                      'message':
                      "Revision saved to GitDB",
                      'blueprint_id':
                      uuid.uuid4(),
                      'url':
                      'https://google.com',
                      'commit_sha':
                      'commit_sha',
                      'version_id':
                      'v2.0',
                      'users': ['xopera'],
                      'timestamp':
                      timestamp_util.datetime_now_to_string()
                  }, None))
     resp = client.post(f"/blueprint/{uuid.uuid4()}", data=csar_1)
     assert_that(resp.status_code).is_equal_to(500)
     assert_that(resp.json).contains('Failed to save project data')
Ejemplo n.º 14
0
class TestSessionData:
    session_data = {
        'deployment_id': uuid.uuid4(),
        'timestamp': timestamp_util.datetime_now_to_string(),
        'tree': {}
    }

    def test_save_success(self, mocker, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        deployment_id = uuid.uuid4()
        assert_that(db.save_opera_session_data(deployment_id, {})).is_true()
        assert_that(caplog.text).contains("Updated dot_opera_data",
                                          str(deployment_id))

    def test_save_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)
        deployment_id = uuid.uuid4()
        assert_that(db.save_opera_session_data(deployment_id, {})).is_false()
        assert_that(caplog.text).contains("Failed to update dot_opera_data",
                                          str(deployment_id))

    def test_get_opera_session_data(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', OperaSessionDataCursor)

        assert_that(
            db.get_opera_session_data(
                self.session_data['deployment_id'])).is_equal_to(
                    self.session_data)

    def test_get_opera_session_data_fail(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        assert_that(
            db.get_opera_session_data(
                self.session_data['deployment_id'])).is_none()

    def test_delete_opera_session_data(self, mocker, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        deployment_id = uuid.uuid4()
        assert_that(db.delete_opera_session_data(deployment_id)).is_true()
        assert_that(caplog.text).contains("Deleted opera_session_data",
                                          str(deployment_id))

    def test_delete_opera_session_data_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        deployment_id = uuid.uuid4()
        assert_that(db.delete_opera_session_data(deployment_id)).is_false()
        assert_that(caplog.text).contains(
            "Failed to delete opera_session_data", str(deployment_id))
Ejemplo n.º 15
0
class TestGetBlueprint:
    blueprints = [{
        "blueprint_id": '91df79b1-d78b-4cac-ae24-4edaf49c5030',
        "blueprint_name": 'TestBlueprint',
        "aadm_id": 'aadm_id',
        "username": '******',
        "project_domain": 'SODALITE',
        "timestamp": timestamp_util.datetime_now_to_string()
    }, {
        "blueprint_id": 'b02e465f-eb6e-42a0-af1c-13bc63c3eed5',
        "blueprint_name": 'BlueprintNoDeployment',
        "aadm_id": 'aadm_id',
        "username": '******',
        "project_domain": 'SODALITE',
        "timestamp": timestamp_util.datetime_now_to_string()
    }, {
        "blueprint_id": 'b02e465f-eb6e-42a0-af1c-13bc63c3eed6',
        "blueprint_name": 'BlueprintInactiveDeployment',
        "aadm_id": 'aadm_id',
        "username": '******',
        "project_domain": 'SODALITE',
        "timestamp": timestamp_util.datetime_now_to_string()
    }]

    deployments = [{
        'deployment_id': '3fa85f64-5717-4562-b3fc-2c963f66afa6',
        'blueprint_id': '91df79b1-d78b-4cac-ae24-4edaf49c5030',
        'state': InvocationState.SUCCESS,
        'operation': OperationType.DEPLOY_FRESH,
        'timestamp': '2021-10-15T10:33:50.318695+00:00'
    }, {
        'deployment_id': '3fa85f64-5717-4562-b3fc-2c963f66afa7',
        'blueprint_id': 'b02e465f-eb6e-42a0-af1c-13bc63c3eed6',
        'state': InvocationState.SUCCESS,
        'operation': OperationType.UNDEPLOY,
        'timestamp': '2021-10-15T10:34:51.318695+00:00'
    }, {
        'deployment_id': '3fa85f64-5717-4562-b3fc-2c963f66afa7',
        'blueprint_id': 'b02e465f-eb6e-42a0-af1c-13bc63c3eed6',
        'state': InvocationState.SUCCESS,
        'operation': OperationType.UNDEPLOY,
        'timestamp': '2021-10-15T10:34:55.318695+00:00'
    }]

    def test_user(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintCursor)

        # testing
        assert db.get_blueprints_by_user_or_project(
            username='******', active=False) == self.blueprints

    def test_project_domain(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintCursor)

        # testing
        assert db.get_blueprints_by_user_or_project(
            project_domain='project_domain', active=False) == self.blueprints

    def test_user_and_project_domain(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintCursor)

        # testing
        assert db.get_blueprints_by_user_or_project(
            username='******', project_domain='project_domain',
            active=False) == self.blueprints

    def test_active(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintCursor)

        # testing
        assert db.get_blueprints_by_user_or_project(
            username='******', active=True) == [self.blueprints[0]]
Ejemplo n.º 16
0
class TestGitTransactionData:
    git_log = GitLog.from_dict({
        'blueprint_id':
        uuid.uuid4(),
        'version_id':
        'v1.0',
        'revision_msg':
        'revision_msg',
        'job':
        'update',
        'git_backend':
        'gitlab',
        'repo_url':
        'https://gitlab.com/sodalite.xopera/gitDB_546c27fb-faa0-4b51-a241-22d9d1e6faf2',
        'commit_sha':
        '4eb6309f062eb9d62a916c85d12824a73057cd7d',
        'timestamp':
        timestamp_util.datetime_now_to_string()
    })

    def test_get(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GitTransactionDataCursor)

        # testing
        assert_that(
            db.get_git_transaction_data(
                blueprint_id=self.git_log.blueprint_id)).is_equal_to(
                    [obj_to_json(self.git_log)])

    def test_save_success(self, mocker, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        # testing
        assert_that(
            db.save_git_transaction_data(
                blueprint_id=self.git_log.blueprint_id,
                version_id=self.git_log.version_id,
                revision_msg=self.git_log.revision_msg,
                job=self.git_log.job,
                git_backend=self.git_log.git_backend,
                repo_url=self.git_log.repo_url,
                commit_sha=self.git_log.commit_sha)).is_true()

        assert_that(caplog.text).contains("Updated git log",
                                          str(self.git_log.blueprint_id),
                                          str(self.git_log.version_id))

    def test_save_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        # testing
        assert_that(
            db.save_git_transaction_data(
                blueprint_id=self.git_log.blueprint_id,
                version_id=self.git_log.version_id,
                revision_msg=self.git_log.revision_msg,
                job=self.git_log.job,
                git_backend=self.git_log.git_backend,
                repo_url=self.git_log.repo_url,
                commit_sha=self.git_log.commit_sha)).is_false()

        assert_that(caplog.text).contains("Failed to update git log",
                                          str(self.git_log.blueprint_id),
                                          str(self.git_log.version_id))
Ejemplo n.º 17
0
 def test_datetime_now_to_string(self):
     tmstp_now_str = timestamp_util.datetime_now_to_string()
     assert_that(tmstp_now_str).is_type_of(str)
     datetime.datetime.strptime(tmstp_now_str, '%Y-%m-%dT%H:%M:%S.%f%z')
Ejemplo n.º 18
0
class TestInvocation:
    inv = Invocation(
        deployment_id=str(uuid.uuid4()),
        deployment_label='label',
        timestamp_submission=timestamp_util.datetime_now_to_string(),
        blueprint_id=str(uuid.uuid4()),
        version_id='v1.0',
        state=InvocationState.SUCCESS,
        operation=OperationType.DEPLOY_CONTINUE)
    invocation_id = str(uuid.uuid4())
    _log = 'deployment log'

    def test_get_last_invocation_id_fail(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        assert_that(db.get_last_invocation_id(uuid.uuid4())).is_none()

    def test_get_last_invocation_id_success(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(db.get_last_invocation_id(uuid.uuid4())).is_equal_to(
            self.invocation_id)

    def test_get_deployment_history(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that([
            obj_to_json(x) for x in db.get_deployment_history(uuid.uuid4())
        ]).is_equal_to([self.inv.to_dict()])

    def test_get_last_completed_invocation(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(obj_to_json(db.get_last_completed_invocation(
            uuid.uuid4()))).is_equal_to(self.inv.to_dict())

    def test_get_last_completed_invocation_fail(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        assert_that(db.get_last_completed_invocation(uuid.uuid4())).is_none()

    def test_get_deployment_status(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(obj_to_json(db.get_deployment_status(
            uuid.uuid4()))).is_equal_to(self.inv.to_dict())

    def test_get_deployment_status_fail(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        assert_that(db.get_deployment_status(uuid.uuid4())).is_none()

    def test_update_deployment_log_success(self, mocker, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        assert_that(db.update_deployment_log(self.invocation_id,
                                             self.inv)).is_true()

        assert_that(caplog.text).contains("Updated deployment log",
                                          str(self.inv.deployment_id),
                                          str(self.invocation_id))

    def test_update_deployment_log_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        assert_that(db.update_deployment_log(self.invocation_id,
                                             self.inv)).is_false()

        assert_that(caplog.text).contains("Failed to update deployment log",
                                          str(self.inv.deployment_id),
                                          str(self.invocation_id))

    def test_get_deployment_ids(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(db.get_deployment_ids(uuid.uuid4())).is_equal_to(
            [self.inv.deployment_id])

    def test_get_deployment_ids_version(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(db.get_deployment_ids(uuid.uuid4(), 'v1.0')).is_equal_to(
            [self.inv.deployment_id])

    def test_blueprint_used_in_deployment_no_deployment_ids(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        mocker.patch(
            'opera.api.service.sqldb_service.PostgreSQL.get_deployment_ids',
            return_value=None)
        db = PostgreSQL()

        assert_that(db.blueprint_used_in_deployment(uuid.uuid4(),
                                                    'v1.0')).is_false()

    def test_blueprint_used_in_deployment(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(db.blueprint_used_in_deployment(uuid.uuid4())).is_true()

    def test_blueprint_used_in_deployment_version(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(
            db.blueprint_used_in_deployment(uuid.uuid4(),
                                            self.inv.version_id)).is_true()

    def test_blueprint_used_in_deployment_version_no_ids(
            self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', InvocationCursor)

        assert_that(db.blueprint_used_in_deployment(uuid.uuid4(),
                                                    'blah')).is_false()

    def test_delete_deployment(self, mocker, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        deployment_id = uuid.uuid4()
        assert_that(db.delete_deployment(deployment_id)).is_true()
        assert_that(caplog.text).contains("Deleted deployment",
                                          str(deployment_id))

    def test_delete_deployment_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        deployment_id = uuid.uuid4()
        assert_that(db.delete_deployment(deployment_id)).is_false()
        assert_that(caplog.text).contains("Failed to delete deployment",
                                          str(deployment_id))
Ejemplo n.º 19
0
class TestBlueprintMeta:
    def test_save_blueprint_meta(self, mocker, monkeypatch, caplog,
                                 generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        monkeypatch.setattr(FakePostgres, 'cursor', NoneCursor)
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        # testing
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        db.save_blueprint_meta(blueprint_meta)
        replacements = NoneCursor.get_replacements()
        assert_that(replacements).contains_only(*[
            str(blueprint_meta.blueprint_id), blueprint_meta.version_id,
            blueprint_meta.blueprint_name, blueprint_meta.aadm_id,
            blueprint_meta.username, blueprint_meta.project_domain,
            blueprint_meta.url, blueprint_meta.commit_sha
        ])
        assert_that(caplog.text).contains("Updated blueprint meta",
                                          str(blueprint_meta.blueprint_id))

    def test_save_blueprint_meta_exception(self, mocker, caplog, monkeypatch,
                                           generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        db.save_blueprint_meta(blueprint_meta)

        assert_that(caplog.text).contains("Fail to update blueprint meta",
                                          str(blueprint_meta.blueprint_id))

    blueprint_meta = BlueprintVersion(
        blueprint_id=str(uuid.uuid4()),
        version_id='v1.0',
        blueprint_name='a',
        aadm_id=str(uuid.uuid4()),
        username='******',
        project_domain='some_domain',
        url='www.google.com',
        timestamp=datetime.datetime.now(),
        commit_sha='d955c23e2771639202f52db9d40c633f6f732e55')

    def test_get_blueprint_meta(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintMetaCursor)

        # test
        blueprint_meta: BlueprintVersion = self.blueprint_meta
        assert_that(
            BlueprintVersion.from_dict(
                db.get_blueprint_meta(
                    blueprint_meta.blueprint_id))).is_equal_to(blueprint_meta)

    def test_get_blueprint_meta_version(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintMetaCursor)

        # test
        blueprint_meta: BlueprintVersion = self.blueprint_meta
        assert_that(
            BlueprintVersion.from_dict(
                db.get_blueprint_meta(
                    blueprint_id=blueprint_meta.blueprint_id,
                    version_id=blueprint_meta.version_id))).is_equal_to(
                        blueprint_meta)

    def test_get_project_blueprint_meta_missing(self, mocker, caplog,
                                                generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        assert db.get_blueprint_meta(blueprint_meta.blueprint_id) is None

    def test_get_project_domain(self, mocker, caplog, monkeypatch,
                                generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintMetaCursor)

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        assert db.get_project_domain(
            blueprint_meta.blueprint_id) == blueprint_meta.project_domain

    def test_get_project_domain_missing(self, mocker, caplog,
                                        generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        assert db.get_project_domain(blueprint_meta.blueprint_id) is None

    def test_get_blueprint_name(self, mocker, caplog, monkeypatch,
                                generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintMetaCursor)

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        assert db.get_blueprint_name(
            blueprint_meta.blueprint_id) == blueprint_meta.blueprint_name

    def test_save_blueprint_name(self, mocker, monkeypatch, caplog,
                                 generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', NoneCursor)

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        new_name = 'new_name'
        db.update_blueprint_name(blueprint_meta.blueprint_id, new_name)
        command = NoneCursor.get_command()
        assert_that(command).contains(blueprint_meta.blueprint_name, new_name)
        assert_that(caplog.text).contains("Updated blueprint name", new_name,
                                          str(blueprint_meta.blueprint_id))

    def test_save_blueprint_name_exception(self, mocker, monkeypatch, caplog,
                                           generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        new_name = 'new_name'
        db.update_blueprint_name(blueprint_meta.blueprint_id, new_name)

        assert_that(caplog.text).contains("Fail to update blueprint name",
                                          new_name,
                                          str(blueprint_meta.blueprint_id))

    def test_get_blueprint_name_missing(self, mocker, caplog,
                                        generic_blueprint_meta):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        # test
        blueprint_meta: BlueprintVersion = generic_blueprint_meta
        assert db.get_blueprint_name(blueprint_meta.blueprint_id) is None

    def test_delete_blueprint_meta(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', NoneCursor)

        # testing
        blueprint_id = uuid.uuid4()
        assert db.delete_blueprint_meta(blueprint_id)
        command = NoneCursor.get_command()
        assert_that(command).contains("delete")
        assert_that(caplog.text).contains("Deleted blueprint meta",
                                          str(blueprint_id))

    def test_delete_blueprint_version_meta(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', NoneCursor)

        # testing
        blueprint_id = uuid.uuid4()
        version_id = 'v1.0'
        assert db.delete_blueprint_meta(blueprint_id, version_id)
        command = NoneCursor.get_command()
        assert_that(command).contains("delete")
        assert_that(caplog.text).contains("Deleted blueprint meta",
                                          str(blueprint_id), str(version_id))

    def test_delete_blueprint_meta_fail(self, mocker, monkeypatch, caplog):
        # test set up
        caplog.set_level(logging.DEBUG,
                         logger="opera.api.service.sqldb_service")
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', PsycopgErrorCursor)

        # testing
        blueprint_id = uuid.uuid4()
        assert not db.delete_blueprint_meta(blueprint_id)
        assert_that(caplog.text).contains(
            "Failed to delete blueprint metadata", str(blueprint_id))

    inputs = {'foo': 'bar', 'foo2': 'bar2'}

    def test_get_inputs(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetInputsCursor)

        deployment_id = uuid.uuid4()
        assert_that(db.get_inputs(deployment_id=deployment_id)).is_equal_to(
            self.inputs)

    def test_get_inputs_missing(self, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()

        deployment_id = uuid.uuid4()
        assert_that(db.get_inputs(deployment_id=deployment_id)).is_none()

    def test_get_inputs_exception(self, monkeypatch, mocker):
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetStringCursor)

        deployment_id = uuid.uuid4()
        assert_that(db.get_inputs(deployment_id=deployment_id)).is_none()

    deployment = {
        'deployment_id': str(uuid.uuid4()),
        'state': InvocationState.SUCCESS,
        'operation': OperationType.DEPLOY_CONTINUE,
        'timestamp': timestamp_util.datetime_now_to_string(),
        'last_inputs': None,
        'deployment_label': 'label'
    }

    def test_get_deployments(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetBlueprintMetaCursor)

        blueprint_id = uuid.uuid4()
        assert_that(
            db.get_deployments_for_blueprint(
                blueprint_id, active=False)).is_equal_to([self.deployment])

    deployments = [{
        "deployment_id": "71ceef1c-f169-4204-b180-e95948329108",
        "operation": OperationType.DEPLOY_FRESH,
        "state": InvocationState.SUCCESS,
        "timestamp": timestamp_util.datetime_now_to_string(),
        'last_inputs': None,
        'deployment_label': 'label'
    }, {
        "deployment_id":
        "30e143c9-e614-41bc-9b22-47c588f394e3",
        "operation":
        OperationType.UNDEPLOY,
        "state":
        InvocationState.SUCCESS,
        "timestamp":
        timestamp_util.datetime_to_str(datetime.datetime.fromtimestamp(1)),
        'last_inputs':
        None,
        'deployment_label':
        'label'
    }]

    def test_get_active_deployments(self, monkeypatch, mocker):
        # test set up
        mocker.patch('psycopg2.connect', new=FakePostgres)
        db = PostgreSQL()
        monkeypatch.setattr(FakePostgres, 'cursor', GetDeploymentsCursor)

        blueprint_id = uuid.uuid4()
        assert_that(
            db.get_deployments_for_blueprint(
                blueprint_id, active=False)).is_equal_to(self.deployments)
        assert_that(db.get_deployments_for_blueprint(
            blueprint_id, active=True)).is_equal_to([self.deployments[0]])