Example #1
0
def add_type():
    from bson import json_util

    type_manager = TypeManager(database_manager=current_app.database_manager)

    error_collection = {}
    upload = request.form.get('uploadFile')
    new_type_list = json.loads(upload, object_hook=json_util.object_hook)
    for new_type_data in new_type_list:
        try:
            new_type_data['public_id'] = object_manager.get_new_id(TypeModel.COLLECTION)
            new_type_data['creation_time'] = datetime.now(timezone.utc)
        except TypeError as e:
            LOGGER.warning(e)
            return abort(400)
        try:
            type_instance = TypeModel.from_data(new_type_data)
        except CMDBError:
            return abort(400)
        try:
            type_manager.insert(type_instance)
        except Exception as ex:
            error_collection.update({"public_id": type_instance.public_id, "message": ex.message})

    resp = make_response(error_collection)
    return resp
    def test_get_type(self, rest_api, example_type, full_access_user, none_access_user):
        # Route callable
        default_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}')
        assert default_response.status_code == HTTPStatus.OK

        # Response parsable
        response_dict = default_response.get_json()
        test_type_json = response_dict['result']
        test_type = TypeModel.from_data(test_type_json)
        assert isinstance(test_type, TypeModel)
        assert len(test_type.fields[0].keys()) == 9

        # Not Found
        not_found_response = rest_api.get(f'{self.ROUTE_URL}/{-1}')
        assert not_found_response.status_code == HTTPStatus.NOT_FOUND

        # ACCESS OK
        access_get_types_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}', user=full_access_user)
        assert access_get_types_response.status_code != (HTTPStatus.FORBIDDEN or HTTPStatus.UNAUTHORIZED)

        # ACCESS FORBIDDEN
        none_get_types_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}', user=none_access_user)
        assert none_get_types_response.status_code == HTTPStatus.FORBIDDEN

        # ACCESS UNAUTHORIZED
        none_get_types_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}', unauthorized=True)
        assert none_get_types_response.status_code == HTTPStatus.UNAUTHORIZED
def update_type():
    from bson import json_util

    error_collection = {}
    upload = request.form.get('uploadFile')
    data_dump = json.loads(upload, object_hook=json_util.object_hook)
    for add_data_dump in data_dump:
        try:
            update_type_instance = TypeModel.from_data(add_data_dump)
        except CMDBError:
            return abort(400)
        try:
            old_fields = object_manager.get_type(
                update_type_instance.get_public_id()).get_fields()
            new_fields = update_type_instance.get_fields()

        except Exception as ex:
            error_collection.update({
                "public_id": add_data_dump['public_id'],
                "message": ex.message
            })
        try:
            object_manager.update_type(update_type_instance)
        except Exception as ex:
            error_collection.update({
                "public_id": update_type_instance.public_id,
                "message": ex.details
            })

    resp = make_response(error_collection)
    return resp
Example #4
0
    def find(self, filter: dict, *args, **kwargs) -> ListResult[TypeModel]:
        """
        Get a list of types by a filter query.
        Args:
            filter: Filter for matched querys

        Returns:
            ListResult
        """
        results = self._get(self.collection, filter=filter)
        types: List[TypeModel] = [TypeModel.from_data(result) for result in results]
        return ListResult(types)
Example #5
0
    def get(self, public_id: Union[PublicID, int]) -> TypeModel:
        """
        Get a single type by its id.

        Args:
            public_id (int): ID of the type.

        Returns:
            TypeModel: Instance of TypeModel with data.
        """
        result = super(TypeManager, self).get(public_id=public_id)
        return TypeModel.from_data(result)
Example #6
0
    def get(self, public_id: Union[PublicID, int]) -> TypeModel:
        """
        Get a single type by its id.

        Args:
            public_id (int): ID of the type.

        Returns:
            TypeModel: Instance of TypeModel with data.
        """
        cursor_result = self._get(self.collection, filter={'public_id': public_id}, limit=1)
        for resource_result in cursor_result.limit(-1):
            return TypeModel.from_data(resource_result)
        raise ManagerGetError(f'Type with ID: {public_id} not found!')
Example #7
0
    def test_get_types(self, rest_api, full_access_user, none_access_user):
        # Route callable
        default_response = rest_api.get(f'{self.ROUTE_URL}/')
        assert default_response.status_code == HTTPStatus.OK

        # Response parsable
        response_dict = default_response.get_json()
        test_type_json = response_dict['results'][0]
        test_type = TypeModel.from_data(test_type_json)

        assert len(response_dict['results']) == int(
            default_response.headers['X-Total-Count'])
        assert len(response_dict['results'])
        assert isinstance(test_type, TypeModel)

        # Test filter
        filter_response = rest_api.get(
            f'{self.ROUTE_URL}/',
            query_string={'filter': dumps({'public_id': 1})})
        assert filter_response.status_code == HTTPStatus.OK
        assert int(filter_response.headers['X-Total-Count']) == 1

        # Test empty filter
        empty_filter_response = rest_api.get(
            f'{self.ROUTE_URL}/',
            query_string={'filter': dumps({'public_id': 2})})
        assert empty_filter_response.status_code == HTTPStatus.OK
        assert int(empty_filter_response.headers['X-Total-Count']) == 0

        # Test wrong filter
        wrong_filter_response = rest_api.get(f'{self.ROUTE_URL}/',
                                             query_string={'filter': '\xE9'})
        assert wrong_filter_response.status_code == HTTPStatus.BAD_REQUEST

        # ACCESS OK
        access_get_types_response = rest_api.get(f'{self.ROUTE_URL}/',
                                                 user=full_access_user)
        assert access_get_types_response.status_code != (
            HTTPStatus.FORBIDDEN or HTTPStatus.UNAUTHORIZED)

        # ACCESS FORBIDDEN
        none_get_types_response = rest_api.get(f'{self.ROUTE_URL}/',
                                               user=none_access_user)
        assert none_get_types_response.status_code == HTTPStatus.FORBIDDEN

        # ACCESS UNAUTHORIZED
        none_get_types_response = rest_api.get(f'{self.ROUTE_URL}/',
                                               unauthorized=True)
        assert none_get_types_response.status_code == HTTPStatus.UNAUTHORIZED
def update_type():
    error_collection = {}
    upload = request.form.get('uploadFile')
    data_dump = json.loads(upload, object_hook=json_util.object_hook)
    for add_data_dump in data_dump:
        try:
            update_type_instance = TypeModel.from_data(add_data_dump)
        except CMDBError:
            return abort(400)
        try:
            type_manager.get(update_type_instance.public_id)
            type_manager.update(update_type_instance.public_id,
                                update_type_instance)
        except (Exception, ManagerGetError) as err:
            error_collection.update({
                "public_id": add_data_dump['public_id'],
                "message": err.message
            })

    resp = make_response(error_collection)
    return resp
def add_type():
    error_collection = {}
    upload = request.form.get('uploadFile')
    new_type_list = json.loads(upload, object_hook=json_util.object_hook)
    for new_type_data in new_type_list:
        try:
            new_type_data['public_id'] = object_manager.get_new_id(
                TypeModel.COLLECTION)
            new_type_data['creation_time'] = datetime.now(timezone.utc)
        except TypeError as e:
            LOGGER.error(e)
            return abort(400)
        try:
            type_instance = TypeModel.from_data(new_type_data)
            type_manager.insert(type_instance)
        except (ManagerInsertError, CMDBError) as err:
            error_collection.update({
                "public_id": new_type_data['public_id'],
                "message": err.message
            })

    resp = make_response(error_collection)
    return resp