def test_init(): """Test extension initialization.""" app = Flask('testapp') app.config.update( ACCOUNTS_USE_CELERY=False, SECRET_KEY="test_key", ) Babel(app) Mail(app) Menu(app) InvenioDB(app) InvenioAccounts(app) ext = InvenioUserProfiles(app) assert 'invenio-userprofiles' in app.extensions app = Flask('testapp') app.config.update( ACCOUNTS_USE_CELERY=False, SECRET_KEY="test_key", ) Babel(app) Mail(app) Menu(app) InvenioDB(app) InvenioAccounts(app) ext = InvenioUserProfiles() assert 'invenio-userprofiles' not in app.extensions ext.init_app(app) assert 'invenio-userprofiles' in app.extensions
def base_app(): """Flask application fixture.""" instance_path = tempfile.mkdtemp() base_app = Flask(__name__, instance_path=instance_path) base_app.config.update( ACCOUNTS_USE_CELERY=False, LOGIN_DISABLED=False, SECRET_KEY='testing_key', SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), TEST_USER_EMAIL='*****@*****.**', TEST_USER_PASSWORD='******', TESTING=True, WTF_CSRF_ENABLED=False, ) Babel(base_app) Mail(base_app) Menu(base_app) InvenioDB(base_app) InvenioAccounts(base_app) base_app.register_blueprint(accounts_blueprint) 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() yield base_app with base_app.app_context(): drop_database(str(db.engine.url)) shutil.rmtree(instance_path)
def _app_factory(config=None): """Application factory.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( ACCOUNTS_USE_CELERY=False, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SECURITY_CONFIRM_EMAIL_WITHIN="2 seconds", SECURITY_RESET_PASSWORD_WITHIN="2 seconds", SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SERVER_NAME='example.com', TESTING=True, WTF_CSRF_ENABLED=False, ) # Set key value session store to use Redis when running on TravisCI. if os.environ.get('CI', 'false') == 'true': app.config.update( ACCOUNTS_SESSION_REDIS_URL='redis://localhost:6379/0', ) app.config.update(config or {}) Menu(app) Babel(app) Mail(app) InvenioDB(app) return app
def _app_factory(config=None): """Application factory.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( ACCOUNTS_USE_CELERY=False, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SERVER_NAME='example.com', TESTING=True, WTF_CSRF_ENABLED=False, ) app.config.update(config or {}) Menu(app) Babel(app) Mail(app) InvenioDB(app) return app
def init_app(self, app): """Flask application initialization.""" self.init_config(app) Menu(app=app) @app.teardown_appcontext def shutdown_reana_db_session(response_or_exc): """Close session on app teardown.""" from reana_db.database import Session as reana_db_session from invenio_db import db as invenio_db reana_db_session.remove() invenio_db.session.remove() return response_or_exc @app.before_first_request def connect_signals(): """Connect OAuthClient signals.""" from invenio_oauthclient.signals import account_info_received from flask_security.signals import user_registered from .utils import ( _create_and_associate_local_user, _create_and_associate_oauth_user, ) account_info_received.connect(_create_and_associate_oauth_user) user_registered.connect(_create_and_associate_local_user)
def test_dynamic_list_constructor(self): bar = ['Item 1', 'Item 2', 'Item 3'] def get_menu_items(): return bar @register_menu(self.app, 'foo', 'foo', dynamic_list_constructor=get_menu_items) @self.app.route('/') def foo(): return 'foo' @register_menu(self.app, 'other', 'Other') @self.app.route('/other') def other(): return 'other' Menu(self.app) with self.app.test_client() as c: c.get('/') self.assertEquals(current_menu.submenu('foo').dynamic_list, bar) self.assertEquals( current_menu.submenu('other').dynamic_list, [current_menu.submenu('other')])
def init_app(app): app.config.update( DB_VERSIONING=True, 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)
def test_blueprint(self): Menu(self.app) blueprint = Blueprint('foo', 'foo', url_prefix="/foo") @self.app.route('/test') @register_menu(self.app, '.', 'Test') def test(): return 'test' @blueprint.route('/bar') @register_menu(blueprint, 'bar', 'Foo Bar') def bar(): return 'bar' self.app.register_blueprint(blueprint) with self.app.test_client() as c: c.get('/test') assert request.endpoint == 'test' assert current_menu.text == 'Test' with self.app.test_client() as c: c.get('/foo/bar') self.assertEqual(current_menu.submenu('bar').text, 'Foo Bar') self.assertTrue(current_menu.submenu('bar').active)
def test_create_menu_first(self): from flask_menu import Menu menu = Menu(self.app) entry = self.app.extensions['menu'] # it must reuse existing menu extension. Breadcrumbs(self.app, init_menu=False) assert entry == self.app.extensions['menu']
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( # HTTPretty doesn't play well with Redis. # See gabrielfalcao/HTTPretty#110 CACHE_TYPE='simple', CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND='memory', CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND='cache', GITHUB_SHIELDSIO_BASE_URL='http://example.org/badge/', GITHUB_APP_CREDENTIALS=dict( consumer_key='changeme', consumer_secret='changeme', ), LOGIN_DISABLED=False, OAUTHLIB_INSECURE_TRANSPORT=True, OAUTH2_CACHE_TYPE='simple', OAUTHCLIENT_REMOTE_APPS=dict( github=REMOTE_APP, ), SECRET_KEY='test_key', SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SECURITY_PASSWORD_HASH='plaintext', SECURITY_PASSWORD_SCHEMES=['plaintext'], TESTING=True, WTF_CSRF_ENABLED=False, ) app.url_map.converters['pid'] = PIDConverter FlaskCLI(app) celeryext = FlaskCeleryExt(app) celeryext.celery.flask_app = app # Make sure both apps are the same! Babel(app) Mail(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioOAuthClient(app) app.register_blueprint(oauthclient_blueprint) InvenioOAuth2Server(app) app.register_blueprint(server_blueprint) app.register_blueprint(settings_blueprint) InvenioPIDStore(app) InvenioRecordsREST(app) InvenioDepositREST(app) InvenioWebhooks(app) app.register_blueprint(webhooks_blueprint) InvenioGitHub(app) with app.app_context(): yield app shutil.rmtree(instance_path)
def app(request): """Flask application fixture.""" app = Flask('testapp') app.config.update( TESTING=True, SQLALCHEMY_DATABASE_URI=os.getenv('SQLALCHEMY_DATABASE_URI', 'sqlite://'), SERVER_NAME='localhost', ) Babel(app) Menu(app) Breadcrumbs(app) InvenioDB(app) InvenioCollections(app) InvenioRecords(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() def teardown(): with app.app_context(): if str(db.engine.url) != 'sqlite://': drop_database(str(db.engine.url)) request.addfinalizer(teardown) with app.app_context(): db.create_all() return app
def base_app(): """Flask application fixture.""" app_ = Flask('testapp') app_.config.update( TESTING=True, # Celery 3 CELERY_ALWAYS_EAGER=True, CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, # Celery 4 CELERY_TASK_ALWAYS_EAGER=True, CELERY_TASK_EAGER_PROPAGATES=True, SQLALCHEMY_TRACK_MODIFICATIONS=True, SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///:memory:'), WTF_CSRF_ENABLED=False, SERVER_NAME='invenio.org', SECURITY_PASSWORD_SALT='TEST_SECURITY_PASSWORD_SALT', SECRET_KEY='TEST_SECRET_KEY', FILES_REST_MULTIPART_CHUNKSIZE_MIN=2, FILES_REST_MULTIPART_CHUNKSIZE_MAX=20, FILES_REST_MULTIPART_MAX_PARTS=100, FILES_REST_TASK_WAIT_INTERVAL=0.1, FILES_REST_TASK_WAIT_MAX_SECONDS=1, ) FlaskCeleryExt(app_) InvenioDB(app_) Babel(app_) Menu(app_) return app_
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
def _app_factory(config=None): """Application factory.""" # TODO use the fixtures from pytest-invenio instead instance_path = tempfile.mkdtemp() app = Flask("testapp", instance_path=instance_path) icons = { "semantic-ui": { "key": "key icon", "link": "linkify icon", "shield": "shield alternate icon", "user": "******", "codepen": "codepen icon", "cogs": "cogs icon", "*": "{} icon", }, "bootstrap3": { "key": "fa fa-key fa-fw", "link": "fa fa-link fa-fw", "shield": "fa fa-shield fa-fw", "user": "******", "codepen": "fa fa-codepen fa-fw", "cogs": "fa fa-cogs fa-fw", "*": "fa fa-{} fa-fw", }, } app.config.update( ACCOUNTS_USE_CELERY=False, ACCOUNTS_LOCAL_LOGIN_ENABLED=True, APP_THEME=["semantic-ui"], THEME_ICONS=icons, CELERY_TASK_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", CELERY_TASK_EAGER_PROPAGATES=True, CELERY_RESULT_BACKEND="cache", LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SECURITY_CONFIRM_EMAIL_WITHIN="2 seconds", SECURITY_RESET_PASSWORD_WITHIN="2 seconds", SECURITY_CHANGEABLE=True, SECURITY_RECOVERABLE=True, SECURITY_REGISTERABLE=True, SQLALCHEMY_DATABASE_URI=os.environ.get("SQLALCHEMY_DATABASE_URI", "sqlite:///test.db"), SERVER_NAME="example.com", TESTING=True, WTF_CSRF_ENABLED=False, ) app.config.update(config or {}) Menu(app) Babel(app) Mail(app) InvenioDB(app) InvenioI18N(app) return app
def test_simple_app(self): Menu(self.app) @self.app.route('/test') @register_menu(self.app, '.', 'Test') def test(): return 'test' @self.app.route('/level2') @register_menu(self.app, 'level2', 'Level 2') def level2(): return 'level2' @self.app.route('/level3') @register_menu(self.app, 'level2.level3', 'Level 3', order=2) def level3(): return 'level3' @self.app.route('/level3B') @register_menu(self.app, 'level2.level3B', 'Level 3B', order=1) def level3B(): return 'level3B' with self.app.test_client() as c: c.get('/test') assert request.endpoint == 'test' assert current_menu.url == '/test' assert current_menu.text == 'Test' assert current_menu.active self.assertEqual(current_menu.submenu('level2').text, 'Level 2') assert not current_menu.submenu('level2').active assert current_menu.submenu('missing', auto_create=False) is None assert len(current_menu.list_path('.', '.level2.level3')) == 3 assert current_menu.list_path('.', 'missing') is None assert current_menu.list_path('missing', '.level2.level3') is None assert current_menu.list_path('level2.level3B', 'level2.level3') is None with self.app.test_client() as c: c.get('/level2') assert current_menu.submenu('level2').active with self.app.test_client() as c: c.get('/level3') assert current_menu.submenu('.level2.level3').active assert current_menu.submenu('level2.level3').active assert not current_menu.has_active_child(recursive=False) assert current_menu.has_active_child() assert current_menu.submenu('level2').has_active_child( recursive=False) assert current_menu.submenu('level2').has_active_child() item_2 = current_menu.submenu('level2.level3') item_1 = current_menu.submenu('level2.level3B') assert item_1.order < item_2.order assert item_1 == current_menu.submenu('level2').children[0] assert item_2 == current_menu.submenu('level2').children[1]
def test_classy_endpoint(self): from flask_classy import FlaskView class MyEndpoint(FlaskView): route_base = '/' def index(self): return '' @classy_menu_item('page1', 'Page 1') def page1(self): return '' @classy_menu_item('page2', 'Page 2') def page2(self): return '' @classy_menu_item('page3', 'Page 3') @classy_menu_item('page31', 'Page 3.1') def page3(self): return '' Menu(self.app) MyEndpoint.register(self.app) register_flaskview(self.app, MyEndpoint) data = { '/page1/': { 'page1': True, 'page2': False, 'page3': False, 'page31': False }, '/page2/': { 'page1': False, 'page2': True, 'page3': False, 'page31': False }, '/page3/': { 'page1': False, 'page2': False, 'page3': True, 'page31': True } } for (path, v) in data.items(): with self.app.test_client() as c: c.get(path) for (endpoint, active_should) in v.items(): active_is = current_menu.submenu(endpoint).active self.assertEqual( active_is, active_should, 'path="{0}" submenu_by_endpoint="{1}" ' 'active_is={2} active_should={3}'.format( path, endpoint, active_is, active_should))
def _app_factory(config=None): """Application factory.""" # TODO use the fixtures from pytest-invenio instead instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) icons = { 'semantic-ui': { 'key': 'key icon', 'link': 'linkify icon', 'shield': 'shield alternate icon', 'user': '******', 'codepen': 'codepen icon', 'cogs': 'cogs icon', '*': '{} icon' }, 'bootstrap3': { 'key': 'fa fa-key fa-fw', 'link': 'fa fa-link fa-fw', 'shield': 'fa fa-shield fa-fw', 'user': '******', 'codepen': 'fa fa-codepen fa-fw', 'cogs': 'fa fa-cogs fa-fw', '*': 'fa fa-{} fa-fw', } } app.config.update( ACCOUNTS_USE_CELERY=False, ACCOUNTS_LOCAL_LOGIN_ENABLED=True, APP_THEME=["semantic-ui"], THEME_ICONS=icons, CELERY_ALWAYS_EAGER=True, CELERY_CACHE_BACKEND="memory", CELERY_EAGER_PROPAGATES_EXCEPTIONS=True, CELERY_RESULT_BACKEND="cache", LOGIN_DISABLED=False, MAIL_SUPPRESS_SEND=True, SECRET_KEY="CHANGE_ME", SECURITY_PASSWORD_SALT="CHANGE_ME_ALSO", SECURITY_CONFIRM_EMAIL_WITHIN="2 seconds", SECURITY_RESET_PASSWORD_WITHIN="2 seconds", SECURITY_CHANGEABLE=True, SECURITY_RECOVERABLE=True, SECURITY_REGISTERABLE=True, SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SERVER_NAME='example.com', TESTING=True, WTF_CSRF_ENABLED=False, ) app.config.update(config or {}) Menu(app) Babel(app) Mail(app) InvenioDB(app) return app
def create_app(config, mode): """ create_app::Flask.Config->binder.Mode->Flask Creates a Flask app and registers blueprints if any. config is the path to a configuration file. If the path to the config file is a relative path, then the instance folder of the app is searched. If the config file is located outside the app's instance folder, an absolute path can be used for it. """ app = Flask('binder', instance_relative_config=True) # Add bootstrap functionality Bootstrap(app) # init flask_menu Menu(app) # Apply configuration options config_app(mode, config, app) # initialize and configure the db for use in request handlers config_db(db, app) # flask login setup_login_manager(app) # init logging Logging(app) # app error handlers @app.errorhandler(404) def error_handler(exc): logging.error(exc) return render_template('error_404.html'), 404 @app.errorhandler(OperationalError) def create_db_if_not_exists(exc): logging.error(exc) db = g.get('db', None) if db: db.create_all() return redirect('/') @app.route('/favicon.ico') def send_favicon(): return send_from_directory(os.path.join(app.root_path, 'static'), 'img/favicon.ico', mimetype='image/vnd.microsoft.icon') # Register app blueprints for blueprint in BLUEPRINTS: app.register_blueprint(blueprint) return app
def __init__(self, app=None, **kwargs): """Extension initialization.""" self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() self.weblinks = self.init_weblinks_dictionary() if app: self.init_app(app, **kwargs) self.setup_app(app)
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='helpers:' 'only_authenticated_users', ) Menu(app) InvenioRecordsUI(app) accounts = InvenioAccounts(app) app.register_blueprint(accounts_blueprint) InvenioAccess(app) setup_record_fixture(app) # Create admin with app.app_context(): 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') 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 anonymous with app.test_client() as client: res = client.get(record_url) res.status_code == 403
def test_kwargs_override(self): """Test if optional arguments cannot be overriden.""" Menu(self.app) @self.app.route('/test') @register_menu(self.app, 'test', 'Test', url='/test') def test(): pass with self.app.test_client() as c: self.assertRaises(RuntimeError, c.get, '/test')
def __init__(self, app=None, **kwargs): r"""Extension initialization. :param app: An instance of :class:`~flask.Flask`. :param \**kwargs: Keyword arguments are passed to ``init_app`` method. """ self.menu_ext = Menu() self.menu = None self.breadcrumbs = Breadcrumbs() if app: self.init_app(app, **kwargs)
def create_app(config=Config): app = Flask(__name__) app.config.from_object(config) app.secret_key = os.urandom(24) app.register_blueprint(main) Menu(app=app) db.init_app(app) login_manager.init_app(app) login_manager.login_view = "main.login" login_manager.login_message_category = "warning" mail.init_app(app) return 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_kwargs(self): """Test optional arguments.""" Menu(self.app) count = 5 @self.app.route('/test') @register_menu(self.app, 'test', 'Test', count=count) def test(): return 'count' with self.app.test_client() as c: c.get('/test') assert count == current_menu.submenu('test').count
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 init_app(self, app): """Flask application initialization.""" self.init_config(app) Menu(app=app) @app.before_first_request def connect_signals(): """Connect OAuthClient signals.""" from invenio_oauthclient.signals import account_info_received from .utils import _create_and_associate_reana_user account_info_received.connect( _create_and_associate_reana_user )
def test_active_checks_segment_not_prefix(self): Menu(self.app) @register_menu(self.app, 'object', 'Object') @self.app.route('/object') def object(): return 'object' @register_menu(self.app, 'objects', 'Objects') @self.app.route('/objects') def objects(): return 'objects' with self.app.test_client() as c: c.get('/objects') assert current_menu.submenu('object').active is not True
def test_classy_endpoint_with_args(self): from flask_classy import FlaskView, route class MyEndpoint(FlaskView): route_base = '/' @classy_menu_item('withid.page1', 'Page 1') @route('/<int:id>/page1') def page1(self, id): return 'page1' @classy_menu_item('withid.page2', 'Page 2') @route('/<int:id>/page2') def page2(self, id): return 'page2' Menu(self.app) MyEndpoint.register(self.app) register_flaskview(self.app, MyEndpoint) data = { '/1/page1': { 'withid.page1': True, 'withid.page2': False, }, '/1/page2': { 'withid.page1': False, 'withid.page2': True, } } for (path, v) in data.items(): with self.app.test_client() as c: c.get(path) for (endpoint, active_should) in v.items(): active_is = current_menu.submenu(endpoint).active self.assertEqual( active_is, active_should, 'path="{0}" submenu_by_endpoint="{1}" ' 'active_is={2} active_should={3}'.format( path, endpoint, active_is, active_should ) )
def test_external_url(self): """Test that external_url works, and is not overriding endpoint.""" Menu(self.app) menu = self.app.extensions['menu'] url = 'https://python.org' item1 = menu.submenu('menuitem1') # Do not allow endpoint and external_url at the same time. self.assertRaises(TypeError, item1.register, endpoint='test', text='Test', external_url=url) item1.register(text='Test', external_url=url) assert menu.submenu('menuitem1').url == url