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_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 test_configuration(base_app): """Test configuration.""" app = base_app app.config['ACCOUNTS_USE_CELERY'] = 'deadbeef' InvenioAccounts(app) assert 'deadbeef' == app.config['ACCOUNTS_USE_CELERY']
def app(request): """Flask application fixture.""" # Set temporary instance path for sqlite instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update(SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), TESTING=True, SECRET_KEY='SECRET_KEY', SQLALCHEMY_TRACK_MODIFICATIONS=False, JSONSCHEMAS_ENDPOINT='/schema', JSONSCHEMAS_HOST='ils.test.rero.ch', RECORDS_UI_ENDPOINTS={ "doc": { "pid_type": "doc", "route": "/documents/<pid_value>", "template": "reroils_data/detailed_view_documents_items.html" } }) InvenioDB(app) InvenioPIDStore(app) InvenioRecords(app) InvenioAccounts(app) REROILSDATA(app) InvenioAccess(app) InvenioJSONSchemas(app) InvenioRecordsUI(app) Menu(app) Babel(app) app.register_blueprint(item_blueprint) @app.route('/test/login') def login(): from flask_security import login_user from flask import request as flask_request role = flask_request.args.get('role') if role: datastore.create_role(name=role) datastore.add_role_to_user(user, role) datastore.commit() login_user(user) return "Logged In" @app.route('/test/login') def logout(): from flask_security import logout_user logout_user() return "Logged Out" from invenio_db import db as db_ with app.app_context(): if not database_exists(str(db_.engine.url)): create_database(str(db_.engine.url)) db_.create_all() security = LocalProxy(lambda: app.extensions['security']) datastore = LocalProxy(lambda: security.datastore) user = datastore.create_user(email='*****@*****.**', active=True, password=hash_password('aafaf4as5fa')) yield app # Teardown instance path. db_.session.remove() db_.drop_all() shutil.rmtree(instance_path)
def app(): instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( JSONSCHEMAS_HOST="nusl.cz", SQLALCHEMY_TRACK_MODIFICATIONS=True, SERVER_NAME='127.0.0.1:5000', INVENIO_INSTANCE_PATH=instance_path, DEBUG=True, # in tests, api is not on /api but directly in the root PIDSTORE_RECID_FIELD='pid', FLASK_TAXONOMIES_URL_PREFIX='/2.0/taxonomies/', # RECORDS_REST_ENDPOINTS=RECORDS_REST_ENDPOINTS, CELERY_BROKER_URL='amqp://*****:*****@localhost:5672//', CELERY_TASK_ALWAYS_EAGER=True, CELERY_RESULT_BACKEND='cache', CELERY_CACHE_BACKEND='memory', CELERY_TASK_EAGER_PROPAGATES=True, SUPPORTED_LANGUAGES=["cs", "en"], OAREPO_COMMUNITIES_ENDPOINTS=[], ELASTICSEARCH_DEFAULT_LANGUAGE_TEMPLATE={ "type": "text", "fields": { "keywords": { "type": "keyword" } } }) app.secret_key = 'changeme' print(os.environ.get("INVENIO_INSTANCE_PATH")) InvenioDB(app) OarepoTaxonomies(app) OARepoReferences(app) InvenioAccounts(app) InvenioAccess(app) Principal(app) InvenioJSONSchemas(app) InvenioSearch(app) InvenioIndexer(app) OARepoMappingIncludesExt(app) InvenioRecords(app) InvenioRecordsREST(app) InvenioCelery(app) NRNresults(app) InvenioPIDStore(app) OARepoValidate(app) OARepoCommunities(app) # Invenio Records Draft initialization RecordsDraft(app) app.url_map.converters['pid'] = PIDConverter app.url_map.converters['commpid'] = CommunityPIDConverter # Celery print(app.config["CELERY_BROKER_URL"]) 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.register_blueprint(create_blueprint_from_app(app)) @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) login_user(user) set_identity(user) return response # app.extensions['invenio-search'].mappings["test"] = mapping # app.extensions["invenio-jsonschemas"].schemas["test"] = schema app_loaded.send(app, app=app) with app.app_context(): # app.register_blueprint(taxonomies_blueprint) print(app.url_map) yield app shutil.rmtree(instance_path)
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( cern=CERN_REMOTE_APP, orcid=ORCID_REMOTE_APP, github=GITHUB_REMOTE_APP, globus=GLOBUS_REMOTE_APP, ), OAUTHCLIENT_REST_REMOTE_APPS=dict( cern=CERN_REMOTE_REST_APP, orcid=ORCID_REMOTE_REST_APP, github=GITHUB_REMOTE_REST_APP, globus=GLOBUS_REMOTE_REST_APP, ), OAUTHCLIENT_STATE_EXPIRES=300, GITHUB_APP_CREDENTIALS=dict( consumer_key='github_key_changeme', consumer_secret='github_secret_changeme', ), ORCID_APP_CREDENTIALS=dict( consumer_key='orcid_key_changeme', consumer_secret='orcid_secret_changeme', ), CERN_APP_CREDENTIALS=dict( consumer_key='cern_key_changeme', consumer_secret='cern_secret_changeme', ), GLOBUS_APP_CREDENTIALS=dict( consumer_key='globus_key_changeme', consumer_secret='globus_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_DEPRECATED_PASSWORD_SCHEMES=[], SQLALCHEMY_TRACK_MODIFICATIONS=False, SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], APP_ALLOWED_HOSTS=['localhost'] ) 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 base_app(request): """Flask application fixture without OAuthClient initialized.""" # allow HTTP for keycloak tests, and create the KEYCLOAK_REMOTE_APP os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" base_url, realm = "http://localhost:8080", "test" helper = KeycloakSettingsHelper(title="Keycloak", description="", base_url=base_url, realm=realm) KEYCLOAK_REMOTE_APP = helper.remote_app instance_path = tempfile.mkdtemp() base_app = Flask('testapp') base_app.config.update( ACCOUNTS_LOCAL_LOGIN_ENABLED=True, TESTING=True, WTF_CSRF_ENABLED=False, LOGIN_DISABLED=False, CACHE_TYPE='simple', OAUTHCLIENT_SIGNUP_FORM=_create_registrationform, OAUTHCLIENT_REMOTE_APPS=dict( cern=CERN_REMOTE_APP, cern_openid=CERN_OPENID_REMOTE_APP, orcid=ORCID_REMOTE_APP, github=GITHUB_REMOTE_APP, globus=GLOBUS_REMOTE_APP, keycloak=KEYCLOAK_REMOTE_APP, ), OAUTHCLIENT_REST_REMOTE_APPS=dict( cern=CERN_REMOTE_REST_APP, cern_openid=CERN_OPENID_REMOTE_REST_APP, orcid=ORCID_REMOTE_REST_APP, github=GITHUB_REMOTE_REST_APP, globus=GLOBUS_REMOTE_REST_APP, ), OAUTHCLIENT_STATE_EXPIRES=300, GITHUB_APP_CREDENTIALS=dict( consumer_key='github_key_changeme', consumer_secret='github_secret_changeme', ), ORCID_APP_CREDENTIALS=dict( consumer_key='orcid_key_changeme', consumer_secret='orcid_secret_changeme', ), CERN_APP_CREDENTIALS=dict( consumer_key='cern_key_changeme', consumer_secret='cern_secret_changeme', ), CERN_APP_OPENID_CREDENTIALS=dict( consumer_key='cern_key_changeme', consumer_secret='cern_secret_changeme', ), GLOBUS_APP_CREDENTIALS=dict( consumer_key='globus_key_changeme', consumer_secret='globus_secret_changeme', ), TEST_APP_CREDENTIALS=dict( consumer_key='test_key_changeme', consumer_secret='test_secret_changeme', ), OAUTHCLIENT_KEYCLOAK_USER_INFO_URL=helper.user_info_url, OAUTHCLIENT_KEYCLOAK_REALM_URL=helper.realm_url, OAUTHCLIENT_KEYCLOAK_VERIFY_AUD=True, OAUTHCLIENT_KEYCLOAK_VERIFY_EXP=False, OAUTHCLIENT_KEYCLOAK_AUD="invenio", KEYCLOAK_APP_CREDENTIALS=dict( consumer_key="keycloak_key_changeme", consumer_secret="keycloak_secret_changeme", ), # use local memory mailbox EMAIL_BACKEND='flask_email.backends.locmem.Mail', SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), # Alembic runs all migrations in a single transaction, and in # oauthclient the useridentity table can be in state where it's created # and then deleted in the same transaction. On PostgreSQL which # supports transactional DDL therefore fails if we don't run each # migration in its own migration. ALEMBIC_CONTEXT={ 'transaction_per_migration': True, }, SERVER_NAME='localhost', DEBUG=False, SECRET_KEY='TEST', SECURITY_DEPRECATED_PASSWORD_SCHEMES=[], SQLALCHEMY_TRACK_MODIFICATIONS=False, SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], APP_ALLOWED_HOSTS=['localhost'], APP_THEME=['semantic-ui'], THEME_ICONS={'semantic-ui': dict(link='linkify icon')}) 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) db.engine.dispose() request.addfinalizer(teardown) base_app.test_request_context().push() return base_app
def test_admin(app): """Test flask-admin interace.""" InvenioAccounts(app) assert isinstance(role_adminview, dict) assert isinstance(user_adminview, dict) assert 'model' in role_adminview assert 'modelview' in role_adminview assert 'model' in user_adminview assert 'modelview' in user_adminview admin = Admin(app, name="Test") user_model = user_adminview.pop('model') user_view = user_adminview.pop('modelview') admin.add_view(user_view(user_model, db.session, **user_adminview)) # Test activation and deactivation with app.app_context(): # create user and save url for testing request_url = url_for("user.action_view") kwargs = dict(email="*****@*****.**", active=False, password=encrypt_password('aafaf4as5fa')) _datastore.create_user(**kwargs) _datastore.commit() with app.app_context(): with app.test_client() as client: inserted_id = _datastore.get_user('*****@*****.**').id res = client.post(request_url, data={ 'rowid': inserted_id, 'action': 'activate' }, follow_redirects=True) assert res.status_code == 200 res = client.post(request_url, data={ 'rowid': inserted_id, 'action': 'inactivate' }, follow_redirects=True) assert res.status_code == 200 pytest.raises(ValueError, client.post, request_url, data={ 'rowid': -42, 'action': 'inactivate' }, follow_redirects=True) pytest.raises(ValueError, client.post, request_url, data={ 'rowid': -42, 'action': 'activate' }, follow_redirects=True)
def test_permission(app): """Test permission control to records.""" app.config.update( WTF_CSRF_ENABLED=False, SECRET_KEY='CHANGEME', SECURITY_PASSWORD_SALT='CHANGEME', # conftest switches off permission checking, so re-enable it for this # app. RECORDS_UI_DEFAULT_PERMISSION_FACTORY='invenio_records.permissions' ':read_permission_factory') Menu(app) InvenioRecordsUI(app) accounts = InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioAccess(app) setup_record_fixture(app) # Create admin with app.app_context(): admin = accounts.datastore.create_user( email='*****@*****.**', password=encrypt_password('123456'), active=True, ) reader = accounts.datastore.create_user( email='*****@*****.**', password=encrypt_password('123456'), active=True, ) # Get record 1 r = Resolver(pid_type='recid', object_type='rec', getter=Record.get_record) dummy_pid, record = r.resolve('1') # Setup permissions for record 1 (grant 'admin', deny 'reader') db.session.add( ActionUsers(action=records_read_all.value, argument=str(record.id), user=admin)) db.session.add( ActionUsers(action=records_read_all.value, argument=str(record.id), user=reader, exclude=True)) db.session.commit() with app.test_request_context(): login_url = url_for('security.login') record_url = url_for('invenio_records_ui.recid', pid_value='1') # Access record 1 as admin with app.test_client() as client: res = client.get(record_url) assert res.status_code == 302 res = client.post(login_url, data={ 'email': '*****@*****.**', 'password': '******' }) assert res.status_code == 302 res = client.get(record_url) res.status_code == 200 # Access record 1 as reader with app.test_client() as client: res = client.post(login_url, data={ 'email': '*****@*****.**', 'password': '******' }) assert res.status_code == 302 res = client.get(record_url) res.status_code == 403
CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", MAIL_SUPPRESS_SEND=True, SECRET_KEY="1q2w3e4r5t!Q", SECURITY_PASSWORD_SALT="1q2w3e4r5t!Qw#E$R%T6", ) app.secret_key = 'ExampleApp' app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///instance/test.db') app.testing = True os.environ['CI'] = 'false' Babel(app) Menu(app) InvenioDB(app) InvenioAccounts(app=app, sessionstore=None) InvenioAdmin(app) app.register_blueprint(blueprint_accounts) console = InvenioLoggingConsole(app) fs = InvenioLoggingFS(app) WekoAccounts(app) app.app_context().push() @app.before_request def check_session_time(): current_app.logger.info('first check session timeout') if __name__ == '__main__': app.run(host='0.0.0.0', port=80, debug=True)
def app(): instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( JSONSCHEMAS_HOST="nusl.cz", SQLALCHEMY_TRACK_MODIFICATIONS=True, SERVER_NAME='127.0.0.1:5000', INVENIO_INSTANCE_PATH=instance_path, DEBUG=True, # SQLALCHEMY_ECHO=True, SUPPORTED_LANGUAGES=["cs", "en"], # SQLALCHEMY_DATABASE_URI='postgresql+psycopg2://oarepo:oarepo@localhost/oarepo', OAREPO_COMMUNITIES_ENDPOINTS=[], OAREPO_OAI_PROVIDERS={ "nusl": { "description": "NUŠL", "synchronizers": [{ "name": "marcxml", "oai_endpoint": "http://invenio.nusl.cz/oai2d/", "set": "global", "metadata_prefix": "marcxml", "unhandled_paths": [ '/leader', '/005', '/008', '020__/q', '/0248_', '/246__', '/340__', '/500__', '/502__/a', '/502__/b', '/502__/d', '/502__/g', '/506__', '/6530_', '/6557_', '/655_7', "/656_7/2", '/8560_', '/85642/z', '/8564_', '/909CO/p', '999c1', '/999C2', 'FFT_0' ], "default_endpoint": "common", }] }, }, # RECORDS_REST_ENDPOINTS=RECORDS_REST_ENDPOINTS, PIDSTORE_RECID_FIELD='pid') app.secret_key = 'changeme' InvenioDB(app) InvenioAccounts(app) InvenioAccess(app) Principal(app) InvenioJSONSchemas(app) InvenioSearch(app) InvenioIndexer(app) InvenioRecords(app) InvenioRecordsREST(app) InvenioPIDStore(app) app.url_map.converters['pid'] = PIDConverter app.url_map.converters['commpid'] = CommunityPIDConverter OarepoTaxonomies(app) OArepoOAIClient(app) OARepoValidate(app) RecordsDraft(app) # NRCommon(app) NRTheses(app) NRNresults(app) NREvents(app) app_loaded.send(app, app=app) with app.app_context(): yield app shutil.rmtree(instance_path)
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()
def app(mapping, schema): instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( JSONSCHEMAS_HOST="example.com", SQLALCHEMY_TRACK_MODIFICATIONS=True, SERVER_NAME='127.0.0.1:5000', INVENIO_INSTANCE_PATH=instance_path, DEBUG=True, # in tests, api is not on /api but directly in the root PIDSTORE_RECID_FIELD='pid', FLASK_TAXONOMIES_URL_PREFIX='/2.0/taxonomies/', RECORDS_REST_ENDPOINTS=RECORDS_REST_ENDPOINTS, CELERY_BROKER_URL='amqp://*****:*****@localhost:5672//', CELERY_TASK_ALWAYS_EAGER=True, CELERY_RESULT_BACKEND='cache', CELERY_CACHE_BACKEND='memory', CELERY_TASK_EAGER_PROPAGATES=True) app.secret_key = 'changeme' print(os.environ.get("INVENIO_INSTANCE_PATH")) InvenioDB(app) OarepoTaxonomies(app) OARepoReferences(app) InvenioAccounts(app) InvenioAccess(app) Principal(app) InvenioJSONSchemas(app) InvenioSearch(app) OARepoMappingIncludesExt(app) InvenioRecords(app) InvenioRecordsREST(app) InvenioCelery(app) OARepoValidate(app) # Celery print(app.config["CELERY_BROKER_URL"]) 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.register_blueprint(create_blueprint_from_app(app)) @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) login_user(user) set_identity(user) return response app.extensions['invenio-search'].mappings["test"] = mapping app.extensions["invenio-jsonschemas"].schemas["test"] = schema app_loaded.send(app, app=app) with app.app_context(): # app.register_blueprint(taxonomies_blueprint) yield app shutil.rmtree(instance_path)
'sqlite:///globus_app.db'), OAUTHCLIENT_REMOTE_APPS=dict(globus=globus.REMOTE_APP, ), GLOBUS_APP_CREDENTIALS=GLOBUS_APP_CREDENTIALS, DEBUG=True, SECRET_KEY='TEST', SQLALCHEMY_ECHO=False, SECURITY_PASSWORD_SALT='security-password-salt', MAIL_SUPPRESS_SEND=True, TESTING=True, USERPROFILES_EXTEND_SECURITY_FORMS=True, ) Babel(app) FlaskMenu(app) InvenioDB(app) InvenioAccounts(app) InvenioUserProfiles(app) FlaskOAuth(app) InvenioOAuthClient(app) InvenioMail(app) app.register_blueprint(blueprint_user) app.register_blueprint(blueprint_client) app.register_blueprint(blueprint_settings) app.register_blueprint(blueprint_userprofile_init) @app.route('/') def index(): """Homepage.""" return 'Home page (without any restrictions)'
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 test_configuration(base_app): """Test configuration.""" app = base_app app.config["ACCOUNTS_USE_CELERY"] = "deadbeef" InvenioAccounts(app) assert "deadbeef" == app.config["ACCOUNTS_USE_CELERY"]
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)