test_user_error_handler.py
This file
Path
tests/test_user_error_handler.py
281 lines · 7.8 KiB · Python
Last changed by
remove unused module docstringsDavid Lordbefore adoptionf2f027d
History of this fileTake it
1import pytest2from werkzeug.exceptions import Forbidden3from werkzeug.exceptions import HTTPException4from werkzeug.exceptions import InternalServerError5from werkzeug.exceptions import NotFound67import flask8910def test_error_handler_no_match(app, client):11 class CustomException(Exception):12 pass1314 @app.errorhandler(CustomException)15 def custom_exception_handler(e):16 assert isinstance(e, CustomException)17 return "custom"1819 @app.errorhandler(500)20 def handle_500(e):21 assert isinstance(e, InternalServerError)22 original = getattr(e, "original_exception", None)2324 if original is not None:25 return f"wrapped {type(original).__name__}"2627 return "direct"2829 @app.route("/custom")30 def custom_test():31 raise CustomException()3233 @app.route("/keyerror")34 def key_error():35 raise KeyError()3637 @app.route("/abort")38 def do_abort():39 flask.abort(500)4041 app.testing = False42 assert client.get("/custom").data == b"custom"43 assert client.get("/keyerror").data == b"wrapped KeyError"44 assert client.get("/abort").data == b"direct"454647def test_error_handler_subclass(app):48 class ParentException(Exception):49 pass5051 class ChildExceptionUnregistered(ParentException):52 pass5354 class ChildExceptionRegistered(ParentException):55 pass5657 @app.errorhandler(ParentException)58 def parent_exception_handler(e):59 assert isinstance(e, ParentException)60 return "parent"6162 @app.errorhandler(ChildExceptionRegistered)63 def child_exception_handler(e):64 assert isinstance(e, ChildExceptionRegistered)65 return "child-registered"6667 @app.route("/parent")68 def parent_test():69 raise ParentException()7071 @app.route("/child-unregistered")72 def unregistered_test():73 raise ChildExceptionUnregistered()7475 @app.route("/child-registered")76 def registered_test():77 raise ChildExceptionRegistered()7879 c = app.test_client()8081 assert c.get("/parent").data == b"parent"82 assert c.get("/child-unregistered").data == b"parent"83 assert c.get("/child-registered").data == b"child-registered"848586def test_error_handler_http_subclass(app):87 class ForbiddenSubclassRegistered(Forbidden):88 pass8990 class ForbiddenSubclassUnregistered(Forbidden):91 pass9293 @app.errorhandler(403)94 def code_exception_handler(e):95 assert isinstance(e, Forbidden)96 return "forbidden"9798 @app.errorhandler(ForbiddenSubclassRegistered)99 def subclass_exception_handler(e):100 assert isinstance(e, ForbiddenSubclassRegistered)101 return "forbidden-registered"102103 @app.route("/forbidden")104 def forbidden_test():105 raise Forbidden()106107 @app.route("/forbidden-registered")108 def registered_test():109 raise ForbiddenSubclassRegistered()110111 @app.route("/forbidden-unregistered")112 def unregistered_test():113 raise ForbiddenSubclassUnregistered()114115 c = app.test_client()116117 assert c.get("/forbidden").data == b"forbidden"118 assert c.get("/forbidden-unregistered").data == b"forbidden"119 assert c.get("/forbidden-registered").data == b"forbidden-registered"120121122def test_error_handler_blueprint(app):123 bp = flask.Blueprint("bp", __name__)124125 @bp.errorhandler(500)126 def bp_exception_handler(e):127 return "bp-error"128129 @bp.route("/error")130 def bp_test():131 raise InternalServerError()132133 @app.errorhandler(500)134 def app_exception_handler(e):135 return "app-error"136137 @app.route("/error")138 def app_test():139 raise InternalServerError()140141 app.register_blueprint(bp, url_prefix="/bp")142143 c = app.test_client()144145 assert c.get("/error").data == b"app-error"146 assert c.get("/bp/error").data == b"bp-error"147148149def test_default_error_handler():150 bp = flask.Blueprint("bp", __name__)151152 @bp.errorhandler(HTTPException)153 def bp_exception_handler(e):154 assert isinstance(e, HTTPException)155 assert isinstance(e, NotFound)156 return "bp-default"157158 @bp.errorhandler(Forbidden)159 def bp_forbidden_handler(e):160 assert isinstance(e, Forbidden)161 return "bp-forbidden"162163 @bp.route("/undefined")164 def bp_registered_test():165 raise NotFound()166167 @bp.route("/forbidden")168 def bp_forbidden_test():169 raise Forbidden()170171 app = flask.Flask(__name__)172173 @app.errorhandler(HTTPException)174 def catchall_exception_handler(e):175 assert isinstance(e, HTTPException)176 assert isinstance(e, NotFound)177 return "default"178179 @app.errorhandler(Forbidden)180 def catchall_forbidden_handler(e):181 assert isinstance(e, Forbidden)182 return "forbidden"183184 @app.route("/forbidden")185 def forbidden():186 raise Forbidden()187188 @app.route("/slash/")189 def slash():190 return "slash"191192 app.register_blueprint(bp, url_prefix="/bp")193194 c = app.test_client()195 assert c.get("/bp/undefined").data == b"bp-default"196 assert c.get("/bp/forbidden").data == b"bp-forbidden"197 assert c.get("/undefined").data == b"default"198 assert c.get("/forbidden").data == b"forbidden"199 # Don't handle RequestRedirect raised when adding slash.200 assert c.get("/slash", follow_redirects=True).data == b"slash"201202203class TestGenericHandlers:204 """Test how very generic handlers are dispatched to."""205206 class Custom(Exception):207 pass208209 @pytest.fixture()210 def app(self, app):211 @app.route("/custom")212 def do_custom():213 raise self.Custom()214215 @app.route("/error")216 def do_error():217 raise KeyError()218219 @app.route("/abort")220 def do_abort():221 flask.abort(500)222223 @app.route("/raise")224 def do_raise():225 raise InternalServerError()226227 app.config["PROPAGATE_EXCEPTIONS"] = False228 return app229230 def report_error(self, e):231 original = getattr(e, "original_exception", None)232233 if original is not None:234 return f"wrapped {type(original).__name__}"235236 return f"direct {type(e).__name__}"237238 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))239 def test_handle_class_or_code(self, app, client, to_handle):240 """``InternalServerError`` and ``500`` are aliases, they should241 have the same behavior. Both should only receive242 ``InternalServerError``, which might wrap another error.243 """244245 @app.errorhandler(to_handle)246 def handle_500(e):247 assert isinstance(e, InternalServerError)248 return self.report_error(e)249250 assert client.get("/custom").data == b"wrapped Custom"251 assert client.get("/error").data == b"wrapped KeyError"252 assert client.get("/abort").data == b"direct InternalServerError"253 assert client.get("/raise").data == b"direct InternalServerError"254255 def test_handle_generic_http(self, app, client):256 """``HTTPException`` should only receive ``HTTPException``257 subclasses. It will receive ``404`` routing exceptions.258 """259260 @app.errorhandler(HTTPException)261 def handle_http(e):262 assert isinstance(e, HTTPException)263 return str(e.code)264265 assert client.get("/error").data == b"500"266 assert client.get("/abort").data == b"500"267 assert client.get("/not-found").data == b"404"268269 def test_handle_generic(self, app, client):270 """Generic ``Exception`` will handle all exceptions directly,271 including ``HTTPExceptions``.272 """273274 @app.errorhandler(Exception)275 def handle_exception(e):276 return self.report_error(e)277278 assert client.get("/custom").data == b"direct Custom"279 assert client.get("/error").data == b"direct KeyError"280 assert client.get("/abort").data == b"direct InternalServerError"281 assert client.get("/not-found").data == b"direct NotFound"