def test_dict_setting(self): """ Test that dictionary-type settings can be "complemented", that is existing setting keys/values are not overriden by user settings, but merged into the existing dict. """ s = LazySettings() # Start with fresh settings from global_settings.py # Simply overwriting the key s.configure(CACHES={'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'}}) self.assertEqual(s.CACHES['default']['BACKEND'], 'django.core.cache.backends.dummy.DummyCache') s = LazySettings() # More complex overwriting s.configure(CACHES={ 'default': {'LOCATION': 'unique-snowflake'}, 'temp': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'} }) self.assertDictEqual(s.CACHES, { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake' }, 'temp': { 'BACKEND': 'django.core.cache.backends.dummy.DummyCache', } })
def settings(request): """ This fixture initializes a Django settings object that wraps our `awx.conf.settings.SettingsWrapper` and passes it as an argument into the test function. This mimics the work done by `awx.conf.settings.SettingsWrapper.initialize` on `django.conf.settings`. """ cache = LocMemCache(str(uuid4()), {}) # make a new random cache each time settings = LazySettings() registry = SettingsRegistry(settings) defaults = {} # @pytest.mark.defined_in_file can be used to mark specific setting values # as "defined in a settings file". This is analogous to manually # specifying a setting on the filesystem (e.g., in a local_settings.py in # development, or in /etc/tower/conf.d/<something>.py) for marker in request.node.own_markers: if marker.name == 'defined_in_file': defaults = marker.kwargs defaults['DEFAULTS_SNAPSHOT'] = {} settings.configure(**defaults) settings._wrapped = SettingsWrapper(settings._wrapped, cache, registry) return settings
def test_dict_setting_clear_defaults(self): """ Test the ability to deactivate the merge feature of dictionary settings. """ s = LazySettings() s.configure(CACHES={ '_clear_defaults': True, 'temp': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'} }) self.assertDictEqual(s.CACHES, { '_clear_defaults': True, 'temp': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache'} }) # Also work on a subkey s = LazySettings() s.configure(CACHES={ 'default': { '_clear_defaults': True, 'LOCATION': 'unique-snowflake', } }) self.assertDictEqual(s.CACHES, { 'default': { '_clear_defaults': True, 'LOCATION': 'unique-snowflake', } })
def test_protocol_not_specified(): settings = LazySettings() settings.configure( **{ 'LOG_AGGREGATOR_HOST': 'https://server.invalid', 'LOG_AGGREGATOR_PORT': 22222, 'LOG_AGGREGATOR_PROTOCOL': None # awx/settings/defaults.py }) handler = AWXProxyHandler().get_handler(custom_settings=settings) assert isinstance(handler, logging.NullHandler)
def test_invalid_kwarg_to_real_handler(): settings = LazySettings() settings.configure( **{ 'LOG_AGGREGATOR_HOST': 'https://server.invalid', 'LOG_AGGREGATOR_PORT': 22222, 'LOG_AGGREGATOR_PROTOCOL': 'udp', 'LOG_AGGREGATOR_VERIFY_CERT': False # setting not valid for UDP handler }) handler = AWXProxyHandler().get_handler(custom_settings=settings) assert not hasattr(handler, 'verify_cert')
def test_real_handler_from_django_settings(params): settings = LazySettings() settings.configure(**params) handler = AWXProxyHandler().get_handler(custom_settings=settings) # need the _reverse_ dictionary from PARAM_NAMES attr_lookup = {} for attr_name, setting_name in PARAM_NAMES.items(): attr_lookup[setting_name] = attr_name for setting_name, val in params.items(): attr_name = attr_lookup[setting_name] if attr_name == 'protocol': continue assert hasattr(handler, attr_name)
def test_use_deprecated_pytz_deprecation(self): settings_module = ModuleType('fake_settings_module') settings_module.USE_DEPRECATED_PYTZ = True settings_module.USE_TZ = True sys.modules['fake_settings_module'] = settings_module try: with self.assertRaisesMessage(RemovedInDjango50Warning, USE_DEPRECATED_PYTZ_DEPRECATED_MSG): Settings('fake_settings_module') finally: del sys.modules['fake_settings_module'] holder = LazySettings() with self.assertRaisesMessage(RemovedInDjango50Warning, USE_DEPRECATED_PYTZ_DEPRECATED_MSG): holder.configure(USE_DEPRECATED_PYTZ=True)
def test_https_logging_handler_connectivity_test(https_adapter, status, reason, exc, protocol): host = 'example.org' if protocol: host = '://'.join([protocol, host]) https_adapter.status = status https_adapter.reason = reason settings = LazySettings() settings.configure( **{ 'LOG_AGGREGATOR_HOST': host, 'LOG_AGGREGATOR_PORT': 8080, 'LOG_AGGREGATOR_TYPE': 'logstash', 'LOG_AGGREGATOR_USERNAME': '******', 'LOG_AGGREGATOR_PASSWORD': '******', 'LOG_AGGREGATOR_LOGGERS': ['awx', 'activity_stream', 'job_events', 'system_tracking'], 'LOG_AGGREGATOR_PROTOCOL': 'https', 'CLUSTER_HOST_ID': '', 'LOG_AGGREGATOR_TOWER_UUID': str(uuid4()), 'LOG_AGGREGATOR_LEVEL': 'DEBUG', }) class FakeHTTPSHandler(HTTPSHandler): def __init__(self, *args, **kwargs): super(FakeHTTPSHandler, self).__init__(*args, **kwargs) self.session.mount('{}://'.format(protocol or 'https'), https_adapter) def emit(self, record): return super(FakeHTTPSHandler, self).emit(record) with mock.patch.object(AWXProxyHandler, 'get_handler_class') as mock_get_class: mock_get_class.return_value = FakeHTTPSHandler if exc: with pytest.raises(exc) as e: AWXProxyHandler().perform_test(settings) assert str(e).endswith('%s: %s' % (status, reason)) else: assert AWXProxyHandler().perform_test(settings) is None
def reg(request): """ This fixture initializes an awx settings registry object and passes it as an argument into the test function. """ cache = LocMemCache(str(uuid4()), {}) # make a new random cache each time settings = LazySettings() registry = SettingsRegistry(settings) # @pytest.mark.defined_in_file can be used to mark specific setting values # as "defined in a settings file". This is analogous to manually # specifying a setting on the filesystem (e.g., in a local_settings.py in # development, or in /etc/tower/conf.d/<something>.py) defaults = request.node.get_marker('defined_in_file') if defaults: settings.configure(**defaults.kwargs) settings._wrapped = SettingsWrapper(settings._wrapped, cache, registry) return registry
def test_usersettingsholder_repr(self): lazy_settings = LazySettings() lazy_settings.configure(APPEND_SLASH=False) expected = '<UserSettingsHolder>' self.assertEqual(repr(lazy_settings._wrapped), expected)
def test_configure(self): s = LazySettings() s.configure(SECRET_KEY='foo') self.assertTrue(s.is_overridden('SECRET_KEY'))
def test_configure_initializes_logging(self): settings = LazySettings() settings.configure(LOGGING_CONFIG='logging_tests.tests.dictConfig') self.assertTrue(dictConfig.called)
def test_configure_initializes_logging(self): settings = LazySettings() settings.configure( LOGGING_CONFIG='regressiontests.logging_tests.tests.dictConfig') self.assertTrue(dictConfig.called)
def test_nonupper_settings_ignored_in_default_settings(self): s = LazySettings() s.configure(SimpleNamespace(foo='bar')) with self.assertRaises(AttributeError): getattr(s, 'foo')
def test_nonupper_settings_prohibited_in_configure(self): s = LazySettings() with self.assertRaisesMessage(TypeError, "Setting 'foo' must be uppercase."): s.configure(foo='bar')
# -*- coding: utf-8 -*- DJANGO_REQUEST_ENABLE_SETTING = 'DJANGO_REQUEST_ENABLE' DJANGO_REQUEST_LOGFILE_SETTING = 'DJANGO_REQUEST_LOGFILE' REQUEST_ID_HEADER_SETTING = 'DJANGO_REQUEST_LOG_REQUEST_ID_HEADER' REQUEST_ID_RESPONSE_HEADER_SETTING = 'DJANGO_REQUEST_SET_REQUEST_ID_HEADER' NO_REQUEST_ID = '-' from django.conf import settings, LazySettings from django_request_logger.log import LOGGING import threading __version__ = "0.1" # ThreadLocal - dirty but does the job local = threading.local() if getattr(settings, DJANGO_REQUEST_ENABLE_SETTING, True): # override any existing logging configuration settings.LOGGING = LOGGING # create a new Settings object and pass in our settings, # we don't need/use the new Settings object, it is just to # get the private _configure_logging() method called unused_settings = LazySettings() unused_settings.configure(default_settings=settings)
def test_configure(self): s = LazySettings() s.configure(SECRET_KEY="foo") self.assertTrue(s.is_overridden("SECRET_KEY"))