def test_alembic(db, app): """Test alembic recipes.""" ext = InvenioDB(app, entry_point_group=False, db=db) with app.app_context(): if db.engine.name == 'sqlite': raise pytest.skip('Upgrades are not supported on SQLite.') ext.alembic.upgrade() ext.alembic.downgrade(target='96e796392533')
def _create_app(**config): app_ = Flask( __name__, instance_path=instance_path, ) app_.config.update(config) InvenioCelery(app_) InvenioDB(app_) InvenioRecords(app_) return app_
def test_init(): """Test extension initialization.""" app = Flask('testapp') FlaskCLI(app) Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts(app) assert 'invenio-accounts' in app.extensions app = Flask('testapp') FlaskCLI(app) Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts() assert 'invenio-accounts' not in app.extensions ext.init_app(app) assert 'invenio-accounts' in app.extensions
def test_transaction(db, app): """Test transcation commit and rollback. This is necessary to make sure that pysqlite hacks are properly working. """ class Demo(db.Model): __tablename__ = "demo" pk = sa.Column(sa.Integer, primary_key=True) app.config["DB_VERSIONING"] = False InvenioDB(app, entry_point_group=False, db=db) with app.app_context(): db.drop_all() db.create_all() assert len(db.metadata.tables) == 1 # Test rollback with app.app_context(): d1 = Demo() d1.pk = 1 db.session.add(d1) db.session.rollback() with app.app_context(): res = Demo.query.all() assert len(res) == 0 db.session.rollback() # Test nested session rollback with app.app_context(): with db.session.begin_nested(): d1 = Demo() d1.pk = 1 db.session.add(d1) db.session.rollback() with app.app_context(): res = Demo.query.all() assert len(res) == 0 db.session.rollback() # Test commit with app.app_context(): d1 = Demo() d1.pk = 1 db.session.add(d1) db.session.commit() with app.app_context(): res = Demo.query.all() assert len(res) == 1 assert res[0].pk == 1 db.session.commit() with app.app_context(): db.drop_all()
def app(): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', 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_HOST='inveniosoftware.org', TESTING=True, SECRET_KEY='CHANGE_ME', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SERVER_NAME='app', OAISERVER_RECORD_INDEX='_all', OAISERVER_REGISTER_SET_SIGNALS=True, SEARCH_ELASTIC_KEYWORD_MAPPING={None: ['_all']}, ) 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.create(ignore=[400])) sleep(5) 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])) shutil.rmtree(instance_path)
def app(instance_path, config): """Flask application fixture.""" app = Flask('testapp', instance_path=instance_path) app.config.update(config) InvenioDB(app) InvenioAccounts(app) InvenioJSONSchemas(app) InvenioSIPStore(app) with app.app_context(): yield app
def test_versioning(db, app): """Test SQLAlchemy-Continuum enabled versioning.""" app.config['DB_VERSIONING'] = True idb = InvenioDB(app, entry_point_group='invenio_db.models_b', db=db, versioning_manager=VersioningManager()) with app.app_context(): assert 4 == len(db.metadata.tables) db.create_all() from demo.versioned_b import UnversionedArticle, VersionedArticle original_name = 'original_name' versioned = VersionedArticle() unversioned = UnversionedArticle() versioned.name = original_name unversioned.name = original_name db.session.add(versioned) db.session.add(unversioned) db.session.commit() assert unversioned.name == versioned.name modified_name = 'modified_name' versioned.name = modified_name unversioned.name = modified_name db.session.commit() assert unversioned.name == modified_name assert versioned.name == modified_name assert versioned.versions[0].name == original_name assert versioned.versions[1].name == versioned.name versioned.versions[0].revert() db.session.commit() assert unversioned.name == modified_name assert versioned.name == original_name versioned.versions[1].revert() db.session.commit() assert unversioned.name == versioned.name with app.app_context(): db.drop_all() remove_versioning(manager=idb.versioning_manager)
def test_init(): """Test extension initialization.""" app = Flask('testapp') Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts(app) assert 'invenio-accounts' in app.extensions assert 'security' in app.blueprints.keys() app = Flask('testapp') Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts() assert 'invenio-accounts' not in app.extensions assert 'security' not in app.blueprints.keys() ext.init_app(app) assert 'invenio-accounts' in app.extensions assert 'security' in app.blueprints.keys()
def app_deposit(): """App configuration for using InvenioDeposit.""" 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', 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, 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 Babel(app) FlaskCeleryExt(app) InvenioDB(app) Breadcrumbs(app) InvenioAccounts(app) InvenioAccess(app) app.register_blueprint(accounts_blueprint) InvenioAssets(app) InvenioJSONSchemas(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) InvenioSSE(app) InvenioSearch(app) with app.app_context(): yield app
def app(request, docid_record_type_endpoint): """Flask application fixture.""" from invenio_records_files.api import Record as RecordFiles instance_path = tempfile.mkdtemp() app_ = Flask(__name__, instance_path=instance_path) RECORDS_REST_ENDPOINTS.update(docid=docid_record_type_endpoint) # Endpoint with files support RECORDS_REST_ENDPOINTS['recid']['record_class'] = RecordFiles RECORDS_REST_ENDPOINTS['recid']['item_route'] = \ '/records/<pid(recid, ' \ 'record_class="invenio_records_files.api.Record"):pid_value>' RECORDS_REST_ENDPOINTS['recid']['indexer_class'] = None # Application app_.config.update( FILES_REST_PERMISSION_FACTORY=lambda *a, **kw: type( 'Allow', (object, ), {'can': lambda self: True})(), SECRET_KEY='CHANGE_ME', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, RECORDS_FILES_REST_ENDPOINTS={ 'RECORDS_REST_ENDPOINTS': { 'recid': 'files', 'docid': 'nofiles', } }, RECORDS_REST_ENDPOINTS=RECORDS_REST_ENDPOINTS, RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=allow_all, ) app_.url_map.converters['pid'] = PIDConverter InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioIndexer(app_) InvenioPIDStore(app_) InvenioRecordsREST(app_) InvenioRecordsFiles(app_) app_.register_blueprint(files_rest_blueprint) app_.register_blueprint(create_blueprint_from_app(app_)) app_.register_blueprint(records_rest_create_blueprint_from_app(app_)) search = InvenioSearch(app_) search.register_mappings('records-files', 'data') with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def app(request): """Test mdcobject.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update(ACCOUNTS_JWT_ENABLE=False, INDEXER_DEFAULT_DOC_TYPE='record-v1.0.0', RECORDS_REST_ENDPOINTS={}, RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=None, SERVER_NAME='localhost:5000', JSONSCHEMAS_HOST='localhost:5000', CELERY_ALWAYS_EAGER=True, CELERY_RESULT_BACKEND='cache', CELERY_CACHE_BACKEND='memory', FLASK_TAXONOMIES_URL_PREFIX='/2.0/taxonomies/', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SUPPORTED_LANGUAGES=["cs", "en"], TESTING=True, ELASTICSEARCH_DEFAULT_LANGUAGE_TEMPLATE={ "type": "text", "fields": { "keywords": { "type": "keyword" } } }) app.secret_key = 'changeme' InvenioDB(app) OarepoTaxonomies(app) OARepoReferences(app) InvenioRecords(app) InvenioJSONSchemas(app) InvenioPIDStore(app) InvenioSearch(app) InvenioIndexer(app) OARepoMappingIncludesExt(app) # app_loaded.send(app, app=app) with app.app_context(): yield app # Teardown instance path. shutil.rmtree(instance_path)
def app(): """Flask application fixture.""" app = Flask('testapp') app.config.update(TESTING=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db')) Babel(app) FlaskCLI(app) InvenioDB(app) InvenioWorkflows(app) InvenioWorkflowsUI(app) return app
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 base_app(request): """Flask application fixture without ShibbolethAuthenticator init.""" instance_path = tempfile.mkdtemp() base_app = Flask('testapp') base_app.config.update( TESTING=True, WTF_CSRF_ENABLED=False, LOGIN_DISABLED=False, CACHE_TYPE='simple', SHIBBOLETH_REMOTE_APPS=dict( hzdr=dict(title='HZDR Shibboleth Authentication', saml_path='data/', mappings=dict( email='email_mapping', user_unique_id='id_mapping', full_name='full_name_mapping', ))), DEBUG=False, EMAIL_BACKEND='flask_email.backends.locmem.Mail', SQLALCHEMY_TRACK_MODIFICATIONS=False, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', SECRET_KEY='TEST', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], ) FlaskMenu(base_app) InvenioDB(base_app) InvenioAccounts(base_app) Mail(base_app) with base_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() def teardown(): with base_app.app_context(): db.session.close() if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) print('Path: ' + instance_path) shutil.rmtree(instance_path) request.addfinalizer(teardown) base_app.test_request_context().push() return base_app
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)
def test_init(): """Test extension initialization.""" app = Flask("testapp") app.config["SECRET_KEY"] = "CHANGEME" Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts(app) assert "invenio-accounts" in app.extensions assert "security" in app.blueprints.keys() app = Flask("testapp") app.config["SECRET_KEY"] = "CHANGEME" Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccounts() assert "invenio-accounts" not in app.extensions assert "security" not in app.blueprints.keys() ext.init_app(app) assert "invenio-accounts" in app.extensions assert "security" in app.blueprints.keys()
def test_versioning_without_versioned_tables(db, app): """Test SQLAlchemy-Continuum without versioned tables.""" app.config['DB_VERSIONING'] = True idb = InvenioDB(app, db=db, entry_point_group=None, versioning_manager=VersioningManager()) with app.app_context(): assert 'transaction' in db.metadata.tables remove_versioning(manager=idb.versioning_manager)
def factory(**config): app = Flask('testapp') app.config.update(SERVER_NAME='localhost', **config) InvenioDB(app) InvenioAccounts(app) InvenioAccess(app) InvenioFilesREST(app) InvenioIIIFAPI(app) app.register_blueprint(blueprint) return app
def test_actions(): """Test if the actions are registered properly.""" app = Flask('testapp') Babel(app) Mail(app) InvenioDB(app) InvenioAccounts(app) InvenioAccess(app, entry_point_group=None) with app.app_context(): current_access.register_action(ActionNeed('action_a')) assert len(current_access.actions) == 1 current_access.register_action(ActionNeed('action_b')) assert len(current_access.actions) == 2
def create_app(config_mapping=None): """REANA Server application factory.""" logging.basicConfig(level=REANA_LOG_LEVEL, format=REANA_LOG_FORMAT, force=True) app = Flask(__name__) app.config.from_object("reana_server.config") if config_mapping: app.config.from_mapping(config_mapping) app.secret_key = "hyper secret key" app.session = Session Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) FlaskOAuth(app) InvenioOAuthClient(app) # Register Invenio OAuth endpoints app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) # Register API routes from .rest import ( config, gitlab, ping, secrets, status, users, workflows, info, ) # noqa app.register_blueprint(ping.blueprint, url_prefix="/api") app.register_blueprint(workflows.blueprint, url_prefix="/api") app.register_blueprint(users.blueprint, url_prefix="/api") app.register_blueprint(secrets.blueprint, url_prefix="/api") app.register_blueprint(gitlab.blueprint, url_prefix="/api") app.register_blueprint(config.blueprint, url_prefix="/api") app.register_blueprint(status.blueprint, url_prefix="/api") app.register_blueprint(info.blueprint, url_prefix="/api") @app.teardown_appcontext def shutdown_session(response_or_exc): """Close session on app teardown.""" current_app.session.remove() return response_or_exc return app
def base_app(request): """Flask application fixture without OAuthClient initialized.""" instance_path = tempfile.mkdtemp() base_app = Flask('testapp') base_app.config.update( TESTING=True, WTF_CSRF_ENABLED=False, LOGIN_DISABLED=False, CACHE_TYPE='simple', OAUTHCLIENT_REMOTE_APPS=dict( orcid=REMOTE_APP, ), ORCID_APP_CREDENTIALS=dict( consumer_key='changeme', consumer_secret='changeme', ), # use local memory mailbox EMAIL_BACKEND='flask_email.backends.locmem.Mail', SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', DEBUG=False, SECRET_KEY='TEST', SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], ) FlaskCLI(base_app) FlaskMenu(base_app) Babel(base_app) Mail(base_app) InvenioDB(base_app) InvenioAccounts(base_app) with base_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() def teardown(): with base_app.app_context(): db.session.close() if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) base_app.test_request_context().push() return base_app
def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( ACCOUNTS_JWT_ENABLE=False, BROKER_TRANSPORT='redis', CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', CELERY_TRACK_STARTED=True, LOGIN_DISABLED=False, OAUTH2_CACHE_TYPE='simple', OAUTHLIB_INSECURE_TRANSPORT=True, SECRET_KEY='test_key', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, WTF_CSRF_ENABLED=False, ) 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) InvenioOAuth2Server(app) InvenioOAuth2ServerREST(app) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) InvenioWebhooks(app) app.register_blueprint(blueprint) 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)) request.addfinalizer(teardown) return app
def test_init_rest(): """Test REST extension initialization.""" app = Flask("testapp") app.config["SECRET_KEY"] = "CHANGEME" Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST(app) assert "invenio-accounts" in app.extensions assert "security" not in app.blueprints.keys() assert "security_email_templates" in app.blueprints.keys() app = Flask("testapp") app.config["SECRET_KEY"] = "CHANGEME" Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST() assert "invenio-accounts" not in app.extensions assert "security" not in app.blueprints.keys() ext.init_app(app) assert "invenio-accounts" in app.extensions assert "security" not in app.blueprints.keys() assert "security_email_templates" in app.blueprints.keys() app = Flask("testapp") app.config["SECRET_KEY"] = "CHANGEME" app.config["ACCOUNTS_REGISTER_BLUEPRINT"] = True Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST() assert "invenio-accounts" not in app.extensions assert "security" not in app.blueprints.keys() ext.init_app(app) assert "invenio-accounts" in app.extensions assert "security" in app.blueprints.keys() assert "security_email_templates" in app.blueprints.keys()
def test_init_rest(): """Test REST extension initialization.""" app = Flask('testapp') app.config['SECRET_KEY'] = 'CHANGEME' Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST(app) assert 'invenio-accounts' in app.extensions assert 'security' not in app.blueprints.keys() assert 'security_email_templates' in app.blueprints.keys() app = Flask('testapp') app.config['SECRET_KEY'] = 'CHANGEME' Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST() assert 'invenio-accounts' not in app.extensions assert 'security' not in app.blueprints.keys() ext.init_app(app) assert 'invenio-accounts' in app.extensions assert 'security' not in app.blueprints.keys() assert 'security_email_templates' in app.blueprints.keys() app = Flask('testapp') app.config['SECRET_KEY'] = 'CHANGEME' app.config['ACCOUNTS_REGISTER_BLUEPRINT'] = True Babel(app) Mail(app) InvenioDB(app) ext = InvenioAccountsREST() assert 'invenio-accounts' not in app.extensions assert 'security' not in app.blueprints.keys() ext.init_app(app) assert 'invenio-accounts' in app.extensions assert 'security' in app.blueprints.keys() assert 'security_email_templates' in app.blueprints.keys()
def factory(**config): app = Flask("testapp", instance_path=instance_path) app.config.update(**config) Babel(app) InvenioDB(app) no_permissions = dict(permission_factory=None, view_class_factory=lambda x: x) InvenioAdmin(app, **no_permissions) InvenioBanners(app) app.register_blueprint(blueprint) app.register_blueprint(api_blueprint) return app
def test_entry_points(db, app): """Test entrypoints loading.""" InvenioDB(app, db=db) runner = CliRunner() script_info = ScriptInfo(create_app=lambda info: app) assert len(db.metadata.tables) == 2 # Test merging a base another file. with runner.isolated_filesystem(): result = runner.invoke(db_cmd, [], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['destroy', '--yes-i-know'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['init'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['create', '-v'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['drop'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['drop', '-v', '--yes-i-know'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['drop', 'create'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['drop', '--yes-i-know', 'create'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['destroy'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['destroy', '--yes-i-know'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['init'], obj=script_info) assert result.exit_code == 0
def test_db_create_alembic_upgrade(app, db): """Test that 'db create/drop' and 'alembic create' are compatible. It also checks that "alembic_version" table is processed properly as it is normally created by alembic and not by sqlalchemy. """ app.config['DB_VERSIONING'] = True ext = InvenioDB(app, entry_point_group=None, db=db, versioning_manager=VersioningManager()) with app.app_context(): try: if db.engine.name == 'sqlite': raise pytest.skip('Upgrades are not supported on SQLite.') db.drop_all() runner = CliRunner() script_info = ScriptInfo(create_app=lambda info: app) # Check that 'db create' creates the same schema as # 'alembic upgrade'. result = runner.invoke(db_cmd, ['create', '-v'], obj=script_info) assert result.exit_code == 0 assert db.engine.has_table('transaction') assert ext.alembic.migration_context._has_version_table() # Note that compare_metadata does not detect additional sequences # and constraints. assert not ext.alembic.compare_metadata() ext.alembic.upgrade() assert db.engine.has_table('transaction') ext.alembic.downgrade(target='96e796392533') assert db.engine.table_names() == ['alembic_version'] # Check that 'db drop' removes all tables, including # 'alembic_version'. ext.alembic.upgrade() result = runner.invoke(db_cmd, ['drop', '-v', '--yes-i-know'], obj=script_info) assert result.exit_code == 0 assert len(db.engine.table_names()) == 0 ext.alembic.upgrade() db.drop_all() drop_alembic_version_table() assert len(db.engine.table_names()) == 0 finally: drop_database(str(db.engine.url)) remove_versioning(manager=ext.versioning_manager) create_database(str(db.engine.url))
def test_init(): """Test extension initialization.""" app = Flask('testapp') app.config.update(ACCOUNTS_USE_CELERY=False) Babel(app) Mail(app) Menu(app) InvenioDB(app) InvenioAccounts(app) ext = WekoUserProfiles(app) assert 'weko-user-profiles' in app.extensions app = Flask('testapp') app.config.update(ACCOUNTS_USE_CELERY=False) Babel(app) Mail(app) Menu(app) InvenioDB(app) InvenioAccounts(app) ext = WekoUserProfiles() assert 'weko-user-profiles' not in app.extensions ext.init_app(app) assert 'weko-user-profiles' in app.extensions
def test_entry_points(script_info): """Test entrypoints loading.""" import invenio_db from invenio_db import shared from flask_sqlalchemy import SQLAlchemy db = invenio_db.db = shared.db = SQLAlchemy() app = Flask('demo') app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db') FlaskCLI(app) InvenioDB(app) runner = CliRunner() script_info = ScriptInfo(create_app=lambda info: app) assert len(db.metadata.tables) == 2 # Test merging a base another file. with runner.isolated_filesystem(): result = runner.invoke(db_cmd, [], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['init'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['create'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['drop', '-v'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['drop', '--yes-i-know'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['drop', 'create', '-v'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['drop', '--yes-i-know', 'create'], obj=script_info) assert result.exit_code == 0 result = runner.invoke(db_cmd, ['destroy'], obj=script_info) assert result.exit_code == 1 result = runner.invoke(db_cmd, ['destroy', '--yes-i-know'], obj=script_info) assert result.exit_code == 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)