Ejemplo n.º 1
0
    def test_04_logging_config_yaml(self):
        class Config(TestingConfig):
            PI_LOGCONFIG = "tests/testdata/logging.yml"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app(config_name='testing')
            # check the correct initialization of the logging from config file
            logger = logging.getLogger('privacyidea')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison(
                    'logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison('privacyidea.lib.log.SecureFormatter',
                                         _fmt="[%(asctime)s][%(process)d]"
                                         "[%(thread)d][%(levelname)s]"
                                         "[%(name)s:%(lineno)d] "
                                         "%(message)s",
                                         strict=False),
                    backupCount=5,
                    level=logging.DEBUG,
                    strict=False)
            ], logger.handlers)
            logger = logging.getLogger('audit')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison('logging.handlers.RotatingFileHandler',
                           backupCount=14,
                           baseFilename=os.path.join(dirname, 'audit.log'),
                           level=logging.INFO,
                           formatter=None,
                           strict=False)
            ], logger.handlers)
Ejemplo n.º 2
0
 def test_factory(self):
     slot_list = slot_factory(["gen", "por", "ret"])
     self.assertTrue(
         Comparison(Slot, name="gen", activation=0) == slot_list[0])
     self.assertTrue(
         Comparison(Slot, name="por", activation=0) == slot_list[1])
     self.assertTrue(
         Comparison(Slot, name="ret", activation=0) == slot_list[2])
Ejemplo n.º 3
0
 def test_01_create_default_app(self):
     # This will create the app with the 'development' configuration
     app = create_app()
     self.assertIsInstance(app, flask.app.Flask, app)
     self.assertEqual(app.env, 'production', app)
     self.assertTrue(app.debug, app)
     self.assertFalse(app.testing, app)
     self.assertEqual(app.import_name, 'privacyidea.app', app)
     self.assertEqual(app.name, 'privacyidea.app', app)
     self.assertTrue(app.response_class == PiResponseClass, app)
     blueprints = [
         'validate_blueprint', 'token_blueprint', 'system_blueprint',
         'resolver_blueprint', 'realm_blueprint', 'defaultrealm_blueprint',
         'policy_blueprint', 'login_blueprint', 'jwtauth', 'user_blueprint',
         'audit_blueprint', 'machineresolver_blueprint',
         'machine_blueprint', 'application_blueprint',
         'caconnector_blueprint', 'cert_blueprint', 'ttype_blueprint',
         'register_blueprint', 'smtpserver_blueprint', 'recover_blueprint',
         'radiusserver_blueprint', 'periodictask_blueprint',
         'privacyideaserver_blueprint', 'eventhandling_blueprint',
         'smsgateway_blueprint', 'client_blueprint',
         'subscriptions_blueprint', 'monitoring_blueprint'
     ]
     self.assertTrue(all(k in app.before_request_funcs for k in blueprints),
                     app)
     self.assertTrue(all(k in app.blueprints for k in blueprints), app)
     extensions = ['sqlalchemy', 'migrate', 'babel']
     self.assertTrue(all(k in extensions for k in app.extensions), app)
     self.assertEqual(app.secret_key, 't0p s3cr3t', app)
     # TODO: check url_map and view_functions
     # check that the configuration was loaded successfully
     # the default configuration is 'development'
     dc = config['development']()
     members = inspect.getmembers(dc, lambda a: not (inspect.isroutine(a)))
     conf = [
         m for m in members
         if not (m[0].startswith('__') and m[0].endswith('__'))
     ]
     self.assertTrue(all(app.config[k] == v for k, v in conf), app)
     # check the correct initialization of the logging
     logger = logging.getLogger('privacyidea')
     self.assertEqual(logger.level, logging.DEBUG, logger)
     compare([
         Comparison('logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison(
                        'privacyidea.lib.log.SecureFormatter',
                        _fmt="[%(asctime)s][%(process)d]"
                        "[%(thread)d][%(levelname)s]"
                        "[%(name)s:%(lineno)d] "
                        "%(message)s",
                        strict=False),
                    level=logging.DEBUG,
                    strict=False)
     ], logger.handlers)
Ejemplo n.º 4
0
    def __exit__(self, type, actual, traceback):
        # bug in python :-(
        if type is not None and not isinstance(actual, type):
            # fixed in 2.7 onwards!
            actual = type(actual)  # pragma: no cover

        self.raised = actual

        if self.expected:
            if self.exception:
                comparison = Comparison(self.exception)
                if comparison != actual:
                    repr_actual = repr(actual)
                    repr_expected = repr(self.exception)
                    message = '%s raised, %s expected' % (repr_actual,
                                                          repr_expected)
                    if repr_actual == repr_expected:
                        print(str(comparison).split('\n'))
                        extra = [', attributes differ:']
                        extra.extend(str(comparison).split('\n')[2:-1])
                        message += '\n'.join(extra)
                    raise AssertionError(message)

            elif not actual:
                raise AssertionError('No exception raised!')
        elif actual:
            raise AssertionError('%r raised, no exception expected' % actual)

        return True
Ejemplo n.º 5
0
 def handle(self, actual):
     self.raised = actual
     if self.expected:
         if Comparison(self.expected) != actual:
             raise AssertionError('%r raised, %r expected' %
                                  (actual, self.expected))
     elif not actual:
         raise AssertionError('No exception raised!')
Ejemplo n.º 6
0
    def test_extra_expected_attribute_not_strict(self):

        class MyClass(object):
            def __init__(self, **attrs):
                self.__dict__.update(attrs)

        c = Comparison(MyClass, a=1, strict=False)
        assert c == MyClass(a=1, b=2)
Ejemplo n.º 7
0
    def test_missing_expected_attribute_strict(self):

        class MyClass(object):
            def __init__(self, **attrs):
                self.__dict__.update(attrs)

        c = Comparison(MyClass, b=2, c=3, strict=True)
        assert c != MyClass(a=1, b=2)
Ejemplo n.º 8
0
 def test_default_logger_with_exception(self):
     """Test exception logging with the default config and json logger."""
     reconplogger.load_config('reconplogger_default_cfg')
     logger = logging.getLogger('json_logger')
     error_msg = 'error message'
     exception = RuntimeError('Exception message')
     with LogCapture(names='json_logger') as log:
         try:
             raise exception
         except Exception as e:
             logger.error(error_msg, exc_info=True)
             compare(Comparison(exception), log.records[-1].exc_info[1])
             log.check(('json_logger', 'ERROR', error_msg))
Ejemplo n.º 9
0
    def test_05_logging_config_broken_yaml(self):
        class Config(TestingConfig):
            PI_LOGCONFIG = "tests/testdata/logging_broken.yaml"

        with mock.patch.dict("privacyidea.config.config", {"testing": Config}):
            app = create_app(config_name='testing')
            # check the correct initialization of the logging with the default
            # values since the yaml file is broken
            logger = logging.getLogger('privacyidea')
            self.assertEqual(logger.level, logging.INFO, logger)
            compare([
                Comparison(
                    'logging.handlers.RotatingFileHandler',
                    baseFilename=os.path.join(dirname, 'privacyidea.log'),
                    formatter=Comparison('privacyidea.lib.log.SecureFormatter',
                                         _fmt="[%(asctime)s][%(process)d]"
                                         "[%(thread)d][%(levelname)s]"
                                         "[%(name)s:%(lineno)d] "
                                         "%(message)s",
                                         strict=False),
                    level=logging.INFO,
                    strict=False)
            ], logger.handlers)
Ejemplo n.º 10
0
    def __exit__(self, type, actual, traceback):
        # bug in python :-(
        if type is not None and not isinstance(actual, type):
            # fixed in 2.7 onwards!
            actual = type(actual)  # pragma: no cover

        self.raised = actual

        if self.expected:
            if self.exception:
                if Comparison(self.exception) != actual:
                    raise AssertionError('%r raised, %r expected' %
                                         (actual, self.exception))
            elif not actual:
                raise AssertionError('No exception raised!')
        elif actual:
            raise AssertionError('%r raised, no exception expected' % actual)

        return True