def test_init(): """Test extension initialization.""" app = Flask('testapp') ext = InvenioFilesREST(app) assert 'invenio-files-rest' in app.extensions app = Flask('testapp') ext = InvenioFilesREST() assert 'invenio-files-rest' not in app.extensions ext.init_app(app) assert 'invenio-files-rest' in app.extensions
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app_ = Flask(__name__, instance_path=instance_path) 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, ) app_.register_blueprint(files_rest_blueprint) InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioIndexer(app_) search = InvenioSearch(app_) search.register_mappings('records-files', 'data') with app_.app_context(): yield app_ shutil.rmtree(instance_path)
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) Babel(app) InvenioDB(app) InvenioPIDStore(app) InvenioRecords(app) InvenioFilesREST(app) with app.app_context(): db.create_all() def finalize(): with app.app_context(): db.drop_all() request.addfinalizer(finalize) return app
def app(base_app): """Flask full application fixture.""" InvenioDB(base_app) InvenioFilesREST(base_app) InvenioPIDStore(base_app) with base_app.app_context(): yield base_app
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', ) 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_
def app(): """Create fixture app.""" # Set temporary instance path for sqlite instance_path = tempfile.mkdtemp() _app = Flask('testapp', instance_path=instance_path) InvenioAccess(_app) InvenioAccounts(_app) InvenioDB(_app) InvenioUserProfiles(_app) InvenioRecords(_app) InvenioFilesREST(_app) # UserProfile(_app) _app.config.update( SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, SECRET_KEY='test', ) with _app.app_context(): yield _app # Teardown instance path. shutil.rmtree(instance_path)
def app(base_app): """Flask application fixture.""" InvenioDB(base_app) InvenioAccounts(base_app) InvenioFilesREST(base_app) InvenioJSONSchemas(base_app) with base_app.app_context(): yield base_app
def base_app(): """Flask application fixture without InvenioStats.""" from invenio_stats.config import STATS_EVENTS instance_path = tempfile.mkdtemp() app_ = Flask('testapp', instance_path=instance_path) stats_events = { 'file-download': deepcopy(STATS_EVENTS['file-download']), 'record-view': { 'signal': 'invenio_records_ui.signals.record_viewed', 'event_builders': ['invenio_stats.contrib.event_builders' '.record_view_event_builder'] } } stats_events.update({'event_{}'.format(idx): {} for idx in range(5)}) app_.config.update(dict( CELERY_ALWAYS_EAGER=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_TASK_EAGER_PROPAGATES=True, CELERY_RESULT_BACKEND='cache', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, OAUTH2SERVER_CLIENT_ID_SALT_LEN=64, OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60, OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60, STATS_MQ_EXCHANGE=Exchange( 'test_events', type='direct', delivery_mode='transient', # in-memory queue durable=True, ), SECRET_KEY='asecretkey', SERVER_NAME='localhost', STATS_QUERIES={'bucket-file-download-histogram': {}, 'bucket-file-download-total': {}, 'test-query': {}, 'test-query2': {}}, STATS_EVENTS=stats_events, STATS_AGGREGATIONS={'file-download-agg': {}} )) FlaskCeleryExt(app_) InvenioAccounts(app_) InvenioAccountsREST(app_) InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioPIDStore(app_) InvenioCache(app_) InvenioQueues(app_) InvenioOAuth2Server(app_) InvenioOAuth2ServerREST(app_) InvenioSearch(app_, entry_point_group=None) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def factory(**config): app = Flask('testapp') app.config.update(**config) InvenioDB(app) InvenioFilesREST(app) InvenioS3(app) return 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(): """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)
def app(base_app): """Flask application fixture.""" InvenioAccounts(base_app) InvenioAccess(base_app) base_app.register_blueprint(accounts_blueprint) InvenioFilesREST(base_app) base_app.register_blueprint(blueprint) with base_app.app_context(): yield base_app
def _create_app(**config): app_ = Flask( __name__, instance_path=instance_path, ) app_.config.update(config) InvenioDB(app_) InvenioFilesREST(app_) InvenioRecordsMARC21(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 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 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)
def app(base_app): """Flask full application fixture.""" Breadcrumbs(base_app) InvenioDB(base_app) InvenioAccess(base_app) InvenioAccounts(base_app) InvenioFilesREST(base_app) InvenioOAuth2Server(base_app) InvenioOAuth2ServerREST(base_app) InvenioREST(base_app) InvenioSIPStore(base_app) base_app.register_blueprint(server_blueprint) base_app.register_blueprint(blueprint) with base_app.app_context(): yield base_app
def app(base_app): """Flask application fixture.""" Babel(base_app) InvenioAccounts(base_app) InvenioAccess(base_app) InvenioDB(base_app) InvenioFilesREST(base_app) InvenioRecords(base_app) InvenioRecordsUI(base_app) InvenioREST(base_app) InvenioIIIFAPI(base_app) InvenioIIIFManifest(base_app) with base_app.app_context(): yield base_app
def factory(**config): app = Flask('testapp') app.config.update(SERVER_NAME='localhost', **config) InvenioDB(app) InvenioAccounts(app) InvenioAccess(app) InvenioPIDStore(app) InvenioFilesREST(app) InvenioRecordsFiles(app) InvenioIIIFAPI(app) app.register_blueprint(blueprint) app.register_blueprint(create_blueprint_from_app(app)) return app
def base_app(events_config, aggregations_config): """Flask application fixture without InvenioStats.""" instance_path = tempfile.mkdtemp() app_ = Flask('testapp', instance_path=instance_path) app_.config.update(dict( CELERY_ALWAYS_EAGER=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_TASK_EAGER_PROPAGATES=True, CELERY_RESULT_BACKEND='cache', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, # Bump the ES client timeout for slower environments (like Travis CI) SEARCH_CLIENT_CONFIG={'timeout': 30, 'max_retries': 5}, TESTING=True, OAUTH2SERVER_CLIENT_ID_SALT_LEN=64, OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60, OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60, STATS_MQ_EXCHANGE=Exchange( 'test_events', type='direct', delivery_mode='transient', # in-memory queue durable=True, ), SECRET_KEY='asecretkey', SERVER_NAME='localhost', STATS_QUERIES={}, STATS_EVENTS=events_config, STATS_AGGREGATIONS=aggregations_config, )) FlaskCeleryExt(app_) InvenioAccounts(app_) InvenioAccountsREST(app_) InvenioDB(app_) InvenioRecords(app_) InvenioFilesREST(app_) InvenioPIDStore(app_) InvenioCache(app_) InvenioQueues(app_) InvenioOAuth2Server(app_) InvenioOAuth2ServerREST(app_) InvenioSearch(app_, entry_point_group=None) 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( SECRET_KEY='CHANGE_ME', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, ) FlaskCLI(app_) InvenioDB(app_) InvenioRecords(app_) InvenioRecordsREST(app_) InvenioFilesREST(app_) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
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')
def base_app(): """Flask application fixture without InvenioStats.""" from invenio_stats.config import STATS_EVENTS app_ = Flask('testapp') stats_events = {'file-download': deepcopy(STATS_EVENTS['file-download'])} stats_events.update({'event_{}'.format(idx): {} for idx in range(5)}) app_.config.update( dict( CELERY_ALWAYS_EAGER=True, CELERY_TASK_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_TASK_EAGER_PROPAGATES=True, CELERY_RESULT_BACKEND='cache', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, STATS_MQ_EXCHANGE=Exchange( 'test_events', type='direct', delivery_mode='transient', # in-memory queue durable=True, ), STATS_EVENTS=stats_events, STATS_AGGREGATIONS=['file-download-agg'])) FlaskCeleryExt(app_) InvenioDB(app_) InvenioRecords(app_) InvenioRecordsUI(app_) InvenioPIDStore(app_) InvenioQueues(app_) InvenioFilesREST(app_) InvenioSearch(app_, entry_point_group=None) with app_.app_context(): yield app_
InvenioTheme(app) InvenioJSONSchemas(app) InvenioAccounts(app) InvenioRecords(app) InvenioRecordsUI(app) search = InvenioSearch(app) # search.register_mappings('testrecords', 'data') InvenioSearchUI(app) InvenioREST(app) InvenioIndexer(app) InvenioPIDStore(app) InvenioAdmin(app) InvenioOAuth2Server(app) InvenioRecordsREST(app) InvenioFilesREST(app) assets = InvenioAssets(app) assets.env.register('invenio_search_ui_search_js', js) InvenioDeposit(app) InvenioDepositREST(app) app.register_blueprint(accounts_blueprint) app.register_blueprint(settings_blueprint) app.register_blueprint(server_blueprint) @app.cli.group() def fixtures():
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_APP_CREDENTIALS=dict( consumer_key='changeme', consumer_secret='changeme', ), GITHUB_PID_FETCHER='doi_fetcher', LOGIN_DISABLED=False, OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', OAUTHCLIENT_REMOTE_APPS=dict(github=REMOTE_APP, ), SECRET_KEY='test_key', SERVER_NAME='testserver', SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], TESTING=True, WTF_CSRF_ENABLED=False, ) app_.config['OAUTHCLIENT_REMOTE_APPS']['github']['params'][ 'request_token_params'][ 'scope'] = 'user:email,admin:repo_hook,read:org' app_.url_map.converters['pid'] = PIDConverter celeryext = FlaskCeleryExt(app_) Babel(app_) Mail(app_) Menu(app_) Breadcrumbs(app_) InvenioAssets(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) InvenioFormatter(app_) from .helpers import doi_fetcher pidstore = InvenioPIDStore(app_) pidstore.register_fetcher('doi_fetcher', doi_fetcher) InvenioJSONSchemas(app_) InvenioRecords(app_) InvenioSearch(app_) InvenioIndexer(app_) InvenioFilesREST(app_) InvenioRecordsREST(app_) InvenioDepositREST(app_) InvenioWebhooks(app_) celeryext.celery.flask_app = app_ # Make sure both apps are the same! app_.register_blueprint(webhooks_blueprint) InvenioGitHub(app_) app_.register_blueprint(github_blueprint) app_.register_blueprint(github_badge_blueprint) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
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)
def base_app(app_config): """Flask application fixture.""" instance_path = os.path.join(sys.prefix, 'var', 'test-instance') # empty the instance path if os.path.exists(instance_path): shutil.rmtree(instance_path) os.makedirs(instance_path) os.environ['INVENIO_INSTANCE_PATH'] = instance_path app_ = Flask('oarepo-s3-testapp', instance_path=instance_path) app_.config.update( TESTING=True, JSON_AS_ASCII=True, FILES_REST_PERMISSION_FACTORY=allow_all, SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:'), SERVER_NAME='localhost:5000', SECURITY_PASSWORD_SALT='TEST_SECURITY_PASSWORD_SALT', SECRET_KEY='TEST_SECRET_KEY', INVENIO_INSTANCE_PATH=instance_path, # SEARCH_INDEX_PREFIX='records-', RECORDS_REST_ENDPOINTS={}, SEARCH_INDEX_PREFIX='test-', FILES_REST_DEFAULT_STORAGE_CLASS='S', CELERY_ALWAYS_EAGER=True, JSONSCHEMAS_HOST='localhost:5000', SEARCH_ELASTIC_HOSTS=os.environ.get('SEARCH_ELASTIC_HOSTS', None) ) app_.config.update(**app_config) app.test_client_class = JsonClient Principal(app_) login_manager = LoginManager() login_manager.init_app(app_) login_manager.login_view = 'login' @login_manager.user_loader def basic_user_loader(user_id): user_obj = User.query.get(int(user_id)) return user_obj @app_.route('/test/login/<int:id>', methods=['GET', 'POST']) def test_login(id): print("test: logging user with id", id) response = make_response() user = User.query.get(id) print('User is', user) login_user(user) set_identity(user) return response @app_.route('/test/logout', methods=['GET', 'POST']) def test_logout(): print("test: logging out") response = make_response() logout_user() # Remove session keys set by Flask-Principal for key in ('identity.name', 'identity.auth_type'): session.pop(key, None) # Tell Flask-Principal the user is anonymous identity_changed.send(current_app._get_current_object(), identity=AnonymousIdentity()) return response from oarepo_s3 import config # noqa InvenioAccess(app_) InvenioDB(app_) InvenioFilesREST(app_) InvenioS3(app_) InvenioIndexer(app_) InvenioSearch(app_) RecordsDraft(app_) OARepoS3(app_) return app_