Exemplo n.º 1
0
 def get(filename: str) -> Response:  # pragma: no cover
     entity = Entity.get_by_id(int(Pathlib_path(filename).stem), types=True)
     license_ = None
     for node in entity.types:
         if node.root and node.root[0] == Type.get_hierarchy('License').id:
             license_ = node.name
     if not license_:
         raise AccessDeniedError
     parser = image.parse_args()
     if parser['download']:
         return send_file(
             f"{app.config['UPLOAD_DIR']}/{filename}",
             as_attachment=True)
     if parser['image_size'] and check_processed_image(filename):
         size = app.config['IMAGE_SIZE'][parser['image_size']]
         return send_from_directory(
             f"{app.config['RESIZED_IMAGES']}/{size}",
             filename)
     return send_from_directory(app.config['UPLOAD_DIR'], filename)
Exemplo n.º 2
0
def add_reference_systems(form: Any, class_: str) -> None:
    precisions = [('', '')] + [
        (str(g.types[id_].id), g.types[id_].name)
        for id_ in Type.get_hierarchy('External reference match').subs
    ]
    systems = list(g.reference_systems.values())
    systems.sort(key=lambda x: x.name.casefold())
    for system in systems:
        if class_ not in system.classes:
            continue
        setattr(
            form, f'reference_system_id_{system.id}',
            StringField(uc_first(system.name), [OptionalValidator()],
                        description=system.description,
                        render_kw={
                            'autocomplete': 'off',
                            'placeholder': system.placeholder
                        }))
        setattr(
            form, f'reference_system_precision_{system.id}',
            SelectField(_('precision'),
                        choices=precisions,
                        default=system.precision_default_id))
Exemplo n.º 3
0
 def test_duplicates(self) -> None:
     with app.app_context():
         with app.test_request_context():
             app.preprocess_request()  # type: ignore
             event = Entity.insert('acquisition', 'Event Horizon')
             source = Entity.insert('source', 'Tha source')
             source.link('P67', event)
             source.link('P67', event)
             source_type = Type.get_hierarchy('Source')
             source.link('P2', g.types[source_type.subs[0]])
             source.link('P2', g.types[source_type.subs[1]])
         rv = self.app.get(url_for('admin_check_link_duplicates'))
         assert b'Event Horizon' in rv.data
         rv = self.app.get(
             url_for('admin_check_link_duplicates', delete='delete'),
             follow_redirects=True)
         assert b'Remove' in rv.data
         rv = self.app.get(
             url_for(
                 'admin_delete_single_type_duplicate',
                 entity_id=source.id,
                 type_id=source_type.subs[0]),
             follow_redirects=True)
         assert b'Congratulations, everything looks fine!' in rv.data
Exemplo n.º 4
0
    def test_type(self) -> None:
        with app.app_context():
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor_type = Type.get_hierarchy('Actor actor relation')
                dimension_type = Type.get_hierarchy('Dimensions')
                historical_type = Type.get_hierarchy('Historical place')
                sex_type = Type.get_hierarchy('Sex')
                place = insert_entity('Home', 'place')
                place.link('P2', g.types[dimension_type.subs[0]], '46')
                location = place.get_linked_entity_safe('P53')
                location.link('P89', g.types[historical_type.subs[0]])
            rv: Any = self.app.get(url_for('view', id_=historical_type.subs[0]))
            assert b'Historical place' in rv.data
            rv = self.app.get(url_for('type_index'))
            assert b'Actor actor relation' in rv.data
            rv = self.app.get(
                url_for('insert', class_='type', origin_id=actor_type.id))
            assert b'Actor actor relation' in rv.data
            data = {
                'name': 'My secret type',
                'name_inverse': 'Do I look inverse?',
                'description': 'Very important!'}
            rv = self.app.post(
                url_for('insert', class_='type', origin_id=actor_type.id),
                data=data)
            type_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('update', id_=type_id))
            assert b'My secret type' in rv.data and b'Super' in rv.data
            self.app.post(
                url_for('insert', class_='type', origin_id=sex_type.id),
                data=data)
            rv = self.app.post(
                url_for('update', id_=type_id),
                data=data,
                follow_redirects=True)
            assert b'Changes have been saved.' in rv.data

            # Insert and continue
            data['continue_'] = 'yes'
            rv = self.app.post(
                url_for('insert', class_='type', origin_id=actor_type.id),
                data=data,
                follow_redirects=True)
            assert b'An entry has been created' in rv.data
            data['continue_'] = ''

            # Forbidden system type
            rv = self.app.post(
                url_for('update', id_=actor_type.id),
                data=data,
                follow_redirects=True)
            assert b'Forbidden' in rv.data

            # Update with self as root
            data[str(actor_type.id)] = type_id
            rv = self.app.post(
                url_for('update', id_=type_id),
                data=data,
                follow_redirects=True)
            assert b'Type can't have itself as super' in rv.data

            # Update with sub as root
            rv = self.app.post(
                url_for('insert', class_='type', origin_id=actor_type.id),
                data=data)
            sub_type_id = rv.location.split('/')[-1].replace('type#tab-', '')
            data[str(actor_type.id)] = sub_type_id
            rv = self.app.post(
                url_for('update', id_=type_id),
                data=data,
                follow_redirects=True)
            assert b'Type can't have a sub as super' in rv.data

            # Custom type
            rv = self.app.get(
                url_for('view', id_=sex_type.id),
                follow_redirects=True)
            assert b'Male' in rv.data

            # Administrative unit
            admin_unit_id = Type.get_hierarchy('Administrative unit').id
            rv = self.app.get(
                url_for('view', id_=admin_unit_id), follow_redirects=True)
            assert b'Austria' in rv.data
            rv = self.app.post(
                url_for(
                    'insert',
                    class_='administrative_unit',
                    origin_id=g.types[admin_unit_id].subs[0]),
                data={'name': 'admin unit'},
                follow_redirects=True)
            assert b'An entry has been created' in rv.data

            # Value type
            rv = self.app.get(
                url_for('view', id_=dimension_type.id),
                follow_redirects=True)
            assert b'Height' in rv.data
            rv = self.app.get(url_for('view', id_=dimension_type.subs[0]))
            assert b'Unit' in rv.data
            rv = self.app.get(url_for('update', id_=dimension_type.subs[0]))
            assert b'Dimensions' in rv.data

            # Test parent value type view after creating a sub subtype
            rv = self.app.post(
                url_for(
                    'insert',
                    class_='type',
                    origin_id=dimension_type.subs[0]),
                data={
                    'name': "Sub sub type",
                    dimension_type.id: dimension_type.subs[0]},
                follow_redirects=True)
            assert b'An entry has been created' in rv.data
            rv = self.app.get(url_for('view', id_=dimension_type.subs[0]))
            assert b'Sub sub type' in rv.data

            # Untyped entities
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('person', 'Connor MacLeod')
            rv = self.app.get(url_for('show_untyped_entities', id_=sex_type.id))
            assert b'Connor MacLeod' in rv.data
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor.link('P2', g.types[sex_type.subs[0]])
            rv = self.app.get(url_for('show_untyped_entities', id_=sex_type.id))
            assert b'No entries' in rv.data

            # Delete
            rv = self.app.get(
                url_for('type_delete', id_=actor_type.id),
                follow_redirects=True)
            assert b'Forbidden' in rv.data
            rv = self.app.get(
                url_for('type_delete', id_=sub_type_id),
                follow_redirects=True)
            assert b'The entry has been deleted.' in rv.data
Exemplo n.º 5
0
    def test_image(self) -> None:
        app.config['IMAGE_SIZE']['tmp'] = '1'
        with app.app_context():
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                place = insert_entity('Nostromos',
                                      'place',
                                      description='That is the Nostromos')
                logo = \
                    pathlib.Path(app.root_path) \
                    / 'static' / 'images' / 'layout' / 'logo.png'

            # Resizing through UI insert
            with open(logo, 'rb') as img:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=place.id),
                                   data={
                                       'name': 'OpenAtlas logo',
                                       '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
                files = Entity.get_by_class('file')
                file_id = files[0].id

            # Set and unset as main image
            self.app.get(url_for('set_profile_image',
                                 id_=file_id,
                                 origin_id=place.id),
                         follow_redirects=True)

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

            # Create entities for file
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                file_pathless = insert_entity('Pathless_File', 'file')

                file = insert_entity('Test_File', 'file')
                file.link('P2', g.types[Type.get_hierarchy('License').subs[0]])
                file_name = f'{file.id}.jpeg'
                src_png = \
                    pathlib.Path(app.root_path) \
                    / 'static' / 'images' / 'layout' / 'logo.png'
                dst_png = \
                    pathlib.Path(app.config['UPLOAD_DIR'] / file_name)
                copyfile(src_png, dst_png)

                file2 = insert_entity('Test_File2', 'file')
                file2.link('P2',
                           g.types[Type.get_hierarchy('License').subs[0]])
                file2_name = f'{file2.id}.jpeg'
                src2_png = \
                    pathlib.Path(app.root_path) \
                    / 'static' / 'images' / 'layout' / 'logo.png'
                dst2_png = pathlib.Path(app.config['UPLOAD_DIR'] / file2_name)
                copyfile(src2_png, dst2_png)

                file_py = insert_entity('Test_Py', 'file')
                file_name_py = f'{file_py.id}.py'
                src_py = pathlib.Path(app.root_path) / 'views' / 'index.py'
                dst_py = pathlib.Path(app.config['UPLOAD_DIR'] / file_name_py)
                copyfile(src_py, dst_py)

                # Exception
                safe_resize_image(file2.id, '.png', size="???")
                display_profile_image(file_pathless)

            # Resizing images (don't change order!)
            rv = self.app.get(url_for('view', id_=file.id))
            assert b'Test_File' in rv.data
            rv = self.app.get(url_for('view', id_=file_py.id))
            assert b'No preview available' in rv.data
            rv = self.app.get(url_for('view', id_=file_pathless.id))
            assert b'Missing file' in rv.data
            rv = self.app.get(url_for('index', view='file'))
            assert b'Test_File' in rv.data

            # Display file
            rv = self.app.get(url_for('display_file', filename=file_name))
            assert b'\xff' in rv.data
            rv = self.app.get(
                url_for('display_file',
                        filename=file_name,
                        size=app.config['IMAGE_SIZE']['thumbnail']))
            assert b'\xff' in rv.data
            rv = self.app.get(
                url_for('display_file',
                        filename=file_name,
                        size=app.config['IMAGE_SIZE']['table']))
            assert b'\xff' in rv.data
            rv = self.app.get(
                url_for('display_file',
                        filename=file_name_py,
                        size=app.config['IMAGE_SIZE']['table']))
            assert b'404' in rv.data

            # Make directory if not exist
            rv = self.app.get(url_for('view', id_=file.id))
            assert b'Test_File' in rv.data

            # Exception
            app.config['IMAGE_SIZE']['tmp'] = '<'
            rv = self.app.get(url_for('view', id_=file.id))
            assert b'Test_File' in rv.data
            app.config['IMAGE_SIZE']['tmp'] = '1'

            rv = self.app.get(url_for('admin_resize_images'),
                              follow_redirects=True)
            assert b'Images were created' in rv.data
            rv = self.app.get(url_for('admin_delete_orphaned_resized_images'),
                              follow_redirects=True)
            assert b'Resized orphaned images were deleted' in rv.data

            rv = self.app.get(url_for('index', view='file', delete_id=file.id))
            assert b'The entry has been deleted' in rv.data
            rv = self.app.get(url_for('index', view='file',
                                      delete_id=file2.id))
            assert b'The entry has been deleted' in rv.data

            shutil.rmtree(
                pathlib.Path(app.config['RESIZED_IMAGES'] /
                             app.config['IMAGE_SIZE']['tmp']))

            dst_py.unlink()
            del app.config['IMAGE_SIZE']['tmp']
Exemplo n.º 6
0
    def test_actor(self) -> None:
        with app.app_context():
            rv: Any = self.app.get(url_for('index', view='actor'))
            assert b'No entries' in rv.data
            rv = self.app.post(url_for('insert', class_='place'),
                               data={
                                   'name': 'Captain Miller',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: ''
                               })
            residence_id = rv.location.split('/')[-1]
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                sex_type = Type.get_hierarchy('Sex')
                sex_type_sub_1 = g.types[sex_type.subs[0]]
                sex_type_sub_2 = g.types[sex_type.subs[1]]
                event = Entity.insert('acquisition', 'Event Horizon')
                source = Entity.insert('source', 'Necronomicon')

            # Actor insert
            rv = self.app.get(url_for('insert', class_='person'))
            assert b'+ Person' in rv.data
            self.app.get(
                url_for('insert', class_='person', origin_id=residence_id))
            data = {
                sex_type.id: sex_type_sub_1.id,
                'name': 'Sigourney Weaver',
                'alias-1': 'Ripley',
                'residence': residence_id,
                'begins_in': residence_id,
                'ends_in': residence_id,
                'description':
                'Susan Alexandra Weaver is an American actress.',
                'begin_year_from': '-1949',
                'begin_month_from': '10',
                'begin_day_from': '8',
                'begin_year_to': '-1948',
                'end_year_from': '2049',
                'end_year_to': '2050',
                self.precision_geonames: '',
                self.precision_wikidata: ''
            }
            rv = self.app.post(url_for('insert', class_='person'), data=data)
            actor_id = rv.location.split('/')[-1]
            self.app.post(url_for('insert', class_='group'), data=data)
            rv = self.app.post(url_for('insert',
                                       class_='person',
                                       origin_id=residence_id),
                               data=data,
                               follow_redirects=True)
            assert b'An entry has been created' in rv.data

            # Test actor types
            rv = self.app.get(url_for('view', id_=sex_type_sub_1.id))
            assert b'Susan' in rv.data
            rv = self.app.get(
                url_for('type_move_entities', id_=sex_type_sub_1.id))
            assert b'Sigourney' in rv.data
            rv = self.app.post(url_for('type_move_entities',
                                       id_=sex_type_sub_1.id),
                               follow_redirects=True,
                               data={
                                   sex_type.id: sex_type_sub_2.id,
                                   'selection': [actor_id],
                                   'checkbox_values': str([actor_id])
                               })
            assert b'Entities were updated' in rv.data
            rv = self.app.post(url_for('type_move_entities',
                                       id_=sex_type_sub_2.id),
                               follow_redirects=True,
                               data={
                                   sex_type.id: '',
                                   'selection': [actor_id],
                                   'checkbox_values': str([actor_id])
                               })
            assert b'Entities were updated' in rv.data
            self.app.post(url_for('insert',
                                  class_='person',
                                  origin_id=actor_id),
                          data=data)
            self.app.post(url_for('insert',
                                  class_='person',
                                  origin_id=event.id),
                          data=data)
            self.app.post(url_for('insert',
                                  class_='person',
                                  origin_id=source.id),
                          data=data)
            rv = self.app.post(url_for('insert', class_='external_reference'),
                               data={'name': 'https://openatlas.eu'})
            reference_id = rv.location.split('/')[-1]
            rv = self.app.post(url_for('insert',
                                       class_='person',
                                       origin_id=reference_id),
                               data=data,
                               follow_redirects=True)
            assert b'An entry has been created' in rv.data
            data['continue_'] = 'yes'
            rv = self.app.post(url_for('insert', class_='person'),
                               data=data,
                               follow_redirects=True)
            assert b'An entry has been created' in rv.data
            rv = self.app.get(url_for('index', view='actor'))
            assert b'Sigourney Weaver' in rv.data

            # Add to actor
            rv = self.app.get(url_for('entity_add_source', id_=actor_id))
            assert b'Link source' in rv.data
            rv = self.app.post(url_for('entity_add_source', id_=actor_id),
                               data={'checkbox_values': str([source.id])},
                               follow_redirects=True)
            assert b'Necronomicon' in rv.data

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

            # Actor update
            rv = self.app.get(url_for('update', id_=actor_id))
            assert b'American actress' in rv.data
            data['name'] = 'Susan Alexandra Weaver'
            data['alias-1'] = 'Ripley1'
            data['end_year_from'] = ''
            data['end_year_to'] = ''
            data['begin_year_to'] = '1950'
            data['begin_day_from'] = ''
            rv = self.app.post(url_for('update', id_=actor_id),
                               data=data,
                               follow_redirects=True)
            assert b'Changes have been saved' in rv.data
            rv = self.app.post(url_for('ajax_bookmark'),
                               data={'entity_id': actor_id},
                               follow_redirects=True)
            assert b'Remove bookmark' in rv.data
            rv = self.app.get('/')
            assert b'Weaver' in rv.data
            rv = self.app.post(url_for('ajax_bookmark'),
                               data={'entity_id': actor_id},
                               follow_redirects=True)
            assert b'Bookmark' in rv.data
            rv = self.app.get(url_for('link_delete',
                                      origin_id=actor_id,
                                      id_=666),
                              follow_redirects=True)
            assert b'removed' in rv.data

            # Actor delete
            rv = self.app.get(
                url_for('index', view='actor', delete_id=actor_id))
            assert b'The entry has been deleted.' in rv.data
Exemplo n.º 7
0
    def get_all(objects: Optional[list[Entity]] = None,
                structure: Optional[dict[str, Any]] = None) -> dict[str, Any]:

        if not objects:
            objects = []
        all_: dict[str, list[Any]] = {
            'point': [],
            'linestring': [],
            'polygon': []
        }
        extra: dict[str, list[Any]] = {
            'supers': [],
            'subs': [],
            'siblings': []
        }
        selected: dict[str, list[Any]] = {
            'point': [],
            'linestring': [],
            'polygon': [],
            'polygon_point': []
        }

        # Include GIS of subunits which would be otherwise omitted
        subunit_ids = [
            subunit.id for subunit in structure['subunits']] \
            if structure else []
        sibling_ids = [
            sibling.id for sibling in structure['siblings']] \
            if structure else []
        extra_ids = [0]
        if structure:
            extra_ids = [
                objects[0].id if objects else 0] \
                + [structure['super_id']] \
                + subunit_ids \
                + sibling_ids
        object_ids = [x.id for x in objects] if objects else []

        for shape in ['point', 'polygon', 'linestring']:
            place_root = Type.get_hierarchy('Place')
            for row in Db.get_by_shape(shape, extra_ids):
                description = row['description'].replace('"', '\"') \
                    if row['description'] else ''
                object_desc = row['object_desc'].replace('"', '\"') \
                    if row['object_desc'] else ''
                item = {
                    'type': 'Feature',
                    'geometry': json.loads(row['geojson']),
                    'properties': {
                        'objectId': row['object_id'],
                        'objectName': row['object_name'].replace('"', '\"'),
                        'objectDescription': object_desc,
                        'id': row['id'],
                        'name':
                        row['name'].replace('"', '\"') if row['name'] else '',
                        'description': description,
                        'shapeType': row['type']
                    }
                }
                if 'types' in row and row['types']:
                    type_ids = ast.literal_eval(f"[{row['types']}]")
                    for type_id in list(set(type_ids)):
                        type_ = g.types[type_id]
                        if type_.root and type_.root[0] == place_root.id:
                            item['properties']['objectType'] = \
                                type_.name.replace('"', '\"')
                            break
                if structure and row['object_id'] == structure['super_id']:
                    extra['supers'].append(item)
                elif row['object_id'] in object_ids:
                    selected[shape].append(item)
                elif row['object_id'] in subunit_ids:  # pragma no cover
                    extra['subs'].append(item)
                elif row['object_id'] in sibling_ids:  # pragma no cover
                    extra['siblings'].append(item)
                else:
                    all_[shape].append(item)
                if 'polygon_point' in row:
                    polygon_point_item = dict(item)  # Make a copy
                    polygon_point_item['geometry'] = json.loads(
                        row['polygon_point'])
                    if row['object_id'] in object_ids:
                        selected['polygon_point'].append(polygon_point_item)
                    elif row['object_id'] and structure and \
                            row['object_id'] == structure['super_id']:
                        extra['supers'].append(polygon_point_item)
                    elif row['object_id'] in subunit_ids:  # pragma no cover
                        extra['subs'].append(polygon_point_item)
                    elif row['object_id'] in sibling_ids:  # pragma no cover
                        extra['siblings'].append(polygon_point_item)
                    else:
                        all_['point'].append(polygon_point_item)
        return {
            'gisPointAll':
            json.dumps(all_['point']),
            'gisPointSelected':
            json.dumps(selected['point']),
            'gisPointSupers':
            json.dumps(extra['supers']),
            'gisPointSubs':
            json.dumps(extra['subs']),
            'gisPointSibling':
            json.dumps(extra['siblings']),
            'gisLineAll':
            json.dumps(all_['linestring']),
            'gisLineSelected':
            json.dumps(selected['linestring']),
            'gisPolygonAll':
            json.dumps(all_['polygon']),
            'gisPolygonSelected':
            json.dumps(selected['polygon']),
            'gisPolygonPointSelected':
            json.dumps(selected['polygon_point']),
            'gisAllSelected':
            json.dumps(selected['polygon'] + selected['linestring'] +
                       selected['point'])
        }
Exemplo n.º 8
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)))
Exemplo n.º 9
0
    def test_hierarchy(self) -> None:
        with app.app_context():
            # Custom types
            data = {
                'name': 'Geronimo',
                'classes':
                    ['file', 'group', 'move', 'person', 'place', 'source'],
                'multiple': True,
                'description': 'Very important!'}
            rv: Any = self.app.post(
                url_for('hierarchy_insert', category='custom'),
                follow_redirects=True,
                data=data)
            assert b'An entry has been created' in rv.data
            rv = self.app.post(
                url_for('hierarchy_insert', category='custom'),
                follow_redirects=True,
                data=data)
            assert b'The name is already in use' in rv.data
            with app.test_request_context():
                hierarchy = Type.get_hierarchy('Geronimo')
            rv = self.app.get(url_for('hierarchy_update', id_=hierarchy.id))
            assert b'Geronimo' in rv.data
            data['classes'] = ['acquisition']
            rv = self.app.post(
                url_for('hierarchy_update', id_=hierarchy.id),
                data=data,
                follow_redirects=True)
            assert b'Changes have been saved.' in rv.data

            rv = self.app.get(url_for('hierarchy_insert', category='custom'))
            assert b'+ Custom' in rv.data

            data = {'name': 'My secret type', 'description': 'Very important!'}
            rv = self.app.post(
                url_for('insert', class_='type', origin_id=hierarchy.id),
                data=data)
            type_id = rv.location.split('/')[-1]
            rv = self.app.get(
                url_for('remove_class', id_=hierarchy.id, class_name='person'),
                follow_redirects=True)
            assert b'Changes have been saved.' in rv.data
            rv = self.app.get(
                url_for('type_delete', id_=type_id),
                follow_redirects=True)
            assert b'deleted' in rv.data

            rv = self.app.post(
                url_for('hierarchy_update', id_=hierarchy.id),
                data={'name': 'Actor actor relation'},
                follow_redirects=True)
            assert b'The name is already in use' in rv.data
            rv = self.app.post(
                url_for('hierarchy_delete', id_=hierarchy.id),
                follow_redirects=True)
            assert b'deleted' in rv.data

            # Value types
            rv = self.app.get(url_for('hierarchy_insert', category='value'))
            assert b'+ Value' in rv.data
            rv = self.app.post(
                url_for('hierarchy_insert', category='value'),
                follow_redirects=True,
                data={
                    'name': 'A valued value',
                    'classes': ['file'],
                    'description': ''})
            assert b'An entry has been created' in rv.data
            with app.test_request_context():
                value_type = Type.get_hierarchy('A valued value')
            rv = self.app.get(url_for('hierarchy_update', id_=value_type.id))
            assert b'valued' in rv.data

            # Test checks
            relation_type = Type.get_hierarchy('Actor actor relation')
            rv = self.app.get(
                url_for('hierarchy_update', id_=relation_type.id),
                follow_redirects=True)
            assert b'Forbidden' in rv.data
            rv = self.app.get(
                url_for('hierarchy_delete', id_=relation_type.id),
                follow_redirects=True)
            assert b'Forbidden' in rv.data
Exemplo n.º 10
0
    def test_event(self) -> None:
        with app.app_context():
            # Create entities for event
            place_name = 'Lewis and Clark'
            rv: Any = 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 = \
                f"reference_system_id_" \
                f"{ReferenceSystem.get_by_name('Wikidata').id}"
            precision = Type.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('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('view', id_=move_id))
            assert b'Keep it moving' in rv.data
            rv = self.app.get(url_for('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

            # Production
            rv = self.app.post(url_for('insert', class_='production'),
                               data={
                                   'name': 'A very productive event',
                                   'artifact': carrier.id,
                                   self.precision_wikidata: ''
                               })
            production_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('view', id_=production_id))
            assert b'Artifact' in rv.data
            rv = self.app.get(url_for('view', id_=carrier.id))
            assert b'A very productive event' in rv.data
            rv = self.app.get(url_for('update', id_=production_id))
            assert b'A very productive event' 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('view', id_=residence_id))
            assert bytes(place_name, 'utf-8') in rv.data
            rv = self.app.get(url_for('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('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
            rv = self.app.post(url_for('update', id_=event_id),
                               data={
                                   'name': 'Event',
                                   'event': event_id,
                                   'event_id': event_id
                               },
                               follow_redirects=True)
            assert b'Self as super not allowed' in rv.data

            # Preceding event
            rv = self.app.post(url_for('update', id_=event_id),
                               data={
                                   'name': 'Event',
                                   'event_preceding': event_id,
                                   'event_id': event_id
                               },
                               follow_redirects=True)
            assert b'Self as preceding not allowed' in rv.data
            rv = self.app.post(url_for('update', id_=event_id),
                               data={
                                   'name': 'Event with preceding',
                                   'event_preceding': activity_id,
                                   'event_id': event_id
                               },
                               follow_redirects=True)
            assert b'Event with preceding' in rv.data
            rv = self.app.get(url_for('view', id_=activity_id))
            assert b'Event with preceding' 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
Exemplo n.º 11
0
    def test_involvement(self) -> None:
        with app.app_context():
            rv: Any = self.app.post(url_for('insert', class_='acquisition'),
                                    data={
                                        'name': 'Event Horizon',
                                        'begin_year_from': '949',
                                        'begin_month_from': '10',
                                        'begin_day_from': '8',
                                        'end_year_from': '1951',
                                        self.precision_geonames: '',
                                        self.precision_wikidata: ''
                                    })
            event_id = int(rv.location.split('/')[-1])
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('person', 'Captain Miller')
                involvement = Type.get_hierarchy('Involvement')

            # Add involvement
            rv = self.app.get(url_for('involvement_insert',
                                      origin_id=actor.id))
            assert b'Involvement' in rv.data
            rv = self.app.post(url_for('involvement_insert',
                                       origin_id=actor.id),
                               data={
                                   'event': str([event_id]),
                                   'activity': 'P11',
                                   'begin_year_from': '950',
                                   'end_year_from': '1950',
                                   involvement.id: involvement.id
                               },
                               follow_redirects=True)
            assert b'Event Horizon' in rv.data
            rv = self.app.post(url_for('involvement_insert',
                                       origin_id=event_id),
                               data={
                                   'actor': str([actor.id]),
                                   'continue_': 'yes',
                                   'activity': 'P22'
                               },
                               follow_redirects=True)
            assert b'Event Horizon' in rv.data
            rv = self.app.get(url_for('view', id_=event_id))
            assert b'Event Horizon' in rv.data
            rv = self.app.get(url_for('view', id_=actor.id))
            assert b'Appears first' in rv.data

            # Update involvement
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                link_id = Link.get_links(event_id, 'P22')[0].id
            rv = self.app.get(
                url_for('link_update', id_=link_id, origin_id=event_id))
            assert b'Captain' in rv.data
            rv = self.app.post(url_for('link_update',
                                       id_=link_id,
                                       origin_id=actor.id),
                               data={
                                   'description':
                                   'Infinite Space - Infinite Terror',
                                   'activity': 'P23'
                               },
                               follow_redirects=True)
            assert b'Infinite Space - Infinite Terror' in rv.data
            rv = self.app.get(url_for('view', id_=actor.id))
            assert b'Appears first' in rv.data
            rv = self.app.get(url_for('view', id_=event_id))
            assert b'Infinite Space - Infinite Terror' in rv.data
Exemplo n.º 12
0
    def test_relation(self) -> None:
        with app.app_context():
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('person', 'Connor MacLeod')
                related = Entity.insert('person', 'The Kurgan')

            # Add relationship
            rv = self.app.get(url_for('relation_insert', origin_id=actor.id))
            assert b'Actor actor relation' in rv.data
            relation_id = Type.get_hierarchy('Actor actor relation').id
            relation_sub_id = g.types[relation_id].subs[0]
            relation_sub_id2 = g.types[relation_id].subs[1]
            data = {
                'actor': str([related.id]),
                relation_id: relation_sub_id,
                'inverse': None,
                'begin_year_from': '-1949',
                'begin_month_from': '10',
                'begin_day_from': '8',
                'begin_year_to': '-1948',
                'end_year_from': '2049',
                'end_year_to': '2050'}
            rv = self.app.post(
                url_for('relation_insert', origin_id=actor.id),
                data=data,
                follow_redirects=True)
            assert b'The Kurgan' in rv.data
            rv = self.app.get(url_for('view', id_=relation_sub_id))
            assert b'Connor' in rv.data
            data['continue_'] = 'yes'
            data['inverse'] = True
            rv = self.app.post(
                url_for('relation_insert', origin_id=actor.id),
                data=data,
                follow_redirects=True)
            assert b'The Kurgan' in rv.data
            rv = self.app.get(url_for('view', id_=actor.id))
            assert b'The Kurgan' in rv.data

            rv = self.app.post(
                url_for('relation_insert', origin_id=related.id),
                data=data,
                follow_redirects=True)
            assert b"link to itself" in rv.data

            # Relation types
            rv = self.app.get(
                url_for('type_move_entities', id_=relation_sub_id))
            assert b'The Kurgan' in rv.data

            # Update relationship
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                link_id = Link.get_links(actor.id, 'OA7')[0].id
                link_id2 = Link.get_links(actor.id, 'OA7', True)[0].id

            rv = self.app.post(
                url_for('type_move_entities', id_=relation_sub_id),
                follow_redirects=True,
                data={
                    relation_id: relation_sub_id2,
                    'selection': [link_id],
                    'checkbox_values': str([link_id])})
            assert b'Entities were updated' in rv.data
            rv = self.app.post(
                url_for('type_move_entities', id_=relation_sub_id2),
                data={
                    relation_id: '',
                    'selection': [link_id],
                    'checkbox_values': str([link_id])},
                follow_redirects=True)
            assert b'Entities were updated' in rv.data

            rv = self.app.get(
                url_for('link_update', id_=link_id, origin_id=related.id))
            assert b'Connor' in rv.data
            rv = self.app.post(
                url_for('link_update', id_=link_id, origin_id=actor.id),
                data={'description': 'There can be only one', 'inverse': True},
                follow_redirects=True)
            assert b'only one' in rv.data
            rv = self.app.post(
                url_for('link_update', id_=link_id2, origin_id=actor.id),
                data={'description': 'There can be only one', 'inverse': None},
                follow_redirects=True)
            assert b'only one' in rv.data
Exemplo n.º 13
0
    def test_event(self) -> None:
        with app.app_context():
            # Create entities for file
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                actor = Entity.insert('person', 'File keeper')
                reference = Entity.insert('edition', 'Ancient Books')
                type_id = Type.get_hierarchy('Sex').subs[0]

            # Insert
            rv = self.app.get(
                url_for('insert', class_='file', origin_id=actor.id))
            assert b'+ File' in rv.data
            logo = \
                pathlib.Path(app.root_path) \
                / 'static' / 'images' / 'layout' / 'logo.png'
            with open(logo, 'rb') as img:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=actor.id),
                                   data={
                                       'name': 'OpenAtlas logo',
                                       'file': img
                                   },
                                   follow_redirects=True)
            assert b'An entry has been created' in rv.data
            with open(logo, 'rb') as img1, open(logo, 'rb') as img2:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=actor.id),
                                   data={
                                       'name': 'OpenAtlas logo',
                                       'file': [img1, img2]
                                   },
                                   follow_redirects=True)
            assert b'An entry has been created' in rv.data
            with open(logo, 'rb') as img:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=reference.id),
                                   data={
                                       'name': 'OpenAtlas logo',
                                       '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
                files = Entity.get_by_class('file')
                file_id = files[0].id
                file_id2 = files[1].id

            # Logo
            rv = self.app.get(url_for('admin_logo'),
                              data={'file': file_id},
                              follow_redirects=True)
            assert b'OpenAtlas logo' in rv.data
            with self.app.get(
                    url_for('display_logo', filename=str(file_id) + '.png')):
                pass  # Test logo with "with" to prevent unclosed files warning
            rv = self.app.get(url_for('admin_logo', id_=file_id),
                              follow_redirects=True)
            assert b'Remove custom logo' in rv.data
            rv = self.app.get(url_for('admin_index',
                                      action="remove_logo",
                                      id_=0),
                              follow_redirects=True)
            assert b'Logo' in rv.data

            with open(
                    pathlib.Path(app.root_path) / 'views' / 'index.py', 'rb') \
                    as invalid_file:
                rv = self.app.post(url_for('insert',
                                           class_='file',
                                           origin_id=actor.id),
                                   data={
                                       'name': 'Invalid file',
                                       'file': invalid_file
                                   },
                                   follow_redirects=True)
            assert b'File type not allowed' in rv.data

            rv = self.app.post(url_for('insert',
                                       class_='file',
                                       origin_id=actor.id),
                               follow_redirects=True,
                               data={'name': 'This is not a file'})
            assert b'This field is required' in rv.data

            # View
            rv = self.app.get(url_for('view', id_=file_id))
            assert b'OpenAtlas logo' in rv.data
            rv = self.app.get(url_for('view', id_=file_id2))
            assert b'OpenAtlas logo' in rv.data

            with self.app.get(
                    url_for('download_file', filename=str(file_id) + '.png')):
                pass  # Calling with "with" to prevent unclosed files warning
            with self.app.get(
                    url_for('display_file', filename=str(file_id) + '.png')):
                pass  # Calling with "with" to prevent unclosed files warning

            # Index
            rv = self.app.get(url_for('index', view='file'))
            assert b'OpenAtlas logo' in rv.data

            # Set and unset as main image
            self.app.get(url_for('set_profile_image',
                                 id_=file_id,
                                 origin_id=actor.id),
                         follow_redirects=True)
            self.app.get(
                url_for('file_remove_profile_image', entity_id=actor.id))

            # Add to reference
            rv = self.app.get(
                url_for('reference_add', id_=reference.id, view='file'))
            assert b'OpenAtlas logo' in rv.data
            rv = self.app.post(url_for('reference_add',
                                       id_=reference.id,
                                       view='file'),
                               data={
                                   'file': file_id,
                                   'page': '777'
                               },
                               follow_redirects=True)
            assert b'777' in rv.data

            # Update
            rv = self.app.get(url_for('update', id_=file_id))
            assert b'OpenAtlas logo' in rv.data
            rv = self.app.post(url_for('update', id_=file_id),
                               data={'name': 'Updated file'},
                               follow_redirects=True)
            assert b'Changes have been saved' in rv.data \
                   and b'Updated file' in rv.data
            rv = self.app.get(url_for('file_add', id_=file_id, view='actor'))
            assert b'Link actor' in rv.data
            rv = self.app.post(url_for('file_add', id_=file_id, view='actor'),
                               data={'checkbox_values': [actor.id]},
                               follow_redirects=True)
            assert b'File keeper' in rv.data
            rv = self.app.post(url_for('entity_add_file', id_=type_id),
                               data={'checkbox_values': str([file_id])},
                               follow_redirects=True)
            assert b'Updated file' in rv.data

            # Create source coming from file
            self.app.post(url_for('insert', class_='source',
                                  origin_id=file_id),
                          data={'name': 'Created source coming from file'})
            with app.test_request_context():
                app.preprocess_request()  # type: ignore
                source_id = Entity.get_by_class('source')[0].id
            rv = self.app.get(url_for('view', id_=source_id))
            assert b'Created source coming from file' in rv.data

            # Delete
            for file in files:
                rv = self.app.get(
                    url_for('index', view='file', delete_id=file.id))
                assert b'The entry has been deleted' in rv.data
Exemplo n.º 14
0
    def test_reference_system(self) -> None:
        with app.app_context():
            rv: Any = 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 = \
                Type.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: dict[Any, Any] = {
                'name': 'Wikipedia',
                'website_url': 'https://wikipedia.org',
                'resolver_url': 'https://wikipedia.org',
                'classes': ['place']
            }
            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 classes are attached' in rv.data
            rv = self.app.get(url_for('reference_system_remove_class',
                                      system_id=wikipedia_id,
                                      class_name='place'),
                              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),
                              follow_redirects=True)
            assert b'The entry has been deleted' in rv.data
            rv = self.app.get(url_for('update', id_=geonames.id))
            assert b'Website URL' in rv.data
            data = {
                'name': 'GeoNames',
                Type.get_hierarchy('External reference match').id:
                precision_id,
                'website_url': 'https://www.geonames2.org/',
                'resolver_url': 'https://www.geonames2.org/',
                'placeholder': ''
            }
            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',
                                   f'reference_system_id_{wikidata.id}':
                                   'Q123',
                                   self.precision_geonames: '',
                                   self.precision_wikidata: precision_id
                               })
            person_id = rv.location.split('/')[-1]
            rv = self.app.get(url_for('view', id_=wikidata.id))
            assert b'Actor test' in rv.data
            rv = self.app.get(url_for('view', id_=person_id))
            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',
                                   f'reference_system_id_{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',
                                   f'reference_system_id_{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',
                                   f'reference_system_id_{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_class',
                                      system_id=geonames.id,
                                      class_name='place'),
                              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
Exemplo n.º 15
0
    def test_place(self) -> None:
        with app.app_context():
            rv: Any = 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_type = Type.get_hierarchy('Administrative unit')
                unit_sub1 = g.types[unit_type.subs[0]]
                unit_sub2 = g.types[unit_type.subs[1]]
                reference = Entity.insert('external_reference',
                                          'https://openatlas.eu')
                place_type = Type.get_hierarchy('Place')
                source = Entity.insert('source', 'Necronomicon')
            geonames = \
                f"reference_system_id_" \
                f"{ReferenceSystem.get_by_name('GeoNames').id}"
            precision = Type.get_hierarchy('External reference match').subs[0]
            data = {
                'name': 'Asgard',
                'alias-0': 'Valhöll',
                unit_type.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('view', id_=precision))
            assert b'Asgard' in rv.data
            rv = self.app.get(
                url_for('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_type.id] = place_type.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('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)
            rv = self.app.get(url_for('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('type_move_entities', id_=unit_sub1.id))
            assert b'Asgard' in rv.data

            # Test move entities of multiple type if link to new type exists
            rv = self.app.post(url_for('type_move_entities', id_=unit_sub1.id),
                               follow_redirects=True,
                               data={
                                   unit_type.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 type
            rv = self.app.post(url_for('type_move_entities', id_=unit_sub2.id),
                               follow_redirects=True,
                               data={
                                   unit_type.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 artifact' in rv.data
            rv = self.app.post(url_for('insert',
                                       class_='feature',
                                       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_='stratigraphic_unit',
                                       origin_id=feat_id),
                               data=data)
            stratigraphic_id = rv.location.split('/')[-1]

            # Create a stratigraphic unit "sibling"
            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_type_id = Type.get_hierarchy('Dimensions').subs[0]
            data = {
                'name': 'You never find me',
                dimension_type_id: 50,
                self.precision_geonames: precision,
                self.precision_wikidata: ''
            }
            rv = self.app.post(url_for('insert',
                                       class_='artifact',
                                       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

            # Anthropological features
            rv = self.app.get(
                url_for('anthropology_index', id_=stratigraphic_id))
            assert b'Sex estimation' in rv.data
            rv = self.app.get(url_for('sex', id_=stratigraphic_id))
            assert b'Anthropological analyses' in rv.data
            rv = self.app.post(url_for('sex_update', id_=stratigraphic_id),
                               follow_redirects=True,
                               data={'Glabella': 'Female'})
            assert b'-2.0' in rv.data
            rv = self.app.post(url_for('sex_update', id_=stratigraphic_id),
                               follow_redirects=True,
                               data={'Glabella': 'Female'})
            assert b'-2.0' in rv.data
            rv = self.app.get(url_for('sex_update', id_=stratigraphic_id))
            assert b'Glabella' in rv.data
            rv = self.app.post(url_for('update', id_=stratigraphic_id),
                               data={'name': 'New name'},
                               follow_redirects=True)
            assert b'Changes have been saved.' in rv.data

            rv = self.app.get(url_for('view', id_=feat_id))
            assert b'not a bug' in rv.data

            rv = self.app.get(url_for('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