Skip to content
Myr

test_appctx.py

This file

Path

tests/test_appctx.py

209 lines · 4.9 KiB · Python

Last changed by

use ruff linter and formatterDavid Lordbefore adoption54e05a2

History of this file

Take it

1import pytest23import flask4from flask.globals import app_ctx5from flask.globals import request_ctx678def 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    assert cleanup_stuff == [None]111112113def test_app_tearing_down_with_unhandled_exception(app, client):114    app.config["PROPAGATE_EXCEPTIONS"] = True115    cleanup_stuff = []116117    @app.teardown_appcontext118    def cleanup(exception):119        cleanup_stuff.append(exception)120121    @app.route("/")122    def index():123        raise ValueError("dummy")124125    with pytest.raises(ValueError, match="dummy"):126        with app.app_context():127            client.get("/")128129    assert len(cleanup_stuff) == 1130    assert isinstance(cleanup_stuff[0], ValueError)131    assert str(cleanup_stuff[0]) == "dummy"132133134def test_app_ctx_globals_methods(app, app_ctx):135    # get136    assert flask.g.get("foo") is None137    assert flask.g.get("foo", "bar") == "bar"138    # __contains__139    assert "foo" not in flask.g140    flask.g.foo = "bar"141    assert "foo" in flask.g142    # setdefault143    flask.g.setdefault("bar", "the cake is a lie")144    flask.g.setdefault("bar", "hello world")145    assert flask.g.bar == "the cake is a lie"146    # pop147    assert flask.g.pop("bar") == "the cake is a lie"148    with pytest.raises(KeyError):149        flask.g.pop("bar")150    assert flask.g.pop("bar", "more cake") == "more cake"151    # __iter__152    assert list(flask.g) == ["foo"]153    # __repr__154    assert repr(flask.g) == "<flask.g of 'flask_test'>"155156157def test_custom_app_ctx_globals_class(app):158    class CustomRequestGlobals:159        def __init__(self):160            self.spam = "eggs"161162    app.app_ctx_globals_class = CustomRequestGlobals163    with app.app_context():164        assert flask.render_template_string("{{ g.spam }}") == "eggs"165166167def test_context_refcounts(app, client):168    called = []169170    @app.teardown_request171    def teardown_req(error=None):172        called.append("request")173174    @app.teardown_appcontext175    def teardown_app(error=None):176        called.append("app")177178    @app.route("/")179    def index():180        with app_ctx:181            with request_ctx:182                pass183184        assert flask.request.environ["werkzeug.request"] is not None185        return ""186187    res = client.get("/")188    assert res.status_code == 200189    assert res.data == b""190    assert called == ["request", "app"]191192193def test_clean_pop(app):194    app.testing = False195    called = []196197    @app.teardown_request198    def teardown_req(error=None):199        raise ZeroDivisionError200201    @app.teardown_appcontext202    def teardown_app(error=None):203        called.append("TEARDOWN")204205    with app.app_context():206        called.append(flask.current_app.name)207208    assert called == ["flask_test", "TEARDOWN"]209    assert not flask.current_app