test_user_error_handler.py
This file
Path
tests/test_user_error_handler.py
295 lines · 8.2 KiB · Python
Last changed by
Merge pull request #4560 from qingpeng9802/fix-old-behaviorDavid Lordbefore adoption127df57
History of this fileTake it
The walk stopped after 200 commits: lines older than 50eb6e5 point at it.
Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5
lines 1–18why, one step back1import 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"18Merge pull request #4560 from qingpeng9802/fix-old-behaviorDavid Lordbefore adoption127df57
lines 19–20why, one step back19 with pytest.raises(TypeError) as exc_info:20 app.register_error_handler(CustomException(), None)Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5
line 21why, one step back21Merge pull request #4560 from qingpeng9802/fix-old-behaviorDavid Lordbefore adoption127df57
lines 22–28why, one step back22 assert "CustomException() is an instance, not a class." in str(exc_info.value)2324 with pytest.raises(ValueError) as exc_info:25 app.register_error_handler(list, None)2627 assert "'list' is not a subclass of Exception." in str(exc_info.value)28Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5
lines 29–32why, one step back29 @app.errorhandler(500)30 def handle_500(e):31 assert isinstance(e, InternalServerError)32Merge pull request #4560 from qingpeng9802/fix-old-behaviorDavid Lordbefore adoption127df57
lines 33–34why, one step back33 if e.original_exception is not None:34 return f"wrapped {type(e.original_exception).__name__}"Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5
lines 35–36why, one step back3536 return "direct"Merge pull request #4560 from qingpeng9802/fix-old-behaviorDavid Lordbefore adoption127df57
lines 37–41why, one step back3738 with pytest.raises(ValueError) as exc_info:39 app.register_error_handler(999, None)4041 assert "Use a subclass of HTTPException" in str(exc_info.value)Merge pull request #3856 from pallets/dependabot/pip/pre-commit-2.9.3dependabot-preview[bot]before adoption50eb6e5
lines 42–295why, one step back4243 @app.route("/custom")44 def custom_test():45 raise CustomException()4647 @app.route("/keyerror")48 def key_error():49 raise KeyError()5051 @app.route("/abort")52 def do_abort():53 flask.abort(500)5455 app.testing = False56 assert client.get("/custom").data == b"custom"57 assert client.get("/keyerror").data == b"wrapped KeyError"58 assert client.get("/abort").data == b"direct"596061def test_error_handler_subclass(app):62 class ParentException(Exception):63 pass6465 class ChildExceptionUnregistered(ParentException):66 pass6768 class ChildExceptionRegistered(ParentException):69 pass7071 @app.errorhandler(ParentException)72 def parent_exception_handler(e):73 assert isinstance(e, ParentException)74 return "parent"7576 @app.errorhandler(ChildExceptionRegistered)77 def child_exception_handler(e):78 assert isinstance(e, ChildExceptionRegistered)79 return "child-registered"8081 @app.route("/parent")82 def parent_test():83 raise ParentException()8485 @app.route("/child-unregistered")86 def unregistered_test():87 raise ChildExceptionUnregistered()8889 @app.route("/child-registered")90 def registered_test():91 raise ChildExceptionRegistered()9293 c = app.test_client()9495 assert c.get("/parent").data == b"parent"96 assert c.get("/child-unregistered").data == b"parent"97 assert c.get("/child-registered").data == b"child-registered"9899100def test_error_handler_http_subclass(app):101 class ForbiddenSubclassRegistered(Forbidden):102 pass103104 class ForbiddenSubclassUnregistered(Forbidden):105 pass106107 @app.errorhandler(403)108 def code_exception_handler(e):109 assert isinstance(e, Forbidden)110 return "forbidden"111112 @app.errorhandler(ForbiddenSubclassRegistered)113 def subclass_exception_handler(e):114 assert isinstance(e, ForbiddenSubclassRegistered)115 return "forbidden-registered"116117 @app.route("/forbidden")118 def forbidden_test():119 raise Forbidden()120121 @app.route("/forbidden-registered")122 def registered_test():123 raise ForbiddenSubclassRegistered()124125 @app.route("/forbidden-unregistered")126 def unregistered_test():127 raise ForbiddenSubclassUnregistered()128129 c = app.test_client()130131 assert c.get("/forbidden").data == b"forbidden"132 assert c.get("/forbidden-unregistered").data == b"forbidden"133 assert c.get("/forbidden-registered").data == b"forbidden-registered"134135136def test_error_handler_blueprint(app):137 bp = flask.Blueprint("bp", __name__)138139 @bp.errorhandler(500)140 def bp_exception_handler(e):141 return "bp-error"142143 @bp.route("/error")144 def bp_test():145 raise InternalServerError()146147 @app.errorhandler(500)148 def app_exception_handler(e):149 return "app-error"150151 @app.route("/error")152 def app_test():153 raise InternalServerError()154155 app.register_blueprint(bp, url_prefix="/bp")156157 c = app.test_client()158159 assert c.get("/error").data == b"app-error"160 assert c.get("/bp/error").data == b"bp-error"161162163def test_default_error_handler():164 bp = flask.Blueprint("bp", __name__)165166 @bp.errorhandler(HTTPException)167 def bp_exception_handler(e):168 assert isinstance(e, HTTPException)169 assert isinstance(e, NotFound)170 return "bp-default"171172 @bp.errorhandler(Forbidden)173 def bp_forbidden_handler(e):174 assert isinstance(e, Forbidden)175 return "bp-forbidden"176177 @bp.route("/undefined")178 def bp_registered_test():179 raise NotFound()180181 @bp.route("/forbidden")182 def bp_forbidden_test():183 raise Forbidden()184185 app = flask.Flask(__name__)186187 @app.errorhandler(HTTPException)188 def catchall_exception_handler(e):189 assert isinstance(e, HTTPException)190 assert isinstance(e, NotFound)191 return "default"192193 @app.errorhandler(Forbidden)194 def catchall_forbidden_handler(e):195 assert isinstance(e, Forbidden)196 return "forbidden"197198 @app.route("/forbidden")199 def forbidden():200 raise Forbidden()201202 @app.route("/slash/")203 def slash():204 return "slash"205206 app.register_blueprint(bp, url_prefix="/bp")207208 c = app.test_client()209 assert c.get("/bp/undefined").data == b"bp-default"210 assert c.get("/bp/forbidden").data == b"bp-forbidden"211 assert c.get("/undefined").data == b"default"212 assert c.get("/forbidden").data == b"forbidden"213 # Don't handle RequestRedirect raised when adding slash.214 assert c.get("/slash", follow_redirects=True).data == b"slash"215216217class TestGenericHandlers:218 """Test how very generic handlers are dispatched to."""219220 class Custom(Exception):221 pass222223 @pytest.fixture()224 def app(self, app):225 @app.route("/custom")226 def do_custom():227 raise self.Custom()228229 @app.route("/error")230 def do_error():231 raise KeyError()232233 @app.route("/abort")234 def do_abort():235 flask.abort(500)236237 @app.route("/raise")238 def do_raise():239 raise InternalServerError()240241 app.config["PROPAGATE_EXCEPTIONS"] = False242 return app243244 def report_error(self, e):245 original = getattr(e, "original_exception", None)246247 if original is not None:248 return f"wrapped {type(original).__name__}"249250 return f"direct {type(e).__name__}"251252 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))253 def test_handle_class_or_code(self, app, client, to_handle):254 """``InternalServerError`` and ``500`` are aliases, they should255 have the same behavior. Both should only receive256 ``InternalServerError``, which might wrap another error.257 """258259 @app.errorhandler(to_handle)260 def handle_500(e):261 assert isinstance(e, InternalServerError)262 return self.report_error(e)263264 assert client.get("/custom").data == b"wrapped Custom"265 assert client.get("/error").data == b"wrapped KeyError"266 assert client.get("/abort").data == b"direct InternalServerError"267 assert client.get("/raise").data == b"direct InternalServerError"268269 def test_handle_generic_http(self, app, client):270 """``HTTPException`` should only receive ``HTTPException``271 subclasses. It will receive ``404`` routing exceptions.272 """273274 @app.errorhandler(HTTPException)275 def handle_http(e):276 assert isinstance(e, HTTPException)277 return str(e.code)278279 assert client.get("/error").data == b"500"280 assert client.get("/abort").data == b"500"281 assert client.get("/not-found").data == b"404"282283 def test_handle_generic(self, app, client):284 """Generic ``Exception`` will handle all exceptions directly,285 including ``HTTPExceptions``.286 """287288 @app.errorhandler(Exception)289 def handle_exception(e):290 return self.report_error(e)291292 assert client.get("/custom").data == b"direct Custom"293 assert client.get("/error").data == b"direct KeyError"294 assert client.get("/abort").data == b"direct InternalServerError"295 assert client.get("/not-found").data == b"direct NotFound"