def test_init_rest(): """Test REST extension initialization.""" app = Flask('testapp') ext = InvenioOAuth2ServerREST(app) assert verify_oauth_token_and_set_current_user in \ app.before_request_funcs[None] app = Flask('testapp') ext = InvenioOAuth2ServerREST() assert verify_oauth_token_and_set_current_user not in \ app.before_request_funcs.get(None, []) ext.init_app(app) assert verify_oauth_token_and_set_current_user in \ app.before_request_funcs[None]
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() def init_app(app): app.config.update( LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, OAUTH2_CACHE_TYPE='simple', OAUTHLIB_INSECURE_TRANSPORT=True, SECRET_KEY='CHANGE_ME', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO', SECURITY_PASSWORD_SCHEMES=['plaintext'], SQLALCHEMY_DATABASE_URI=os.getenv( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///' + os.path.join(instance_path, 'test.db')), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, WTF_CSRF_ENABLED=False, ) Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioOAuth2Server(app) api_app = Flask('testapiapp', instance_path=instance_path) api_app.config.update(APPLICATION_ROOT='/api', ACCOUNTS_REGISTER_BLUEPRINT=True) init_app(api_app) InvenioAccountsREST(api_app) InvenioOAuth2ServerREST(api_app) app = Flask('testapp', instance_path=instance_path) init_app(app) InvenioAccountsUI(app) app.register_blueprint(accounts_blueprint) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) 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() def teardown(): with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) shutil.rmtree(instance_path) request.addfinalizer(teardown) return 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 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(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 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 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 test_init_rest_with_oauthlib_monkeypatch(): """Test REST OAuthlib monkeypatching.""" app = Flask('testapp') from oauthlib.common import urlencoded assert '^' not in urlencoded old_urlencoded = set(urlencoded) app.config['OAUTH2SERVER_ALLOWED_URLENCODE_CHARACTERS'] = '^' with pytest.warns(RuntimeWarning): InvenioOAuth2ServerREST(app) assert verify_oauth_token_and_set_current_user in \ app.before_request_funcs[None] from oauthlib.common import urlencoded assert old_urlencoded != urlencoded assert '^' in urlencoded
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(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() def init_app(app_): app_.config.update( CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', JSONSCHEMAS_URL_SCHEME='http', SECRET_KEY='CHANGE_ME', SECURITY_PASSWORD_SALT='CHANGE_ME_ALSO', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_ECHO=False, TESTING=True, WTF_CSRF_ENABLED=False, DEPOSIT_SEARCH_API='/api/search', SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', ACCOUNTS_JWT_ENABLE=False, ) Babel(app_) FlaskCeleryExt(app_) Breadcrumbs(app_) OAuth2Provider(app_) InvenioDB(app_) InvenioAccounts(app_) InvenioAccess(app_) InvenioIndexer(app_) InvenioJSONSchemas(app_) InvenioOAuth2Server(app_) InvenioFilesREST(app_) InvenioPIDStore(app_) InvenioRecords(app_) search = InvenioSearch(app_) search.register_mappings('deposits', 'invenio_deposit.mappings') api_app = Flask('testapiapp', instance_path=instance_path) api_app.url_map.converters['pid'] = PIDConverter # initialize InvenioDeposit first in order to detect any invalid dependency InvenioDepositREST(api_app) init_app(api_app) InvenioREST(api_app) InvenioOAuth2ServerREST(api_app) InvenioRecordsREST(api_app) app = Flask('testapp', instance_path=instance_path) app.url_map.converters['pid'] = PIDConverter # initialize InvenioDeposit first in order to detect any invalid dependency InvenioDeposit(app) init_app(app) app.register_blueprint(accounts_blueprint) app.register_blueprint(oauth2server_settings_blueprint) InvenioAssets(app) InvenioSearchUI(app) InvenioRecordsUI(app) app.register_blueprint(records_ui_bp(app)) app.register_blueprint(records_rest_bp(app)) app.wsgi_app = DispatcherMiddleware(app.wsgi_app, { '/api': api_app.wsgi_app }) with app.app_context(): if str(db.engine.url) != 'sqlite://' and \ not database_exists(str(db.engine.url)): create_database(str(db.engine.url)) db.create_all() yield app with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) shutil.rmtree(instance_path)
I18N_LANGUAGES=[ ('de', 'German'), ('es', 'Spanish'), ('fr', 'French'), ('it', 'Italian'), ], ) InvenioAssets(app) InvenioTheme(app) InvenioI18N(app) Breadcrumbs(app) InvenioDB(app) InvenioAdmin(app) InvenioAccess(app) OAuth2Provider(app) InvenioOAuth2ServerREST(app) accounts = InvenioAccountsUI(app) InvenioAccountsREST(app) app.register_blueprint(blueprint_account) InvenioOAuth2Server(app) # Register blueprints app.register_blueprint(settings_blueprint) app.register_blueprint(server_blueprint) app.register_blueprint(blueprint_admin_ui) with app.app_context(): # Register a test scope current_oauth2server.register_scope(
def app(request, accounts_rest_permission_factory): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask(__name__, instance_path=instance_path) InvenioAccess(app) InvenioAccounts(app) InvenioAccountsREST(app) InvenioOAuth2Server(app) InvenioOAuth2ServerREST(app) InvenioDB(app) Babel(app) Mail(app) Menu(app) Breadcrumbs(app) # this is done mainly for coverage so that tests are run with and without # userprofiles being loaded in the app if not hasattr(request, 'param') or \ 'with_profiles' not in request.param or \ request.param['with_profiles']: # tests without invenio-userprofiles being installed at all try: from invenio_userprofiles import InvenioUserProfiles InvenioUserProfiles(app) except ImportError: pass read_role = accounts_rest_permission_factory['read_role'] update_role = accounts_rest_permission_factory['update_role'] delete_role = accounts_rest_permission_factory['delete_role'] read_roles = accounts_rest_permission_factory['read_roles_list'] create_role = accounts_rest_permission_factory['create_role'] assign_role = accounts_rest_permission_factory['assign_role'] unassign_role = accounts_rest_permission_factory['unassign_role'] role_users = accounts_rest_permission_factory['read_role_users_list'] user_roles = accounts_rest_permission_factory['read_user_roles_list'] read_user_prop = accounts_rest_permission_factory['read_user_properties'] mod_user_prop = accounts_rest_permission_factory['update_user_properties'] read_users = accounts_rest_permission_factory['read_users_list'] app.config.update( ACCOUNTS_REST_READ_ROLE_PERMISSION_FACTORY=read_role, ACCOUNTS_REST_UPDATE_ROLE_PERMISSION_FACTORY=update_role, ACCOUNTS_REST_DELETE_ROLE_PERMISSION_FACTORY=delete_role, ACCOUNTS_REST_READ_ROLES_LIST_PERMISSION_FACTORY=read_roles, ACCOUNTS_REST_CREATE_ROLE_PERMISSION_FACTORY=create_role, ACCOUNTS_REST_ASSIGN_ROLE_PERMISSION_FACTORY=assign_role, ACCOUNTS_REST_UNASSIGN_ROLE_PERMISSION_FACTORY=unassign_role, ACCOUNTS_REST_READ_ROLE_USERS_LIST_PERMISSION_FACTORY=role_users, ACCOUNTS_REST_READ_USER_ROLES_LIST_PERMISSION_FACTORY=user_roles, ACCOUNTS_REST_READ_USER_PROPERTIES_PERMISSION_FACTORY=read_user_prop, ACCOUNTS_REST_UPDATE_USER_PROPERTIES_PERMISSION_FACTORY=mod_user_prop, ACCOUNTS_REST_READ_USERS_LIST_PERMISSION_FACTORY=read_users, OAUTH2SERVER_CLIENT_ID_SALT_LEN=40, OAUTH2SERVER_CLIENT_SECRET_SALT_LEN=60, OAUTH2SERVER_TOKEN_PERSONAL_SALT_LEN=60, SECRET_KEY='changeme', TESTING=True, SERVER_NAME='localhost', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SECURITY_SEND_PASSWORD_CHANGE_EMAIL=False) from invenio_oauth2server.views.server import blueprint with app.app_context(): db_.create_all() yield app with app.app_context(): db_.drop_all()