Skip to content
Myr

test_appctx.py

This file

Path

tests/test_appctx.py

259 lines · 6.5 KiB · Python

Last changed by

drop support for Python 3.10 (#6168)David Lordbefore adoption728c5e4

History of this file

Take it

1import pytest23import flask4from flask.globals import app_ctx5from flask.testing import FlaskClient678def test_basic_url_generation(app):9    app.config["SERVER_NAME"] = "localhost"10    app.config["PREFERRED_URL_SCHEME"] = "https"1112    @app.route("/")13    def index():14        pass1516    with app.app_context():17        rv = flask.url_for("index")18        assert rv == "https://localhost/"192021def test_url_generation_requires_server_name(app):22    with app.app_context():23        with pytest.raises(RuntimeError):24            flask.url_for("index")252627def test_url_generation_without_context_fails():28    with pytest.raises(RuntimeError):29        flask.url_for("index")303132def test_request_context_means_app_context(app):33    with app.test_request_context():34        assert flask.current_app._get_current_object() is app35    assert not flask.current_app363738def test_app_context_provides_current_app(app):39    with app.app_context():40        assert flask.current_app._get_current_object() is app41    assert not flask.current_app424344def test_app_tearing_down(app):45    cleanup_stuff = []4647    @app.teardown_appcontext48    def cleanup(exception):49        cleanup_stuff.append(exception)5051    with app.app_context():52        pass5354    assert cleanup_stuff == [None]555657def test_app_tearing_down_with_previous_exception(app):58    cleanup_stuff = []5960    @app.teardown_appcontext61    def cleanup(exception):62        cleanup_stuff.append(exception)6364    try:65        raise Exception("dummy")66    except Exception:67        pass6869    with app.app_context():70        pass7172    assert cleanup_stuff == [None]737475def test_app_tearing_down_with_handled_exception_by_except_block(app):76    cleanup_stuff = []7778    @app.teardown_appcontext79    def cleanup(exception):80        cleanup_stuff.append(exception)8182    with app.app_context():83        try:84            raise Exception("dummy")85        except Exception:86            pass8788    assert cleanup_stuff == [None]899091def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):92    app.config["PROPAGATE_EXCEPTIONS"] = True93    cleanup_stuff = []9495    @app.teardown_appcontext96    def cleanup(exception):97        cleanup_stuff.append(exception)9899    @app.route("/")100    def index():101        raise Exception("dummy")102103    @app.errorhandler(Exception)104    def handler(f):105        return flask.jsonify(str(f))106107    with app.app_context():108        client.get("/")109110    # teardown request context, and with block context111    assert cleanup_stuff == [None, None]112113114def test_app_tearing_down_with_unhandled_exception(app, client):115    app.config["PROPAGATE_EXCEPTIONS"] = True116    cleanup_stuff = []117118    @app.teardown_appcontext119    def cleanup(exception):120        cleanup_stuff.append(exception)121122    @app.route("/")123    def index():124        raise ValueError("dummy")125126    with pytest.raises(ValueError, match="dummy"):127        with app.app_context():128            client.get("/")129130    assert len(cleanup_stuff) == 2131    assert isinstance(cleanup_stuff[0], ValueError)132    assert str(cleanup_stuff[0]) == "dummy"133    # exception propagated, seen by request context and with block context134    assert cleanup_stuff[0] is cleanup_stuff[1]135136137def test_app_ctx_globals_methods(app, app_ctx):138    # get139    assert flask.g.get("foo") is None140    assert flask.g.get("foo", "bar") == "bar"141    # __contains__142    assert "foo" not in flask.g143    flask.g.foo = "bar"144    assert "foo" in flask.g145    # setdefault146    flask.g.setdefault("bar", "the cake is a lie")147    flask.g.setdefault("bar", "hello world")148    assert flask.g.bar == "the cake is a lie"149    # pop150    assert flask.g.pop("bar") == "the cake is a lie"151    with pytest.raises(KeyError):152        flask.g.pop("bar")153    assert flask.g.pop("bar", "more cake") == "more cake"154    # __iter__155    assert list(flask.g) == ["foo"]156    # __repr__157    assert repr(flask.g) == "<flask.g of 'flask_test'>"158159160def test_custom_app_ctx_globals_class(app):161    class CustomRequestGlobals:162        def __init__(self):163            self.spam = "eggs"164165    app.app_ctx_globals_class = CustomRequestGlobals166    with app.app_context():167        assert flask.render_template_string("{{ g.spam }}") == "eggs"168169170def test_context_refcounts(app, client):171    called = []172173    @app.teardown_request174    def teardown_req(error=None):175        called.append("request")176177    @app.teardown_appcontext178    def teardown_app(error=None):179        called.append("app")180181    @app.route("/")182    def index():183        with app_ctx:184            pass185186        assert flask.request.environ["werkzeug.request"] is not None187        return ""188189    res = client.get("/")190    assert res.status_code == 200191    assert res.data == b""192    assert called == ["request", "app"]193194195def test_clean_pop(app):196    app.testing = False197    called = []198199    @app.teardown_request200    def teardown_req(error=None):201        raise ZeroDivisionError202203    @app.teardown_appcontext204    def teardown_app(error=None):205        called.append("TEARDOWN")206207    with app.app_context():208        called.append(flask.current_app.name)209210    assert called == ["flask_test", "TEARDOWN"]211    assert not flask.current_app212213214def test_robust_teardown(app: flask.Flask, client: FlaskClient) -> None:215    count = 0216217    @app.teardown_request218    def request_teardown(e: Exception | None) -> None:219        nonlocal count220        count += 1221        raise ValueError("request_teardown")222223    @app.teardown_appcontext224    def app_teardown(e: Exception | None) -> None:225        nonlocal count226        count += 1227        raise ValueError("app_teardown")228229    @app.get("/")230    def index() -> str:231        return ""232233    def request_signal(sender: flask.Flask, exc: Exception | None) -> None:234        nonlocal count235        count += 1236        raise ValueError("request_signal")237238    def app_signal(sender: flask.Flask, exc: Exception | None) -> None:239        nonlocal count240        count += 1241        raise ValueError("app_signal")242243    with (244        flask.request_tearing_down.connected_to(request_signal, app),245        flask.appcontext_tearing_down.connected_to(app_signal, app),246    ):247        with pytest.raises(ExceptionGroup, match="context teardown") as exc_info:  # noqa: F821248            client.get()249250        assert len(exc_info.value.exceptions) == 2251        eg1, eg2 = exc_info.value.exceptions252        assert isinstance(eg1, ExceptionGroup)  # noqa: F821253        assert "request teardown" in eg1.message254        assert len(eg1.exceptions) == 2255        assert isinstance(eg2, ExceptionGroup)  # noqa: F821256        assert "app teardown" in eg2.message257        assert len(eg2.exceptions) == 2258259    assert count == 4