def test_init_post(app):
    """Test module initialization using init_app."""
    assets = InvenioAssets()
    assert assets.env
    assert assets.collect
    assert 'REQUIREJS_BASEURL' not in app.config
    assert 'COLLECT_STATIC_ROOT' not in app.config
    assets.init_app(app)
    assert 'REQUIREJS_BASEURL' in app.config
    assert 'COLLECT_STATIC_ROOT' in app.config
Exemple #2
0
def test_init(app):
    """Test module initialization."""
    InvenioAssets(app)
    assets = app.extensions['invenio-assets']
    assert assets.env
    assert assets.collect
    assert app.config['REQUIREJS_BASEURL'] == app.static_folder
    assert app.config['COLLECT_STATIC_ROOT'] == app.static_folder
Exemple #3
0
def test_init(app):
    """Test module initialization."""
    InvenioAssets(app)
    assets = app.extensions['invenio-assets']
    assert assets.collect
    assert assets.webpack
    assert app.config['COLLECT_STATIC_ROOT'] == app.static_folder
    assert 'WEBPACKEXT_PROJECT' in app.config
def test_bundles(app):
    """Test package bundles."""
    InvenioAssets(app)

    with app.app_context():
        from invenio_i18n.webpack import i18n

        assert i18n
Exemple #5
0
def base_app(instance_path):
    """Flask application fixture."""
    app_ = Flask("testapp", instance_path=instance_path)
    app_.config.update(SECRET_KEY="SECRET_KEY", TESTING=True)
    InvenioAccounts(app_)
    InvenioAssets(app_)
    InvenioRecordsEditor(app_)
    return app_
Exemple #6
0
def test_lazy_bundles(app):
    """Test configurable bundles."""
    InvenioTheme(app)
    InvenioAssets(app)

    with app.app_context():
        from invenio_theme.bundles import admin_lte_css, lazy_skin

        assert str(lazy_skin()) in admin_lte_css.contents
Exemple #7
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)
Exemple #8
0
def test_assets_usage(app):
    """Test assets usage."""
    class Ext(object):
        def __init__(self, app):
            assets = app.extensions['invenio-assets']
            assets.env.register('testbundle', Bundle())

    assets = InvenioAssets(app)
    Ext(app)
    assert len(assets.env) == 1
Exemple #9
0
 def test_clean_CSS(self):
     """Test method of Clean CSS filter."""
     app = Flask(__name__)
     FlaskCLI(app)
     InvenioAssets(app)
     with app.app_context():
         bundle = self.mkbundle('foo.css',
                                filters=CleanCSSFilter(),
                                output='out.css')
         bundle.build()
         assert self.get('out.css') == 'h1{font-family:Verdana;color:#FFF}'
def app():
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        SEARCH_UI_SEARCH_API='api'
    )
    Babel(app)

    FlaskCLI(app)
    assets = InvenioAssets(app)
    assets.init_cli(app.cli)
    InvenioTrendsUI(app)

    @app.route('/api')
    def api():
        return {}

    app.register_blueprint(blueprint)
    return app
Exemple #11
0
 def test_clean_CSS(self, static_dir):
     """Test method of Clean CSS filter."""
     app = Flask(__name__)
     InvenioAssets(app)
     with app.app_context():
         filter = 'cleancssurl'
         result = 'h1{font-family:Verdana;color:#fff}'
         bundle = self.mkbundle('foo.css', filters=filter, output='out.css')
         bundle.build()
         # v4 returns #fff while v3 returns #FFF
         assert self.get('out.css').lower() == result.lower()
Exemple #12
0
def script_info(request):
    """Get ScriptInfo object for testing CLI."""
    instance_path = tempfile.mkdtemp()
    app = Flask(__name__, instance_path=instance_path)
    FlaskCLI(app)
    InvenioAssets(app)

    def teardown():
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return ScriptInfo(create_app=lambda info: app)
Exemple #13
0
def test_render_template(app):
    """Test ability to render template."""
    # Remove assets to avoid problems compiling them.
    test_tpl = r"""{% extends 'invenio_theme/page.html' %}
    {% block css %}{% endblock %}
    {% block javascript %}{% endblock %}
    """

    InvenioTheme(app)
    InvenioAssets(app)
    with app.test_request_context():
        assert render_template_string(test_tpl)
Exemple #14
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)
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()

    app_ = Flask(__name__, instance_path=instance_path)
    app_.config.update(
        SQLALCHEMY_DATABASE_URI=os.getenv(
            'SQLALCHEMY_DATABASE_URI',
            'postgresql+psycopg2://localhost/circulation_test'),
        OAUTH2SERVER_CLIENT_ID_SALT_LEN=40,
        OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60,
        OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60,
        SECRET_KEY='changeme',
        SERVER_NAME='localhost:5000',
        REPLACE_REFS=False,
        TESTING=True,
        CIRCULATION_ACTION_LOAN_URL=(
            '/hooks/receivers/circulation_loan/events/'),
        CIRCULATION_ACTION_REQUEST_URL=(
            '/hooks/receivers/circulation_request/events/'),
        CIRCULATION_ACTION_RETURN_URL=(
            '/hooks/receivers/circulation_return/events/'),
    )

    app_.url_map.converters['pid'] = PIDConverter

    Babel(app_)
    Menu(app_)
    Breadcrumbs(app_)
    InvenioAccounts(app_)
    InvenioAssets(app_)
    InvenioDB(app_)
    InvenioIndexer(app_)
    InvenioJSONSchemas(app_)
    InvenioPIDStore(app_)
    InvenioRecords(app_)
    InvenioRecordsREST(app_)
    InvenioWebhooks(app_)
    InvenioOAuth2Server(app_)
    InvenioCirculation(app_)
    InvenioCirculationREST(app_)
    InvenioSearch(app_)

    app_.register_blueprint(server_blueprint)
    app_.register_blueprint(settings_blueprint)
    app_.register_blueprint(webhooks_blueprint)
    app_.register_blueprint(circulation_blueprint)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Exemple #16
0
def base_app(instance_path):
    """Flask application fixture."""
    app_ = Flask('testapp', instance_path=instance_path)
    app_.config.update(
        SECRET_KEY='SECRET_KEY',
        TESTING=True,
    )
    Babel(app_)
    InvenioI18N(app_)
    InvenioTheme(app_)
    InvenioAssets(app_)
    WekoRecords(app_)
    return app_
Exemple #17
0
def script_info_assets(app, static_dir, testcss):
    """Get ScriptInfo object for testing CLI."""
    InvenioAssets(app)

    blueprint = Blueprint(__name__, 'test_bp', static_folder=static_dir)

    class Ext(object):
        def __init__(self, app):
            assets = app.extensions['invenio-assets']
            app.register_blueprint(blueprint)

    Ext(app)

    yield ScriptInfo(create_app=lambda info: app)
Exemple #18
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)
Exemple #19
0
 def test_angular_gettext(self, static_dir):
     """Test method of Clean CSS filter."""
     app = Flask(__name__)
     InvenioAssets(app)
     with app.app_context():
         bundle = self.mkbundle(
             'messages-js.po',
             filters=AngularGettextFilter(catalog_name='testInvenioAssets'),
             output='catalog.js')
         bundle.build()
         catalog = self.get('catalog.js')
         assert '"fr"' in catalog
         assert 'testInvenioAssets' in catalog
         assert 'Erreur' in catalog
         assert 'Missing' not in catalog
Exemple #20
0
def test_settings_template_blocks(app):
    """Test template blocks in page_settings.html."""
    base_tpl = r"""{% extends 'invenio_theme/page_settings.html' %}
    {% block css %}{% endblock %}
    {% block javascript %}{% endblock %}
    """

    blocks = [
        'page_body', 'settings_menu', 'settings_content', 'settings_form'
    ]
    InvenioTheme(app)
    InvenioAssets(app)

    with app.test_request_context():
        assert_template_blocks(
            'invenio_theme/page_settings.html', blocks, base_tpl=base_tpl)
def test_header_template_blocks(app):
    """Test template blokcs in header.html."""
    blocks = [
        'navbar',
        'navbar_header',
        'brand',
        'navbar_inner',
        'navbar_right',
        'breadcrumbs',
        'flashmessages',
        'navbar_nav',
    ]
    InvenioTheme(app)
    InvenioAssets(app)
    with app.test_request_context():
        assert_template_blocks("invenio_theme/header.html", blocks)
Exemple #22
0
def test_header_template_blocks(app):
    """Test template blokcs in header.html."""
    blocks = [
        'navbar', 'navbar_header', 'brand', 'navbar_inner', 'navbar_right',
        'breadcrumbs', 'flashmessages', 'navbar_nav', 'navbar_search',
    ]
    InvenioTheme(app)
    InvenioAssets(app)
    with app.test_request_context():
        assert_template_blocks('invenio_theme/header.html', blocks)

    app.config.update(dict(THEME_SEARCHBAR=False))
    with app.test_request_context():
        tpl = \
            r'{% extends "invenio_theme/header.html" %}' \
            r'{% block navbar_search %}TPLTEST{% endblock %}'
        assert 'TPLTEST' not in render_template_string(tpl)
Exemple #23
0
def app():
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        SEARCH_UI_SEARCH_API='api',
    )
    Babel(app)
    InvenioAssets(app)
    InvenioSearchUI(app)

    @app.route('/api')
    def api():
        return {}

    app.register_blueprint(blueprint)
    return app
Exemple #24
0
def test_cover_template_blocks(app):
    """Test template blocks in page.html."""
    base_tpl = r"""{% extends 'invenio_theme/page_cover.html' %}
    {% set panel_title = 'Test' %}
    {% block css %}{% endblock %}
    {% block javascript %}{% endblock %}
    """

    # Test template API
    blocks = [
        'panel', 'page_header', 'page_body', 'page_footer', 'panel_content',
    ]
    InvenioTheme(app)
    InvenioAssets(app)

    with app.test_request_context():
        assert_template_blocks(
            'invenio_theme/page_cover.html', blocks, base_tpl=base_tpl)
Exemple #25
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        TESTING=True,
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND="cache",
        COMMUNITIES_MAIL_ENABLED=False,
        SECRET_KEY='CHANGE_ME',
        SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SEARCH_ELASTIC_HOSTS=os.environ.get('SEARCH_ELASTIC_HOSTS', None),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        OAISERVER_REGISTER_RECORD_SIGNALS=True,
        OAISERVER_REGISTER_SET_SIGNALS=False,
        OAISERVER_ID_PREFIX='oai:localhost:recid/',
        SERVER_NAME='inveniosoftware.org',
        THEME_SITEURL='https://inveniosoftware.org',
        MAIL_SUPPRESS_SEND=True,
    )
    FlaskCeleryExt(app)
    Menu(app)
    Babel(app)
    InvenioDB(app)
    InvenioAccounts(app)
    InvenioAssets(app)
    InvenioSearch(app)
    InvenioRecords(app)
    InvenioIndexer(app)
    InvenioOAIServer(app)
    InvenioCommunities(app)
    InvenioMail(app)

    app.register_blueprint(ui_blueprint)
    app.register_blueprint(api_blueprint, url_prefix='/api/communities')

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
Exemple #26
0
def test_page_template_blocks(app):
    """Test template blocks in page.html."""
    base_tpl = r"""{% extends 'invenio_theme/page.html' %}
    {% block css %}{% endblock %}
    {% block javascript %}{% endblock %}
    """

    # Test template API
    blocks = [
        'head', 'head_meta', 'head_title', 'head_links', 'head_links_langs',
        'head_apple_icons', 'header', 'body', 'browserupgrade', 'page_header',
        'page_body', 'page_footer', 'trackingcode', 'body_inner'
    ]
    InvenioTheme(app)
    InvenioAssets(app)

    with app.test_request_context():
        assert_template_blocks(
            'invenio_theme/page.html', blocks, base_tpl=base_tpl)
def base_app(instance_path, editor_config):
    """Flask application fixture."""
    app = Flask("testapp", instance_path=instance_path)

    app.config.update(
        SECRET_KEY="SECRET_KEY", TESTING=True, SERVER_NAME="localhost"
    )
    app.config.update(RECORDS_EDITOR_UI_CONFIG=editor_config)

    InvenioAccounts(app)
    InvenioAssets(app)
    InvenioJSONSchemas(app)
    InvenioRecordsEditor(app)
    Menu(app)

    from invenio_accounts.views.settings import blueprint
    app.register_blueprint(blueprint)

    app.register_blueprint(create_editor_blueprint(app))
    return app
Exemple #28
0
def test_header_template_blocks(app):
    """Test template blokcs in header.html."""
    blocks = [
        "navbar",
        "navbar_header",
        "brand",
        "navbar_inner",
        "navbar_right",
        "breadcrumbs",
        "flashmessages",
        "navbar_nav",
        "navbar_search",
    ]
    InvenioTheme(app)
    InvenioAssets(app)
    with app.test_request_context():
        assert_template_blocks("invenio_theme/header.html", blocks)

    app.config.update(dict(THEME_SEARCHBAR=False))
    with app.test_request_context():
        tpl = (r'{% extends "invenio_theme/header.html" %}'
               r"{% block navbar_search %}TPLTEST{% endblock %}")
        assert "TPLTEST" not in render_template_string(tpl)
Exemple #29
0
def test_html_lang(app):
    """Test HTML language attribute."""
    base_tpl = r"""{% extends 'invenio_theme/page.html' %}
    {% block css %}{% endblock %}
    {% block javascript %}{% endblock %}
    """

    @app.route('/index')
    def index():
        """Render default page."""
        return render_template_string(base_tpl)

    InvenioTheme(app)
    InvenioAssets(app)

    with app.test_client() as client:
        response = client.get('/index')
        assert b'lang="en" ' in response.data

        response = client.get('/index?ln=de')
        assert b'lang="de" ' in response.data

        response = client.get('/index?ln=en')
        assert b'lang="en" ' in response.data
Exemple #30
0
    app.jinja_loader
 ])

InvenioDB(app)
InvenioTheme(app)
InvenioRecords(app)
InvenioRecordsUI(app)
search = InvenioSearch(app)
search.register_mappings('records', 'data')
InvenioSearchUI(app)
InvenioIndexer(app)
InvenioPIDStore(app)

InvenioRecordsREST(app)

assets = InvenioAssets(app)
assets.init_cli(app.cli)

# Register assets
assets.env.register('invenio_search_ui_search_js', js)


@app.cli.group()
def fixtures():
    """Command for working with test data."""


@fixtures.command()
def records():
    """Load records."""
    import pkg_resources
Exemple #31
0
if os.environ.get('RECAPTCHA_PUBLIC_KEY') is not None \
        and os.environ.get('RECAPTCHA_PRIVATE_KEY') is not None:
    app.config.setdefault('RECAPTCHA_PUBLIC_KEY',
                          os.environ['RECAPTCHA_PUBLIC_KEY'])
    app.config.setdefault('RECAPTCHA_PRIVATE_KEY',
                          os.environ['RECAPTCHA_PRIVATE_KEY'])

Babel(app)
Mail(app)
InvenioDB(app)
InvenioAccounts(app)
InvenioI18N(app)

if INVENIO_ASSETS_AVAILABLE:
    InvenioAssets(app)
if INVENIO_THEME_AVAILABLE:
    InvenioTheme(app)
else:
    Menu(app)
if INVENIO_ADMIN_AVAILABLE:
    InvenioAdmin(app,
                 permission_factory=lambda x: x,
                 view_class_factory=lambda x: x)
app.register_blueprint(blueprint)


@app.route("/")
def index():
    """Basic test view."""
    if current_user.is_authenticated:
def test_init_cli(app):
    """Test cli registration."""
    assets = InvenioAssets(app)
    assert len(app.cli.commands) == 0
    assets.init_cli(app.cli)
    assert len(app.cli.commands) == 3
Exemple #33
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)
Exemple #34
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)