Ejemplo n.º 1
0
def setup(request, collection, example_type):
    collection.insert_one(document=TypeModel.to_json(example_type))
    dummy_type = example_type
    dummy_type.public_id = 2
    dummy_type.fields = []
    dummy_type.fields.append({
        "type":
        "ref",
        "name":
        "test-field",
        "label":
        "simple reference field",
        "ref_types": [1],
        "summaries": [{
            "type_id": 1,
            "line": "ReferenceTO: {}",
            "label": "ReferenceTO",
            "fields": ["test-dummy-field"],
            "icon": "fa fa-cube",
            "prefix": False
        }],
        "value":
        ""
    })
    collection.insert_one(document=TypeModel.to_json(dummy_type))

    def drop_collection():
        collection.drop()

    request.addfinalizer(drop_collection)
Ejemplo n.º 2
0
    def test_delete_type(self, rest_api, example_type, full_access_user, none_access_user):
        # Test default route
        rest_api.post(f'{self.ROUTE_URL}/', json=TypeModel.to_json(example_type))

        default_response = rest_api.delete(f'{self.ROUTE_URL}/{example_type.public_id}')
        assert default_response.status_code == HTTPStatus.ACCEPTED

        default_response = rest_api.post(f'{self.ROUTE_URL}/', json=TypeModel.to_json(example_type))
        assert default_response.status_code == HTTPStatus.CREATED

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

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

        # ACCESS UNAUTHORIZED
        un_get_types_response = rest_api.delete(f'{self.ROUTE_URL}/{example_type.public_id}', unauthorized=True)
        assert un_get_types_response.status_code == HTTPStatus.UNAUTHORIZED
Ejemplo n.º 3
0
    def test_update_type(self, rest_api, example_type, full_access_user, none_access_user):
        example_type.name = 'updated'

        # Test default route
        default_response = rest_api.put(f'{self.ROUTE_URL}/{example_type.public_id}',
                                        json=TypeModel.to_json(example_type))
        assert default_response.status_code == HTTPStatus.ACCEPTED

        validate_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.OK
        assert validate_response.get_json()['result']['name'] == 'updated'

        # ACCESS OK
        access_update_types_response = rest_api.put(f'{self.ROUTE_URL}/{example_type.public_id}',
                                                    json=TypeModel.to_json(example_type), user=full_access_user)
        assert access_update_types_response.status_code != (HTTPStatus.FORBIDDEN or HTTPStatus.UNAUTHORIZED)
        validate_response = rest_api.get(f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.OK
        rest_api.delete(f'{self.ROUTE_URL}/{example_type.public_id}')

        # ACCESS FORBIDDEN
        none_update_types_response = rest_api.put(f'{self.ROUTE_URL}/{example_type.public_id}',
                                                  json=TypeModel.to_json(example_type), user=none_access_user)
        assert none_update_types_response.status_code == HTTPStatus.FORBIDDEN

        # ACCESS UNAUTHORIZED
        un_get_types_response = rest_api.put(f'{self.ROUTE_URL}/{example_type.public_id}',
                                             json=TypeModel.to_json(example_type), unauthorized=True)
        assert un_get_types_response.status_code == HTTPStatus.UNAUTHORIZED
        example_type.public_id = 1
        example_type.name = 'test'
Ejemplo n.º 4
0
    def test_insert_type(self, rest_api, example_type, full_access_user,
                         none_access_user):
        example_type.public_id = 2
        example_type.name = 'test2'

        # Test default route
        default_response = rest_api.post(f'{self.ROUTE_URL}/',
                                         json=TypeModel.to_json(example_type))
        assert default_response.status_code == HTTPStatus.CREATED
        validate_response = rest_api.get(
            f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.OK
        double_check_response = rest_api.post(
            f'{self.ROUTE_URL}/', json=TypeModel.to_json(example_type))
        assert double_check_response.status_code == HTTPStatus.BAD_REQUEST
        rest_api.delete(f'{self.ROUTE_URL}/{example_type.public_id}')

        # ACCESS OK
        access_insert_types_response = rest_api.post(
            f'{self.ROUTE_URL}/',
            json=TypeModel.to_json(example_type),
            user=full_access_user)
        assert access_insert_types_response.status_code != (
            HTTPStatus.FORBIDDEN or HTTPStatus.UNAUTHORIZED)
        validate_response = rest_api.get(
            f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.OK
        rest_api.delete(f'{self.ROUTE_URL}/{example_type.public_id}')

        # ACCESS FORBIDDEN
        forbidden_insert_types_response = rest_api.post(
            f'{self.ROUTE_URL}/',
            json=TypeModel.to_json(example_type),
            user=none_access_user)
        assert forbidden_insert_types_response.status_code == HTTPStatus.FORBIDDEN
        validate_response = rest_api.get(
            f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.NOT_FOUND

        # ACCESS UNAUTHORIZED
        un_insert_types_response = rest_api.post(
            f'{self.ROUTE_URL}/',
            json=TypeModel.to_json(example_type),
            unauthorized=True)
        assert un_insert_types_response.status_code == HTTPStatus.UNAUTHORIZED
        validate_response = rest_api.get(
            f'{self.ROUTE_URL}/{example_type.public_id}')
        assert validate_response.status_code == HTTPStatus.NOT_FOUND
        example_type.public_id = 1
        example_type.name = 'test'
Ejemplo n.º 5
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
Ejemplo n.º 6
0
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
def example_type():
    return TypeModel(public_id=1,
                     name='test',
                     label='Test',
                     author_id=1,
                     creation_time=datetime.now(),
                     active=True,
                     version=None,
                     description='Test type',
                     render_meta=TypeRenderMeta(
                         sections=[
                             TypeFieldSection(
                                 type='section',
                                 name='test-section',
                                 label='TEST',
                                 fields=['dummy-field-1', 'dummy-field-2'])
                         ],
                         summary=TypeSummary(fields=['dummy-field-1'])),
                     fields=[{
                         "type": "text",
                         "name": "dummy-field-1",
                         "label": "Test"
                     }, {
                         "type": "text",
                         "name": "dummy-field-2",
                         "label": "Test"
                     }],
                     acl=AccessControlList(activated=False,
                                           groups=GroupACL(includes=None)))
Ejemplo n.º 8
0
def export_type_by_ids(public_ids):
    try:
        query_list = []
        for key, value in {'public_id': public_ids}.items():
            for v in value.split(","):
                try:
                    query_list.append({key: int(v)})
                except (ValueError, TypeError):
                    return abort(400)
        type_list_data = json.dumps([
            TypeModel.to_json(type_)
            for type_ in object_manager.get_types_by(sort="public_id",
                                                     **{'$or': query_list})
        ],
                                    default=json_encoding.default,
                                    indent=2)
    except TypeNotFoundError as e:
        return abort(400, e.message)
    except ModuleNotFoundError as e:
        return abort(400, e)
    except CMDBError as e:
        return abort(404, jsonify(message='Not Found', error=e.message))
    timestamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y_%m_%d-%H_%M_%S')

    return Response(type_list_data,
                    mimetype="text/json",
                    headers={
                        "Content-Disposition":
                        "attachment; filename=%s.%s" % (timestamp, 'json')
                    })
Ejemplo n.º 9
0
def setup(request, collection, example_type):
    collection.insert_one(document=TypeModel.to_json(example_type))

    def drop_collection():
        collection.drop()

    request.addfinalizer(drop_collection)
Ejemplo n.º 10
0
    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
Ejemplo n.º 11
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)
Ejemplo n.º 12
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)
Ejemplo n.º 13
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!')
Ejemplo n.º 14
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
Ejemplo n.º 15
0
    def insert(self, type: dict) -> PublicID:
        """
        Insert a single type into the system.

        Args:
            type (dict): Raw data of the type.

        Notes:
            If no public id was given, the database manager will auto insert the next available ID.

        Returns:
            int: The Public ID of the new inserted type
        """
        if isinstance(type, TypeModel):
            type = TypeModel.to_json(type)
        return self._insert(self.collection, resource=type)
Ejemplo n.º 16
0
    def update(self, public_id: Union[PublicID, int], type: Union[TypeModel,
                                                                  dict]):
        """
        Update a existing type in the system.
        Args:
            public_id (int): PublicID of the type in the system.
            type:

        Notes:
            If a TypeModel instance was passed as type argument, \
            it will be auto converted via the model `to_json` method.
        """
        if isinstance(type, TypeModel):
            type = TypeModel.to_json(type)
        return super(TypeManager, self).update(public_id=public_id,
                                               resource=type)
Ejemplo n.º 17
0
    def insert(self, type: Union[TypeModel, dict]) -> PublicID:
        """
        Insert a single type into the system.

        Args:
            type (dict): Raw data of the type.

        Notes:
            If no public id was given, the database manager will auto insert the next available ID.

        Returns:
            int: The Public ID of the new inserted type
        """
        if isinstance(type, TypeModel):
            type = TypeModel.to_json(type)
        elif isinstance(type, dict):
            type = json.loads(json.dumps(type, default=json_util.default), object_hook=object_hook)

        return self._insert(self.collection, resource=type)
Ejemplo n.º 18
0
    def update(self, public_id: Union[PublicID, int], type: Union[TypeModel,
                                                                  dict]):
        """
        Update a existing type in the system.
        Args:
            public_id (int): PublicID of the type in the system.
            type: New type data

        Notes:
            If a TypeModel instance was passed as type argument, \
            it will be auto converted via the model `to_json` method.
        """
        if isinstance(type, TypeModel):
            type = TypeModel.to_json(type)
        update_result = self._update(self.collection,
                                     filter={'public_id': public_id},
                                     resource=type)
        if update_result.matched_count != 1:
            raise ManagerUpdateError(f'Something happened during the update!')
        return update_result
Ejemplo n.º 19
0
def export_type():
    try:
        type_list = [
            TypeModel.to_json(type) for type in object_manager.get_all_types()
        ]
        resp = json.dumps(type_list, default=json_encoding.default, indent=2)
    except TypeNotFoundError as e:
        return abort(400, e.message)
    except ModuleNotFoundError as e:
        return abort(400, e)
    except CMDBError as e:
        return abort(404, jsonify(message='Not Found', error=e.message))
    timestamp = datetime.datetime.fromtimestamp(
        time.time()).strftime('%Y_%m_%d-%H_%M_%S')

    return Response(resp,
                    mimetype="text/json",
                    headers={
                        "Content-Disposition":
                        "attachment; filename=%s.%s" % (timestamp, 'json')
                    })
Ejemplo n.º 20
0
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
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
def example_type():
    return TypeModel(
        public_id=1, name='test', label='Test', author_id=1, creation_time=datetime.now(),
        active=True, version=None, description='Test type',
        render_meta=TypeRenderMeta(
            sections=[
                TypeFieldSection(type='section', name='test-section', label='TEST', fields=['test-field'])
            ],
            summary=TypeSummary(fields=['test-field'])
        ),
        fields=[{
            "type": "text",
            "name": "test-field",
            "label": "Test",
            "required": False,
            "description": "Description",
            "regex": "TEST .*",
            "placeholder": "entre you value",
            "value": "this ist the default value",
            "helperText": "Help, i need somebody"
        }],
        acl=AccessControlList(activated=False, groups=GroupACL(includes=None))
    )