def test_init(): """Test extension initialization.""" app = Flask('testapp') ext = InvenioRecordsREST() assert 'invenio-records-rest' not in app.extensions ext.init_app(app) assert 'invenio-records-rest' in app.extensions
def test_init(): """Test extension initialization.""" app = Flask('testapp') app.config.update(SERVER_NAME='http://localhost:5000/') ext = InvenioRecordsREST() assert 'invenio-records-rest' not in app.extensions ext.init_app(app) assert 'invenio-records-rest' in app.extensions
def test_init(): """Test extension initialization.""" app = Flask('testapp') app.url_map.converters['pid'] = PIDConverter ext = InvenioRecordsREST() assert 'invenio-records-rest' not in app.extensions ext.init_app(app) assert 'invenio-records-rest' in app.extensions
def test_valid_put(app): """Test VALID record patch request (PATCH .../records/<record_id>).""" with app.app_context(): InvenioRecordsREST(app) # create the record using the internal API internal_record = Record.create(test_data) with app.test_client() as client: headers = [('Content-Type', 'application/json'), ('Accept', 'application/json')] res = client.put(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), data=json.dumps(test_data_patched), headers=headers) assert res.status_code == 200 # check that the returned record matches the given data response_data = json.loads(res.get_data(as_text=True)) assert response_data['data'] == test_data_patched # check that an internal record returned id and that it contains # the same data assert 'id' in response_data.keys() internal_record = Record.get_record(response_data['id']) assert internal_record == response_data['data'] # check that the returned self link returns the same data subtest_self_link(response_data, res.headers, client)
def test_records_rest(app, db, es, grants): """Test Records REST.""" app.config['RECORDS_REST_ENDPOINTS'] = OPENAIRE_REST_ENDPOINTS app.config['RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY'] = None InvenioRecordsREST(app) # invenio-records-rest >= 1.1.0 doesn't automatically register endpoints if 'invenio_records_rest.frdoi_item' not in app.url_map._rules_by_endpoint: app.register_blueprint(create_blueprint(OPENAIRE_REST_ENDPOINTS)) with app.test_client() as client: # Item res = client.get("/funders/10.13039/001") assert res.status_code == 200 # List res = client.get("/funders/") assert res.status_code == 200 print(res.get_data(as_text=True)) # Suggest res = client.get("/funders/_suggest?text=Uni") assert res.status_code == 200 # Item res = client.get("/grants/10.13039/501100000923::LP0667725") assert res.status_code == 200 # List res = client.get("/grants/") assert res.status_code == 200 # Suggest res = client.get( "/grants/_suggest?text=open&funder=10.13039/501100000923") assert res.status_code == 200
def test_records_rest(app, db, es, grants): """Test Records REST.""" app.config['RECORDS_REST_ENDPOINTS'] = OPENAIRE_REST_ENDPOINTS app.config['RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY'] = None InvenioRecordsREST(app) with app.test_client() as client: # Item res = client.get("/funders/10.13039/001") assert res.status_code == 200 # List res = client.get("/funders/") assert res.status_code == 200 print(res.get_data(as_text=True)) # Suggest res = client.get("/funders/_suggest?text=Uni") assert res.status_code == 200 # Item res = client.get("/grants/10.13039/501100000923::LP0667725") assert res.status_code == 200 # List res = client.get("/grants/") assert res.status_code == 200 # Suggest res = client.get( "/grants/_suggest?text=open&funder=10.13039/501100000923") assert res.status_code == 200
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.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( TESTING=True, SERVER_NAME='localhost:5000', SQLALCHEMY_DATABASE_URI=os.environ.get( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db' ) ) FlaskCLI(app) InvenioDB(app) InvenioREST(app) InvenioRecords(app) InvenioPIDStore(app) InvenioRecordsREST(app) with app.app_context(): if not database_exists(str(db.engine.url)) and \ app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': create_database(db.engine.url) db.drop_all() db.create_all() def finalize(): with app.app_context(): db.drop_all() if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': drop_database(db.engine.url) shutil.rmtree(instance_path) request.addfinalizer(finalize) return app
def test_invalid_create(app): """Test INVALID record creation request (POST .../records/).""" with app.app_context(): InvenioRecordsREST(app) with app.test_client() as client: # check that creating with non accepted format will return 406 headers = [('Content-Type', 'application/json'), ('Accept', 'video/mp4')] res = client.post(url_for(blueprint.name + '.' + RecordsListResource.view_name), data=json.dumps(test_data), headers=headers) assert res.status_code == 406 # check that creating with non-json Content-Type will return 400 headers = [('Content-Type', 'video/mp4'), ('Accept', 'application/json')] res = client.post(url_for(blueprint.name + '.' + RecordsListResource.view_name), data=json.dumps(test_data), headers=headers) assert res.status_code == 415 # check that creating with invalid json will return 400 headers = [('Content-Type', 'application/json'), ('Accept', 'application/json')] res = client.post(url_for(blueprint.name + '.' + RecordsListResource.view_name), data='{fdssfd', headers=headers) assert res.status_code == 400
def app(request): """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', 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, TESTING=True, ) FlaskCLI(app_) FlaskCeleryExt(app_) InvenioDB(app_) InvenioAccounts(app_) InvenioJSONSchemas(app_) InvenioSearch(app_) InvenioRecords(app_) InvenioRecordsREST(app_) InvenioPIDStore(app_) InvenioDeposit(app_) with app_.app_context(): yield app_ shutil.rmtree(instance_path)
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( TESTING=True, SERVER_NAME='localhost:5000', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, RECORDS_REST_ENDPOINTS=config.RECORDS_REST_ENDPOINTS, # No permission checking RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_SEARCH_INDEX=ES_INDEX, RECORDS_REST_SORT_OPTIONS={ ES_INDEX: dict(year=dict(fields=['year'], )) }, ) app.config['RECORDS_REST_ENDPOINTS']['recid']['search_class'] = TestSearch # update the application with the configuration provided by the test if hasattr(request, 'param') and 'config' in request.param: app.config.update(**request.param['config']) FlaskCLI(app) InvenioDB(app) InvenioREST(app) InvenioRecords(app) InvenioPIDStore(app) InvenioSearch(app) InvenioAccess(app) InvenioRecordsREST(app) with app.app_context(): # Setup app if not database_exists(str(db.engine.url)) and \ app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': create_database(db.engine.url) db.drop_all() db.create_all() if current_search_client.indices.exists(ES_INDEX): current_search_client.indices.delete(ES_INDEX) current_search_client.indices.create(ES_INDEX) prepare_indexing(app) with app.app_context(): # Yield app in request context with app.test_request_context(): yield app with app.app_context(): # Teardown app db.drop_all() if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': drop_database(db.engine.url) shutil.rmtree(instance_path)
def app(request): """Flask application fixture.""" instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) es_index = 'invenio_records_rest_test_index' app.config.update( TESTING=True, SERVER_NAME='localhost:5000', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, RECORDS_REST_ENDPOINTS=config.RECORDS_REST_ENDPOINTS, # No permission checking RECORDS_REST_DEFAULT_CREATE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_READ_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_UPDATE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_DELETE_PERMISSION_FACTORY=None, RECORDS_REST_DEFAULT_SEARCH_INDEX=es_index, RECORDS_REST_SORT_OPTIONS={ es_index: dict(year=dict(fields=['year'], )) }, SEARCH_QUERY_ENHANCERS=[filter_record_access_query_enhancer], ) app.config['RECORDS_REST_ENDPOINTS']['recid']['search_index'] = es_index # update the application with the configuration provided by the test if hasattr(request, 'param') and 'config' in request.param: app.config.update(**request.param['config']) FlaskCLI(app) InvenioDB(app) InvenioREST(app) InvenioRecords(app) InvenioPIDStore(app) InvenioSearch(app) InvenioAccess(app) InvenioRecordsREST(app) with app.app_context(): if not database_exists(str(db.engine.url)) and \ app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': create_database(db.engine.url) db.drop_all() db.create_all() if current_search_client.indices.exists(es_index): current_search_client.indices.delete(es_index) current_search_client.indices.create(es_index) prepare_indexing(app) def finalize(): with app.app_context(): db.drop_all() if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://': drop_database(db.engine.url) shutil.rmtree(instance_path) request.addfinalizer(finalize) return app
def test_invalid_patch(app): """Test INVALID record patch request (PATCH .../records/<record_id>).""" with app.app_context(): InvenioRecordsREST(app) with app.test_client() as client: # check that PATCH with non existing id will return 404 headers = [('Content-Type', 'application/json-patch+json'), ('Accept', 'application/json')] res = client.patch(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=0), data=json.dumps(test_patch), headers=headers) assert res.status_code == 404 # create the record using the internal API internal_record = Record.create(test_data) # check that PATCH with non accepted format will return 406 headers = [('Content-Type', 'application/json-patch+json'), ('Accept', 'video/mp4')] res = client.patch(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), data=json.dumps(test_patch), headers=headers) assert res.status_code == 406 # check that PATCH with non-json Content-Type will return 400 headers = [('Content-Type', 'video/mp4'), ('Accept', 'application/json')] res = client.patch(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), data=json.dumps(test_patch), headers=headers) assert res.status_code == 415 # check that PATCH with invalid json-patch will return 400 headers = [('Content-Type', 'application/json-patch+json'), ('Accept', 'application/json')] res = client.patch(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), data=json.dumps([{ 'invalid': 'json-patch' }]), headers=headers) assert res.status_code == 400 # check that PATCH with invalid json will return 400 headers = [('Content-Type', 'application/json-patch+json'), ('Accept', 'application/json')] res = client.patch(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), data='{sdfsdf', headers=headers) assert res.status_code == 400
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, 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): """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_records_rest(app, es, loaded_example_licenses): """Test Records REST.""" app.config['RECORDS_REST_ENDPOINTS'] = OPENDEFINITION_REST_ENDPOINTS InvenioRecordsREST(app) assert PersistentIdentifier.query.count() == 109 with app.test_client() as client: resp = client.get('/licenses/MIT') assert resp.status_code == 200 resp_json = json.loads(resp.get_data(as_text=True)) assert resp_json['metadata'] == loaded_example_licenses['MIT'] resp = client.get('/licenses/') assert resp.status_code == 200
def app(base_app): """Flask application fixture.""" base_app._internal_jsonschemas = InvenioJSONSchemas(base_app) InvenioREST(base_app) InvenioRecordsREST(base_app) InvenioRecords(base_app) InvenioPIDStore(base_app) base_app.url_map.converters['pid'] = PIDConverter base_app.register_blueprint(create_blueprint_from_app(base_app)) app_loaded.send(None, app=base_app) with base_app.app_context(): yield base_app
def previewer_deposit(app): """.""" # FIXME workaround for previewer tests because they require app and api_app from invenio_records_rest import InvenioRecordsREST from invenio_deposit import InvenioDepositREST from invenio_records_rest.utils import PIDConverter backup = app.debug app.debug = False if 'invenio-records-rest' not in app.extensions: InvenioRecordsREST(app) if 'invenio-deposit-rest' not in app.extensions: InvenioDepositREST(app) app.url_map.converters['pid'] = PIDConverter app.debug = backup return app
def test_conflict_in_endpoint_prefixes(): """Test conflict in endpoint prefixes.""" app = Flask('testapp') app.url_map.converters['pid'] = PIDConverter InvenioRecordsREST(app) ext = InvenioDepositREST() ext.init_config(app) endpoints = app.config['RECORDS_REST_ENDPOINTS'] deposit_endpoints = deepcopy(app.config['DEPOSIT_REST_ENDPOINTS']) deposit_endpoints['recid'] = endpoints['recid'] app.config['DEPOSIT_REST_ENDPOINTS'] = deposit_endpoints ext.init_app(app) with app.test_client() as c: assert 500 == c.get('/').status_code
def test_records_rest(app, es, loaded_example_licenses): """Test Records REST.""" app.config['RECORDS_REST_ENDPOINTS'] = OPENDEFINITION_REST_ENDPOINTS InvenioRecordsREST(app) # invenio-records-rest >= 1.1.0 doesn't automatically register endpoints app_endpoints = app.url_map._rules_by_endpoint if 'invenio_records_rest.od_lic_item' not in app_endpoints: app.register_blueprint(create_blueprint(OPENDEFINITION_REST_ENDPOINTS)) assert PersistentIdentifier.query.count() == 202 with app.test_client() as client: for license_id in ('MIT', 'mit'): resp = client.get('/licenses/{}'.format(license_id)) assert resp.status_code == 200 resp_json = json.loads(resp.get_data(as_text=True)) assert resp_json['metadata'] == loaded_example_licenses['MIT'] resp = client.get('/licenses/') resp_json = json.loads(resp.get_data(as_text=True)) assert resp.status_code == 200 assert resp_json['hits']['total'] == 109 resp = client.get('/licenses/_suggest?text=mit') resp_json = json.loads(resp.get_data(as_text=True)) assert resp.status_code == 200 options = resp_json['text'][0]['options'] assert len(options) == 2 assert { (o['_source']['id'], o['_source']['title']) for o in options } == { ('MIT', 'MIT License'), ('mitre', 'MITRE Collaborative Virtual Workspace License (CVW License)') } resp = client.get('/licenses/_suggest?text=cc0') resp_json = json.loads(resp.get_data(as_text=True)) assert resp.status_code == 200 options = resp_json['text'][0]['options'] assert len(options) == 1 assert { (o['_source']['id'], o['_source']['title']) for o in options} == {('CC0-1.0', 'CC0 1.0'), }
def app(request): """Basic Flask application.""" instance_path = tempfile.mkdtemp() app = Flask("testapp") app.config.update( SQLALCHEMY_DATABASE_URI=os.getenv("SQLALCHEMY_DATABASE_URI", "sqlite://"), SQLALCHEMY_TRACK_MODIFICATIONS=False, TESTING=True, SECRET_KEY="testing", # SERVER_NAME='localhost:5000', ) app.url_map.converters['pid'] = PIDConverter InvenioDB(app) InvenioPIDStore(app) InvenioRecords(app) InvenioAccounts(app) InvenioAccess(app) InvenioIndexer(app) InvenioSearch(app) InvenioREST(app) InvenioRecordsREST(app) InvenioConfigDefault(app) with app.app_context(): db_url = str(db.engine.url) if db_url != "sqlite://" and not database_exists(db_url): create_database(db_url) db.create_all() def teardown(): with app.app_context(): db_url = str(db.engine.url) db.session.close() if db_url != "sqlite://": drop_database(db_url) shutil.rmtree(instance_path) request.addfinalizer(teardown) app.test_request_context().push() return app
def app(base_app): """Flask application fixture.""" base_app._internal_jsonschemas = InvenioJSONSchemas(base_app) InvenioREST(base_app) InvenioRecordsREST(base_app) InvenioRecords(base_app) InvenioPIDStore(base_app) base_app.url_map.converters['pid'] = PIDConverter SampleExt(base_app) OARepoMappingIncludesExt(base_app) LoginManager(base_app) Permission(base_app) InvenioAccess(base_app) Principal(base_app) OARepoValidate(base_app) Actions(base_app) base_app.register_blueprint( invenio_records_rest.views.create_blueprint_from_app(base_app)) login_manager = LoginManager() login_manager.init_app(base_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 @base_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_loaded.send(None, app=base_app) with base_app.app_context(): yield base_app
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 test_conflict_in_endpoint_prefixes(): """Test conflict in endpoint prefixes.""" app = Flask('testapp') app.url_map.converters['pid'] = PIDConverter InvenioRecordsREST(app) ext = InvenioDepositREST() ext.init_config(app) endpoints = app.config['RECORDS_REST_ENDPOINTS'] # Due to incompatibilty with how we are registering endpoints between # invenio packages we need to now sanitize the endpoints registered in this # test. for endpoint in endpoints: endpoints[endpoint].pop('error_handlers', None) deposit_endpoints = deepcopy(app.config['DEPOSIT_REST_ENDPOINTS']) deposit_endpoints['recid'] = endpoints['recid'] app.config['DEPOSIT_REST_ENDPOINTS'] = deposit_endpoints ext.init_app(app) with app.test_client() as c: assert 500 == c.get('/').status_code
def test_invalid_get(app): """Test INVALID record get request (GET .../records/<record_id>).""" with app.app_context(): InvenioRecordsREST(app) with app.test_client() as client: # check that GET with non existing id will return 404 headers = [('Accept', 'application/json')] res = client.get(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=0), headers=headers) assert res.status_code == 404 # create the record using the internal API internal_record = Record.create(test_data) # check that GET with non accepted format will return 406 headers = [('Accept', 'video/mp4')] res = client.get(url_for(blueprint.name + '.' + RecordResource.view_name, record_id=internal_record.model.id), headers=headers) assert res.status_code == 406
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)
InvenioDB(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 app(request, search_class): """Flask application fixture. Note that RECORDS_REST_ENDPOINTS is used during application creation to create blueprints on the fly, hence once you have this fixture in a test, it's too late to customize the configuration variable. You can however customize it using parameterized tests: .. code-block:: python @pytest.mark.parametrize('app', [dict( endpoint=dict( search_class='conftest:TestSearch', ) def test_mytest(app, db, es): # ... This will parameterize the default 'recid' endpoint in RECORDS_REST_ENDPOINTS. Alternatively: .. code-block:: python @pytest.mark.parametrize('app', [dict( records_rest_endpoints=dict( recid=dict( search_class='conftest:TestSearch', ) ) def test_mytest(app, db, es): # ... This will fully parameterize RECORDS_REST_ENDPOINTS. """ instance_path = tempfile.mkdtemp() app = Flask('testapp', instance_path=instance_path) app.config.update( ACCOUNTS_JWT_ENABLE=False, INDEXER_DEFAULT_DOC_TYPE='testrecord', INDEXER_DEFAULT_INDEX=search_class.Meta.index, RECORDS_REST_ENDPOINTS=copy.deepcopy(config.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, RECORDS_REST_DEFAULT_SEARCH_INDEX=search_class.Meta.index, RECORDS_REST_FACETS={ search_class.Meta.index: { 'aggs': { 'stars': { 'terms': { 'field': 'stars' } } }, 'post_filters': { 'stars': terms_filter('stars'), } } }, RECORDS_REST_SORT_OPTIONS={ search_class.Meta.index: dict(year=dict(fields=['year'], )) }, SERVER_NAME='localhost:5000', SQLALCHEMY_DATABASE_URI=os.environ.get('SQLALCHEMY_DATABASE_URI', 'sqlite:///test.db'), SQLALCHEMY_TRACK_MODIFICATIONS=True, TESTING=True, ) app.config['RECORDS_REST_ENDPOINTS']['recid']['search_class'] = \ search_class # Parameterize application. if hasattr(request, 'param'): if 'endpoint' in request.param: app.config['RECORDS_REST_ENDPOINTS']['recid'].update( request.param['endpoint']) if 'records_rest_endpoints' in request.param: original_endpoint = app.config['RECORDS_REST_ENDPOINTS']['recid'] del app.config['RECORDS_REST_ENDPOINTS']['recid'] for new_endpoint_prefix, new_endpoint_value in \ request.param['records_rest_endpoints'].items(): new_endpoint = dict(original_endpoint) new_endpoint.update(new_endpoint_value) app.config['RECORDS_REST_ENDPOINTS'][new_endpoint_prefix] = \ new_endpoint app.url_map.converters['pid'] = PIDConverter InvenioDB(app) InvenioREST(app) InvenioRecords(app) InvenioIndexer(app) InvenioPIDStore(app) search = InvenioSearch(app) search.register_mappings(search_class.Meta.index, 'mock_module.mappings') InvenioRecordsREST(app) with app.app_context(): yield app # Teardown instance path. shutil.rmtree(instance_path)