Exemplo n.º 1
0
def package_setup():
    """Make sure the application starts in a pristine state.
    """
    # This will make sure we always connect to the test database.
    os.environ['TESTING'] = 'true'

    # This will make sure we always connect to the test database.
    os.environ['TESTING'] = 'true'

    # Ensure that the log configuration starts in a known state.
    LogConfiguration.initialize(None, testing=True)

    # Drop any existing schema. It will be recreated when
    # SessionManager.initialize() runs.
    #
    # Base.metadata.drop_all(connection) doesn't work here, so we
    # approximate by dropping every item individually.
    engine = SessionManager.engine()
    for table in reversed(Base.metadata.sorted_tables):
        if table.name.startswith('mv_'):
            statement = "drop materialized view %s" % table.name
        else:
            statement = table.delete()

        try:
            engine.execute(statement)
        except ProgrammingError, e:
            if 'does not exist' in e.message:
                # This is the first time running these tests
                # on this server, and the tables don't exist yet.
                pass
Exemplo n.º 2
0
def package_setup():
    """Make sure the application starts in a pristine state.
    """
    # This will make sure we always connect to the test database.
    os.environ['TESTING'] = 'true'

    # This will make sure we always connect to the test database.
    os.environ['TESTING'] = 'true'

    # Ensure that the log configuration starts in a known state.
    LogConfiguration.initialize(None, testing=True)

    # Drop any existing schema. It will be recreated when
    # SessionManager.initialize() runs.
    #
    # Base.metadata.drop_all(connection) doesn't work here, so we
    # approximate by dropping every item individually.
    engine = SessionManager.engine()
    for table in reversed(Base.metadata.sorted_tables):
        if table.name.startswith('mv_'):
            statement = "drop materialized view %s" % table.name
        else:
            statement = table.delete()

        try:
            engine.execute(statement)
        except ProgrammingError, e:
            if 'does not exist' in e.message:
                # This is the first time running these tests
                # on this server, and the tables don't exist yet.
                pass
Exemplo n.º 3
0
    def handle(self, exception):
        """Something very bad has happened. Notify the client."""
        # By default, when reporting errors, err on the side of
        # terseness, to avoid leaking sensitive information.
        debug = self.app.config['DEBUG'] or self.debug

        if hasattr(self.app, 'manager') and hasattr(self.app.manager, '_db'):
            # There is an active database session.

            # Use it to determine whether we are in debug mode, in
            # which case we _should_ provide the client with a lot of
            # information about the problem, without worrying
            # whether it contains sensitive information.
            _db = self.app.manager._db
            try:
                LogConfiguration.from_configuration(_db)
                (log_level, database_log_level, handlers,
                 errors) = LogConfiguration.from_configuration(
                     self.app.manager._db)
                debug = debug or (LogConfiguration.DEBUG
                                  in (log_level, database_log_level))
            except SQLAlchemyError, e:
                # The database session could not be used, possibly due to
                # the very error under consideration. Go with the
                # preexisting value for `debug`.
                pass

            # Then roll the session back.
            self.app.manager._db.rollback()
Exemplo n.º 4
0
    def handle(self, exception):
        """Something very bad has happened. Notify the client."""
        # By default, when reporting errors, err on the side of
        # terseness, to avoid leaking sensitive information.
        debug = self.app.config['DEBUG'] or self.debug

        if hasattr(self.app, 'manager') and hasattr(self.app.manager, '_db'):
            # There is an active database session.

            # Use it to determine whether we are in debug mode, in
            # which case we _should_ provide the client with a lot of
            # information about the problem, without worrying
            # whether it contains sensitive information.
            _db = self.app.manager._db
            try:
                LogConfiguration.from_configuration(_db)
                (log_level, database_log_level, handlers,
                 errors) = LogConfiguration.from_configuration(
                     self.app.manager._db
                 )
                debug = debug or (
                    LogConfiguration.DEBUG in (log_level, database_log_level)
                )
            except SQLAlchemyError, e:
                # The database session could not be used, possibly due to
                # the very error under consideration. Go with the
                # preexisting value for `debug`.
                pass

            # Then roll the session back.
            self.app.manager._db.rollback()
Exemplo n.º 5
0
def package_setup():
    """Make sure the database schema is initialized and initial
    data is in place.
    """

    # Ensure that the log configuration starts in a known state.
    LogConfiguration.initialize(None, testing=True)

    engine, connection = DatabaseTest.get_database_connection()

    # First, recreate the schema.
    #
    # Base.metadata.drop_all(connection) doesn't work here, so we
    # approximate by dropping everything except the materialized
    # views.
    for table in reversed(Base.metadata.sorted_tables):
        if not table.name.startswith('mv_'):
            engine.execute(table.delete())

    Base.metadata.create_all(connection)

    # Initialize basic database data needed by the application.
    _db = Session(connection)
    SessionManager.initialize_data(_db)    
    _db.commit()
    connection.close()
    engine.dispose()
Exemplo n.º 6
0
    def test_loggly_handler(self):
        """Turn an appropriate ExternalIntegration into a LogglyHandler."""

        integration = self.loggly_integration()
        handler = LogConfiguration.loggly_handler(integration)
        assert isinstance(handler, LogglyHandler)
        eq_("http://example.com/a_token/", handler.url)

        # Remove the loggly handler's .url, and the default URL will
        # be used.
        integration.url = None
        handler = LogConfiguration.loggly_handler(integration)
        eq_(LogConfiguration.DEFAULT_LOGGLY_URL % dict(token="a_token"),
            handler.url)
Exemplo n.º 7
0
    def test_set_formatter(self):
        # Create a generic handler.
        handler = logging.StreamHandler()

        # Configure it for text output.
        template = '%(filename)s:%(message)s'
        LogConfiguration.set_formatter(handler,
                                       LogConfiguration.TEXT_LOG_FORMAT,
                                       template)
        formatter = handler.formatter
        assert isinstance(formatter, StringFormatter)
        eq_(template, formatter._fmt)

        # Configure a similar handler for JSON output.
        handler = logging.StreamHandler()
        LogConfiguration.set_formatter(handler,
                                       LogConfiguration.JSON_LOG_FORMAT,
                                       template)
        formatter = handler.formatter
        assert isinstance(formatter, JSONFormatter)

        # In this case the template is irrelevant. The JSONFormatter
        # uses the default format template, but it doesn't matter,
        # because JSONFormatter overrides the format() method.
        eq_('%(message)s', formatter._fmt)

        # Configure a handler for output to Loggly. In this case
        # the format and template are irrelevant.
        handler = LogglyHandler("no-such-url")
        LogConfiguration.set_formatter(handler, None, None)
        assert isinstance(formatter, JSONFormatter)
Exemplo n.º 8
0
)

app = Flask(__name__)
babel = Babel(app)

# Create annotators for this app.
has_library = has_library_factory(app)
uses_location = uses_location_factory(app)

testing = 'TESTING' in os.environ
db_url = Configuration.database_url(testing)
SessionManager.initialize(db_url)
session_factory = SessionManager.sessionmaker(db_url)
_db = flask_scoped_session(session_factory, app)

log_level = LogConfiguration.initialize(_db, testing=testing)
debug = log_level == 'DEBUG'
app.config['DEBUG'] = debug
app.debug = debug
app._db = _db

if os.environ.get('AUTOINITIALIZE') == 'False':
    pass
    # It's the responsibility of the importing code to set app.library_registry
    # appropriately.
else:
    if getattr(app, 'library_registry', None) is None:
        app.library_registry = LibraryRegistry(_db)


@app.before_first_request