Пример #1
0
 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'])
Пример #2
0
 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'
                 }
             }
         })
Пример #3
0
    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)))
Пример #4
0
    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, [])
Пример #5
0
 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'], [])
Пример #6
0
    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])
Пример #7
0
    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'], [])
Пример #8
0
    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()}
Пример #10
0
    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'], [])
Пример #11
0
    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, [])
Пример #12
0
    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'])
Пример #13
0
 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'
                 }
             }
         })
Пример #14
0
 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': []
             },
         })
Пример #15
0
 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']
             }
         })
Пример #16
0
 def setUp(self):
     Config.default().apply()
     main_scheduler.reset_timer()
Пример #17
0
 def test_config_property_getter_empty(self):
     c = Config(name='lol', config_json='')
     self.assertEqual(c.config, {})
Пример #18
0
 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))
Пример #19
0
 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, [])
Пример #20
0
 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, {})
Пример #21
0
 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)
Пример #22
0
 def tearDown(self):
     # reset the default config
     Config.default().apply()
     main_scheduler.reset_timer()