def test_messages_passed(self): with MockHandler.capture() as messages: self.assertEqual(messages['debug'], []) logger = logging.getLogger('testproject.testapp') logger.debug("couocu") # handler not attached to this logger self.assertEqual(messages['debug'], []) # setup new config cfg = Config(name='empty') cfg.config = { "loggers": { "dynamic_logging": { "handlers": ["console", "null"], "level": "ERROR", }, "testproject.testapp": { "handlers": ["mock"], "level": "WARN", } } } cfg.apply() # log debug ineficient logger.debug("couocu") with MockHandler.capture() as messages: self.assertEqual(messages['debug'], []) self.assertEqual(messages['warning'], []) logger.warn("hey") self.assertEqual(messages['debug'], []) self.assertEqual(messages['warning'], ['hey'])
def test_config_property_getter(self): c = Config(name='lol', config_json='{}') self.maxDiff = None c.config_json = json.dumps({ 'handlers': { 'added': {} }, 'loggers': { 'console': { 'level': 'CRITICAL', 'class': 'missed' } } }) self.assertEqual( c.config, { 'handlers': { 'added': {} }, 'loggers': { 'console': { 'level': 'CRITICAL' } } })
def render(self, name, value, attrs=None): attrs = attrs or {} try: data = json.loads(value) data['handlers'] = self.merge_handlers_value( data.get('handlers', {})) data['loggers'] = OrderedDict(sorted(data['loggers'].items())) value = json.dumps(data) except ValueError: pass attrs['style'] = attrs.get('style', '') + ' display: none;' res = super(JsonLoggerWidget, self).render(name, value, attrs) extra = { 'handlers': list(Config.get_all_handlers().keys()), 'filters': list(Config.get_all_filters().keys()), 'loggers': list() } return res + format_html( '<div id="{anchorid}"></div>' '<script type="application/javascript">' '(function ($) {{' ' $(function() {{' ' logging_widget($("#{anchorid}"), $("#{areaid}"), {extra});' ' }});' '}}(jQuery));' '</script>', anchorid=attrs.get('id', name) + '_display', areaid=attrs.get('id', name), extra=mark_safe(json.dumps(extra)))
def test_simple_config(self): cfg = Config( name='empty', config_json= '{"loggers": {"dynamic_logging": {"handlers": ["console"]}}}') cfg.apply() for logger in Config.get_existing_loggers().values(): if logger.name in cfg.config['loggers']: self.assertEqual(len(logger.handlers), 1) else: self.assertEqual(logger.handlers, [])
def test_log_with_cfg(self): cfg = Config(name='mocklog') cfg.config = { "loggers": { "testproject.testapp": { "handlers": ["mock"], "level": "WARN", } } } cfg.apply() with MockHandler.capture() as messages: res = self.client.get('/testapp/log/DEBUG/testproject.testapp/') self.assertEqual(res.status_code, 200) self.assertEqual(messages['debug'], [])
def test_apply_by_scheduler_same_config(self): called = [] c = Config(name="lol", config_json='{}') t = Trigger(name='lol', config=c, start_date=None, end_date=None) c.apply = lambda tt: called.append(tt) main_scheduler.apply(t) self.assertEqual(called, [t]) main_scheduler.apply(t) self.assertEqual(called, [t]) c.config_json = '' main_scheduler.apply(t) self.assertEqual(called, [t, t]) main_scheduler.apply(t) self.assertEqual(called, [t, t])
def test_db_debug_not_debug(self): # bad config = Config(name='nothing') config.config = { "loggers": { "django.db": { "handlers": ["mock"], "level": 15, } } } config.apply() with MockHandler.capture() as msg: Config.objects.count() self.assertEqual(msg['debug'], [])
def test_db_debug_debug_ok(self): config = Config(name='nothing') config.config = { "loggers": { "django.db.backends": { "handlers": ["mock"], "level": "DEBUG", } } } config.apply() with MockHandler.capture() as msg: Config.objects.count() self.assertEqual(len(msg['debug']), 1) self.assertTrue('SELECT COUNT(*)' in msg['debug'][0])
def display_config(config=None): if config is None: config = main_scheduler.current_trigger.config try: config.config except ValueError: return {} return {'config': config, 'handlers': Config.get_all_handlers()}
def test_config_reversed(self): logger = logging.getLogger('testproject.testapp') # handler not attached to this logger # setup new config cfg = Config(name='empty') cfg.config = { "loggers": { "dynamic_logging": { "handlers": ["console", "null"], "level": "ERROR", }, "testproject.testapp": { "handlers": ["mock"], "level": "WARN", } } } cfg.apply() # log debug ineficient with MockHandler.capture() as messages: logger.warn("hey") self.assertEqual(messages['warning'], ['hey']) logger.warn("hey") self.assertEqual(messages['warning'], ['hey', 'hey']) with MockHandler.capture() as messages: # default config does not add to mockhandler Config.default().apply() logger.warn("hey") self.assertEqual(messages['warning'], [])
def test_level_config(self): loggers = Config.get_existing_loggers() self.assertEqual(loggers['testproject.testapp'].level, logging.DEBUG) # default to info cfg = Config(name='empty') cfg.config = { "loggers": { "dynamic_logging": { "handlers": ["console", "null"], "level": "ERROR", }, "testproject.testapp": { "handlers": ["devnull"], "level": "WARNING", } } } cfg.apply() self.assertEqual(loggers['testproject.testapp'].level, logging.WARNING) # default to info for logger in Config.get_existing_loggers().values(): logger_config = cfg.config['loggers'].get(logger.name) if logger_config: self.assertEqual(len(logger.handlers), len(logger_config['handlers'])) self.assertEqual(logger.level, getattr(logging, logger_config["level"])) else: self.assertEqual(logger.handlers, [])
def test_filter_apply(self): # handler not attached to this logger # setup new config cfg_filtered = Config(name='empty') cfg_filtered.config = { "loggers": { "testproject.testapp": { "handlers": ["mock"], "level": "WARN", "filters": ['polite'] } } } cfg_passall = Config(name='empty') cfg_passall.config = { "loggers": { "testproject.testapp": { "handlers": ["mock"], "level": "WARN", "filters": [] } } } logger_old = logging.getLogger('testproject.testapp') cfg_filtered.apply() logger = logging.getLogger('testproject.testapp') self.assertEqual(logger, logger_old) # log debug ineficient with MockHandler.capture() as messages: self.assertEqual(len(logger.filters), 1) logger.warn("hey") self.assertEqual(messages['warning'], []) logger.warn("hello, you") self.assertEqual(messages['warning'], ['hello, you']) with MockHandler.capture() as messages: # default config does not add cfg_passall.apply() logger.warn("hey") self.assertEqual(messages['warning'], ['hey']) logger.warn("hello, you") self.assertEqual(messages['warning'], ['hey', 'hello, you'])
def test_config_property_setter(self): c = Config(name='lol', config_json='{}') c.config = { 'handlers': { 'added': {} }, 'loggers': { 'console': { 'level': 'CRITICAL', 'class': 'missed' } } } self.assertEqual( json.loads(c.config_json), { 'handlers': { 'added': {} }, 'loggers': { 'console': { 'level': 'CRITICAL' } } })
def test_loggers_creation(self): asked_cfg = { 'django': { 'level': 'ERROR', 'propagate': False, }, 'django.request': { 'handlers': ['null'], 'filters': ['filter'] }, 'testproject.testapp': { 'handlers': ['null', 'devnull'], }, 'lol': { 'ignored': 'lol', } } self.maxDiff = None self.assertEqual( Config.create_loggers(asked_cfg), { 'django': { 'handlers': [], 'level': 'ERROR', 'propagate': False, 'filters': [] }, 'django.request': { 'handlers': ['null'], 'level': 'INFO', 'propagate': True, 'filters': ['filter'] }, 'testproject.testapp': { 'handlers': ['null', 'devnull'], 'level': 'INFO', 'propagate': True, 'filters': [] }, 'lol': { 'handlers': [], 'level': 'INFO', 'propagate': True, 'filters': [] }, })
def test_handler_merging(self): original_cfg = { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', }, 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'colored', 'propagate': False } } new_cfg = { 'dont exists': { # ignored 'level': 'ERROR' }, 'console': { 'level': 'INFO', # ok 'class': 'logging.HACKME', # ignored 'formatter': 'prout', # ignored 'ignored': True, # ignored 'filters': ['nofilter'] # ok } } res = Config.merge_handlers(original_cfg, new_cfg) self.assertEqual( res, { 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler', }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'colored', 'propagate': False, 'filters': ['nofilter'] } })
def setUp(self): Config.default().apply() main_scheduler.reset_timer()
def test_config_property_getter_empty(self): c = Config(name='lol', config_json='') self.assertEqual(c.config, {})
def test_default_config_by_default(self): loggers = Config.get_existing_loggers() for name, configured in settings.LOGGING['loggers'].items(): self.assertEqual(len(configured['handlers']), len(loggers[name].handlers))
def test_empty_config(self): cfg = Config(name='empty', config_json='{"loggers": {}}') cfg.apply() for logger in Config.get_existing_loggers().values(): self.assertEqual(logger.handlers, [])
def test_display_fallback_bad_config(self): c = Config(name="lol", config_json='}') self.assertRaises(ValueError, getattr, c, 'config') config = display_config(c) self.assertEqual(config, {})
def test_display_config_given(self): c = Config(name="lol", config_json='{}') config = display_config(c) self.assertEqual(config['config'], c) self.assertGreater(len(config['handlers']), 0)
def tearDown(self): # reset the default config Config.default().apply() main_scheduler.reset_timer()