all teardown callbacks are called despite errors (#5928)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 7b00886, fbb6f0b · Browse files · 10 files·+194 added−80 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+194 added−80 removed
- tests:+120 added−70 removed
- other:+74 added−10 removed
Provenance
- Commit
c34d6e8- Tree
a5b249e- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
7b00886- Parent 2
fbb6f0b
10 files changed+194 added−80 removed
modified:docs/appcontext.rst+2 added-1 removed
161 unmodified lines162 The teardown callbacks are called by the context when it is popped. They are163 called even if there is an unhandled exception during dispatch. They may be164 called multiple times in some test scenarios. This means there is no guarantee165 that any other parts of the request dispatch have run. Be sure to write these166-functions in a way that does not depend on other callbacks and will not fail.166+functions in a way that does not depend on other callbacks. All callbacks are167+called even if any raise an error.168 169 170 How the Context Works171 ---------------------16 unmodified linesmodified:src/flask/app.py+23 added-4 removed
34 unmodified lines35 from .globals import app_ctx36 from .globals import g37 from .globals import request38 from .globals import session39+from .helpers import _CollectErrors40 from .helpers import get_debug_flag41 from .helpers import get_flashed_messages42 from .helpers import get_load_dotenv43 from .helpers import send_from_directory1386 unmodified lines1430 1431 :param exc: An unhandled exception raised while dispatching the request.1432 Passed to each teardown function.1433 1434+ .. versionchanged:: 3.21435+ All callbacks are called rather than stopping on the first error.1436+1437 .. versionchanged:: 0.91438 Added the ``exc`` argument.1439 """1440+ collect_errors = _CollectErrors()1441+1442 for name in chain(ctx.request.blueprints, (None,)):1443 if name in self.teardown_request_funcs:1444 for func in reversed(self.teardown_request_funcs[name]):1445+ with collect_errors:1439- self.ensure_sync(func)(exc)1446+ self.ensure_sync(func)(exc)1447 1448+ with collect_errors:1441- request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1449+ request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1450 1451+ collect_errors.raise_any("Errors during request teardown")1452+1453 def do_teardown_appcontext(1454 self, ctx: AppContext, exc: BaseException | None = None1455 ) -> None:1456 """Called right before the application context is popped. Called by4 unmodified lines1461 1462 :param exc: An unhandled exception raised while the context was active.1463 Passed to each teardown function.1464 1465+ .. versionchanged:: 3.21466+ All callbacks are called rather than stopping on the first error.1467+1468 .. versionadded:: 0.91469 """1470+ collect_errors = _CollectErrors()1471+1472 for func in reversed(self.teardown_appcontext_funcs):1473+ with collect_errors:1458- self.ensure_sync(func)(exc)1474+ self.ensure_sync(func)(exc)1475 1476+ with collect_errors:1460- appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1477+ appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1478 1479+ collect_errors.raise_any("Errors during app teardown")1480+1481 def app_context(self) -> AppContext:1482 """Create an :class:`.AppContext`. When the context is pushed,1483 :data:`.current_app` and :data:`.g` become available.1484 141 unmodified linesmodified:src/flask/ctx.py+16 added-5 removed
8 unmodified lines9 from werkzeug.routing import MapAdapter10 11 from . import typing as ft12 from .globals import _cv_app13+from .helpers import _CollectErrors14 from .signals import appcontext_popped15 from .signals import appcontext_pushed16 17 if t.TYPE_CHECKING:464 unmodified lines482 483 if self._push_count > 0:484 return485 485- try:486- if self._request is not None:486+ collect_errors = _CollectErrors()487+488+ if self._request is not None:489+ with collect_errors:490 self.app.do_teardown_request(self, exc)491+492+ with collect_errors:493 self._request.close()489- finally:494+495+ with collect_errors:496 self.app.do_teardown_appcontext(self, exc)497+491- _cv_app.reset(self._cv_token)492- self._cv_token = None498+ _cv_app.reset(self._cv_token)499+ self._cv_token = None500+501+ with collect_errors:502 appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)503 504+ collect_errors.raise_any("Errors during context teardown")505+506 def __enter__(self) -> te.Self:507 self.push()508 return self509 31 unmodified linesmodified:src/flask/helpers.py+32 added
5 unmodified lines6 import typing as t7 from datetime import datetime8 from functools import cache9 from functools import update_wrapper10+from types import TracebackType11 12 import werkzeug.utils13 from werkzeug.exceptions import abort as _wz_abort14 from werkzeug.utils import redirect as _wz_redirect621 unmodified lines636 if "." in name:637 out.extend(_split_blueprint_path(name.rpartition(".")[0]))638 639 return out640+641+642+class _CollectErrors:643+ """A context manager that records and silences an error raised within it.644+ Used to run all teardown functions, then raise any errors afterward.645+ """646+647+ def __init__(self) -> None:648+ self.errors: list[BaseException] = []649+650+ def __enter__(self) -> None:651+ pass652+653+ def __exit__(654+ self,655+ exc_type: type[BaseException] | None,656+ exc_val: BaseException | None,657+ exc_tb: TracebackType | None,658+ ) -> bool:659+ if exc_val is not None:660+ self.errors.append(exc_val)661+662+ return True663+664+ def raise_any(self, message: str) -> None:665+ """Raise if any errors were collected."""666+ if self.errors:667+ if sys.version_info >= (3, 11):668+ raise BaseExceptionGroup(message, self.errors) # noqa: F821669+ else:670+ raise self.errors[0]modified:tests/test_appctx.py+55 added
1+import sys2+3 import pytest4 5 import flask6 from flask.globals import app_ctx7+from flask.testing import FlaskClient8 9 10 def test_basic_url_generation(app):11 app.config["SERVER_NAME"] = "localhost"198 unmodified lines210 called.append(flask.current_app.name)211 212 assert called == ["flask_test", "TEARDOWN"]213 assert not flask.current_app214+215+216+def test_robust_teardown(app: flask.Flask, client: FlaskClient) -> None:217+ count = 0218+219+ @app.teardown_request220+ def request_teardown(e: Exception | None) -> None:221+ nonlocal count222+ count += 1223+ raise ValueError("request_teardown")224+225+ @app.teardown_appcontext226+ def app_teardown(e: Exception | None) -> None:227+ nonlocal count228+ count += 1229+ raise ValueError("app_teardown")230+231+ @app.get("/")232+ def index() -> str:233+ return ""234+235+ def request_signal(sender: flask.Flask, exc: Exception | None) -> None:236+ nonlocal count237+ count += 1238+ raise ValueError("request_signal")239+240+ def app_signal(sender: flask.Flask, exc: Exception | None) -> None:241+ nonlocal count242+ count += 1243+ raise ValueError("app_signal")244+245+ with (246+ flask.request_tearing_down.connected_to(request_signal, app),247+ flask.appcontext_tearing_down.connected_to(app_signal, app),248+ ):249+ if sys.version_info >= (3, 11):250+ with pytest.raises(ExceptionGroup, match="context teardown") as exc_info: # noqa: F821251+ client.get()252+253+ assert len(exc_info.value.exceptions) == 2254+ eg1, eg2 = exc_info.value.exceptions255+ assert isinstance(eg1, ExceptionGroup) # noqa: F821256+ assert "request teardown" in eg1.message257+ assert len(eg1.exceptions) == 2258+ assert isinstance(eg2, ExceptionGroup) # noqa: F821259+ assert "app teardown" in eg2.message260+ assert len(eg2.exceptions) == 2261+ else:262+ with pytest.raises(ValueError, match="request_teardown"):263+ client.get()264+265+ assert count == 4modified:tests/test_basic.py+26 added-24 removed
1418 unmodified lines1419 flask.url_for("/")1420 1421 1422 def test_static_files(app, client):1423- rv = client.get("/static/index.html")1424- assert rv.status_code == 2001425- assert rv.data.strip() == b"<h1>Hello World!</h1>"1426- with app.test_request_context():1427- assert flask.url_for("static", filename="index.html") == "/static/index.html"1428- rv.close()1423+ with client.get("/static/index.html") as rv:1424+ assert rv.status_code == 2001425+ assert rv.data.strip() == b"<h1>Hello World!</h1>"1426+ with app.test_request_context():1427+ assert (1428+ flask.url_for("static", filename="index.html") == "/static/index.html"1429+ )1430 1431 1432 def test_static_url_path():1433 app = flask.Flask(__name__, static_url_path="/foo")1434 app.testing = True1434- rv = app.test_client().get("/foo/index.html")1435- assert rv.status_code == 2001436- rv.close()1435 1436+ with app.test_client().get("/foo/index.html") as rv:1437+ assert rv.status_code == 2001438+1439 with app.test_request_context():1440 assert flask.url_for("static", filename="index.html") == "/foo/index.html"1441 1442 1443 def test_static_url_path_with_ending_slash():1444 app = flask.Flask(__name__, static_url_path="/foo/")1445 app.testing = True1445- rv = app.test_client().get("/foo/index.html")1446- assert rv.status_code == 2001447- rv.close()1446 1447+ with app.test_client().get("/foo/index.html") as rv:1448+ assert rv.status_code == 2001449+1450 with app.test_request_context():1451 assert flask.url_for("static", filename="index.html") == "/foo/index.html"1452 1453 1454 def test_static_url_empty_path(app):1455 app = flask.Flask(__name__, static_folder="", static_url_path="")1455- rv = app.test_client().open("/static/index.html", method="GET")1456- assert rv.status_code == 2001457- rv.close()1456 1457+ with app.test_client().open("/static/index.html", method="GET") as rv:1458+ assert rv.status_code == 2001459 1460+1461 def test_static_url_empty_path_default(app):1462 app = flask.Flask(__name__, static_folder="")1462- rv = app.test_client().open("/static/index.html", method="GET")1463- assert rv.status_code == 2001464- rv.close()1463 1464+ with app.test_client().open("/static/index.html", method="GET") as rv:1465+ assert rv.status_code == 2001466 1467+1468 def test_static_folder_with_pathlib_path(app):1469 from pathlib import Path1470 1471 app = flask.Flask(__name__, static_folder=Path("static"))1471- rv = app.test_client().open("/static/index.html", method="GET")1472- assert rv.status_code == 2001473- rv.close()1472 1473+ with app.test_client().open("/static/index.html", method="GET") as rv:1474+ assert rv.status_code == 2001475 1476+1477 def test_static_folder_with_ending_slash():1478 app = flask.Flask(__name__, static_folder="static/")1479 1480 @app.route("/<path:path>")6 unmodified lines1487 1488 def test_static_route_with_host_matching():1489 app = flask.Flask(__name__, host_matching=True, static_host="example.com")1490 c = app.test_client()1490- rv = c.get("http://example.com/static/index.html")1491- assert rv.status_code == 2001492- rv.close()1491+1492+ with c.get("http://example.com/static/index.html") as rv:1493+ assert rv.status_code == 2001494+1495 with app.test_request_context():1496 rv = flask.url_for("static", filename="index.html", _external=True)1497 assert rv == "http://example.com/static/index.html"1498 # Providing static_host without host_matching=True should error.472 unmodified linesmodified:tests/test_blueprints.py+10 added-10 removed
182 unmodified lines183 rv = client.get("/admin/")184 assert rv.data == b"Hello from the Admin"185 rv = client.get("/admin/index2")186 assert rv.data == b"Hello from the Admin"187- rv = client.get("/admin/static/test.txt")188- assert rv.data.strip() == b"Admin File"189- rv.close()190- rv = client.get("/admin/static/css/test.css")191- assert rv.data.strip() == b"/* nested file */"192- rv.close()187 188+ with client.get("/admin/static/test.txt") as rv:189+ assert rv.data.strip() == b"Admin File"190+191+ with client.get("/admin/static/css/test.css") as rv:192+ assert rv.data.strip() == b"/* nested file */"193+194 # try/finally, in case other tests use this app for Blueprint tests.195 max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]196 try:197 expected_max_age = 3600198 if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == expected_max_age:199 expected_max_age = 7200200 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = expected_max_age201- rv = client.get("/admin/static/css/test.css")202- cc = parse_cache_control_header(rv.headers["Cache-Control"])203- assert cc.max_age == expected_max_age204- rv.close()201+202+ with client.get("/admin/static/css/test.css") as rv:203+ cc = parse_cache_control_header(rv.headers["Cache-Control"])204+ assert cc.max_age == expected_max_age205 finally:206 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default207 208 with app.test_request_context():910 unmodified linesmodified:tests/test_helpers.py+29 added-35 removed
30 unmodified lines31 32 33 class TestSendfile:34 def test_send_file(self, app, req_ctx):35- rv = flask.send_file("static/index.html")36- assert rv.direct_passthrough37- assert rv.mimetype == "text/html"38-35 with app.open_resource("static/index.html") as f:36+ expect = f.read()37+38+ with flask.send_file("static/index.html") as rv:39+ assert rv.direct_passthrough40+ assert rv.mimetype == "text/html"41 rv.direct_passthrough = False41- assert rv.data == f.read()42+ assert rv.data == expect43 43- rv.close()44-44 def test_static_file(self, app, req_ctx):45 # Default max_age is None.46 47 # Test with static file handler.49- rv = app.send_static_file("index.html")50- assert rv.cache_control.max_age is None51- rv.close()48+ with app.send_static_file("index.html") as rv:49+ assert rv.cache_control.max_age is None50 51 # Test with direct use of send_file.54- rv = flask.send_file("static/index.html")55- assert rv.cache_control.max_age is None56- rv.close()52+ with flask.send_file("static/index.html") as rv:53+ assert rv.cache_control.max_age is None54 55 app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 360056 57 # Test with static file handler.61- rv = app.send_static_file("index.html")62- assert rv.cache_control.max_age == 360063- rv.close()58+ with app.send_static_file("index.html") as rv:59+ assert rv.cache_control.max_age == 360060 61 # Test with direct use of send_file.66- rv = flask.send_file("static/index.html")67- assert rv.cache_control.max_age == 360068- rv.close()62+ with flask.send_file("static/index.html") as rv:63+ assert rv.cache_control.max_age == 360064 65 # Test with pathlib.Path.71- rv = app.send_static_file(FakePath("index.html"))72- assert rv.cache_control.max_age == 360073- rv.close()66+ with app.send_static_file(FakePath("index.html")) as rv:67+ assert rv.cache_control.max_age == 360068 69 class StaticFileApp(flask.Flask):70 def get_send_file_max_age(self, filename):71 return 101 unmodified line73 app = StaticFileApp(__name__)74 75 with app.test_request_context():76 # Test with static file handler.83- rv = app.send_static_file("index.html")84- assert rv.cache_control.max_age == 1085- rv.close()77+ with app.send_static_file("index.html") as rv:78+ assert rv.cache_control.max_age == 1079 80 # Test with direct use of send_file.88- rv = flask.send_file("static/index.html")89- assert rv.cache_control.max_age == 1090- rv.close()81+ with flask.send_file("static/index.html") as rv:82+ assert rv.cache_control.max_age == 1083 84 def test_send_from_directory(self, app, req_ctx):85 app.root_path = os.path.join(86 os.path.dirname(__file__), "test_apps", "subdomaintestmodule"87 )96- rv = flask.send_from_directory("static", "hello.txt")97- rv.direct_passthrough = False98- assert rv.data.strip() == b"Hello Subdomain"99- rv.close()88 89+ with flask.send_from_directory("static", "hello.txt") as rv:90+ rv.direct_passthrough = False91+ assert rv.data.strip() == b"Hello Subdomain"92 93+94 class TestUrlFor:95 def test_url_for_with_anchor(self, app, req_ctx):96 @app.route("/")97 def index():212 unmodified lines310 return flask.Response(gen())311 312 # response is closed without reading stream313 client.get().close()314+315 # response stream is read316+ with client.get() as rv:323- assert client.get().text == "flask"317+ assert rv.text == "flask"318 319 # same as above, but with client context preservation320 with client:321 client.get().close()322 329- with client:330- assert client.get().text == "flask"323+ with client, client.get() as rv:324+ assert rv.text == "flask"325 326 327 class TestHelpers:328 @pytest.mark.parametrize(49 unmodified linesmodified:tests/test_testing.py-1 removed
74 unmodified lines75 def index():76 return flask.request.remote_addr77 78 builder = EnvironBuilder(app, path="/index", method="GET")79- request.addfinalizer(builder.close)79 80 rv = client.open(builder)81 assert rv.data == b"127.0.0.1"82 302 unmodified linesmodified:CHANGES.rst+1 added
12 unmodified lines13 ``AppContext`` as the first parameter, instead of using the proxy objects.14 If subclasses were overriding these methods, the old signature is detected,15 shows a deprecation warning, and will continue to work during the16 deprecation period. :issue:`5815`17+- All teardown callbacks are called, even if any raise an error. :pr:`5928`18 - The ``should_ignore_error`` is deprecated. Handle errors as needed in19 teardown handlers instead. :issue:`5816`20 - ``template_filter``, ``template_test``, and ``template_global`` decorators21 can be used without parentheses. :issue:`5729`1642 unmodified lines