def test_ignore_case(self): str_entry1 = StringConfigEntry( key_path=["tHiS", "Is", "CaseInsensitive"], default="value") str_entry2 = StringConfigEntry( key_path=["This", "is", "caseinsensitive"], default="value") str_entry3 = StringConfigEntry(key_path=["this", "or", "iSit"], default="value") source = YamlSource("case_insensitive", ["./", "./tests"], ignore_case_in_keys=True) source.load() self.assertTrue(source.has(str_entry1)) self.assertEqual(source.get(str_entry1), "value") self.assertTrue(source.has(str_entry2)) self.assertEqual(source.get(str_entry2), "value") self.assertTrue(source.has(str_entry3)) self.assertEqual(source.get(str_entry3), "?")
class TestBase(IsolatedAsyncioTestCase): from barcode_server.config import AppConfig from container_app_conf.source.yaml_source import YamlSource # load config from test folder config = AppConfig(singleton=True, data_sources=[YamlSource("barcode_server", "./tests/")])
def __new__(cls, *args, **kwargs): data_sources = [ EnvSource(), YamlSource(FILE_NAME), TomlSource(FILE_NAME) ] kwargs["data_sources"] = data_sources return super(Config, cls).__new__(cls, *args, **kwargs)
def test_init_with_config(self): from container_app_conf.source.yaml_source import YamlSource conf = config.Config( singleton=False, data_sources=[YamlSource("test_creds", "./tests/")]) api_client = api.Api(conf) self.assertIsNotNone(api_client.config) self.assertEqual(api_client.config, conf)
def __new__(cls, *args, **kwargs): if "data_sources" not in kwargs.keys(): yaml_source = YamlSource("n26") toml_source = TomlSource("n26") data_sources = [EnvSource(), yaml_source, toml_source] kwargs["data_sources"] = data_sources return super(Config, cls).__new__(cls, *args, **kwargs)
def test_yaml(self): str_entry = StringConfigEntry(key_path=["testing", "key1"], default="value") int_entry = IntConfigEntry(key_path=["testing", "key2"], default=2) source = YamlSource("test") source.load() self.assertTrue(source.has(str_entry)) self.assertEqual(source.get(str_entry), "value") self.assertTrue(source.has(int_entry)) self.assertEqual(source.get(int_entry), 2)
def __new__(cls, *args, **kwargs): yaml_source = YamlSource(NODE_MAIN) toml_source = TomlSource(NODE_MAIN) data_sources = [ EnvSource(), yaml_source, toml_source ] return super(Config, cls).__new__(cls, data_sources=data_sources)
def __new__(cls, *args, **kwargs): yaml_source = YamlSource(CONFIG_NODE_ROOT) toml_source = TomlSource(CONFIG_NODE_ROOT) data_sources = [ EnvSource(), yaml_source, toml_source, ] return super(AppConfig, cls).__new__(cls, data_sources=data_sources)
class WebsocketNotifierTest(AioHTTPTestCase): from barcode_server.config import AppConfig from container_app_conf.source.yaml_source import YamlSource # load config from test folder config = AppConfig(singleton=True, data_sources=[YamlSource("barcode_server", "./tests/")]) webserver = None async def get_application(self): """ Override the get_app method to return your application. """ barcode_reader = MagicMock() self.webserver = Webserver(self.config, barcode_reader) app = self.webserver.create_app() runner = aiohttp.web.AppRunner(app) await runner.setup() site = aiohttp.web.TCPSite(runner, host=self.config.SERVER_HOST.value, port=self.config.SERVER_PORT.value) await site.start() return app # the unittest_run_loop decorator can be used in tandem with # the AioHTTPTestCase to simplify running # tests that are asynchronous @unittest_run_loop async def test_ws_connect_and_event(self): sample_event = create_barcode_event_mock("abcdefg") expected_json = barcode_event_to_json(sample_event) async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ "X-Auth-Token": self.config.SERVER_API_TOKEN.value }) as ws: asyncio.create_task(self.webserver.on_barcode(sample_event)) async for msg in ws: if msg.type == aiohttp.WSMsgType.BINARY: if expected_json == msg.data: await ws.close() assert True return else: assert False else: assert False assert False
def __new__(cls, data_sources: List[DataSource] = None, validate: bool = True, singleton: bool = True): """ Creates a config object and reads configuration. :param data_sources: list of data sources to use. The first value that holds a value for a specific config entry overshadows other data sources. :param validate: if validation should be run (can be disabled for tests) :param singleton: if the returned instance should be a singleton """ if singleton: if cls._instances.get(cls, None) is None: instance = super(ConfigBase, cls).__new__(cls) cls._instances[cls] = instance else: instance = cls._instances[cls] else: instance = super(ConfigBase, cls).__new__(cls) self = instance self._config_entries = self._find_config_entries() if not singleton: # copy class attribute to instance to overshadow class attributes instance_attributes = {} for name, attribute in self._config_entries.items(): attribute_copy = copy.deepcopy(attribute) self.__dict__.setdefault(name, attribute_copy) key = "_".join(attribute.key_path) instance_attributes[key] = attribute_copy # update config_entries list to reflect instance attributes self._config_entries = instance_attributes if data_sources is None: # set default data sources from container_app_conf.source.env_source import EnvSource from container_app_conf.source.yaml_source import YamlSource self.data_sources = [EnvSource(), YamlSource(cls.__name__)] else: self.data_sources = data_sources self.load_config(validate) return instance
class N26TestBase(unittest.TestCase): """Base class for N26 api tests""" from n26.config import Config from container_app_conf.source.yaml_source import YamlSource # create custom config from "test_creds.yml" config = Config(singleton=True, data_sources=[YamlSource("test_creds", "./tests/")]) # this is the Api client _underTest = None def setUp(self): """ This method is called BEFORE each individual test case """ from n26 import api self._underTest = api.Api(self.config) logger = logging.getLogger("n26") logger.setLevel(logging.DEBUG) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") ch.setFormatter(formatter) logger.addHandler(ch) def tearDown(self): """ This method is called AFTER each individual test case """ pass @staticmethod def get_api_response(filename: str) -> dict or None: """ Read an api response from a file :param filename: the file in the "api_responses" subfolder to read :return: the api response dict """ file = read_response_file(filename) if file is None: return None else: return json.loads(file) @staticmethod def _run_cli_cmd(command: callable, args: list = None, ignore_exceptions: bool = False) -> any: """ Runs a cli command and returns it's output. If running the command results in an exception it is automatically rethrown by this method. :param command: the command to execute :param args: command arguments as a list :param ignore_exceptions: if set to true exceptions originating from running the command will not be rethrown and the result object from the cli call will be returned instead. :return: the result of the call """ from click.testing import CliRunner runner = CliRunner(echo_stdin=False) result = runner.invoke(command, args=args or ()) if not ignore_exceptions and result.exception: raise result.exception return result if __name__ == '__main__': unittest.main()
def __new__(cls, *args, **kwargs): yaml_source = YamlSource(CONFIG_FILE_NAME) data_sources = [EnvSource(), yaml_source] return super(AppConfig, cls).__new__(cls, data_sources=data_sources)
def __new__(cls, *args, **kwargs): yaml_source = YamlSource("deinemudda") data_sources = [EnvSource(), yaml_source] return super(AppConfig, cls).__new__(cls, data_sources=data_sources)
class WebsocketNotifierTest(AioHTTPTestCase): from barcode_server.config import AppConfig from container_app_conf.source.yaml_source import YamlSource # load config from test folder config = AppConfig(singleton=True, data_sources=[YamlSource("barcode_server", "./tests/")]) webserver = None async def get_application(self): """ Override the get_app method to return your application. """ barcode_reader = MagicMock() self.webserver = Webserver(self.config, barcode_reader) app = self.webserver.create_app() runner = aiohttp.web.AppRunner(app) await runner.setup() site = aiohttp.web.TCPSite(runner, host=self.config.SERVER_HOST.value, port=self.config.SERVER_PORT.value) await site.start() return app # the unittest_run_loop decorator can be used in tandem with # the AioHTTPTestCase to simplify running # tests that are asynchronous @unittest_run_loop async def test_ws_connect_and_event(self): sample_event = create_barcode_event_mock("abcdefg") expected_json = barcode_event_to_json(sample_event) import uuid client_id = str(uuid.uuid4()) async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ const.Client_Id: client_id, const.X_Auth_Token: self.config.SERVER_API_TOKEN.value }) as ws: asyncio.create_task(self.webserver.on_barcode(sample_event)) async for msg in ws: if msg.type == aiohttp.WSMsgType.BINARY: if expected_json == msg.data: await ws.close() assert True return else: assert False else: assert False assert False @unittest_run_loop async def test_ws_reconnect_event_catchup(self): missed_event = create_barcode_event_mock("abcdefg") second_event = create_barcode_event_mock("123456") missed_event_json = barcode_event_to_json(missed_event) second_event_json = barcode_event_to_json(second_event) import uuid client_id = str(uuid.uuid4()) # connect to the server once async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ const.Client_Id: client_id, const.X_Auth_Token: self.config.SERVER_API_TOKEN.value }) as ws: await ws.close() # then emulate a barcode scan event asyncio.create_task(self.webserver.on_barcode(missed_event)) await asyncio.sleep(0.1) # and then reconnect again, expecting the event in between async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ const.Client_Id: client_id, const.X_Auth_Token: self.config.SERVER_API_TOKEN.value }) as ws: # emulate another event, while connected asyncio.create_task(self.webserver.on_barcode(second_event)) missed_event_received = False async for msg in ws: if msg.type == aiohttp.WSMsgType.BINARY: if missed_event_json == msg.data: if missed_event_received: assert False missed_event_received = True elif second_event_json == msg.data: if not missed_event_received: assert False await ws.close() assert True return else: assert False else: assert False assert False @unittest_run_loop async def test_ws_reconnect_drop_cache(self): missed_event = create_barcode_event_mock("abcdefg") second_event = create_barcode_event_mock("123456") missed_event_json = barcode_event_to_json(missed_event) second_event_json = barcode_event_to_json(second_event) import uuid client_id = str(uuid.uuid4()) # connect to the server once async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ const.Client_Id: client_id, const.X_Auth_Token: self.config.SERVER_API_TOKEN.value }) as ws: await ws.close() # then emulate a barcode scan event while not connected asyncio.create_task(self.webserver.on_barcode(missed_event)) await asyncio.sleep(0.1) # and then reconnect again, passing the "drop cache" header, expecting only # the new live event async with aiohttp.ClientSession() as session: async with session.ws_connect( 'http://127.0.0.1:9654/', headers={ const.Client_Id: client_id, const.Drop_Event_Queue: "", const.X_Auth_Token: self.config.SERVER_API_TOKEN.value }) as ws: # emulate another event, while connected asyncio.create_task(self.webserver.on_barcode(second_event)) async for msg in ws: if msg.type == aiohttp.WSMsgType.BINARY: if missed_event_json == msg.data: assert False elif second_event_json == msg.data: await ws.close() assert True return else: assert False else: assert False assert False
def __new__(cls, *args, **kwargs): yaml_source = YamlSource("py_image_dedup") data_sources = [EnvSource(), yaml_source] return super(DeduplicatorConfig, cls).__new__(cls, data_sources=data_sources)