Example #1
0
def test_view(app):
    """Test view."""
    InvenioRecordEditor(app)
    InvenioAssets(app)
    with app.test_client() as client:
        res = client.get("/editor/")
        assert res.status_code == 200
def test_bundles(app):
    """Test package bundles."""
    InvenioAssets(app)

    with app.app_context():
        from invenio_i18n.webpack import i18n
        assert i18n
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',
    ]
    InvenioTheme(app)
    InvenioAssets(app)

    with app.test_request_context():
        assert_template_blocks("invenio_theme/page.html",
                               blocks,
                               base_tpl=base_tpl)
Example #4
0
def script_info_assets(request):
    """Get ScriptInfo object for testing CLI."""
    initial_dir = os.getcwd()
    instance_path = tempfile.mkdtemp()
    app = Flask(__name__, instance_path=instance_path)
    FlaskCLI(app)
    InvenioAssets(app)
    os.chdir(instance_path)

    class Ext(object):
        def __init__(self, app):
            assets = app.extensions['invenio-assets']
            assets.env.register('testbundle',
                                NpmBundle('test.css', output='testbundle.css'))

    static_dir = os.path.join(os.path.dirname(__file__), 'static')
    if not os.path.exists(static_dir):
        os.makedirs(static_dir)
    test_css = open(os.path.join(static_dir, 'test.css'), 'w+')
    test_css.write("Test")

    Ext(app)

    def teardown():
        shutil.rmtree(instance_path)
        os.chdir(initial_dir)

    request.addfinalizer(teardown)
    return ScriptInfo(create_app=lambda info: app)
Example #5
0
def app_frontpage_handler(request):
    """Flask app error handler fixture."""
    app = Flask('myapp')

    # Creation of a fake theme error template file.
    temp_dir = make_fake_template(
        "{% extends 'invenio_theme/page.html' %}"
        "{% block css %}{% endblock %}"
        "{% block javascript %}{% endblock %}"
    )

    # Adding the temporal path to jinja engine.
    app.jinja_loader = jinja2.ChoiceLoader([
        jinja2.FileSystemLoader(temp_dir),
        app.jinja_loader
    ])

    # Setting by default fake.html as a BASE_TEMPLATE
    app.config['BASE_TEMPLATE'] = 'invenio_theme/fake.html'
    app.config['THEME_FRONTPAGE'] = True

    # Tear down method to clean the temp directory.
    def tear_down():
        shutil.rmtree(temp_dir)
    request.addfinalizer(tear_down)

    app.testing = True
    Babel(app)
    InvenioI18N(app)
    InvenioTheme(app)
    InvenioAssets(app)
    return app
Example #6
0
def app():
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        SEARCH_UI_SEARCH_API='api',
        BASE_TEMPLATE='invenio_search_ui/base.html',
        HEADER_TEMPLATE='invenio_search_ui/base_header.html',
    )
    Babel(app)
    InvenioAssets(app)
    InvenioSearchUI(app)

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

    app.register_blueprint(blueprint)
    # add extra test templates to the search app blueprint, to fake the
    # existence of `invenio-theme` base templates.
    test_templates_path = os.path.join(os.path.dirname(__file__), "templates")
    enhanced_jinja_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader(test_templates_path),
    ])
    # override default app jinja_loader to add the new path
    app.jinja_loader = enhanced_jinja_loader
    return app
Example #7
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_
Example #8
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
Example #9
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
Example #10
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
Example #11
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)
Example #12
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
Example #13
0
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
Example #14
0
def test_init_post(app):
    """Test module initialization using init_app."""
    assets = InvenioAssets()
    assert 'COLLECT_STATIC_ROOT' not in app.config
    assets.init_app(app)
    assert assets.collect
    assert assets.webpack
    assert 'COLLECT_STATIC_ROOT' in app.config
    assert 'WEBPACKEXT_PROJECT' in app.config
    assert app.config['WEBPACKEXT_STORAGE_CLS'] == FileStorage
Example #15
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()
Example #16
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}'
Example #17
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)
Example #18
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)
Example #19
0
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)
Example #20
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)
Example #21
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_
Example #22
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)
Example #23
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)
Example #24
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
Example #25
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)
Example #27
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
Example #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)
Example #29
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)
Example #30
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)