test_user_error_handler.py
This file
Path
tests/test_user_error_handler.py
289 lines · 8.0 KiB · Python
Last changed by
Merge pull request #3574 from jackwardell/adding-error-message-to-assertDavid Lordbefore adoptiond091bb0
History of this fileTake it
The walk stopped after 200 commits: lines older than b05a685 point at it.
Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 1–13why, 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 pass13Merge pull request #3574 from jackwardell/adding-error-message-to-assertDavid Lordbefore adoptiond091bb0
lines 14–16why, one step back14 class UnacceptableCustomException(BaseException):15 pass16Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 17–20why, one step back17 @app.errorhandler(CustomException)18 def custom_exception_handler(e):19 assert isinstance(e, CustomException)20 return "custom"Merge pull request #3574 from jackwardell/adding-error-message-to-assertDavid Lordbefore adoptiond091bb0
lines 21–25why, one step back2122 with pytest.raises(23 AssertionError, match="Custom exceptions must be subclasses of Exception."24 ):25 app.register_error_handler(UnacceptableCustomException, None)Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 26–32why, one step back2627 @app.errorhandler(500)28 def handle_500(e):29 assert isinstance(e, InternalServerError)30 original = getattr(e, "original_exception", None)3132 if original is not None:Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 33why, one step back33 return f"wrapped {type(original).__name__}"Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 34–210why, one step back3435 return "direct"3637 @app.route("/custom")38 def custom_test():39 raise CustomException()4041 @app.route("/keyerror")42 def key_error():43 raise KeyError()4445 @app.route("/abort")46 def do_abort():47 flask.abort(500)4849 app.testing = False50 assert client.get("/custom").data == b"custom"51 assert client.get("/keyerror").data == b"wrapped KeyError"52 assert client.get("/abort").data == b"direct"535455def test_error_handler_subclass(app):56 class ParentException(Exception):57 pass5859 class ChildExceptionUnregistered(ParentException):60 pass6162 class ChildExceptionRegistered(ParentException):63 pass6465 @app.errorhandler(ParentException)66 def parent_exception_handler(e):67 assert isinstance(e, ParentException)68 return "parent"6970 @app.errorhandler(ChildExceptionRegistered)71 def child_exception_handler(e):72 assert isinstance(e, ChildExceptionRegistered)73 return "child-registered"7475 @app.route("/parent")76 def parent_test():77 raise ParentException()7879 @app.route("/child-unregistered")80 def unregistered_test():81 raise ChildExceptionUnregistered()8283 @app.route("/child-registered")84 def registered_test():85 raise ChildExceptionRegistered()8687 c = app.test_client()8889 assert c.get("/parent").data == b"parent"90 assert c.get("/child-unregistered").data == b"parent"91 assert c.get("/child-registered").data == b"child-registered"929394def test_error_handler_http_subclass(app):95 class ForbiddenSubclassRegistered(Forbidden):96 pass9798 class ForbiddenSubclassUnregistered(Forbidden):99 pass100101 @app.errorhandler(403)102 def code_exception_handler(e):103 assert isinstance(e, Forbidden)104 return "forbidden"105106 @app.errorhandler(ForbiddenSubclassRegistered)107 def subclass_exception_handler(e):108 assert isinstance(e, ForbiddenSubclassRegistered)109 return "forbidden-registered"110111 @app.route("/forbidden")112 def forbidden_test():113 raise Forbidden()114115 @app.route("/forbidden-registered")116 def registered_test():117 raise ForbiddenSubclassRegistered()118119 @app.route("/forbidden-unregistered")120 def unregistered_test():121 raise ForbiddenSubclassUnregistered()122123 c = app.test_client()124125 assert c.get("/forbidden").data == b"forbidden"126 assert c.get("/forbidden-unregistered").data == b"forbidden"127 assert c.get("/forbidden-registered").data == b"forbidden-registered"128129130def test_error_handler_blueprint(app):131 bp = flask.Blueprint("bp", __name__)132133 @bp.errorhandler(500)134 def bp_exception_handler(e):135 return "bp-error"136137 @bp.route("/error")138 def bp_test():139 raise InternalServerError()140141 @app.errorhandler(500)142 def app_exception_handler(e):143 return "app-error"144145 @app.route("/error")146 def app_test():147 raise InternalServerError()148149 app.register_blueprint(bp, url_prefix="/bp")150151 c = app.test_client()152153 assert c.get("/error").data == b"app-error"154 assert c.get("/bp/error").data == b"bp-error"155156157def test_default_error_handler():158 bp = flask.Blueprint("bp", __name__)159160 @bp.errorhandler(HTTPException)161 def bp_exception_handler(e):162 assert isinstance(e, HTTPException)163 assert isinstance(e, NotFound)164 return "bp-default"165166 @bp.errorhandler(Forbidden)167 def bp_forbidden_handler(e):168 assert isinstance(e, Forbidden)169 return "bp-forbidden"170171 @bp.route("/undefined")172 def bp_registered_test():173 raise NotFound()174175 @bp.route("/forbidden")176 def bp_forbidden_test():177 raise Forbidden()178179 app = flask.Flask(__name__)180181 @app.errorhandler(HTTPException)182 def catchall_exception_handler(e):183 assert isinstance(e, HTTPException)184 assert isinstance(e, NotFound)185 return "default"186187 @app.errorhandler(Forbidden)188 def catchall_forbidden_handler(e):189 assert isinstance(e, Forbidden)190 return "forbidden"191192 @app.route("/forbidden")193 def forbidden():194 raise Forbidden()195196 @app.route("/slash/")197 def slash():198 return "slash"199200 app.register_blueprint(bp, url_prefix="/bp")201202 c = app.test_client()203 assert c.get("/bp/undefined").data == b"bp-default"204 assert c.get("/bp/forbidden").data == b"bp-forbidden"205 assert c.get("/undefined").data == b"default"206 assert c.get("/forbidden").data == b"forbidden"207 # Don't handle RequestRedirect raised when adding slash.208 assert c.get("/slash", follow_redirects=True).data == b"slash"209210Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 211why, one step back211class TestGenericHandlers:Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 212–241why, one step back212 """Test how very generic handlers are dispatched to."""213214 class Custom(Exception):215 pass216217 @pytest.fixture()218 def app(self, app):219 @app.route("/custom")220 def do_custom():221 raise self.Custom()222223 @app.route("/error")224 def do_error():225 raise KeyError()226227 @app.route("/abort")228 def do_abort():229 flask.abort(500)230231 @app.route("/raise")232 def do_raise():233 raise InternalServerError()234235 app.config["PROPAGATE_EXCEPTIONS"] = False236 return app237238 def report_error(self, e):239 original = getattr(e, "original_exception", None)240241 if original is not None:Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 242why, one step back242 return f"wrapped {type(original).__name__}"Merge branch '1.0.x'David Lordbefore adoptionb05a685
line 243why, one step back243Merge pull request #3554 from pallets/drop-python2David Lordbefore adoptioncd8a374
line 244why, one step back244 return f"direct {type(e).__name__}"Merge branch '1.0.x'David Lordbefore adoptionb05a685
lines 245–289why, one step back245246 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))247 def test_handle_class_or_code(self, app, client, to_handle):248 """``InternalServerError`` and ``500`` are aliases, they should249 have the same behavior. Both should only receive250 ``InternalServerError``, which might wrap another error.251 """252253 @app.errorhandler(to_handle)254 def handle_500(e):255 assert isinstance(e, InternalServerError)256 return self.report_error(e)257258 assert client.get("/custom").data == b"wrapped Custom"259 assert client.get("/error").data == b"wrapped KeyError"260 assert client.get("/abort").data == b"direct InternalServerError"261 assert client.get("/raise").data == b"direct InternalServerError"262263 def test_handle_generic_http(self, app, client):264 """``HTTPException`` should only receive ``HTTPException``265 subclasses. It will receive ``404`` routing exceptions.266 """267268 @app.errorhandler(HTTPException)269 def handle_http(e):270 assert isinstance(e, HTTPException)271 return str(e.code)272273 assert client.get("/error").data == b"500"274 assert client.get("/abort").data == b"500"275 assert client.get("/not-found").data == b"404"276277 def test_handle_generic(self, app, client):278 """Generic ``Exception`` will handle all exceptions directly,279 including ``HTTPExceptions``.280 """281282 @app.errorhandler(Exception)283 def handle_exception(e):284 return self.report_error(e)285286 assert client.get("/custom").data == b"direct Custom"287 assert client.get("/error").data == b"direct KeyError"288 assert client.get("/abort").data == b"direct InternalServerError"289 assert client.get("/not-found").data == b"direct NotFound"