Ejemplo n.º 1
0
def add_tabs_for_reference_system(entity: ReferenceSystem) -> dict[str, Tab]:
    tabs = {}
    for name in entity.classes:
        tabs[name] = Tab(
            name,
            entity=entity,
            table=Table([_('entity'), 'id', _('precision')]))
    for link_ in entity.get_links('P67'):
        name = link_.description
        if entity.resolver_url:
            name = \
                f'<a href="{entity.resolver_url}{name}"' \
                f' target="_blank" rel="noopener noreferrer">{name}</a>'
        tabs[link_.range.class_.name].table.rows.append([
            link(link_.range),
            name,
            link_.type.name])
    for name in entity.classes:
        tabs[name].buttons = []
        if not tabs[name].table.rows and is_authorized('manager'):
            tabs[name].buttons = [button(
                _('remove'),
                url_for(
                    'reference_system_remove_class',
                    system_id=entity.id,
                    class_name=name))]
    return tabs
Ejemplo n.º 2
0
def before_request() -> None:
    from openatlas.models.openatlas_class import (OpenatlasClass,
                                                  view_class_mapping)
    from openatlas.models.cidoc_property import CidocProperty
    from openatlas.models.cidoc_class import CidocClass
    from openatlas.models.type import Type
    from openatlas.models.settings import Settings
    from openatlas.models.reference_system import ReferenceSystem

    if request.path.startswith('/static'):  # pragma: no cover
        return  # Avoid overhead for files if not using Apache with static alias
    open_connection(app.config)
    g.settings = Settings.get_settings()
    session['language'] = get_locale()
    g.cidoc_classes = CidocClass.get_all()
    g.properties = CidocProperty.get_all()
    g.classes = OpenatlasClass.get_all()
    g.types = Type.get_all()
    g.reference_systems = ReferenceSystem.get_all()
    g.view_class_mapping = view_class_mapping
    g.class_view_mapping = OpenatlasClass.get_class_view_mapping()
    g.table_headers = OpenatlasClass.get_table_headers()
    g.file_stats = get_file_stats()

    # Set max file upload in MB
    app.config['MAX_CONTENT_LENGTH'] = \
        g.settings['file_upload_max_size'] * 1024 * 1024

    if request.path.startswith('/api/'):
        ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
        if not current_user.is_authenticated \
                and not g.settings['api_public'] \
                and ip not in app.config['ALLOWED_IPS']:
            raise AccessDeniedError  # pragma: no cover
Ejemplo n.º 3
0
def insert_entity(
        form: FlaskForm,
        class_: str,
        origin: Optional[Union[Entity, Node]] = None) \
        -> Union[Entity, Node, ReferenceSystem]:
    if class_ == 'artifact':
        entity = Entity.insert(class_, form.name.data)
        location = Entity.insert('object_location',
                                 f'Location of {form.name.data}')
        entity.link('P53', location)
    elif class_ in [
            'place', 'human_remains', 'stratigraphic_unit', 'feature', 'find',
            'artifact'
    ]:
        if class_ == 'human_remains':
            entity = Entity.insert(class_, form.name.data)
        elif origin and origin.class_.name == 'stratigraphic_unit':
            entity = Entity.insert('find', form.name.data)
        else:
            system_class = 'place'
            if origin and origin.class_.name == 'place':
                system_class = 'feature'
            elif origin and origin.class_.name == 'feature':
                system_class = 'stratigraphic_unit'
            entity = Entity.insert(system_class, form.name.data)
        entity.link(
            'P53',
            Entity.insert('object_location', f'Location of {form.name.data}'))
    elif class_ == 'reference_system':
        entity = ReferenceSystem.insert_system(form)
    else:
        entity = Entity.insert(class_, form.name.data)
    return entity
Ejemplo n.º 4
0
    def setUp(self) -> None:
        app.testing = True
        app.config['SERVER_NAME'] = 'local.host'
        app.config['WTF_CSRF_ENABLED'] = False
        app.config['WTF_CSRF_METHODS'] = []  # Disable CSRF in tests

        self.setup_database()
        self.app = app.test_client()
        self.login()  # Login on default because needed almost everywhere
        with app.app_context():
            self.app.get('/')  # Needed to initialise g
            self.precision_geonames = \
                'reference_system_precision_' + \
                str(ReferenceSystem.get_by_name('GeoNames').id)
            self.precision_wikidata = \
                'reference_system_precision_' + \
                str(ReferenceSystem.get_by_name('Wikidata').id)
Ejemplo n.º 5
0
 def update_links(self, links: dict[str, Any], new: bool) -> Optional[int]:
     from openatlas.models.reference_system import ReferenceSystem
     if not new:
         if 'delete' in links and links['delete']:
             self.delete_links(links['delete'])
         if 'delete_inverse' in links and links['delete_inverse']:
             self.delete_links(links['delete_inverse'], True)
         if 'delete_reference_system' in links \
                 and links['delete_reference_system']:
             ReferenceSystem.delete_links_from_entity(self)
     redirect_link_id = None
     for link_ in links['insert']:
         ids = self.link(
             link_['property'],
             link_['range'],
             link_['description'] if 'description' in link_ else None,
             type_id=link_['type_id'] if 'type_id' in link_ else None,
             inverse=('inverse' in link_ and link_['inverse']))
         if 'return_link_id' in link_ and link_['return_link_id']:
             redirect_link_id = ids[0]
     return redirect_link_id
Ejemplo n.º 6
0
def insert_entity(form: FlaskForm, class_: str) \
        -> Union[Entity, Type, ReferenceSystem]:
    if class_ == 'reference_system':
        return ReferenceSystem.insert_system({
            'name': form.name.data,
            'description': form.description.data,
            'website_url': form.website_url.data,
            'resolver_url': form.resolver_url.data})
    entity = Entity.insert(class_, form.name.data)
    if class_ == 'artifact' or g.classes[class_].view == 'place':
        entity.link(
            'P53',
            Entity.insert('object_location', f'Location of {form.name.data}'))
    return entity
Ejemplo n.º 7
0
def insert(class_: str,
           origin_id: Optional[int] = None) -> Union[str, Response]:
    if class_ not in g.classes or not g.classes[class_].view \
            or not is_authorized(g.classes[class_].write_access):
        abort(403)  # pragma: no cover
    origin = Entity.get_by_id(origin_id) if origin_id else None
    form = build_form(class_, origin=origin)
    if form.validate_on_submit():
        return redirect(save(form, class_=class_, origin=origin))
    if hasattr(form, 'alias'):
        form.alias.append_entry('')
    view_name = g.classes[class_].view
    geonames_module = False
    if origin:
        populate_insert_form(form, view_name, class_, origin)
    else:
        geonames_module = True if ReferenceSystem.get_by_name(
            'GeoNames').forms else False

    # Archaeological sub units
    structure = None
    gis_data = None
    overlays = None
    if view_name in ['artifact', 'place']:
        structure = get_structure(super_=origin)
        gis_data = Gis.get_all([origin] if origin else None, structure)
        overlays = Overlay.get_by_object(origin) \
            if origin and origin.class_.view == 'place' else None
    return render_template(
        'entity/insert.html',
        form=form,
        class_=class_,
        origin=origin,
        view_name=view_name,
        structure=structure,
        gis_data=gis_data,
        geonames_module=geonames_module,
        writeable=True if os.access(app.config['UPLOAD_DIR'], os.W_OK) else
        False,  # For files
        overlays=overlays,
        title=_(view_name),
        crumbs=add_crumbs(view_name, class_, origin, structure, insert_=True))
Ejemplo n.º 8
0
def insert_entity(
    form: FlaskForm,
    class_: str,
    origin: Optional[Union[Entity, Node]] = None
) -> Union[Entity, Node, ReferenceSystem]:
    if class_ == 'artifact':
        entity = Entity.insert(class_, form.name.data)
        location = Entity.insert('object_location',
                                 'Location of ' + form.name.data)
        entity.link('P53', location)
    elif class_ in [
            'place', 'human_remains', 'stratigraphic_unit', 'feature', 'find',
            'artifact'
    ]:
        if class_ == 'human_remains':
            entity = Entity.insert(class_, form.name.data)
        elif origin and origin.class_.name == 'stratigraphic_unit':
            entity = Entity.insert('find', form.name.data)
        else:
            system_class = 'place'
            if origin and origin.class_.name == 'place':
                system_class = 'feature'
            elif origin and origin.class_.name == 'feature':
                system_class = 'stratigraphic_unit'
            entity = Entity.insert(system_class, form.name.data)
        entity.link(
            'P53',
            Entity.insert('object_location', 'Location of ' + form.name.data))
    elif class_ == 'reference_system':
        entity = ReferenceSystem.insert_system(form)
    else:
        entity = Entity.insert(class_, form.name.data)
    if entity.class_.name == 'file':
        file_ = request.files['file']
        # Add an 'a' to prevent emtpy filename, this won't affect stored information
        filename = secure_filename('a' + file_.filename)  # type: ignore
        new_name = '{id}.{ext}'.format(id=entity.id,
                                       ext=filename.rsplit('.', 1)[1].lower())
        file_.save(str(app.config['UPLOAD_DIR'] / new_name))
    return entity
Ejemplo n.º 9
0
def before_request() -> None:
    from openatlas.models.model import CidocClass, CidocProperty
    from openatlas.models.node import Node
    from openatlas.models.settings import Settings
    from openatlas.models.reference_system import ReferenceSystem
    if request.path.startswith('/static'):  # pragma: no cover
        return  # Only needed if not running with Apache and static alias
    open_connection(app.config)
    session['settings'] = Settings.get_settings()
    session['language'] = get_locale()
    g.cidoc_classes = CidocClass.get_all()
    g.properties = CidocProperty.get_all()

    from openatlas.models import system
    g.table_headers = system.get_table_headers()
    g.classes = system.get_system_classes()
    g.view_class_mapping = system.view_class_mapping
    g.class_view_mapping = system.get_class_view_mapping()
    g.nodes = Node.get_all_nodes()
    g.reference_systems = ReferenceSystem.get_all()

    # Set max file upload in MB
    app.config['MAX_CONTENT_LENGTH'] = session['settings'][
        'file_upload_max_size'] * 1024 * 1024
Ejemplo n.º 10
0
def update(id_: int) -> Union[str, Response]:
    entity = Entity.get_by_id(id_, nodes=True, aliases=True)
    if not entity.class_.view:
        abort(422)  # pragma: no cover
    elif not is_authorized(entity.class_.write_access):
        abort(403)  # pragma: no cover
    elif isinstance(entity, Node):
        root = g.nodes[entity.root[-1]] if entity.root else None
        if not root and (entity.standard or entity.locked):
            abort(403)  # pragma: no cover

    # Archaeological sub units
    geonames_module = False
    if entity.class_.name == 'place' and ReferenceSystem.get_by_name(
            'GeoNames').forms:
        geonames_module = True
    structure = None
    gis_data = None
    overlays = None
    location = None

    if entity.class_.view in ['artifact', 'place']:
        structure = get_structure(entity)
        location = entity.get_linked_entity_safe('P53', nodes=True)
        gis_data = Gis.get_all([entity], structure)
        overlays = Overlay.get_by_object(entity)

    form = build_form(entity.class_.name, entity, location=location)

    if entity.class_.view == 'event':
        form.event_id.data = entity.id
    elif isinstance(entity, ReferenceSystem) and entity.system:
        form.name.render_kw['readonly'] = 'readonly'
    if form.validate_on_submit():
        if isinstance(entity, Node):
            valid = True
            root = g.nodes[entity.root[-1]]
            new_super_id = getattr(form, str(root.id)).data
            new_super = g.nodes[int(new_super_id)] if new_super_id else None
            if new_super:
                if new_super.id == entity.id:
                    flash(_('error node self as super'), 'error')
                    valid = False
                if new_super.root and entity.id in new_super.root:
                    flash(_('error node sub as super'), 'error')
                    valid = False
            if not valid:
                return redirect(url_for('entity_view', id_=entity.id))
        if was_modified(form, entity):  # pragma: no cover
            del form.save
            flash(_('error modified'), 'error')
            return render_template('entity/update.html',
                                   form=form,
                                   entity=entity,
                                   structure=structure,
                                   modifier=link(
                                       logger.get_log_for_advanced_view(
                                           entity.id)['modifier']))
        return redirect(save(form, entity))
    populate_update_form(form, entity)
    return render_template('entity/update.html',
                           form=form,
                           entity=entity,
                           structure=structure,
                           gis_data=gis_data,
                           overlays=overlays,
                           geonames_module=geonames_module,
                           title=entity.name,
                           crumbs=add_crumbs(view_name=entity.class_.view,
                                             class_=entity.class_.name,
                                             origin=entity,
                                             structure=structure))
Ejemplo n.º 11
0
    def test_place(self) -> None:
        with app.app_context():  # type: ignore
            rv = self.app.get(url_for('insert', class_='place'))
            assert b'+ Place' in rv.data
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                unit_node = Node.get_hierarchy('Administrative unit')
                unit_sub1 = g.nodes[unit_node.subs[0]]
                unit_sub2 = g.nodes[unit_node.subs[1]]
                reference = Entity.insert('external_reference',
                                          'https://openatlas.eu')
                place_node = Node.get_hierarchy('Place')
                source = Entity.insert('source', 'Necronomicon')
            geonames = \
                f"reference_system_id_" \
                f"{ReferenceSystem.get_by_name('GeoNames').id}"
            precision = Node.get_hierarchy('External reference match').subs[0]
            data = {
                'name': 'Asgard',
                'alias-0': 'Valhöll',
                unit_node.id: str([unit_sub1.id, unit_sub2.id]),
                geonames: '123456',
                self.precision_geonames: precision,
                self.precision_wikidata: ''
            }
            rv = self.app.post(url_for('insert',
                                       class_='place',
                                       origin_id=reference.id),
                               data=data,
                               follow_redirects=True)
            assert b'Asgard' in rv.data \
                   and b'An entry has been created' in rv.data
            rv = self.app.get(url_for('entity_view', id_=precision))
            assert b'Asgard' in rv.data
            rv = self.app.get(
                url_for('entity_view',
                        id_=ReferenceSystem.get_by_name('GeoNames').id))
            assert b'Asgard' in rv.data

            data['gis_points'] = """[{
                "type": "Feature",
                "geometry": {"type":"Point","coordinates":[9,17]},
                "properties": {
                    "name": "Valhalla",
                    "description": "",
                    "shapeType": "centerpoint"}}]"""
            data['gis_lines'] = """[{
                "type": "Feature",
                "geometry":{
                    "type": "LineString",
                    "coordinates": [
                        [9.75307425847859,17.8111792731339],
                        [9.75315472474904,17.8110005175436],
                        [9.75333711496205,17.8110873417098]]},
                "properties": {
                    "name": "",
                    "description": "",
                    "shapeType": "line"}}]"""
            data['gis_polygons'] = """[{
                "type": "Feature",
                "geometry": {
                    "type": "Polygon",
                    "coordinates": [[
                        [9.75307425847859,17.8111792731339],
                        [9.75315472474904,17.8110005175436],
                        [9.75333711496205,17.8110873417098],
                        [9.75307425847859,17.8111792731339]]]},
                "properties":{
                    "name": "",
                    "description": "",
                    "shapeType": "shape"}}]"""
            data[place_node.id] = place_node.subs
            data['continue_'] = 'yes'
            rv = self.app.post(url_for('insert',
                                       class_='place',
                                       origin_id=source.id),
                               data=data,
                               follow_redirects=True)
            assert b'Necronomicon' in rv.data
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                places = Entity.get_by_class('place')
                place = places[0]
                place2 = places[1]
                location = place2.get_linked_entity_safe('P53')
                actor = Entity.insert('person', 'Milla Jovovich')
                actor.link('P74', location)
            assert b'Necronomicon' in rv.data
            rv = self.app.get(url_for('index', view='place'))
            assert b'Asgard' in rv.data
            rv = self.app.get(url_for('update', id_=place.id))
            assert b'Valhalla' in rv.data
            data['continue_'] = ''
            data['alias-1'] = 'Val-hall'
            data['geonames_id'] = '321'
            rv = self.app.post(url_for('update', id_=place.id),
                               data=data,
                               follow_redirects=True)
            assert b'Val-hall' in rv.data

            # Test error when viewing the corresponding location
            rv = self.app.get(url_for('entity_view', id_=place.id + 1))
            assert b'be viewed directly' in rv.data

            # Test with same GeoNames id
            rv = self.app.post(url_for('update', id_=place.id),
                               data=data,
                               follow_redirects=True)
            assert b'Val-hall' in rv.data

            # Test with same GeoNames id but different precision
            data['geonames_precision'] = ''
            rv = self.app.post(url_for('update', id_=place.id),
                               data=data,
                               follow_redirects=True)
            assert b'Val-hall' in rv.data

            # Test update without the previous GeoNames id
            data['geonames_id'] = ''
            rv = self.app.post(url_for('update', id_=place.id),
                               data=data,
                               follow_redirects=True)
            assert b'Val-hall' in rv.data

            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                event = Entity.insert('acquisition', 'Valhalla rising')
                event.link('P7', location)
                event.link('P24', location)
            rv = self.app.get(url_for('entity_view', id_=place2.id))
            assert rv.data and b'Valhalla rising' in rv.data

            # Test invalid geom
            data['gis_polygons'] = """[{
                "type": "Feature", 
                "geometry": {
                    "type": "Polygon", 
                    "coordinates": [[
                        [298.9893436362036, -5.888919049309554], 
                        [299.00444983737543, -5.9138487869408545],
                        [299.00650977389887, -5.893358673645309], 
                        [298.9848804404028, -5.9070188333813585],
                        [298.9893436362036, -5.888919049309554]]]},
                "properties": {
                "name": "", 
                "description": "", 
                "shapeType": "shape"}}]"""
            rv = self.app.post(url_for('insert',
                                       class_='place',
                                       origin_id=source.id),
                               data=data,
                               follow_redirects=True)
            assert b'An invalid geometry was entered' in rv.data

            # Test Overlays
            path = \
                pathlib.Path(app.root_path) \
                / 'static' / 'images' / 'layout' / 'logo.png'
            with open(path, 'rb') as img:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=place.id),
                                   data={
                                       'name': 'X-Files',
                                       'file': img
                                   },
                                   follow_redirects=True)
            assert b'An entry has been created' in rv.data
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                file = Entity.get_by_class('file')[0]
                link_id = Link.insert(file, 'P67', place)[0]
            rv = self.app.get(
                url_for('overlay_insert',
                        image_id=file.id,
                        place_id=place.id,
                        link_id=link_id))
            assert b'X-Files' in rv.data
            data = {
                'top_left_easting': 42,
                'top_left_northing': 12,
                'top_right_easting': 43,
                'top_right_northing': 13,
                'bottom_left_easting': 10,
                'bottom_left_northing': 20
            }
            rv = self.app.post(url_for('overlay_insert',
                                       image_id=file.id,
                                       place_id=place.id,
                                       link_id=link_id),
                               data=data,
                               follow_redirects=True)
            assert b'Edit' in rv.data
            if os.name == "posix":  # Ignore for other OS e.g. Windows
                with app.test_request_context():
                    app.preprocess_request()  # type: ignore
                    overlay = Overlay.get_by_object(place)
                    overlay_id = overlay[list(overlay.keys())[0]].id
                rv = self.app.get(
                    url_for('overlay_update',
                            id_=overlay_id,
                            place_id=place.id,
                            link_id=link_id))
                assert b'42' in rv.data
                rv = self.app.post(url_for('overlay_update',
                                           id_=overlay_id,
                                           place_id=place.id,
                                           link_id=link_id),
                                   data=data,
                                   follow_redirects=True)
                assert b'Changes have been saved' in rv.data
                self.app.get(url_for('overlay_remove',
                                     id_=overlay_id,
                                     place_id=place.id),
                             follow_redirects=True)

            # Add to place
            rv = self.app.get(url_for('entity_add_file', id_=place.id))
            assert b'Link file' in rv.data

            rv = self.app.post(url_for('entity_add_file', id_=place.id),
                               data={'checkbox_values': str([file.id])},
                               follow_redirects=True)
            assert b'X-Files' in rv.data

            rv = self.app.get(
                url_for('reference_add', id_=reference.id, view='place'))
            assert b'Val-hall' in rv.data
            rv = self.app.get(url_for('entity_add_reference', id_=place.id))
            assert b'Link reference' in rv.data
            rv = self.app.post(url_for('entity_add_reference', id_=place.id),
                               data={
                                   'reference': reference.id,
                                   'page': '777'
                               },
                               follow_redirects=True)
            assert b'777' in rv.data

            # Place types
            rv = self.app.get(url_for('node_move_entities', id_=unit_sub1.id))
            assert b'Asgard' in rv.data

            # Test move entities of multiple node if link to new node exists
            rv = self.app.post(url_for('node_move_entities', id_=unit_sub1.id),
                               follow_redirects=True,
                               data={
                                   unit_node.id: unit_sub2.id,
                                   'selection': location.id,
                                   'checkbox_values': str([location.id])
                               })
            assert b'Entities were updated' in rv.data

            # Test move entities of multiple node
            rv = self.app.post(url_for('node_move_entities', id_=unit_sub2.id),
                               follow_redirects=True,
                               data={
                                   unit_node.id: unit_sub1.id,
                                   'selection': location.id,
                                   'checkbox_values': str([location.id])
                               })
            assert b'Entities were updated' in rv.data

            # Subunits
            data = {
                'name': "Try continue",
                'continue_': 'sub',
                self.precision_geonames: precision,
                self.precision_wikidata: ''
            }
            self.app.get(url_for('insert', class_='place'))
            rv = self.app.post(url_for('insert', class_='place'),
                               data=data,
                               follow_redirects=True)
            assert b'Insert and add strati' in rv.data
            data['name'] = "It's not a bug, it's a feature!"
            rv = self.app.get(
                url_for('insert',
                        class_='stratigraphic_unit',
                        origin_id=place.id))
            assert b'Insert and add find' in rv.data
            rv = self.app.post(url_for('insert',
                                       class_='place',
                                       origin_id=place.id),
                               data=data)
            feat_id = rv.location.split('/')[-1]
            self.app.get(url_for('insert', class_='place', origin_id=feat_id))
            self.app.get(url_for('update', id_=feat_id))
            self.app.post(url_for('update', id_=feat_id), data=data)
            data['name'] = "I'm a stratigraphic unit"
            rv = self.app.post(url_for('insert',
                                       class_='place',
                                       origin_id=feat_id),
                               data=data)
            stratigraphic_id = rv.location.split('/')[-1]
            self.app.get(
                url_for('insert', class_='place', origin_id=stratigraphic_id))
            self.app.get(url_for('update', id_=stratigraphic_id))
            self.app.post(url_for('update', id_=stratigraphic_id),
                          data={'name': "I'm a stratigraphic unit"})
            dimension_node_id = Node.get_hierarchy('Dimensions').subs[0]
            data = {
                'name': 'You never find me',
                dimension_node_id: 50,
                self.precision_geonames: precision,
                self.precision_wikidata: ''
            }
            rv = self.app.post(url_for('insert',
                                       class_='find',
                                       origin_id=stratigraphic_id),
                               data=data)
            find_id = rv.location.split('/')[-1]
            rv = self.app.post(url_for('update', id_=find_id),
                               data=data,
                               follow_redirects=True)
            assert b'50' in rv.data
            self.app.get(url_for('update', id_=find_id))
            data = {
                'name': 'My human remains',
                self.precision_geonames: precision,
                self.precision_wikidata: ''
            }
            rv = self.app.post(url_for('insert',
                                       class_='human_remains',
                                       origin_id=stratigraphic_id),
                               data=data)
            human_remains_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('update', id_=human_remains_id))
            assert b'My human remains' in rv.data
            rv = self.app.get('/')
            assert b'My human remains' in rv.data

            rv = self.app.get(url_for('entity_view', id_=feat_id))
            assert b'not a bug' in rv.data
            rv = self.app.get(url_for('entity_view', id_=stratigraphic_id))
            assert b'a stratigraphic unit' in rv.data
            rv = self.app.get(url_for('entity_view', id_=find_id))
            assert b'You never' in rv.data
            rv = self.app.get(url_for('index',
                                      view='place',
                                      delete_id=place.id),
                              follow_redirects=True)
            assert b'not possible if subunits' in rv.data
            rv = self.app.get(url_for('index', view='place',
                                      delete_id=find_id),
                              follow_redirects=True)
            assert b'The entry has been deleted.' in rv.data
            rv = self.app.get(
                url_for('index', view='place', delete_id=place2.id))
            assert b'The entry has been deleted.' in rv.data
Ejemplo n.º 12
0
def check_geonames_module(class_: str) -> bool:
    return class_ == 'place' \
           and bool(ReferenceSystem.get_by_name('GeoNames').classes)
Ejemplo n.º 13
0
    def test_api(self) -> None:
        with app.app_context():  # type: ignore
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                place = insert_entity('Nostromos',
                                      'place',
                                      description='That is the Nostromos')
                if not place:  # Needed for Mypy
                    return  # pragma: no cover

                # Adding Dates to place
                place.begin_from = '2018-01-31'
                place.begin_to = '2018-03-01'
                place.begin_comment = 'Begin of the Nostromos'
                place.end_from = '2019-01-31'
                place.end_to = '2019-03-01'
                place.end_comment = 'Destruction of the Nostromos'
                place.update()

                location = place.get_linked_entity_safe('P53')
                Gis.add_example_geom(location)

                # Adding Type Settlement
                place.link('P2', Node.get_hierarchy('Place'))

                # Adding Alias
                alias = insert_entity('Cargo hauler', 'appellation')
                place.link('P1', alias)

                # Adding External Reference
                external_reference = insert_entity('https://openatlas.eu',
                                                   'external_reference')
                external_reference.link('P67',
                                        place,
                                        description='OpenAtlas Website')

                # Adding feature to place
                feature = insert_entity('Feature', 'feature', place)

                # Adding stratigraphic to place
                insert_entity('Strato', 'stratigraphic_unit', feature)

                # Adding Administrative Unit Node
                unit_node = Node.get_hierarchy('Administrative unit')

                # Adding File to place
                file = insert_entity('Datei', 'file')
                file.link('P67', place)
                file.link('P2', g.nodes[Node.get_hierarchy('License').subs[0]])

                # Adding Value Type
                value_type = Node.get_hierarchy('Dimensions')
                place.link('P2', Entity.get_by_id(value_type.subs[0]), '23.0')

                # Adding Geonames
                geonames = Entity.get_by_id(
                    ReferenceSystem.get_by_name('GeoNames').id)
                precision_id = Node.get_hierarchy(
                    'External reference match').subs[0]
                geonames.link('P67',
                              place,
                              description='2761369',
                              type_id=precision_id)

            # Test LinkedPlaces output
            self.maxDiff = None
            rv = self.app.get(url_for('api.entity', id_=place.id))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_linked_place_template)

            # Test Geojson output
            rv = self.app.get(
                url_for('api.entity', id_=place.id, format='geojson'))
            self.assertDictEqual(rv.get_json(), api_data.api_geojson_template)

            # ---Content---

            # /api/0.2/classes/
            rv = self.app.get(url_for('api.class_mapping'))
            self.assertAlmostEqual(rv.get_json(), ClassMapping.mapping)

            # /api/0.2/content/
            rv = self.app.get(url_for('api.content', lang='de'))
            self.assertDictEqual(rv.get_json(), api_data.api_content_de)
            rv = self.app.get(url_for('api.content', lang='en', download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_content_en)

            # /api/0.2/geometric_entities/
            rv = self.app.get(url_for('api.geometric_entities'))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_geometries_template)
            rv = self.app.get(url_for('api.geometric_entities', download=True))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_geometries_template)
            rv = self.app.get(url_for('api.geometric_entities', count=True))
            assert b'1' in rv.data
            rv = self.app.get(
                url_for('api.geometric_entities',
                        geometry='gisLineAll',
                        count=True))
            assert b'0' in rv.data

            # /api/0.2/overview_count/
            rv = self.app.get(url_for('api.overview_count'))
            self.assertAlmostEqual(rv.get_json(), api_data.api_overview_count)

            # /api/0.2/overview_count/
            rv = self.app.get(url_for('api.system_class_count'))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_system_class_count)

            # ---Nodes---

            # /api/0.2/node_entities/
            rv = self.app.get(url_for('api.node_entities', id_=unit_node.id))
            self.assertDictEqual(rv.get_json(), api_data.api_node_entities)
            rv = self.app.get(
                url_for('api.node_entities', id_=unit_node.id, download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_node_entities)
            rv = self.app.get(
                url_for('api.node_entities', id_=unit_node.id, count=True))
            assert b'6' in rv.data

            # /api/0.2/node_entities_all/
            rv = self.app.get(
                url_for('api.node_entities_all', id_=unit_node.id))
            self.assertDictEqual(rv.get_json(), api_data.api_node_entities_all)
            rv = self.app.get(
                url_for('api.node_entities_all',
                        id_=unit_node.id,
                        download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_node_entities_all)
            rv = self.app.get(
                url_for('api.node_entities_all', id_=unit_node.id, count=True))
            assert b'8' in rv.data

            # # /api/0.2/node_overview/
            # rv = self.app.get(url_for('api.node_overview'))
            # self.assertDictEqual(rv.get_json(), api_data.api_node_overview)
            # rv = self.app.get(url_for('api.node_overview', download=True))
            # self.assertDictEqual(rv.get_json(), api_data.api_node_overview)

            # /api/0.2/subunit/
            rv = self.app.get(url_for('api.subunit', id_=place.id))
            self.assertDictEqual(rv.get_json(), api_data.api_subunit)
            rv = self.app.get(
                url_for('api.subunit', id_=place.id, download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_subunit)
            rv = self.app.get(url_for('api.subunit', id_=place.id, count=True))
            assert b'1' in rv.data

            # /api/0.2/subunit_hierarchy/
            rv = self.app.get(url_for('api.subunit_hierarchy', id_=place.id))
            self.assertDictEqual(rv.get_json(), api_data.api_subunit_hierarchy)
            rv = self.app.get(
                url_for('api.subunit_hierarchy', id_=place.id, download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_subunit_hierarchy)
            rv = self.app.get(
                url_for('api.subunit_hierarchy', id_=place.id, count=True))
            assert b'2' in rv.data

            # /api/0.2/type_tree/
            # rv = self.app.get(url_for('api.type_tree'))
            # self.assertDictEqual(rv.get_json(), api_data.api_type_tree)
            # rv = self.app.get(url_for('api.type_tree', download=True))
            # self.assertDictEqual(rv.get_json(), api_data.api_type_tree)

            # ---Entity---
            # /api/0.2/code/
            rv = self.app.get(url_for('api.code', code='reference'))
            self.assertDictEqual(rv.get_json(), api_data.api_code_reference)
            rv = self.app.get(
                url_for('api.code', code='reference', format='geojson'))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_code_reference_geojson)
            rv = self.app.get(
                url_for('api.code', code='reference', download=True))
            self.assertDictEqual(rv.get_json(), api_data.api_code_reference)
            rv = self.app.get(url_for('api.code', code='place', count=True))
            assert b'3' in rv.data
            rv = self.app.get(
                url_for('api.code',
                        code='place',
                        show='geometry',
                        limit=2,
                        sort='desc',
                        first=feature.id))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_code_place_first_sort_show_limit)
            rv = self.app.get(
                url_for('api.code',
                        code='place',
                        limit=10,
                        sort='desc',
                        column='name',
                        filter='or|name|like|Nostromos'))
            self.assertDictEqual(
                rv.get_json(),
                api_data.api_code_place_limit_sort_column_filter)
            rv = self.app.get(
                url_for('api.code',
                        code='place',
                        filter='or|id|eq|' + str(place.id)))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_code_place_filter_id)
            rv = self.app.get(
                url_for('api.code',
                        code='place',
                        filter='or|begin_from|ge|2018-1-1'))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_code_place_filter_time)
            rv = self.app.get(
                url_for('api.code', code='reference', export='csv'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('api.entities_linked_to_entity', id_=place.id))
            self.assertDictEqual(rv.get_json(),
                                 api_data.api_entities_linked_entity)

            # Path Tests
            rv = self.app.get(url_for('api.class', class_code='E31'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('api.class', class_code='E31', format='geojson'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('api.class', class_code='E31', download=True))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('api.class', class_code='E18', export='csv'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('api.latest', latest=10))
            assert b'Datei' in rv.data

            rv = self.app.get(url_for('api.latest', count=True, latest=2))
            assert b'2' in rv.data

            rv = self.app.get(
                url_for('api.system_class', system_class='appellation'))
            assert b'Cargo hauler' in rv.data
            rv = self.app.get(
                url_for('api.system_class',
                        system_class='appellation',
                        format='geojson'))
            assert b'Cargo hauler' in rv.data

            rv = self.app.get(url_for('api.type_entities', id_=unit_node.id))
            assert b'Austria' in rv.data
            rv = self.app.get(
                url_for('api.type_entities_all', id_=unit_node.id))
            assert b'Austria' in rv.data
            rv = self.app.get(
                url_for('api.query',
                        entities=place.id,
                        classes='E18',
                        items='place'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('api.query',
                        entities=place.id,
                        classes='E18',
                        items='place',
                        format='geojson'))
            assert b'Nostromos' in rv.data

            # Path test with download
            rv = self.app.get(
                url_for('api.entity', id_=place.id, download=True))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('api.latest', latest=1, download=True))
            assert b'Datei' in rv.data

            rv = self.app.get(
                url_for('api.system_class',
                        system_class='appellation',
                        download=True))
            assert b'Cargo hauler' in rv.data

            rv = self.app.get(
                url_for('api.query', classes='E31', download=True))
            assert b'https://openatlas.eu' in rv.data

            rv = self.app.get(url_for('api.overview_count', download=True))
            assert b'systemClass' in rv.data
            rv = self.app.get(url_for('api.class_mapping', download=True))
            assert b'systemClass' in rv.data

            # Path with export
            rv = self.app.get(url_for('api.entity', id_=place.id,
                                      export='csv'))
            assert b'Nostromos' in rv.data

            rv = self.app.get(
                url_for('api.system_class', system_class='place',
                        export='csv'))
            assert b'Nostromos' in rv.data

            # Testing Subunit

            # Parameter: filter

            rv = self.app.get(
                url_for('api.class',
                        class_code='E18',
                        filter='or|name|like|Nostr'))
            assert b'Nostromos' in rv.data

            # Parameter: last
            rv = self.app.get(
                url_for('api.class', class_code='E18', last=place.id))
            assert b'entities' in rv.data
            # Parameter: first
            rv = self.app.get(
                url_for('api.class', class_code='E18', first=place.id))
            assert b'entities' in rv.data

            # Parameter: show
            rv = self.app.get(
                url_for('api.class', class_code='E31', show='types'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('api.class', class_code='E18', show='when'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('api.class', class_code='E31', show='none'))
            assert b'https://openatlas.eu' in rv.data

            # Parameter: count
            rv = self.app.get(
                url_for('api.class', class_code='E31', count=True))
            assert b'2' in rv.data

            rv = self.app.get(
                url_for('api.system_class',
                        system_class='appellation',
                        count=True))
            assert b'1' in rv.data

            rv = self.app.get(
                url_for('api.query',
                        entities=place.id,
                        classes='E18',
                        codes='place'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('api.query',
                        entities=place.id,
                        classes='E18',
                        codes='place',
                        count=True))
            assert b'7' in rv.data
Ejemplo n.º 14
0
    def test_api(self) -> None:
        pass
        with app.app_context():  # type: ignore
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                place = insert_entity('Nostromos',
                                      'place',
                                      description='That is the Nostromos')
                if not place:
                    return  # pragma: no cover

                # Adding Dates to place
                place.begin_from = '2018-01-31'
                place.begin_to = '2018-03-01'
                place.begin_comment = 'Begin of the Nostromos'
                place.end_from = '2019-01-31'
                place.end_to = '2019-03-01'
                place.end_comment = 'Destruction of the Nostromos'

                location = place.get_linked_entity_safe('P53')
                Gis.add_example_geom(location)

                # Adding Type Settlement
                place.link('P2', Node.get_hierarchy('Place'))

                # Adding Alias
                alias = insert_entity('Cargo hauler', 'appellation')
                place.link('P1', alias)

                # Adding External Reference
                external_reference = insert_entity('https://openatlas.eu',
                                                   'external_reference')
                external_reference.link('P67',
                                        place,
                                        description='OpenAtlas Website')

                # Adding feature to place
                feature = insert_entity('Feature', 'feature', place)

                # Adding stratigraphic to place
                strati = insert_entity('Strato', 'stratigraphic_unit', feature)

                # Adding Administrative Unit Node
                unit_node = Node.get_hierarchy('Administrative unit')

                # Adding File to place
                file = insert_entity('Datei', 'file')
                file.link('P67', place)
                file.link('P2', Node.get_hierarchy('License'))

                # Adding Value Type
                value_type = Node.get_hierarchy('Dimensions')
                place.link('P2', Entity.get_by_id(value_type.subs[0]), '23.0')

                # Adding Geonames
                geonames = Entity.get_by_id(
                    ReferenceSystem.get_by_name('GeoNames').id)
                precision_id = Node.get_hierarchy(
                    'External reference match').subs[0]
                geonames.link('P67',
                              place,
                              description='2761369',
                              type_id=precision_id)

            # Path Tests
            rv = self.app.get(url_for('usage'))
            assert b'message' in rv.data
            rv = self.app.get(url_for('latest', latest=10))
            assert b'Datei' in rv.data
            rv = self.app.get(url_for('latest', count=True, latest=1))
            assert b'1' in rv.data
            rv = self.app.get(url_for('entity', id_=place.id))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('code', code='reference'))
            assert b'openatlas' in rv.data
            rv = self.app.get(
                url_for('system_class', system_class='appellation'))
            assert b'Cargo hauler' in rv.data
            rv = self.app.get(url_for('class', class_code='E31'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(url_for('node_entities', id_=unit_node.id))
            assert b'Austria' in rv.data
            rv = self.app.get(url_for('node_entities_all', id_=unit_node.id))
            assert b'Austria' in rv.data
            rv = self.app.get(
                url_for('query',
                        entities=place.id,
                        classes='E18',
                        items='place'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('content', lang='de'))
            assert b'intro' in rv.data
            rv = self.app.get(url_for('overview_count'))
            assert b'systemClass' in rv.data
            rv = self.app.get(url_for('class_mapping'))
            assert b'systemClass' in rv.data
            rv = self.app.get(url_for('node_overview'))
            assert b'Actor' in rv.data
            rv = self.app.get(url_for('type_tree'))
            assert b'type_tree' in rv.data

            # Path test with download
            rv = self.app.get(url_for('entity', id_=place.id, download=True))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('latest', latest=1, download=True))
            assert b'Datei' in rv.data
            rv = self.app.get(url_for('code', code='reference', download=True))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('system_class',
                        system_class='appellation',
                        download=True))
            assert b'Cargo hauler' in rv.data
            rv = self.app.get(url_for('class', class_code='E31',
                                      download=True))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(
                url_for('node_entities', id_=unit_node.id, download=True))
            assert b'Austria' in rv.data
            rv = self.app.get(
                url_for('node_entities_all', id_=unit_node.id, download=True))
            assert b'Austria' in rv.data
            rv = self.app.get(url_for('query', classes='E31', download=True))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(url_for('content', lang='de', download=True))
            assert b'intro' in rv.data
            rv = self.app.get(url_for('overview_count', download=True))
            assert b'systemClass' in rv.data
            rv = self.app.get(url_for('class_mapping', download=True))
            assert b'systemClass' in rv.data
            rv = self.app.get(url_for('node_overview', download=True))
            assert b'Actor' in rv.data

            # Path with export
            rv = self.app.get(url_for('entity', id_=place.id, export='csv'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('class', class_code='E18', export='csv'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('system_class', system_class='place', export='csv'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('code', code='reference', export='csv'))
            assert b'https://openatlas.eu' in rv.data

            # Testing Subunit
            rv = self.app.get(url_for('subunit', id_=place.id))
            assert b'Feature' in rv.data and b'Strato' not in rv.data
            rv = self.app.get(url_for('subunit', id_=place.id, download=True))
            assert b'Feature' in rv.data and b'Strato' not in rv.data
            rv = self.app.get(url_for('subunit', id_=place.id, count=True))
            assert b'1' in rv.data
            rv = self.app.get(url_for('subunit_hierarchy', id_=place.id))
            assert b'Strato' in rv.data
            rv = self.app.get(
                url_for('subunit_hierarchy', id_=place.id, download=True))
            assert b'Strato' in rv.data
            rv = self.app.get(
                url_for('subunit_hierarchy', id_=place.id, count=True))
            assert b'2' in rv.data

            # Parameter: filter
            rv = self.app.get(
                url_for('code',
                        code='place',
                        limit=10,
                        sort='desc',
                        column='name',
                        filter='or|name|like|Nostromos'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('code', code='reference'))
            assert b'openatlas' in rv.data
            rv = self.app.get(
                url_for('class', class_code='E18',
                        filter='or|name|like|Nostr'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('code',
                        code='place',
                        filter='or|id|eq|' + str(place.id)))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('code',
                        code='place',
                        filter='or|begin_from|ge|2018-1-1'))
            assert b'Nostromos' in rv.data

            # Parameter: last
            rv = self.app.get(url_for('class', class_code='E18',
                                      last=place.id))
            assert b'entities' in rv.data
            # Parameter: first
            rv = self.app.get(
                url_for('class', class_code='E18', first=place.id))
            assert b'entities' in rv.data

            # Parameter: show
            rv = self.app.get(url_for('class', class_code='E31', show='types'))
            assert b'https://openatlas.eu' in rv.data
            rv = self.app.get(url_for('class', class_code='E18', show='when'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(url_for('class', class_code='E31', show='none'))
            assert b'https://openatlas.eu' in rv.data

            # Parameter: count
            rv = self.app.get(url_for('class', class_code='E31', count=True))
            assert b'2' in rv.data
            rv = self.app.get(url_for('code', code='place', count=True))
            assert b'3' in rv.data
            rv = self.app.get(
                url_for('system_class', system_class='appellation',
                        count=True))
            assert b'1' in rv.data

            rv = self.app.get(
                url_for('query',
                        entities=place.id,
                        classes='E18',
                        codes='place'))
            assert b'Nostromos' in rv.data
            rv = self.app.get(
                url_for('query',
                        entities=place.id,
                        classes='E18',
                        codes='place',
                        count=True))
            assert b'7' in rv.data
            rv = self.app.get(
                url_for('node_entities', id_=unit_node.id, count=True))
            assert b'6' in rv.data
            rv = self.app.get(
                url_for('node_entities_all', id_=unit_node.id, count=True))
            assert b'8' in rv.data
Ejemplo n.º 15
0
def update_links(entity: Entity, form: FlaskForm, action: str,
                 origin: Optional[Entity]) -> None:
    if entity.class_.view in ['actor', 'event', 'place', 'artifact', 'type']:
        ReferenceSystem.update_links(form, entity)
    if entity.class_.view == 'actor':
        if action == 'update':
            entity.delete_links(['P74', 'OA8', 'OA9'])
        if form.residence.data:
            object_ = Entity.get_by_id(form.residence.data)
            entity.link('P74', object_.get_linked_entity_safe('P53'))
        if form.begins_in.data:
            object_ = Entity.get_by_id(form.begins_in.data)
            entity.link('OA8', object_.get_linked_entity_safe('P53'))
        if form.ends_in.data:
            object_ = Entity.get_by_id(form.ends_in.data)
            entity.link('OA9', object_.get_linked_entity_safe('P53'))
    if entity.class_.view == 'event':
        if action == 'update':
            entity.delete_links(['P7', 'P24', 'P25', 'P26', 'P27', 'P117'])
        if form.event.data:
            entity.link_string('P117', form.event.data)
        if hasattr(form, 'place') and form.place.data:
            entity.link(
                'P7', Link.get_linked_entity_safe(int(form.place.data), 'P53'))
        if entity.class_.name == 'acquisition' and form.given_place.data:
            entity.link_string('P24', form.given_place.data)
        if entity.class_.name == 'move':
            if form.artifact.data:  # Moved objects
                entity.link_string('P25', form.artifact.data)
            if form.person.data:  # Moved persons
                entity.link_string('P25', form.person.data)
            if form.place_from.data:  # Link place for move from
                linked_place = Link.get_linked_entity_safe(
                    int(form.place_from.data), 'P53')
                entity.link('P27', linked_place)
            if form.place_to.data:  # Link place for move to
                entity.link(
                    'P26',
                    Link.get_linked_entity_safe(int(form.place_to.data),
                                                'P53'))
    elif entity.class_.view in ['artifact', 'place']:
        location = entity.get_linked_entity_safe('P53')
        if action == 'update':
            Gis.delete_by_entity(location)
        location.update(form)
        Gis.insert(location, form)
    elif entity.class_.view == 'source' and not origin:
        if action == 'update':
            entity.delete_links(['P128'], inverse=True)
        if form.artifact.data:
            entity.link_string('P128', form.artifact.data, inverse=True)
    elif entity.class_.view == 'type':
        node = origin if isinstance(origin, Node) else entity
        root = g.nodes[node.root[-1]] if node.root else node
        super_id = g.nodes[node.root[0]] if node.root else node
        new_super_id = getattr(form, str(root.id)).data
        new_super = g.nodes[int(new_super_id)] if new_super_id else root
        if super_id != new_super.id:
            property_code = 'P127' if entity.class_.name == 'type' else 'P89'
            entity.delete_links([property_code])
            entity.link(property_code, new_super)
Ejemplo n.º 16
0
def add_fields(form: Any, class_: str, code: Union[str, None],
               item: Union[Entity, Node, Link,
                           None], origin: Union[Entity, Node, None]) -> None:
    if class_ == 'actor_actor_relation':
        setattr(form, 'inverse', BooleanField(_('inverse')))
        if not item:
            setattr(form, 'actor',
                    TableMultiField(_('actor'), [InputRequired()]))
            setattr(form, 'relation_origin_id', HiddenField())
    elif class_ in ['activity', 'acquisition', 'move']:
        setattr(form, 'event_id', HiddenField())
        setattr(form, 'event', TableField(_('sub event of')))
        if class_ == 'activity':
            setattr(form, 'place', TableField(_('location')))
        if class_ == 'acquisition':
            setattr(form, 'place', TableField(_('location')))
            setattr(form, 'given_place', TableMultiField(_('given place')))
        elif class_ == 'move':
            setattr(form, 'place_from', TableField(_('from')))
            setattr(form, 'place_to', TableField(_('to')))
            setattr(form, 'artifact', TableMultiField())
            setattr(form, 'person', TableMultiField())
    elif class_ == 'file' and not item:
        setattr(form, 'file', FileField(_('file'), [InputRequired()]))
    elif class_ == 'group':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('begins in')))
        setattr(form, 'ends_in', TableField(_('ends in')))
    elif class_ == 'hierarchy':
        if code == 'custom' or (item and not item.value_type):
            setattr(
                form, 'multiple',
                BooleanField(_('multiple'),
                             description=_('tooltip hierarchy multiple')))
        setattr(
            form, 'forms',
            SelectMultipleField(_('classes'),
                                render_kw={'disabled': True},
                                description=_('tooltip hierarchy forms'),
                                choices=[],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False),
                                coerce=int))
    elif class_ == 'involvement':
        if not item and origin:
            involved_with = 'actor' if origin.class_.view == 'event' else 'event'
            setattr(form, involved_with,
                    TableMultiField(_(involved_with), [InputRequired()]))
        setattr(form, 'activity', SelectField(_('activity')))
    elif class_ == 'member' and not item:
        setattr(form, 'member_origin_id', HiddenField())
        setattr(form, 'actor' if code == 'member' else 'group',
                TableMultiField(_('actor'), [InputRequired()]))
    elif class_ in g.classes and g.classes[class_].view == 'type':
        setattr(form, 'is_node_form', HiddenField())
        node = item if item else origin
        root = g.nodes[node.root[-1]] if node.root else node
        setattr(form, str(root.id), TreeField(str(root.id)))
        if root.directional:
            setattr(form, 'name_inverse', StringField(_('inverse')))
    elif class_ == 'person':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('born in')))
        setattr(form, 'ends_in', TableField(_('died in')))
    elif class_ == 'reference_system':
        setattr(
            form, 'website_url',
            StringField(_('website URL'),
                        validators=[OptionalValidator(),
                                    URL()]))
        setattr(
            form, 'resolver_url',
            StringField(_('resolver URL'),
                        validators=[OptionalValidator(),
                                    URL()]))
        setattr(form, 'placeholder', StringField(_('example ID')))
        precision_node_id = str(
            Node.get_hierarchy('External reference match').id)
        setattr(form, precision_node_id, TreeField(precision_node_id))
        choices = ReferenceSystem.get_form_choices(item)
        if choices:
            setattr(
                form, 'forms',
                SelectMultipleField(
                    _('forms'),
                    render_kw={'disabled': True},
                    choices=choices,
                    option_widget=widgets.CheckboxInput(),
                    widget=widgets.ListWidget(prefix_label=False),
                    coerce=int))
    elif class_ == 'source':
        setattr(form, 'artifact', TableMultiField())
Ejemplo n.º 17
0
def add_fields(form: Any, class_: str, code: Union[str, None],
               entity: Union[Entity, Link, ReferenceSystem, Type,
                             None], origin: Union[Entity, Type, None]) -> None:
    if class_ == 'actor_actor_relation':
        setattr(form, 'inverse', BooleanField(_('inverse')))
        if not entity:
            setattr(form, 'actor',
                    TableMultiField(_('actor'), [InputRequired()]))
            setattr(form, 'relation_origin_id', HiddenField())
    elif class_ == 'artifact':
        setattr(form, 'actor', TableField(_('owned by')))
    elif class_ in view_class_mapping['event']:
        setattr(form, 'event_id', HiddenField())
        setattr(form, 'event', TableField(_('sub event of')))
        setattr(form, 'event_preceding', TableField(_('preceding event')))
        if class_ in ['activity', 'acquisition', 'production']:
            setattr(form, 'place', TableField(_('location')))
        if class_ == 'acquisition':
            setattr(form, 'given_place', TableMultiField(_('given place')))
        elif class_ == 'move':
            setattr(form, 'place_from', TableField(_('from')))
            setattr(form, 'place_to', TableField(_('to')))
            setattr(form, 'artifact', TableMultiField())
            setattr(form, 'person', TableMultiField())
        elif class_ == 'production':
            setattr(form, 'artifact', TableMultiField())
    elif class_ == 'file' and not entity:
        setattr(form, 'file', MultipleFileField(_('file'), [InputRequired()]))
        if origin and origin.class_.view == 'reference':
            setattr(form, 'page', StringField())
    elif class_ == 'group':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('begins in')))
        setattr(form, 'ends_in', TableField(_('ends in')))
    elif class_ == 'hierarchy':
        if code == 'custom' or (entity and isinstance(entity, Type)
                                and entity.category != 'value'):
            setattr(
                form, 'multiple',
                BooleanField(_('multiple'),
                             description=_('tooltip hierarchy multiple')))
        setattr(
            form, 'classes',
            SelectMultipleField(_('classes'),
                                render_kw={'disabled': True},
                                description=_('tooltip hierarchy forms'),
                                choices=[],
                                option_widget=widgets.CheckboxInput(),
                                widget=widgets.ListWidget(prefix_label=False)))
    elif class_ == 'involvement':
        if not entity and origin:
            involved_with = 'actor' \
                if origin.class_.view == 'event' else 'event'
            setattr(form, involved_with,
                    TableMultiField(_(involved_with), [InputRequired()]))
        setattr(form, 'activity', SelectField(_('activity')))
    elif class_ == 'actor_function' and not entity:
        setattr(form, 'member_origin_id', HiddenField())
        setattr(form, 'actor' if code == 'member' else 'group',
                TableMultiField(_('actor'), [InputRequired()]))
    elif class_ in g.view_class_mapping['type']:
        setattr(form, 'is_type_form', HiddenField())
        type_ = entity if entity else origin
        if isinstance(type_, Type):
            root = g.types[type_.root[0]] if type_.root else type_
            setattr(form, str(root.id), TreeField(str(root.id)))
            if root.directional:
                setattr(form, 'name_inverse', StringField(_('inverse')))
    elif class_ == 'person':
        setattr(form, 'residence', TableField(_('residence')))
        setattr(form, 'begins_in', TableField(_('born in')))
        setattr(form, 'ends_in', TableField(_('died in')))
    elif class_ == 'reference_system':
        setattr(form, 'website_url',
                StringField(_('website URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'resolver_url',
                StringField(_('resolver URL'),
                            [OptionalValidator(), URL()]))
        setattr(form, 'placeholder', StringField(_('example ID')))
        precision_id = str(Type.get_hierarchy('External reference match').id)
        setattr(form, precision_id, TreeField(precision_id))
        if choices := ReferenceSystem.get_class_choices(
                entity):  # type: ignore
            setattr(
                form, 'classes',
                SelectMultipleField(
                    _('classes'),
                    render_kw={'disabled': True},
                    choices=choices,
                    option_widget=widgets.CheckboxInput(),
                    widget=widgets.ListWidget(prefix_label=False)))
Ejemplo n.º 18
0
    def test_reference_system(self) -> None:
        with app.app_context():  # type: ignore
            rv = self.app.get(url_for('index', view='reference_system'))
            assert b'GeoNames' in rv.data
            geonames = ReferenceSystem.get_by_name('GeoNames')
            wikidata = ReferenceSystem.get_by_name('Wikidata')
            precision_id = Node.get_hierarchy(
                'External reference match').subs[0]

            rv = self.app.get(url_for('insert', class_='reference_system'))
            assert b'Resolver URL' in rv.data
            data = {
                'name': 'Wikipedia',
                'website_url': 'https://wikipedia.org',
                'resolver_url': 'https://wikipedia.org',
                'forms': [geonames.forms[0]]
            }
            rv = self.app.post(url_for('insert', class_='reference_system'),
                               follow_redirects=True,
                               data=data)
            assert b'An entry has been created.' in rv.data
            wikipedia_id = ReferenceSystem.get_by_name('Wikipedia').id
            rv = self.app.get(url_for('index',
                                      view='reference_system',
                                      delete_id=wikipedia_id),
                              follow_redirects=True)
            assert b'Deletion not possible if forms are attached' in rv.data
            rv = self.app.get(url_for('reference_system_remove_form',
                                      system_id=wikipedia_id,
                                      form_id=geonames.forms[0]),
                              follow_redirects=True)
            assert b'Changes have been saved' in rv.data
            rv = self.app.get(
                url_for('index',
                        view='reference_system',
                        delete_id=wikipedia_id))
            assert b'The entry has been deleted' in rv.data

            rv = self.app.post(url_for('update', id_=geonames.id))
            assert b'Website URL' in rv.data
            data = {
                'name': 'GeoNames',
                Node.get_hierarchy('External reference match').id:
                precision_id,
                'website_url': 'https://www.geonames2.org/',
                'resolver_url': 'https://www.geonames2.org/'
            }
            rv = self.app.post(url_for('update', id_=geonames.id),
                               follow_redirects=True,
                               data=data)
            assert b'Changes have been saved.' in rv.data
            rv = self.app.post(url_for('update', id_=geonames.id),
                               follow_redirects=True,
                               data=data)
            assert b'https://www.geonames2.org/' in rv.data
            rv = self.app.post(url_for('insert', class_='person'),
                               data={
                                   'name': 'Actor test',
                                   'reference_system_id_' + str(wikidata.id):
                                   'Q123',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: precision_id
                               })
            person_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('entity_view', id_=wikidata.id),
                              follow_redirects=True)
            assert b'Actor test' in rv.data
            rv = self.app.get(url_for('entity_view', id_=person_id),
                              follow_redirects=True)
            assert b'Wikidata' in rv.data
            rv = self.app.get(url_for('update', id_=person_id))
            assert b'Q123' in rv.data

            # Testing errors
            rv = self.app.post(url_for('insert', class_='reference_system'),
                               follow_redirects=True,
                               data={'name': 'GeoNames'})
            assert b'A transaction error occurred' in rv.data
            rv = self.app.get(
                url_for('index',
                        view='reference_system',
                        delete_id=geonames.id))
            assert b'403' in rv.data
            rv = self.app.post(url_for('insert', class_='person'),
                               data={
                                   'name':
                                   'Actor with Wikidata but without precision',
                                   'reference_system_id_' + str(wikidata.id):
                                   'Q123',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: ''
                               })
            assert b'required' in rv.data
            rv = self.app.post(url_for('insert', class_='person'),
                               data={
                                   'name': 'Actor with invalid Wikidata id',
                                   'reference_system_id_' + str(wikidata.id):
                                   'invalid id',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: precision_id
                               })
            assert b'Wrong id format' in rv.data
            rv = self.app.post(url_for('insert', class_='place'),
                               data={
                                   'name': 'Reference test',
                                   'reference_system_id_' + str(geonames.id):
                                   'invalid id',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: ''
                               })
            assert b'Wrong id format' in rv.data
            rv = self.app.get(url_for('reference_system_remove_form',
                                      system_id=geonames.id,
                                      form_id=geonames.forms[0]),
                              follow_redirects=True)
            assert b'Changes have been saved' in rv.data
            rv = self.app.get(
                url_for('index',
                        view='reference_system',
                        delete_id=geonames.id))
            assert b'403 - Forbidden' in rv.data
Ejemplo n.º 19
0
    def test_event(self) -> None:
        with app.app_context():  # type: ignore
            # Create entities for event
            place_name = 'Lewis and Clark'
            rv = self.app.post(url_for('insert', class_='place'),
                               data={'name': place_name,
                                     self.precision_geonames: '',
                                     self.precision_wikidata: ''})
            residence_id = rv.location.split('/')[-1]
            actor_name = 'Captain Miller'
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('person', actor_name)
                file = Entity.insert('file', 'X-Files')
                source = Entity.insert('source', 'Necronomicon')
                carrier = Entity.insert('artifact', 'Artifact')
                reference = Entity.insert('external_reference', 'https://openatlas.eu')

            # Insert
            rv = self.app.get(url_for('insert', class_='activity'))
            assert b'+ Activity' in rv.data
            data = {
                'name': 'Event Horizon',
                'place': residence_id,
                self.precision_wikidata: ''}
            rv = self.app.post(
                url_for('insert', class_='activity', origin_id=reference.id),
                data=data,
                follow_redirects=True)
            assert bytes('Event Horizon', 'utf-8') in rv.data
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                activity_id = Entity.get_by_view('event')[0].id
            self.app.post(url_for('insert', class_='activity', origin_id=actor.id), data=data)
            self.app.post(url_for('insert', class_='activity', origin_id=file.id), data=data)
            self.app.post(url_for('insert', class_='activity', origin_id=source.id), data=data)
            rv = self.app.get(url_for('insert', class_='activity', origin_id=residence_id))
            assert b'Location' in rv.data
            rv = self.app.get(url_for('insert', class_='move', origin_id=residence_id))
            assert b'Location' not in rv.data

            # Acquisition
            event_name2 = 'Second event'
            wikidata = 'reference_system_id_' + str(ReferenceSystem.get_by_name('Wikidata').id)
            precision = Node.get_hierarchy('External reference match').subs[0]
            rv = self.app.post(url_for('insert', class_='acquisition'),
                               data={'name': event_name2,
                                     'given_place': [residence_id],
                                     'place': residence_id,
                                     'event': activity_id,
                                     'begin_year_from': '1949',
                                     'begin_month_from': '10',
                                     'begin_day_from': '8',
                                     'end_year_from': '1951',
                                     wikidata: 'Q123',
                                     self.precision_wikidata: precision})
            event_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('entity_view', id_=event_id))
            assert b'Event Horizon' in rv.data

            # Move
            rv = self.app.post(url_for('insert', class_='move'), data={
                'name': 'Keep it moving',
                'place_to': residence_id,
                'place_from': residence_id,
                'artifact': carrier.id,
                'person': actor.id,
                self.precision_wikidata: ''})
            move_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('entity_view', id_=move_id))
            assert b'Keep it moving' in rv.data
            rv = self.app.get(url_for('entity_view', id_=carrier.id))
            assert b'Keep it moving' in rv.data
            rv = self.app.get(url_for('update', id_=move_id))
            assert b'Keep it moving' in rv.data

            # Add another event and test if events are seen at place
            event_name3 = 'Third event'
            self.app.post(url_for('insert', class_='acquisition'), data={
                'name': event_name3,
                'given_place': [residence_id],
                self.precision_geonames: '',
                self.precision_wikidata: ''})
            rv = self.app.get(url_for('entity_view', id_=residence_id))
            assert bytes(place_name, 'utf-8') in rv.data
            rv = self.app.get(url_for('entity_view', id_=actor.id))
            assert bytes(actor_name, 'utf-8') in rv.data
            rv = self.app.post(
                url_for('insert', class_='acquisition'), follow_redirects=True, data={
                    'name': 'Event Horizon',
                    'continue_': 'yes',
                    self.precision_geonames: '',
                    self.precision_wikidata: ''})
            assert b'An entry has been created' in rv.data
            rv = self.app.get(url_for('index', view='event'))
            assert b'Event' in rv.data
            self.app.get(url_for('entity_view', id_=activity_id))

            # Add to event
            rv = self.app.get(url_for('entity_add_file', id_=event_id))
            assert b'Link file' in rv.data
            rv = self.app.post(url_for('entity_add_file', id_=event_id),
                               data={'checkbox_values': str([file.id])}, follow_redirects=True)
            assert b'X-Files' in rv.data

            rv = self.app.get(url_for('entity_add_reference', id_=event_id))
            assert b'Link reference' in rv.data
            rv = self.app.post(
                url_for('entity_add_reference', id_=event_id),
                data={'reference': reference.id, 'page': '777'},
                follow_redirects=True)
            assert b'777' in rv.data

            # Update
            rv = self.app.get(url_for('update', id_=activity_id))
            assert b'Event Horizon' in rv.data
            rv = self.app.get(url_for('update', id_=event_id))
            assert b'Event Horizon' in rv.data
            data['name'] = 'Event updated'
            rv = self.app.post(url_for('update', id_=event_id), data=data, follow_redirects=True)
            assert b'Changes have been saved' in rv.data

            # Test super event validation
            data = {'name': 'Event Horizon', 'event': event_id}
            rv = self.app.post(url_for('update', id_=event_id), data=data, follow_redirects=True)
            assert b'error' in rv.data

            # Delete
            rv = self.app.get(url_for('index', view='event', delete_id=event_id))
            assert b'The entry has been deleted.' in rv.data