test_user_error_handler.py
This file
Path
tests/test_user_error_handler.py
288 lines · 7.9 KiB · Python
Last changed by
f-strings everywhereDavid Lordbefore adoption2ae740d
History of this fileTake it
1"""2tests.test_user_error_handler3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~45:copyright: 2010 Pallets6:license: BSD-3-Clause7"""8import pytest9from werkzeug.exceptions import Forbidden10from werkzeug.exceptions import HTTPException11from werkzeug.exceptions import InternalServerError12from werkzeug.exceptions import NotFound1314import flask151617def test_error_handler_no_match(app, client):18 class CustomException(Exception):19 pass2021 @app.errorhandler(CustomException)22 def custom_exception_handler(e):23 assert isinstance(e, CustomException)24 return "custom"2526 @app.errorhandler(500)27 def handle_500(e):28 assert isinstance(e, InternalServerError)29 original = getattr(e, "original_exception", None)3031 if original is not None:32 return f"wrapped {type(original).__name__}"3334 return "direct"3536 @app.route("/custom")37 def custom_test():38 raise CustomException()3940 @app.route("/keyerror")41 def key_error():42 raise KeyError()4344 @app.route("/abort")45 def do_abort():46 flask.abort(500)4748 app.testing = False49 assert client.get("/custom").data == b"custom"50 assert client.get("/keyerror").data == b"wrapped KeyError"51 assert client.get("/abort").data == b"direct"525354def test_error_handler_subclass(app):55 class ParentException(Exception):56 pass5758 class ChildExceptionUnregistered(ParentException):59 pass6061 class ChildExceptionRegistered(ParentException):62 pass6364 @app.errorhandler(ParentException)65 def parent_exception_handler(e):66 assert isinstance(e, ParentException)67 return "parent"6869 @app.errorhandler(ChildExceptionRegistered)70 def child_exception_handler(e):71 assert isinstance(e, ChildExceptionRegistered)72 return "child-registered"7374 @app.route("/parent")75 def parent_test():76 raise ParentException()7778 @app.route("/child-unregistered")79 def unregistered_test():80 raise ChildExceptionUnregistered()8182 @app.route("/child-registered")83 def registered_test():84 raise ChildExceptionRegistered()8586 c = app.test_client()8788 assert c.get("/parent").data == b"parent"89 assert c.get("/child-unregistered").data == b"parent"90 assert c.get("/child-registered").data == b"child-registered"919293def test_error_handler_http_subclass(app):94 class ForbiddenSubclassRegistered(Forbidden):95 pass9697 class ForbiddenSubclassUnregistered(Forbidden):98 pass99100 @app.errorhandler(403)101 def code_exception_handler(e):102 assert isinstance(e, Forbidden)103 return "forbidden"104105 @app.errorhandler(ForbiddenSubclassRegistered)106 def subclass_exception_handler(e):107 assert isinstance(e, ForbiddenSubclassRegistered)108 return "forbidden-registered"109110 @app.route("/forbidden")111 def forbidden_test():112 raise Forbidden()113114 @app.route("/forbidden-registered")115 def registered_test():116 raise ForbiddenSubclassRegistered()117118 @app.route("/forbidden-unregistered")119 def unregistered_test():120 raise ForbiddenSubclassUnregistered()121122 c = app.test_client()123124 assert c.get("/forbidden").data == b"forbidden"125 assert c.get("/forbidden-unregistered").data == b"forbidden"126 assert c.get("/forbidden-registered").data == b"forbidden-registered"127128129def test_error_handler_blueprint(app):130 bp = flask.Blueprint("bp", __name__)131132 @bp.errorhandler(500)133 def bp_exception_handler(e):134 return "bp-error"135136 @bp.route("/error")137 def bp_test():138 raise InternalServerError()139140 @app.errorhandler(500)141 def app_exception_handler(e):142 return "app-error"143144 @app.route("/error")145 def app_test():146 raise InternalServerError()147148 app.register_blueprint(bp, url_prefix="/bp")149150 c = app.test_client()151152 assert c.get("/error").data == b"app-error"153 assert c.get("/bp/error").data == b"bp-error"154155156def test_default_error_handler():157 bp = flask.Blueprint("bp", __name__)158159 @bp.errorhandler(HTTPException)160 def bp_exception_handler(e):161 assert isinstance(e, HTTPException)162 assert isinstance(e, NotFound)163 return "bp-default"164165 @bp.errorhandler(Forbidden)166 def bp_forbidden_handler(e):167 assert isinstance(e, Forbidden)168 return "bp-forbidden"169170 @bp.route("/undefined")171 def bp_registered_test():172 raise NotFound()173174 @bp.route("/forbidden")175 def bp_forbidden_test():176 raise Forbidden()177178 app = flask.Flask(__name__)179180 @app.errorhandler(HTTPException)181 def catchall_exception_handler(e):182 assert isinstance(e, HTTPException)183 assert isinstance(e, NotFound)184 return "default"185186 @app.errorhandler(Forbidden)187 def catchall_forbidden_handler(e):188 assert isinstance(e, Forbidden)189 return "forbidden"190191 @app.route("/forbidden")192 def forbidden():193 raise Forbidden()194195 @app.route("/slash/")196 def slash():197 return "slash"198199 app.register_blueprint(bp, url_prefix="/bp")200201 c = app.test_client()202 assert c.get("/bp/undefined").data == b"bp-default"203 assert c.get("/bp/forbidden").data == b"bp-forbidden"204 assert c.get("/undefined").data == b"default"205 assert c.get("/forbidden").data == b"forbidden"206 # Don't handle RequestRedirect raised when adding slash.207 assert c.get("/slash", follow_redirects=True).data == b"slash"208209210class TestGenericHandlers:211 """Test how very generic handlers are dispatched to."""212213 class Custom(Exception):214 pass215216 @pytest.fixture()217 def app(self, app):218 @app.route("/custom")219 def do_custom():220 raise self.Custom()221222 @app.route("/error")223 def do_error():224 raise KeyError()225226 @app.route("/abort")227 def do_abort():228 flask.abort(500)229230 @app.route("/raise")231 def do_raise():232 raise InternalServerError()233234 app.config["PROPAGATE_EXCEPTIONS"] = False235 return app236237 def report_error(self, e):238 original = getattr(e, "original_exception", None)239240 if original is not None:241 return f"wrapped {type(original).__name__}"242243 return f"direct {type(e).__name__}"244245 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))246 def test_handle_class_or_code(self, app, client, to_handle):247 """``InternalServerError`` and ``500`` are aliases, they should248 have the same behavior. Both should only receive249 ``InternalServerError``, which might wrap another error.250 """251252 @app.errorhandler(to_handle)253 def handle_500(e):254 assert isinstance(e, InternalServerError)255 return self.report_error(e)256257 assert client.get("/custom").data == b"wrapped Custom"258 assert client.get("/error").data == b"wrapped KeyError"259 assert client.get("/abort").data == b"direct InternalServerError"260 assert client.get("/raise").data == b"direct InternalServerError"261262 def test_handle_generic_http(self, app, client):263 """``HTTPException`` should only receive ``HTTPException``264 subclasses. It will receive ``404`` routing exceptions.265 """266267 @app.errorhandler(HTTPException)268 def handle_http(e):269 assert isinstance(e, HTTPException)270 return str(e.code)271272 assert client.get("/error").data == b"500"273 assert client.get("/abort").data == b"500"274 assert client.get("/not-found").data == b"404"275276 def test_handle_generic(self, app, client):277 """Generic ``Exception`` will handle all exceptions directly,278 including ``HTTPExceptions``.279 """280281 @app.errorhandler(Exception)282 def handle_exception(e):283 return self.report_error(e)284285 assert client.get("/custom").data == b"direct Custom"286 assert client.get("/error").data == b"direct KeyError"287 assert client.get("/abort").data == b"direct InternalServerError"288 assert client.get("/not-found").data == b"direct NotFound"