Exemplo n.º 1
0
 def test_unhandled_error(self):
     handler = ErrorHandler(self.app)
     with self.app.test_request_context("/"):
         response = None
         try:
             self.raise_exception()
         except Exception as exception:
             response = handler.handle(exception)
         assert 500 == response.status_code
         assert "An internal error occured" == response.data.decode("utf8")
Exemplo n.º 2
0
    def test_handle_error_as_problem_detail_document(self):
        handler = ErrorHandler(self.app)
        with self.app.test_request_context("/"):
            try:
                self.raise_exception(CanBeProblemDetailDocument)
            except Exception as exception:
                response = handler.handle(exception)

            assert 400 == response.status_code
            data = json.loads(response.data.decode("utf8"))
            assert INVALID_URN.title == data["title"]

            # Since we are not in debug mode, the debug_message is
            # destroyed.
            assert "debug_message" not in data
Exemplo n.º 3
0
    def test_unhandled_error_debug(self):
        # Set the sitewide log level to DEBUG to get a stack trace
        # instead of a generic error message.
        handler = ErrorHandler(self.app)
        self.activate_debug_mode()

        with self.app.test_request_context("/"):
            response = None
            try:
                self.raise_exception()
            except Exception as exception:
                response = handler.handle(exception)
            assert 500 == response.status_code
            assert response.data.startswith(
                b"Traceback (most recent call last)")
Exemplo n.º 4
0
def initialize_database(autoinitialize=True):
    db_url = Configuration.database_url()
    if autoinitialize:
        SessionManager.initialize(db_url)
    session_factory = SessionManager.sessionmaker(db_url)
    _db = flask_scoped_session(session_factory, app)
    app._db = _db

    Configuration.load(_db)
    testing = 'TESTING' in os.environ
    log_level = LogConfiguration.initialize(_db, testing=testing)
    if app.debug is None:
        debug = log_level == 'DEBUG'
        app.debug = debug
    else:
        debug = app.debug
    app.config['DEBUG'] = debug
    _db.commit()
    app.log = logging.getLogger("Metadata web app")
    app.log.info("Application debug mode: %r", app.debug)
    for logger in logging.getLogger().handlers:
        app.log.info("Logs are going to %r", logger)

    # Register an error handler that logs exceptions through the
    # normal logging process and tries to turn them into Problem
    # Detail Documents.
    h = ErrorHandler(app, app.config['DEBUG'])

    @app.errorhandler(Exception)
    def exception_handler(exception):
        return h.handle(exception)
Exemplo n.º 5
0
    def test_handle_error_as_problem_detail_document_debug(self):
        # When in debug mode, the debug_message is preserved and a
        # stack trace is appended to it.
        handler = ErrorHandler(self.app)
        self.activate_debug_mode()
        with self.app.test_request_context("/"):
            try:
                self.raise_exception(CanBeProblemDetailDocument)
            except Exception as exception:
                response = handler.handle(exception)

            assert 400 == response.status_code
            data = json.loads(response.data.decode("utf8"))
            assert INVALID_URN.title == data["title"]
            assert data["debug_message"].startswith(
                "A debug_message which should only appear in debug mode.\n\n"
                "Traceback (most recent call last)")
Exemplo n.º 6
0
        else:
            resp = make_response(f(*args, **kwargs))

        patron_web_domains = app.manager.patron_web_domains
        if patron_web_domains:
            options = get_cors_options(
                app, dict(origins=patron_web_domains, supports_credentials=True)
            )
            set_cors_headers(resp, options)

        return resp

    return update_wrapper(wrapped_function, f)


h = ErrorHandler(app, app.config["DEBUG"])


@app.errorhandler(Exception)
@allows_patron_web
def exception_handler(exception):
    if isinstance(exception, HTTPException):
        # This isn't an exception we need to handle, it's werkzeug's way
        # of interrupting normal control flow with a specific HTTP response.
        # Return the exception and it will be used as the response.
        return exception
    return h.handle(exception)


def has_library(f):
    """Decorator to extract the library short name from the arguments."""
Exemplo n.º 7
0
    patron_web_url = patron_web_integration.get(Configuration.URL)
    allows_patron_web = partial(
        cross_origin,
        origins=[patron_web_url],
        supports_credentials=True,
    )
else:
    # If the patron web client isn't configured, the decorator will do nothing.
    def allows_patron_web():
        def decorated(f):
            return f

        return decorated


h = ErrorHandler(app, app.config['DEBUG'])


@app.errorhandler(Exception)
@allows_patron_web()
def exception_handler(exception):
    return h.handle(exception)


def dir_route(path, *args, **kwargs):
    """Decorator to create routes that work with or without a trailing slash."""

    if path.endswith("/"):
        path_without_slash = path[:-1]
    else:
        path_without_slash = path