def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    ext = InvenioRecordsUI(app)
    assert 'invenio-records-ui' in app.extensions

    app = Flask('testapp')
    ext = InvenioRecordsUI()
    assert 'invenio-records-ui' not in app.extensions
    ext.init_app(app)
    assert 'invenio-records-ui' in app.extensions
Ejemplo n.º 2
0
def test_changed_views(app):
    """Test view."""
    app.config.update(
        dict(PIDSTORE_DATACITE_DOI_PREFIX="10.4321",
             RECORDS_UI_ENDPOINTS=dict(
                 recid=dict(
                     pid_type='recid',
                     route='/records/<pid_value>',
                 ),
                 references=dict(
                     pid_type='recid',
                     route='/records/<pid_value>/references',
                 ),
                 doi=dict(
                     pid_type='doi',
                     route='/doi/<path:pid_value>',
                 ))))
    InvenioRecordsUI(app)
    setup_record_fixture(app)

    with app.test_client() as client:
        res = client.get("/records/1")
        assert res.status_code == 200

        res = client.get("/records/1/references")
        assert res.status_code == 200

        res = client.get("/doi/10.1234/foo")
        assert res.status_code == 200
Ejemplo n.º 3
0
def test_view(app):
    """Test view."""
    InvenioRecordsUI(app)
    setup_record_fixture(app)

    with app.test_client() as client:
        res = client.get("/records/1")
        assert res.status_code == 200

        # Deleted PID
        res = client.get("/records/2")
        assert res.status_code == 410

        res = client.get("/records/3")
        assert res.status_code == 410

        # Missing object
        res = client.get("/records/4")
        assert res.status_code == 500

        # Redirected PID
        res = client.get("/records/5")
        assert res.status_code == 302

        # Non existing endpoint
        res = client.get("/records/6")
        assert res.status_code == 500

        # Unregistered PID
        res = client.get("/records/7")
        assert res.status_code == 404
Ejemplo n.º 4
0
def app(request):
    """Flask application fixture."""
    app_ = Flask('testapp')
    app_.config.update(
        TESTING=True,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite://'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        SECRET_KEY='mysecret',
        SUPPORT_EMAIL='*****@*****.**',
        WTF_CSRF_ENABLED=False,
        SERVER_NAME='test.it',
        RECORDS_UI_ENDPOINTS=dict(
            recid=dict(
                pid_type='recid',
                route='/records/<pid_value>',
                template='invenio_records_ui/detail.html',
            ),
            recid_access_request=dict(
                pid_type='recid',
                route='/records/<pid_value>/accessrequest',
                template='zenodo_accessrequests/access_request.html',
                view_imp='zenodo_accessrequests.views.requests.access_request',
                methods=['GET', 'POST'],
            ),
            recid_access_request_email_confirm=dict(
                pid_type='recid',
                route='/records/<pid_value>/accessrequest/<token>/confirm',
                #  template='invenio_records_ui/detail.html',
                view_imp='zenodo_accessrequests.views.requests.confirm',
            ),
        ),
    )

    InvenioFormatter(app_)
    Babel(app_)
    InvenioDB(app_)
    InvenioAccounts(app_)
    InvenioRecords(app_)
    FlaskMenu(app_)
    Mail(app_)
    InvenioRecordsUI(app_)
    InvenioAccess(app_)
    ZenodoAccessRequests(app_)
    InvenioPIDStore(app_)

    app_.register_blueprint(request_blueprint)
    app_.register_blueprint(settings_blueprint)
    app_.register_blueprint(blueprint_user)
    app_.register_blueprint(create_blueprint_from_app(app_))

    with app_.app_context():
        yield app_
Ejemplo n.º 5
0
def app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        JSONSCHEMAS_URL_SCHEME='http',
        SECRET_KEY='CHANGE_ME',
        SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_ECHO=False,
        TESTING=True,
        WTF_CSRF_ENABLED=False,
        DEPOSIT_SEARCH_API='/api/search',
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
        SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
        OAUTHLIB_INSECURE_TRANSPORT=True,
        OAUTH2_CACHE_TYPE='simple',
    )
    app_.url_map.converters['pid'] = PIDConverter
    FlaskCLI(app_)
    Babel(app_)
    FlaskCeleryExt(app_)
    InvenioDB(app_)
    Breadcrumbs(app_)
    InvenioAccounts(app_)
    InvenioAccess(app_)
    app_.register_blueprint(accounts_blueprint)
    InvenioAssets(app_)
    InvenioJSONSchemas(app_)
    InvenioSearch(app_)
    InvenioRecords(app_)
    app_.url_map.converters['pid'] = PIDConverter
    InvenioRecordsREST(app_)
    InvenioPIDStore(app_)
    InvenioIndexer(app_)
    InvenioDeposit(app_)
    InvenioSearchUI(app_)
    InvenioRecordsUI(app_)
    InvenioFilesREST(app_)
    OAuth2Provider(app_)
    InvenioOAuth2Server(app_)
    InvenioOAuth2ServerREST(app_)
    app_.register_blueprint(oauth2server_settings_blueprint)
    InvenioDepositREST(app_)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Ejemplo n.º 6
0
def test_permission(app):
    """Test permission control to records."""
    app.config.update(
        WTF_CSRF_ENABLED=False,
        SECRET_KEY='CHANGEME',
        SECURITY_PASSWORD_SALT='CHANGEME',
        # conftest switches off permission checking, so re-enable it for this
        # app.
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY='helpers:'
        'only_authenticated_users',
    )
    Menu(app)
    InvenioRecordsUI(app)
    accounts = InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioAccess(app)
    setup_record_fixture(app)

    # Create admin
    with app.app_context():
        accounts.datastore.create_user(
            email='*****@*****.**',
            password=encrypt_password('123456'),
            active=True,
        )

        # Get record 1
        r = Resolver(pid_type='recid',
                     object_type='rec',
                     getter=Record.get_record)
        dummy_pid, record = r.resolve('1')

        db.session.commit()

    with app.test_request_context():
        login_url = url_for('security.login')
        record_url = url_for('invenio_records_ui.recid', pid_value='1')

    # Access record 1 as admin
    with app.test_client() as client:
        res = client.get(record_url)
        assert res.status_code == 302
        res = client.post(login_url,
                          data={
                              'email': '*****@*****.**',
                              'password': '******'
                          })
        assert res.status_code == 302
        res = client.get(record_url)
        res.status_code == 200

    # Access record 1 as anonymous
    with app.test_client() as client:
        res = client.get(record_url)
        res.status_code == 403
Ejemplo n.º 7
0
def app():
    """Flask application fixture with database initialization."""
    instance_path = tempfile.mkdtemp()

    app_ = Flask(
        'testapp', static_folder=instance_path, instance_path=instance_path)
    app_.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI',
            'sqlite:///:memory:'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,
        RECORDS_UI_ENDPOINTS=dict(
            recid=dict(
                pid_type='recid',
                route='/records/<pid_value>',
                template='invenio_records_ui/detail.html',
            ),
            recid_previewer=dict(
                pid_type='recid',
                route='/records/<pid_value>/preview/<filename>',
                view_imp='invenio_previewer.views:preview',
                record_class='invenio_records_files.api:Record',
            ),
            recid_files=dict(
                pid_type='recid',
                route='/record/<pid_value>/files/<filename>',
                view_imp='invenio_records_files.utils.file_download_ui',
                record_class='invenio_records_files.api:Record',
            ),
        ),
        SERVER_NAME='localhost'
    )
    Babel(app_)
    assets_ext = InvenioAssets(app_)
    InvenioDB(app_)
    InvenioRecords(app_)
    previewer = InvenioPreviewer(app_)._state
    InvenioRecordsUI(app_)
    InvenioFilesREST(app_)

    # Add base assets bundles for jQuery and Bootstrap
    # Note: These bundles aren't included by default since package consumers
    # should handle assets and their dependencies manually.
    assets_ext.env.register(previewer.js_bundles[0], previewer_base_js)
    assets_ext.env.register(previewer.css_bundles[0], previewer_base_css)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Ejemplo n.º 8
0
def test_custom_view_method(app):
    """Test view."""
    app.config.update(dict(
        PIDSTORE_DATACITE_DOI_PREFIX='10.4321',
        RECORDS_UI_ENDPOINTS=dict(
            recid=dict(
                pid_type='recid',
                route='/records/<pid_value>',
            ),
            record_with_param=dict(
                pid_type='recid',
                route='/records/<pid_value>/export/<format>',
            ),
            recid_custom=dict(
                pid_type='recid',
                route='/records/<pid_value>/custom/<filename>',
                view_imp='test_invenio_records_ui:custom_view',
            ),
            recid_get_post=dict(
                pid_type='recid',
                route='/records/<pid_value>/custom_get_and_post',
                view_imp='test_invenio_records_ui:custom_get_and_post',
                methods=['GET', 'POST'],
            ),
        )
    ))
    InvenioRecordsUI(app)
    app.register_blueprint(create_blueprint_from_app(app))
    setup_record_fixture(app)

    with app.test_client() as client:
        res = client.get('/records/1')
        assert res.status_code == 200

        # Test that filename parameter is passed to custom view function
        res = client.get('/records/1/custom/afilename')
        assert res.status_code == 200
        assert res.get_data(as_text=True) == 'TEST:1:afilename'

        # Test that default view function can deal with multiple parameters.
        res = client.get('/records/1/export/bibtex')
        assert res.status_code == 200

        # Test GET/POST
        res = client.get('/records/1/custom_get_and_post')
        assert res.status_code == 200
        assert res.get_data(as_text=True) == 'TEST:1:GET'
        res = client.post('/records/1/custom_get_and_post')
        assert res.status_code == 200
        assert res.get_data(as_text=True) == 'TEST:1:POST'
Ejemplo n.º 9
0
def app():
    """Flask application fixture with database initialization."""
    instance_path = tempfile.mkdtemp()

    app_ = Flask('testapp',
                 static_folder=instance_path,
                 instance_path=instance_path)
    app_.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///:memory:'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,
        RECORDS_UI_ENDPOINTS=dict(
            recid=dict(
                pid_type='recid',
                route='/records/<pid_value>',
                template='invenio_records_ui/detail.html',
            ),
            recid_previewer=dict(
                pid_type='recid',
                route='/records/<pid_value>/preview',
                view_imp='invenio_previewer.views:preview',
                record_class='invenio_records_files.api:Record',
            ),
            recid_files=dict(
                pid_type='recid',
                route='/record/<pid_value>/files/<filename>',
                view_imp='invenio_records_files.utils.file_download_ui',
                record_class='invenio_records_files.api:Record',
            ),
        ),
        SERVER_NAME='localhost',
        APP_THEME=['semantic-ui'])
    Babel(app_)
    InvenioAssets(app_)
    InvenioDB(app_)
    InvenioRecords(app_)
    InvenioConfigDefault(app_)
    InvenioFormatter(app_)
    InvenioPreviewer(app_)._state
    InvenioRecordsUI(app_)
    app_.register_blueprint(create_blueprint_from_app(app_))
    InvenioFilesREST(app_)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Ejemplo n.º 10
0
def app(base_app):
    """Flask application fixture."""
    Babel(base_app)
    InvenioAccounts(base_app)
    InvenioAccess(base_app)
    InvenioDB(base_app)
    InvenioFilesREST(base_app)
    InvenioRecords(base_app)
    InvenioRecordsUI(base_app)
    InvenioREST(base_app)
    InvenioIIIFAPI(base_app)
    InvenioIIIFManifest(base_app)

    with base_app.app_context():
        yield base_app
Ejemplo n.º 11
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    ext = InvenioRecordsUI(app)
    assert 'invenio-records-ui' in app.extensions

    app = Flask('testapp')
    ext = InvenioRecordsUI()
    assert 'invenio-records-ui' not in app.extensions
    ext.init_app(app)
    assert 'invenio-records-ui' in app.extensions
Ejemplo n.º 12
0
def test_record_export(app, json_v1):
    """Test record export formats."""
    app.config.update(
        dict(RECORDS_UI_EXPORT_FORMATS=dict(recid=dict(json=dict(
            title='JSON',
            serializer=json_v1,
            order=1,
        )))))

    InvenioRecordsUI(app)
    setup_record_fixture(app)

    with app.test_client() as client:
        res = client.get('/records/1/export/json')
        assert res.status_code == 200
        res = client.get('/records/1/export/None')
        assert res.status_code == 404
Ejemplo n.º 13
0
def test_signal(app):
    """Test view."""
    InvenioRecordsUI(app)
    setup_record_fixture(app)

    called = {'record-viewed': False}

    def _signal_sent(app, record=None, pid=None):
        assert request.path
        assert record
        assert pid
        called['record-viewed'] = record['recid']

    with app.test_client() as client:
        with record_viewed.connected_to(_signal_sent):
            res = client.get("/records/1")
            assert res.status_code == 200
            assert called['record-viewed'] == 1
Ejemplo n.º 14
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    ext = InvenioRecordsUI(app)
    app.register_blueprint(create_blueprint_from_app(app))
    assert 'invenio-records-ui' in app.extensions

    app = Flask('testapp')
    ext = InvenioRecordsUI()
    assert 'invenio-records-ui' not in app.extensions
    ext.init_app(app)
    app.register_blueprint(create_blueprint_from_app(app))
    assert 'invenio-records-ui' in app.extensions
Ejemplo n.º 15
0
def base_app():
    """Flask application fixture without InvenioStats."""
    from invenio_stats.config import STATS_EVENTS
    app_ = Flask('testapp')
    stats_events = {'file-download': deepcopy(STATS_EVENTS['file-download'])}
    stats_events.update({'event_{}'.format(idx): {} for idx in range(5)})
    app_.config.update(
        dict(
            CELERY_ALWAYS_EAGER=True,
            CELERY_TASK_ALWAYS_EAGER=True,
            CELERY_CACHE_BACKEND='memory',
            CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
            CELERY_TASK_EAGER_PROPAGATES=True,
            CELERY_RESULT_BACKEND='cache',
            SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                                   'sqlite://'),
            SQLALCHEMY_TRACK_MODIFICATIONS=True,
            TESTING=True,
            STATS_MQ_EXCHANGE=Exchange(
                'test_events',
                type='direct',
                delivery_mode='transient',  # in-memory queue
                durable=True,
            ),
            STATS_EVENTS=stats_events,
            STATS_AGGREGATIONS=['file-download-agg']))
    FlaskCeleryExt(app_)
    InvenioDB(app_)
    InvenioRecords(app_)
    InvenioRecordsUI(app_)
    InvenioPIDStore(app_)
    InvenioQueues(app_)
    InvenioFilesREST(app_)
    InvenioSearch(app_, entry_point_group=None)
    with app_.app_context():
        yield app_
Ejemplo n.º 16
0
def base_app(request, test_metadata_format):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()

    def init_app(app_):
        app_.config.update(
            CELERY_ALWAYS_EAGER=False,
            CELERY_CACHE_BACKEND="memory",
            CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
            CELERY_RESULT_BACKEND="cache",
            JSONSCHEMAS_URL_SCHEME="http",
            SECRET_KEY="CHANGE_ME",
            SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
            SQLALCHEMY_DATABASE_URI=os.environ.get("SQLALCHEMY_DATABASE_URI",
                                                   "sqlite:///test.db"),
            SQLALCHEMY_TRACK_MODIFICATIONS=True,
            SQLALCHEMY_ECHO=False,
            TESTING=True,
            WTF_CSRF_ENABLED=False,
            DEPOSIT_SEARCH_API="/api/search",
            SECURITY_PASSWORD_HASH="plaintext",
            SECURITY_PASSWORD_SCHEMES=["plaintext"],
            SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
            THEME_SITENAME="Test Site",
            OAUTHLIB_INSECURE_TRANSPORT=True,
            OAUTH2_CACHE_TYPE="simple",
            ACCOUNTS_JWT_ENABLE=False,
            # This allows access to files across all of invenio-files-rest
            FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type(
                "Allow", (object, ), {"can": lambda self: True})(),
            FILES_REST_MULTIPART_CHUNKSIZE_MIN=10,
        )
        Babel(app_)
        FlaskCeleryExt(app_)
        Breadcrumbs(app_)
        OAuth2Provider(app_)
        InvenioDB(app_)
        InvenioAccounts(app_)
        InvenioAccess(app_)
        InvenioIndexer(app_)
        InvenioJSONSchemas(app_)
        InvenioOAuth2Server(app_)
        InvenioPIDStore(app_)
        InvenioRecords(app_)
        search = InvenioSearch(app_)
        search.register_mappings("deposits", "invenio_deposit.mappings")

    api_app = Flask("testapiapp", instance_path=instance_path)
    api_app.url_map.converters["pid"] = PIDConverter
    # initialize InvenioDeposit first in order to detect any invalid dependency
    InvenioDepositREST(api_app)

    init_app(api_app)
    InvenioREST(api_app)
    InvenioOAuth2ServerREST(api_app)
    InvenioRecordsREST(api_app)
    InvenioFilesREST(api_app)
    InvenioSword(api_app)
    api_app.register_blueprint(files_rest_blueprint)
    # api_app.register_blueprint(records_files_bp(api_app))
    api_app.register_blueprint(records_rest_bp(api_app))
    api_app.register_blueprint(invenio_files_rest_blueprint)

    # Register a test (alternate) metadata format
    api_app.config["SWORD_ENDPOINTS"]["depid"]["metadata_formats"][
        test_metadata_format] = TestMetadata

    app = Flask("testapp", instance_path=instance_path)
    app.url_map.converters["pid"] = PIDConverter
    # initialize InvenioDeposit first in order to detect any invalid dependency
    InvenioDeposit(app)
    init_app(app)
    app.register_blueprint(accounts_blueprint)
    app.register_blueprint(oauth2server_settings_blueprint)
    InvenioAssets(app)
    InvenioSearchUI(app)
    InvenioRecordsUI(app)
    app.register_blueprint(records_ui_bp(app))
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app,
                                        {"/api": api_app.wsgi_app})

    with app.app_context():
        if str(db.engine.url) != "sqlite://" and not database_exists(
                str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    yield app

    with app.app_context():
        if str(db.engine.url) != "sqlite://":
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)
Ejemplo n.º 17
0
def base_app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()

    def init_app(app_):
        app_.config.update(
            CELERY_ALWAYS_EAGER=True,
            CELERY_CACHE_BACKEND='memory',
            CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
            CELERY_RESULT_BACKEND='cache',
            JSONSCHEMAS_URL_SCHEME='http',
            SECRET_KEY='CHANGE_ME',
            SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO',
            SQLALCHEMY_DATABASE_URI=os.environ.get(
                'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
            SQLALCHEMY_TRACK_MODIFICATIONS=True,
            SQLALCHEMY_ECHO=False,
            TESTING=True,
            WTF_CSRF_ENABLED=False,
            DEPOSIT_SEARCH_API='/api/search',
            SECURITY_PASSWORD_HASH='plaintext',
            SECURITY_PASSWORD_SCHEMES=['plaintext'],
            SECURITY_DEPRECATED_PASSWORD_SCHEMES=[],
            OAUTHLIB_INSECURE_TRANSPORT=True,
            OAUTH2_CACHE_TYPE='simple',
            ACCOUNTS_JWT_ENABLE=False,
        )
        Babel(app_)
        FlaskCeleryExt(app_)
        Breadcrumbs(app_)
        OAuth2Provider(app_)
        InvenioDB(app_)
        InvenioAccounts(app_)
        InvenioAccess(app_)
        InvenioIndexer(app_)
        InvenioJSONSchemas(app_)
        InvenioOAuth2Server(app_)
        InvenioFilesREST(app_)
        InvenioPIDStore(app_)
        InvenioRecords(app_)
        search = InvenioSearch(app_)
        search.register_mappings('deposits', 'invenio_deposit.mappings')

    api_app = Flask('testapiapp', instance_path=instance_path)
    api_app.url_map.converters['pid'] = PIDConverter
    # initialize InvenioDeposit first in order to detect any invalid dependency
    InvenioDepositREST(api_app)

    init_app(api_app)
    InvenioREST(api_app)
    InvenioOAuth2ServerREST(api_app)
    InvenioRecordsREST(api_app)

    app = Flask('testapp', instance_path=instance_path)
    app.url_map.converters['pid'] = PIDConverter
    # initialize InvenioDeposit first in order to detect any invalid dependency
    InvenioDeposit(app)
    init_app(app)
    app.register_blueprint(accounts_blueprint)
    app.register_blueprint(oauth2server_settings_blueprint)
    InvenioAssets(app)
    InvenioSearchUI(app)
    InvenioRecordsUI(app)
    app.register_blueprint(records_ui_bp(app))
    app.register_blueprint(records_rest_bp(app))
    app.wsgi_app = DispatcherMiddleware(app.wsgi_app, {
        '/api': api_app.wsgi_app
    })

    with app.app_context():
        if str(db.engine.url) != 'sqlite://' and \
           not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    yield app

    with app.app_context():
        if str(db.engine.url) != 'sqlite://':
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)
Ejemplo n.º 18
0
FlaskCLI(app)
Babel(app)

# Set jinja loader to first grab templates from the app's folder.
app.jinja_loader = jinja2.ChoiceLoader([
    jinja2.FileSystemLoader(join(dirname(__file__), "templates")),
    app.jinja_loader
])

InvenioDB(app)
InvenioTheme(app)
InvenioJSONSchemas(app)
InvenioAccounts(app)
InvenioRecords(app)
InvenioRecordsUI(app)
search = InvenioSearch(app)
# search.register_mappings('testrecords', 'data')
InvenioSearchUI(app)
InvenioREST(app)
InvenioIndexer(app)
InvenioPIDStore(app)
InvenioAdmin(app)
InvenioOAuth2Server(app)

InvenioRecordsREST(app)
InvenioFilesREST(app)

assets = InvenioAssets(app)
assets.env.register('invenio_search_ui_search_js', js)
Ejemplo n.º 19
0
def app(request):
    """Flask application fixture."""
    # Set temporary instance path for sqlite
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)

    app.config.update(SQLALCHEMY_DATABASE_URI=os.environ.get(
        'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
                      TESTING=True,
                      SECRET_KEY='SECRET_KEY',
                      SQLALCHEMY_TRACK_MODIFICATIONS=False,
                      JSONSCHEMAS_ENDPOINT='/schema',
                      JSONSCHEMAS_HOST='ils.test.rero.ch',
                      RECORDS_UI_ENDPOINTS={
                          "doc": {
                              "pid_type":
                              "doc",
                              "route":
                              "/documents/<pid_value>",
                              "template":
                              "reroils_data/detailed_view_documents_items.html"
                          }
                      })

    InvenioDB(app)
    InvenioPIDStore(app)
    InvenioRecords(app)
    InvenioAccounts(app)
    REROILSDATA(app)
    InvenioAccess(app)
    InvenioJSONSchemas(app)
    InvenioRecordsUI(app)
    Menu(app)
    Babel(app)
    app.register_blueprint(item_blueprint)

    @app.route('/test/login')
    def login():
        from flask_security import login_user
        from flask import request as flask_request

        role = flask_request.args.get('role')
        if role:
            datastore.create_role(name=role)
            datastore.add_role_to_user(user, role)
        datastore.commit()
        login_user(user)
        return "Logged In"

    @app.route('/test/login')
    def logout():
        from flask_security import logout_user
        logout_user()
        return "Logged Out"

    from invenio_db import db as db_
    with app.app_context():
        if not database_exists(str(db_.engine.url)):
            create_database(str(db_.engine.url))
        db_.create_all()
        security = LocalProxy(lambda: app.extensions['security'])
        datastore = LocalProxy(lambda: security.datastore)
        user = datastore.create_user(email='*****@*****.**',
                                     active=True,
                                     password=hash_password('aafaf4as5fa'))
        yield app

        # Teardown instance path.
        db_.session.remove()
        db_.drop_all()
        shutil.rmtree(instance_path)
Ejemplo n.º 20
0
def test_file_download_ui(base_app, objects, db):
    """Test get buckets."""
    app = base_app
    app.config.update(
        dict(
            RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,  # No permission checking
            RECORDS_UI_ENDPOINTS=dict(
                recid=dict(
                    pid_type='recid',
                    route='/records/<pid_value>',
                ),
                recid_files=dict(
                    pid_type='recid',
                    route='/records/<pid_value>/files/<filename>',
                    view_imp='invenio_files_rest.views.file_download_ui',
                    record_class='invenio_records_files.api:Record',
                ),
            )))
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioRecordsUI(app)

    obj1 = objects[0]

    with app.app_context():
        # Record 1 - Live record
        rec_uuid = uuid.uuid4()
        PersistentIdentifier.create('recid',
                                    '1',
                                    object_type='rec',
                                    object_uuid=rec_uuid,
                                    status=PIDStatus.REGISTERED)
        record = Record.create(
            {
                'title':
                'Registered',
                'recid':
                1,
                '_files': [
                    {
                        'key': obj1.key,
                        'bucket': str(obj1.bucket_id),
                        'checksum': 'invalid'
                    },
                ]
            },
            id_=rec_uuid)
        RecordsBuckets.create(record=record.model, bucket=obj1.bucket)
        db.session.commit()

        main_url = url_for('invenio_records_ui.recid', pid_value='1')
        file_url = url_for('invenio_records_ui.recid_files',
                           pid_value='1',
                           filename=obj1.key)
        no_file_url = url_for('invenio_records_ui.recid_files',
                              pid_value='1',
                              filename='')
        invalid_file_url = url_for('invenio_records_ui.recid_files',
                                   pid_value='1',
                                   filename='no')

    with app.test_client() as client:
        res = client.get(main_url)
        assert res.status_code == 200
        res = client.get(file_url)
        assert res.status_code == 200
        res = client.get(no_file_url)
        assert res.status_code == 404
        res = client.get(invalid_file_url)
        assert res.status_code == 404