def test_client_reference():
    """Test client reference."""
    client1 = {'name': 'client1'}
    client2 = {'name': 'client2'}

    app1 = Flask('testapp1')
    FlaskCLI(app1)
    app2 = Flask('testapp2')
    FlaskCLI(app2)

    ext = InvenioSearch()
    assert 'invenio-search' not in app1.extensions
    assert 'invenio-search' not in app2.extensions

    ext.init_app(app1, client=client1)
    assert 'invenio-search' in app1.extensions

    ext.init_app(app2, client=client2)
    assert 'invenio-search' in app2.extensions

    with app1.app_context():
        assert current_search_client == client1

    with app2.app_context():
        assert current_search_client == client2
Beispiel #2
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    app.url_map.converters['pid'] = PIDConverter
    ext = InvenioDeposit(app)
    assert 'invenio-deposit' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    app.url_map.converters['pid'] = PIDConverter

    # check that current_deposit cannot be resolved
    with app.app_context():
        with pytest.raises(KeyError):
            current_deposit.app

    ext = InvenioDeposit()
    assert 'invenio-deposit' not in app.extensions
    ext.init_app(app)
    assert 'invenio-deposit' in app.extensions

    # check that current_deposit resolves correctly
    with app.app_context():
        current_deposit.app
Beispiel #3
0
def test_ext_init():
    """Test of find_best_app."""
    app = Flask('exttest')
    FlaskCLI(app)
    assert isinstance(app.cli, click.Group)

    app = Flask('exttest')
    ext = FlaskCLI()
    ext.init_app(app)
    assert isinstance(app.cli, click.Group)
    assert app.shell_context_processors == []
    pytest.raises(RuntimeError, ext.init_app, app)
Beispiel #4
0
def test_ext_init():
    """Test of find_best_app."""
    app = Flask('exttest')
    FlaskCLI(app)
    assert isinstance(app.cli, click.Group)

    app = Flask('exttest')
    ext = FlaskCLI()
    ext.init_app(app)
    assert isinstance(app.cli, click.Group)
    assert app.shell_context_processors == []
    pytest.raises(RuntimeError, ext.init_app, app)
Beispiel #5
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioOpenAIRE(app)
    assert 'invenio-openaire' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioOpenAIRE()
    assert 'invenio-openaire' not in app.extensions
    ext.init_app(app)
    assert 'invenio-openaire' in app.extensions
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioCommunities(app)
    assert 'invenio-communities' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioCommunities()
    assert 'invenio-communities' not in app.extensions
    ext.init_app(app)
    assert 'invenio-communities' in app.extensions
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioSearch(app)
    assert 'invenio-search' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioSearch()
    assert 'invenio-search' not in app.extensions
    ext.init_app(app)
    assert 'invenio-search' in app.extensions
Beispiel #8
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioUpgrader(app)
    assert 'invenio-upgrader' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioUpgrader()
    assert 'invenio-upgrader' not in app.extensions
    ext.init_app(app)
    assert 'invenio-upgrader' in app.extensions
Beispiel #9
0
def test_init():
    """Test extension initialization."""
    app = Flask('testapp')
    FlaskCLI(app)
    FlaskOAuth(app)
    ext = InvenioOAuthClient(app)
    assert 'invenio-oauthclient' in app.extensions

    app = Flask('testapp')
    FlaskCLI(app)
    FlaskOAuth(app)
    ext = InvenioOAuthClient()
    assert 'invenio-oauthclient' not in app.extensions
    ext.init_app(app)
    assert 'invenio-oauthclient' in app.extensions
Beispiel #10
0
def app(request):
    """Flask application fixture."""
    app_ = Flask('testapp')
    app_.config.update(
        CELERY_ALWAYS_EAGER=True,
        CELERY_RESULT_BACKEND="cache",
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        TESTING=True,
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI',
            'sqlite:///:memory:'),
        SECURITY_PASSWORD_SALT='TEST',
        SECRET_KEY='TEST',
    )
    FlaskCLI(app_)
    FlaskCeleryExt(app_)
    InvenioDB(app_)
    InvenioRecords(app_)
    InvenioDeposit(app_)
    InvenioJSONSchemas(app_)
    InvenioAccounts(app_)
    InvenioCommunities(app_)
    InvenioPIDStore(app_)
    InvenioSIPStore(app_)
    Babel(app_)
    InvenioFilesREST(app_)
    InvenioMigrator(app_)
    FlaskOAuth(app_)
    InvenioOAuthClient(app_)

    with app_.app_context():
        yield app_
Beispiel #11
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    Babel(app)
    FlaskCLI(app)
    InvenioDB(app)
    LoginManager(app)
    app.admin_app = InvenioAdmin(app)
    protected_view = protected_adminview_factory(TestModelView)
    app.admin_app.admin.add_view(protected_view(TestModel, db.session))

    app.config.update(
        TESTING=True,
        SECRET_KEY="SECRET_KEY",
    )

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.drop_all()
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return app
Beispiel #12
0
def records_app(request):
    """Initialize InvenioRecords."""
    app = Flask('records_testapp')
    FlaskCLI(app)
    app.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
    )
    InvenioDB(app)
    from invenio_records import InvenioRecords
    from invenio_db import db
    InvenioRecords(app)
    InvenioSearch(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(teardown)
    return app
Beispiel #13
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)
Beispiel #14
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        TESTING=True,
        SERVER_NAME='localhost:5000',
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'
        )
    )
    FlaskCLI(app)
    InvenioDB(app)
    InvenioREST(app)
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioRecordsREST(app)

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

    def finalize():
        with app.app_context():
            db.drop_all()
            if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
                drop_database(db.engine.url)
            shutil.rmtree(instance_path)

    request.addfinalizer(finalize)
    return app
Beispiel #15
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        BROKER_URL=os.environ.get('BROKER_URL', 'memory://'),
        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:///test.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=False,
        TESTING=True,
    )
    FlaskCLI(app)
    FlaskCeleryExt(app)
    InvenioDB(app)
    InvenioRecords(app)
    InvenioSearch(app)
    InvenioIndexer(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return app
Beispiel #16
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        # HTTPretty doesn't play well with Redis.
        # See gabrielfalcao/HTTPretty#110
        CACHE_TYPE='simple',
        CELERY_ALWAYS_EAGER=True,
        CELERY_CACHE_BACKEND='memory',
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        CELERY_RESULT_BACKEND='cache',
        GITHUB_SHIELDSIO_BASE_URL='http://example.org/badge/',
        GITHUB_APP_CREDENTIALS=dict(
            consumer_key='changeme',
            consumer_secret='changeme',
        ),
        LOGIN_DISABLED=False,
        OAUTHLIB_INSECURE_TRANSPORT=True,
        OAUTH2_CACHE_TYPE='simple',
        OAUTHCLIENT_REMOTE_APPS=dict(
            github=REMOTE_APP,
        ),
        SECRET_KEY='test_key',
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI',
                                          'sqlite:///test.db'),
        SECURITY_PASSWORD_HASH='plaintext',
        SECURITY_PASSWORD_SCHEMES=['plaintext'],
        TESTING=True,
        WTF_CSRF_ENABLED=False,
    )
    app.url_map.converters['pid'] = PIDConverter

    FlaskCLI(app)
    celeryext = FlaskCeleryExt(app)
    celeryext.celery.flask_app = app  # Make sure both apps are the same!
    Babel(app)
    Mail(app)
    Menu(app)
    Breadcrumbs(app)
    InvenioDB(app)
    InvenioAccounts(app)
    app.register_blueprint(accounts_blueprint)
    InvenioOAuthClient(app)
    app.register_blueprint(oauthclient_blueprint)
    InvenioOAuth2Server(app)
    app.register_blueprint(server_blueprint)
    app.register_blueprint(settings_blueprint)
    InvenioPIDStore(app)
    InvenioRecordsREST(app)
    InvenioDepositREST(app)
    InvenioWebhooks(app)
    app.register_blueprint(webhooks_blueprint)
    InvenioGitHub(app)

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
Beispiel #17
0
def app(request):
    """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",
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        TESTING=True,
    )
    FlaskCLI(app)
    FlaskCeleryExt(app)
    InvenioDB(app)
    InvenioWorkflows(app)
    InvenioOAIHarvester(app)
    INSPIRECrawler(app)

    with app.app_context():
        yield app

    shutil.rmtree(instance_path)
Beispiel #18
0
def script_info(request):
    """Get ScriptInfo object for testing CLI."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        TESTING=True,
    )
    FlaskCLI(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)):
            create_database(str(db.engine.url))
        db.drop_all()
        db.create_all()

    def teardown():
        with app.app_context():
            drop_database(str(db.engine.url))
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)
    return ScriptInfo(create_app=lambda info: app)
Beispiel #19
0
def app(request):
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        TESTING=True,
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite://'),
        CELERY_ALWAYS_EAGER=True,
        CELERY_RESULT_BACKEND="cache",
        CELERY_CACHE_BACKEND="memory",
        CELERY_EAGER_PROPAGATES_EXCEPTIONS=True,
        RECORDS_UI_DEFAULT_PERMISSION_FACTORY=None,  # No permission checking
    )
    FlaskCeleryExt(app)
    FlaskCLI(app)
    Babel(app)
    InvenioDB(app)
    InvenioPIDStore(app)
    InvenioRecords(app)

    with app.app_context():
        db.create_all()

    def finalize():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(finalize)
    return app
Beispiel #20
0
def app(request):
    """Flask application fixture."""
    app = Flask('testapp')
    app.config.update(
        ACCOUNTS_USE_CELERY=False,
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get(
            'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'),
        TESTING=True,
    )
    FlaskCLI(app)
    Babel(app)
    Mail(app)
    InvenioDB(app)
    InvenioAccounts(app)

    with app.app_context():
        db.create_all()

    def teardown():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(teardown)
    return app
Beispiel #21
0
def app(request):
    """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",
        SECRET_KEY="CHANGE_ME",
        SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO",
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        TESTING=True,
    )
    FlaskCLI(app)
    FlaskCeleryExt(app)
    InvenioDB(app)
    InvenioRecords(app)

    with app.app_context():
        db.create_all()

    def teardown():
        with app.app_context():
            db.drop_all()
        shutil.rmtree(instance_path)

    request.addfinalizer(teardown)

    return app
Beispiel #22
0
def register_extensions(app: Flask) -> None:
    db.init_app(app)
    login_manager.init_app(app)
    mail_client.init_app(app)
    FlaskCLI(app)
    controller.app = app
    controller.session = db.create_scoped_session()
def test_db(request):
    """Test database backend."""
    app = Flask(__name__)
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
        'SQLALCHEMY_DATABASE_URI', 'sqlite://')
    FlaskCLI(app)
    InvenioDB(app)
    FlaskOAuth(app)
    InvenioOAuthClient(app)

    def teardown():
        with app.app_context():
            db.drop_all()

    request.addfinalizer(teardown)

    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()
        tables = list(
            filter(lambda table: table.startswith('oauthclient'),
                   db.metadata.tables.keys()))
        assert len(tables) == 3
Beispiel #24
0
def app():
    """Flask application fixture."""
    app = Flask('testapp')
    FlaskCLI(app)
    app.config.update(TESTING=True)
    InvenioSearch(app)
    return app
Beispiel #25
0
def es_app(request):
    """Flask application with records fixture."""
    app = Flask(__name__)
    app.config.update(
        JSONSCHEMAS_HOST='http://localhost:5000',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
    )
    app.config[InvenioJSONSchemas.CONFIG_ENDPOINT] = '/'

    Babel(app)
    FlaskCLI(app)
    InvenioDB(app)
    InvenioRecords(app)
    InvenioMARC21(app)
    search = InvenioSearch(app)
    InvenioIndexer(app)
    InvenioJSONSchemas(app)

    with app.app_context():
        db.create_all()
        list(search.create())
        sleep(10)

    def teardown():
        with app.app_context():
            db.drop_all()
            list(search.delete())

    request.addfinalizer(teardown)

    return app
Beispiel #26
0
def app(request):
    """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',
        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,
        TESTING=True,
    )
    FlaskCLI(app_)
    FlaskCeleryExt(app_)
    InvenioDB(app_)
    InvenioAccounts(app_)
    InvenioJSONSchemas(app_)
    InvenioSearch(app_)
    InvenioRecords(app_)
    InvenioRecordsREST(app_)
    InvenioPIDStore(app_)
    InvenioDeposit(app_)

    with app_.app_context():
        yield app_

    shutil.rmtree(instance_path)
Beispiel #27
0
def app():
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        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',
        JSONSCHEMAS_HOST='inveniosoftware.org',
        TESTING=True,
        SECRET_KEY='CHANGE_ME',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        SERVER_NAME='app',
        OAISERVER_ID_PREFIX='oai:inveniosoftware.org:recid/',
        OAISERVER_QUERY_PARSER_FIELDS=["title_statement"],
        OAISERVER_RECORD_INDEX='_all',
        OAISERVER_REGISTER_SET_SIGNALS=True,
    )
    if not hasattr(app, 'cli'):
        from flask_cli import FlaskCLI
        FlaskCLI(app)
    InvenioDB(app)
    FlaskCeleryExt(app)
    InvenioJSONSchemas(app)
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioMARC21(app)
    client = Elasticsearch(hosts=[os.environ.get('ES_HOST', 'localhost')])
    search = InvenioSearch(app, client=client)
    search.register_mappings('records', 'data')
    InvenioIndexer(app)
    InvenioOAIServer(app)

    app.register_blueprint(blueprint)

    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()
        list(search.delete(ignore=[404]))
        list(search.create())
        search.flush_and_refresh('_all')

    with app.app_context():
        yield app

    with app.app_context():
        db.session.close()
        if str(db.engine.url) != 'sqlite://':
            drop_database(str(db.engine.url))
        list(search.delete(ignore=[404]))
        search.client.indices.delete("*-percolators")
    shutil.rmtree(instance_path)
Beispiel #28
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    app.config.update(
        TESTING=True,
        SERVER_NAME='localhost:5000',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        RECORDS_REST_ENDPOINTS=config.RECORDS_REST_ENDPOINTS,
        # No permission checking
        RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_SEARCH_INDEX=ES_INDEX,
        RECORDS_REST_SORT_OPTIONS={
            ES_INDEX: dict(year=dict(fields=['year'], ))
        },
    )
    app.config['RECORDS_REST_ENDPOINTS']['recid']['search_class'] = TestSearch

    # update the application with the configuration provided by the test
    if hasattr(request, 'param') and 'config' in request.param:
        app.config.update(**request.param['config'])

    FlaskCLI(app)
    InvenioDB(app)
    InvenioREST(app)
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioSearch(app)
    InvenioAccess(app)
    InvenioRecordsREST(app)

    with app.app_context():
        # Setup app
        if not database_exists(str(db.engine.url)) and \
           app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
            create_database(db.engine.url)
        db.drop_all()
        db.create_all()
        if current_search_client.indices.exists(ES_INDEX):
            current_search_client.indices.delete(ES_INDEX)
            current_search_client.indices.create(ES_INDEX)
        prepare_indexing(app)

    with app.app_context():
        # Yield app in request context
        with app.test_request_context():
            yield app

    with app.app_context():
        # Teardown app
        db.drop_all()
        if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
            drop_database(db.engine.url)
        shutil.rmtree(instance_path)
Beispiel #29
0
def test_cli(app, tmpdir, monkeypatch):
    """Test CLI."""
    FlaskCLI(app)
    InvenioDB(app)
    InvenioUpgrader(app)

    runner = CliRunner()
    script_info = ScriptInfo(create_app=lambda info: app)

    assert len(db.metadata.tables) == 1

    runner.invoke(db_cmd, ['init'], obj=script_info)
    runner.invoke(db_cmd, ['create'], obj=script_info)

    result = runner.invoke(cli.applied, obj=script_info)
    assert result.exit_code == 0

    result = runner.invoke(cli.pending, obj=script_info)
    assert result.exit_code == 0

    result = runner.invoke(cli.check, obj=script_info)
    assert result.exit_code == 0

    result = runner.invoke(
        cli.recipe,
        ['-p', 'invenio_upgrader_test.mymod',
         '-d', ['test1', 'test2'],
         '-n','test_name'],
        obj=script_info)
    assert result.exit_code == 0
    expexted_name = "mymod_{0}_test_name".format(
        date.today().strftime("%Y_%m_%d"))
    mod = importlib.import_module(
        'invenio_upgrader_test.mymod.upgrades.{0}'.format(
        expexted_name))
    upgrade = mod.TestName()
    # Test API of created upgrade recipe
    assert upgrade.depends_on == ['test1', 'test2']
    assert upgrade.estimate() == 1
    assert isinstance(upgrade.info, six.string_types)
    upgrade.pre_upgrade()
    upgrade.do_upgrade()
    upgrade.post_upgrade()

    class TestUpgrade(UpgradeBase):
        """Test Upgrade."""
        def do_upgrade(self):
            """Do upgrade."""
            pass

    monkeypatch.setattr(
        'invenio_upgrader.engine.InvenioUpgrader._load_upgrades',
        lambda self, remove_applied: {'test_cli:TestUpgrade': TestUpgrade()})
    result = runner.invoke(cli.run, input='y', obj=script_info)
    assert result.exit_code == 0
    assert '* test_cli:TestUpgrade (Test Upgrade.)' in result.output

    runner.invoke(db_cmd, ['drop', '--yes-i-know'], obj=script_info)
    runner.invoke(db_cmd, ['destroy', '--yes-i-know'], obj=script_info)
def test_actions_entrypoint():
    """Test if the entrypoint is registering actions properly."""
    app = Flask('testapp')
    FlaskCLI(app)
    ext = InvenioAccess(app)
    assert len(ext.actions) == 2
    assert ActionNeed('open') in ext.actions.values()
    assert ActionNeed('close') in ext.actions.values()
Beispiel #31
0
def app(request):
    """Flask application fixture."""
    instance_path = tempfile.mkdtemp()
    app = Flask('testapp', instance_path=instance_path)
    es_index = 'invenio_records_rest_test_index'
    app.config.update(
        TESTING=True,
        SERVER_NAME='localhost:5000',
        SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI',
                                               'sqlite:///test.db'),
        SQLALCHEMY_TRACK_MODIFICATIONS=True,
        RECORDS_REST_ENDPOINTS=config.RECORDS_REST_ENDPOINTS,
        # No permission checking
        RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=None,
        RECORDS_REST_DEFAULT_SEARCH_INDEX=es_index,
        RECORDS_REST_SORT_OPTIONS={
            es_index: dict(year=dict(fields=['year'], ))
        },
        SEARCH_QUERY_ENHANCERS=[filter_record_access_query_enhancer],
    )
    app.config['RECORDS_REST_ENDPOINTS']['recid']['search_index'] = es_index

    # update the application with the configuration provided by the test
    if hasattr(request, 'param') and 'config' in request.param:
        app.config.update(**request.param['config'])

    FlaskCLI(app)
    InvenioDB(app)
    InvenioREST(app)
    InvenioRecords(app)
    InvenioPIDStore(app)
    InvenioSearch(app)
    InvenioAccess(app)
    InvenioRecordsREST(app)

    with app.app_context():
        if not database_exists(str(db.engine.url)) and \
           app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
            create_database(db.engine.url)
        db.drop_all()
        db.create_all()
        if current_search_client.indices.exists(es_index):
            current_search_client.indices.delete(es_index)
            current_search_client.indices.create(es_index)
        prepare_indexing(app)

    def finalize():
        with app.app_context():
            db.drop_all()
            if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
                drop_database(db.engine.url)
            shutil.rmtree(instance_path)

    request.addfinalizer(finalize)
    return app