def setup_function(function): """Ensure each test starts with a fresh Service and configuration.""" config.conf = config.LazyConfig() config.conf["client_properties"]["app"] = function.__name__ if api._twisted_service: pytest_twisted.blockon(api._twisted_service.stopService()) api._twisted_service = None
def test_deep_copy(self): """Assert nested dictionaries in DEFAULTS are not copied into the config instance.""" config = msg_config.LazyConfig().load_config() config["queues"]["somequeue"] = {} self.assertNotIn("somequeue", msg_config.DEFAULTS["queues"])
def test_bad_config_file(self, mock_exists, mock_log): """Assert an invalid TOML file raises a ConfigurationException.""" self.assertRaises(ConfigurationException, msg_config.LazyConfig().load_config) mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml') error = 'Failed to parse /etc/fedora-messaging/config.toml: <string>(1, 1): msg' self.assertEqual(error, mock_log.error.call_args_list[0][0][0])
def test_override_client_props(self, mock_exists): """Assert overriding reserved keys in client properties fails.""" conf = '[client_properties]\n{} = "val"' for key in ('version', 'information', 'product'): with mock.patch('fedora_messaging.config.open', mock.mock_open(read_data=conf.format(key))): config = msg_config.LazyConfig() self.assertRaises(ConfigurationException, config.load_config)
def test_empty_config_file(self, mock_exists, mock_log): """Assert loading the config with an empty file that exists works.""" config = msg_config.LazyConfig().load_config() self.assertEqual(msg_config.DEFAULTS, config) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml')
def test_load_on_update(self, mock_exists, mock_log): """Assert the config is loaded when update is called.""" config = msg_config.LazyConfig() config.update({}) self.assertEqual(msg_config.DEFAULTS, config) mock_exists.assert_called_once_with( "/etc/fedora-messaging/config.toml") mock_log.info.assert_called_once_with( "Loading configuration from /etc/fedora-messaging/config.toml")
def test_load_on_setup_logging(self, mock_exists, mock_log): """Assert the config is loaded when setup_logging is called.""" config = msg_config.LazyConfig() config.setup_logging() self.assertEqual(msg_config.DEFAULTS, config) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml')
def test_bad_config_file(self, mock_exists): """Assert an invalid TOML file raises a ConfigurationException.""" with self.assertRaises(ConfigurationException) as cm: msg_config.LazyConfig().load_config() error = ( "Failed to parse /etc/fedora-messaging/config.toml: error at line 1, column 3: " "Found invalid character in key name: '!'. Try quoting the key name." ) self.assertEqual(error, cm.exception.message)
def test_missing_config_file(self, mock_exists, mock_log): """Assert loading the config with a missing file works.""" config = msg_config.LazyConfig().load_config() self.assertEqual(msg_config.DEFAULTS, config) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'The configuration file, /etc/fedora-messaging/config.toml, does not exist.' )
def test_custom_config_file(self, mock_exists, mock_log): """Assert using the environment variable to set the config path works.""" config = msg_config.LazyConfig().load_config() self.assertNotEqual('special_exchange', msg_config.DEFAULTS['publish_exchange']) self.assertEqual('special_exchange', config['publish_exchange']) mock_exists.assert_called_once_with('/my/config') mock_log.info.assert_called_once_with( 'Loading configuration from /my/config') self.assertEqual(0, mock_log.warning.call_count)
def test_partial_config_file(self, mock_exists, mock_log): """Assert a config file that uses a subset of keys works as expected""" config = msg_config.LazyConfig().load_config() self.assertNotEqual('special_exchange', msg_config.DEFAULTS['publish_exchange']) self.assertEqual('special_exchange', config['publish_exchange']) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml') self.assertEqual(0, mock_log.warning.call_count)
def test_load_on_get(self, mock_exists, mock_log): """Assert the config is loaded when get is called.""" config = msg_config.LazyConfig() self.assertEqual(msg_config.DEFAULTS['callback'], config.get('callback')) self.assertEqual(msg_config.DEFAULTS['amqp_url'], config.get('amqp_url')) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml')
def test_load_on_get_item(self): """Assert load_config is called when __getitem__ is invoked.""" config = msg_config.LazyConfig() config.load_config = mock.Mock() try: config["some_key"] except KeyError: pass config.load_config.assert_called_once_with()
def test_full_config_file(self, mock_exists, mock_log): """Assert a config with the full set of configurations loads correctly.""" expected_config = dict( amqp_url="amqp://*****:*****@rabbit-server1:5672/%2F", client_properties={ "app": "Example App", "product": "Fedora Messaging with Pika", "information": "https://fedora-messaging.readthedocs.io/en/stable/", "version": msg_config.DEFAULTS["client_properties"]["version"], }, publish_exchange="special_exchange", exchanges={ "custom_exchange": { "type": "fanout", "durable": False, "auto_delete": False, "arguments": {}, } }, queues={ "my_queue": { "durable": True, "auto_delete": False, "exclusive": False, "arguments": {}, } }, bindings=[{ "queue": "my_queue", "exchange": "amq.topic", "routing_keys": ["#"] }], qos={ "prefetch_size": 25, "prefetch_count": 25 }, callback="fedora_messaging.examples:print_msg", consumer_config={"example_key": "for my consumer"}, tls={ "ca_cert": "/etc/pki/tls/certs/ca-bundle.crt", "keyfile": "/my/client/key.pem", "certfile": "/my/client/cert.pem", }, log_config={ "version": 1, "disable_existing_loggers": True, "formatters": { "simple": { "format": "[%(name)s %(levelname)s] %(message)s" } }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "simple", "stream": "ext://sys.stderr", } }, "loggers": { "fedora_messaging": { "level": "INFO", "propagate": False, "handlers": ["console"], } }, "root": { "level": "DEBUG", "handlers": ["console"] }, }, ) config = msg_config.LazyConfig().load_config() self.assertEqual(sorted(expected_config.keys()), sorted(config.keys())) for key in expected_config: self.assertEqual(expected_config[key], config[key]) mock_exists.assert_called_once_with( "/etc/fedora-messaging/config.toml") mock_log.info.assert_called_once_with( "Loading configuration from /etc/fedora-messaging/config.toml") self.assertEqual(0, mock_log.warning.call_count)
def test_explode_on_pop(self): """Assert calling pop raises an exception.""" config = msg_config.LazyConfig() self.assertRaises(ConfigurationException, config.pop)
def test_setup_logging(self, mock_exists, mock_dictConfig): """Assert setup_logging passes the log_config key to dictConfig.""" config = msg_config.LazyConfig().load_config() config.setup_logging() mock_dictConfig.assert_called_once_with(config['log_config'])
def tearDown(self): """Make sure each test has a fresh default configuration.""" config.conf = config.LazyConfig() config.conf.load_config(config_path="")
def test_invalid_key(self, mock_exists): """Assert an unknown config key raises an exception.""" config = msg_config.LazyConfig() self.assertRaises(ConfigurationException, config.load_config)
def test_full_config_file(self, mock_exists, mock_log): """Assert a config with the full set of configurations loads correctly.""" expected_config = dict( amqp_url='amqp://*****:*****@rabbit-server1:5672/%2F', client_properties={ 'app': 'Example App', 'product': 'Fedora Messaging with Pika', 'information': 'https://fedora-messaging.readthedocs.io/en/stable/', 'version': msg_config.DEFAULTS['client_properties']['version'] }, publish_exchange='special_exchange', exchanges={ 'custom_exchange': { 'type': 'fanout', 'durable': False, 'auto_delete': False, 'arguments': {}, } }, queues={ 'my_queue': { 'durable': True, 'auto_delete': False, 'exclusive': False, 'arguments': {}, } }, bindings=[{ 'queue': 'my_queue', 'exchange': 'amq.topic', 'routing_keys': ['#'], }], qos={ 'prefetch_size': 25, 'prefetch_count': 25, }, callback='fedora_messaging.examples:print_msg', consumer_config={'example_key': 'for my consumer'}, tls={ 'ca_cert': '/etc/pki/tls/certs/ca-bundle.crt', 'keyfile': '/my/client/key.pem', 'certfile': '/my/client/cert.pem', }, log_config={ 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'simple': { 'format': '[%(name)s %(levelname)s] %(message)s', }, }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'stream': 'ext://sys.stderr', } }, 'loggers': { 'fedora_messaging': { 'level': 'INFO', 'propagate': False, 'handlers': ['console'], }, }, 'root': { 'level': 'DEBUG', 'handlers': ['console'], }, }, ) config = msg_config.LazyConfig().load_config() self.assertEqual(sorted(expected_config.keys()), sorted(config.keys())) for key in expected_config: self.assertEqual(expected_config[key], config[key]) mock_exists.assert_called_once_with( '/etc/fedora-messaging/config.toml') mock_log.info.assert_called_once_with( 'Loading configuration from /etc/fedora-messaging/config.toml') self.assertEqual(0, mock_log.warning.call_count)
def test_bad_config_file(self, mock_exists): """Assert an invalid TOML file raises a ConfigurationException.""" with self.assertRaises(ConfigurationException) as cm: msg_config.LazyConfig().load_config() error = "Failed to parse /etc/fedora-messaging/config.toml: error at line 1, column 1" self.assertEqual(error, cm.exception.message)