def __init__(self, config_file: Optional[str] = None, format_logs: bool = True) -> None: """Constructor method.""" if config_file: self.config = Config(**self.parse_yaml(config_file)) else: self.config = Config() if format_logs: self.configure_logging() logger.debug(f"Parsed config: {self.config.dict(by_alias=True)}")
def test_register_metadata_duplicate_keys_repeated(self): """Test for registering a service; running out of unique identifiers. """ endpoint_config = deepcopy(ENDPOINT_CONFIG) endpoint_config['services']['id']['length'] = MOCK_ID_ONE_CHAR endpoint_config['services']['id']['length'] = 1 app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=endpoint_config, ) mock_resp = deepcopy(MOCK_SERVICE) app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client = mongomock.MongoClient().db.collection app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client.insert_one(mock_resp) data = deepcopy(MOCK_SERVICE) with app.app_context(): with pytest.raises(InternalServerError): obj = RegisterService(data=data) obj.register_metadata() obj = RegisterService(data=data) obj.register_metadata() print(obj.data['id'])
def test_handle_problem_with_private_members(): """Test problem handler with private members.""" app = Flask(__name__) app.config['FOCA'] = Config() app.config['FOCA'].exceptions.private_members = PRIVATE_MEMBERS with app.app_context(): res = handle_problem(UnknownException()) assert isinstance(res, Response) assert res.status == '500 INTERNAL SERVER ERROR' assert res.mimetype == "application/problem+json"
def test_init(self): """Test for constructing class.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) with app.app_context(): service_info = RegisterServiceInfo() assert service_info.url_prefix == SERVICE_CONFIG['url_prefix']
def test_handle_problem_no_fallback_exception(): """Test problem handler; unlisted error without fallback.""" app = Flask(__name__) app.config['FOCA'] = Config() del app.config['FOCA'].exceptions.mapping[Exception] with app.app_context(): res = handle_problem(UnknownException()) assert isinstance(res, Response) assert res.status == '500 INTERNAL SERVER ERROR' assert res.mimetype == "application/problem+json" response = res.data.decode("utf-8") assert response == ""
def test__get_headers(self): """Test for response headers getter.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) with app.app_context(): service_info = RegisterServiceInfo() headers = service_info._get_headers() assert headers == HEADERS_SERVICE_INFO
def test_handle_problem(): """Test problem handler with instance of custom, unlisted error.""" app = Flask(__name__) app.config['FOCA'] = Config() EXPECTED_RESPONSE = app.config['FOCA'].exceptions.mapping[Exception] with app.app_context(): res = handle_problem(UnknownException()) assert isinstance(res, Response) assert res.status == '500 INTERNAL SERVER ERROR' assert res.mimetype == "application/problem+json" response = json.loads(res.data.decode('utf-8')) assert response == EXPECTED_RESPONSE
def test_get_service_info_na(self): """Test for getting service info when service info is unavailable.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection with app.app_context(): with pytest.raises(NotFound): RegisterServiceInfo().get_service_info()
def test_init(self): """Test for constructing class.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) data = deepcopy(MOCK_SERVICE) with app.app_context(): obj = RegisterService(data=data) assert obj.data['name'] == MOCK_SERVICE['name'] assert obj.data['id'] is None
def test_set_service_info_from_config(self): """Test for setting service info from config.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection with app.app_context(): service_info = RegisterServiceInfo() service_info.set_service_info_from_config() assert service_info.get_service_info() == SERVICE_INFO_CONFIG
def test_register_metadata_with_id(self): """Test for registering a service with a user-supplied identifier.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client = MagicMock() data = deepcopy(MOCK_SERVICE) with app.app_context(): obj = RegisterService(data=data, id=MOCK_ID) obj.register_metadata() assert obj.data['id'] == MOCK_ID
def test_set_service_info_from_config_invalid(self): """Test for setting service info from corrupt config.""" app = Flask(__name__) mock_resp = deepcopy(ENDPOINT_CONFIG) del mock_resp[coll]['id'] app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=mock_resp, ) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection with app.app_context(): with pytest.raises(ValidationError): service_info = RegisterServiceInfo() service_info.set_service_info_from_config()
def test__upsert_service_info_insert(self): """Test for creating service info document in database.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection data = deepcopy(SERVICE_INFO_CONFIG) del data['contactUrl'] with app.app_context(): service_info = RegisterServiceInfo() service_info._upsert_service_info(data=data) assert service_info.get_service_info() == data assert service_info.get_service_info() != SERVICE_INFO_CONFIG
def test_get_service_info(self): """Test for getting service info.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) mock_resp = deepcopy(SERVICE_INFO_CONFIG) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection app.config['FOCA'].db.dbs[DB].collections[coll] \ .client.insert_one(mock_resp) with app.app_context(): service_info = RegisterServiceInfo() res = service_info.get_service_info() assert res == SERVICE_INFO_CONFIG
def test_register_metadata_duplicate_key(self): """Test for registering a service; duplicate key error occurs.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) mock_resp = MagicMock(side_effect=[DuplicateKeyError(''), None]) app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client = MagicMock() app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client.insert_one = mock_resp data = deepcopy(MOCK_SERVICE) with app.app_context(): obj = RegisterService(data=data) obj.register_metadata() assert isinstance(obj.data['id'], str)
def test_set_service_info_from_config_skip(self): """Test for skipping setting service info because identical service info is already available. """ app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) mock_resp = deepcopy(SERVICE_INFO_CONFIG) app.config['FOCA'].db.dbs[DB].collections[coll] \ .client = mongomock.MongoClient().db.collection app.config['FOCA'].db.dbs[DB].collections[coll] \ .client.insert_one(mock_resp) with app.app_context(): service_info = RegisterServiceInfo() service_info.set_service_info_from_config() assert service_info.get_service_info() == SERVICE_INFO_CONFIG
def test_register_metadata_with_id_replace(self): """Test for updating an existing obj.""" app = Flask(__name__) app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=ENDPOINT_CONFIG, ) mock_resp = deepcopy(MOCK_SERVICE) mock_resp["id"] = MOCK_ID app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client = MagicMock() app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client.insert_one(mock_resp) data = deepcopy(MOCK_SERVICE) with app.app_context(): obj = RegisterService(data=data, id=MOCK_ID) obj.register_metadata() assert obj.data['id'] == MOCK_ID
def test_register_metadata_literal_id_charset(self): """Test for registering a service with a randomly assigned identifier generated from a literal character set. """ app = Flask(__name__) endpoint_config = deepcopy(ENDPOINT_CONFIG) endpoint_config['services']['id']['charset'] = MOCK_ID_ONE_CHAR endpoint_config['services']['id']['length'] = 1 app.config['FOCA'] = Config( db=MongoConfig(**MONGO_CONFIG), endpoints=endpoint_config, ) app.config['FOCA'].db.dbs['serviceStore'].collections['services'] \ .client = MagicMock() data = deepcopy(MOCK_SERVICE) with app.app_context(): obj = RegisterService(data=data) obj.register_metadata() assert isinstance(obj.data['id'], str)
def test_config_empty(): """Test basic creation of the main config model.""" res = Config() assert isinstance(res, Config)
"""Tests for foca.factories.connexion_app.""" from connexion import App from foca.models.config import Config from foca.factories.connexion_app import ( __add_config_to_connexion_app, create_connexion_app, ) CONFIG = Config() ERROR_CODE = 400 ERROR_ORIGINAL = { 'title': 'BAD REQUEST', 'status_code': str(ERROR_CODE), } ERROR_REWRITTEN = { "msg": "The request is malformed.", "status_code": str(ERROR_CODE), } def test_add_config_to_connexion_app(): """Test if app config is updated.""" cnx_app = App(__name__) cnx_app = __add_config_to_connexion_app(cnx_app, CONFIG) assert isinstance(cnx_app, App) assert cnx_app.app.config['FOCA'] == CONFIG def test_create_connexion_app_without_config():
"""Unit tests for Celery app factory module.""" from celery import Celery from foca.factories.celery_app import create_celery_app from foca.factories.connexion_app import create_connexion_app from foca.models.config import (Config, JobsConfig) CONFIG = Config() CONFIG.jobs = JobsConfig() def test_create_celery_app(): """Test Connexion app creation.""" cnx_app = create_connexion_app(CONFIG) cel_app = create_celery_app(cnx_app.app) assert isinstance(cel_app, Celery) assert cel_app.conf['FOCA'] == CONFIG
""" Tests for config_parser.py """ import pytest from pydantic import ValidationError from foca.config.config_parser import ConfigParser from foca.models.config import Config TEST_CONFIG_INSTANCE = Config() TEST_DICT = {} TEST_FILE = "tests/test_files/conf_valid.yaml" TEST_FILE_INVALID = "tests/test_files/conf_invalid_log_level.yaml" TEST_FILE_INVALID_LOG = "tests/test_files/conf_log_invalid.yaml" def test_config_parser_valid_config_file(): """Test valid YAML parsing.""" conf = ConfigParser(TEST_FILE) assert type(conf.config.dict()) == type(TEST_DICT) assert isinstance(conf.config, type(TEST_CONFIG_INSTANCE)) def test_config_parser_invalid_config_file(): """Test invalid YAML parsing.""" with pytest.raises(ValidationError): ConfigParser(TEST_FILE_INVALID)