Skip to content
Myr

test_appctx.py

This file

Path

tests/test_appctx.py

221 lines · 5.1 KiB · Python

Last changed by

Merge pull request #3183 from singingwolfboy/pre-commitDavid Baumgoldbefore adoption1dda032

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    tests.appctx4    ~~~~~~~~~~~~56    Tests the application context.78    :copyright: © 2010 by the Pallets team.9    :license: BSD, see LICENSE for more details.10"""1112import pytest1314import flask151617def test_basic_url_generation(app):18    app.config["SERVER_NAME"] = "localhost"19    app.config["PREFERRED_URL_SCHEME"] = "https"2021    @app.route("/")22    def index():23        pass2425    with app.app_context():26        rv = flask.url_for("index")27        assert rv == "https://localhost/"282930def test_url_generation_requires_server_name(app):31    with app.app_context():32        with pytest.raises(RuntimeError):33            flask.url_for("index")343536def test_url_generation_without_context_fails():37    with pytest.raises(RuntimeError):38        flask.url_for("index")394041def test_request_context_means_app_context(app):42    with app.test_request_context():43        assert flask.current_app._get_current_object() == app44    assert flask._app_ctx_stack.top is None454647def test_app_context_provides_current_app(app):48    with app.app_context():49        assert flask.current_app._get_current_object() == app50    assert flask._app_ctx_stack.top is None515253def test_app_tearing_down(app):54    cleanup_stuff = []5556    @app.teardown_appcontext57    def cleanup(exception):58        cleanup_stuff.append(exception)5960    with app.app_context():61        pass6263    assert cleanup_stuff == [None]646566def test_app_tearing_down_with_previous_exception(app):67    cleanup_stuff = []6869    @app.teardown_appcontext70    def cleanup(exception):71        cleanup_stuff.append(exception)7273    try:74        raise Exception("dummy")75    except Exception:76        pass7778    with app.app_context():79        pass8081    assert cleanup_stuff == [None]828384def test_app_tearing_down_with_handled_exception_by_except_block(app):85    cleanup_stuff = []8687    @app.teardown_appcontext88    def cleanup(exception):89        cleanup_stuff.append(exception)9091    with app.app_context():92        try:93            raise Exception("dummy")94        except Exception:95            pass9697    assert cleanup_stuff == [None]9899100def test_app_tearing_down_with_handled_exception_by_app_handler(app, client):101    app.config["PROPAGATE_EXCEPTIONS"] = True102    cleanup_stuff = []103104    @app.teardown_appcontext105    def cleanup(exception):106        cleanup_stuff.append(exception)107108    @app.route("/")109    def index():110        raise Exception("dummy")111112    @app.errorhandler(Exception)113    def handler(f):114        return flask.jsonify(str(f))115116    with app.app_context():117        client.get("/")118119    assert cleanup_stuff == [None]120121122def test_app_tearing_down_with_unhandled_exception(app, client):123    app.config["PROPAGATE_EXCEPTIONS"] = True124    cleanup_stuff = []125126    @app.teardown_appcontext127    def cleanup(exception):128        cleanup_stuff.append(exception)129130    @app.route("/")131    def index():132        raise Exception("dummy")133134    with pytest.raises(Exception):135        with app.app_context():136            client.get("/")137138    assert len(cleanup_stuff) == 1139    assert isinstance(cleanup_stuff[0], Exception)140    assert str(cleanup_stuff[0]) == "dummy"141142143def test_app_ctx_globals_methods(app, app_ctx):144    # get145    assert flask.g.get("foo") is None146    assert flask.g.get("foo", "bar") == "bar"147    # __contains__148    assert "foo" not in flask.g149    flask.g.foo = "bar"150    assert "foo" in flask.g151    # setdefault152    flask.g.setdefault("bar", "the cake is a lie")153    flask.g.setdefault("bar", "hello world")154    assert flask.g.bar == "the cake is a lie"155    # pop156    assert flask.g.pop("bar") == "the cake is a lie"157    with pytest.raises(KeyError):158        flask.g.pop("bar")159    assert flask.g.pop("bar", "more cake") == "more cake"160    # __iter__161    assert list(flask.g) == ["foo"]162    # __repr__163    assert repr(flask.g) == "<flask.g of 'flask_test'>"164165166def test_custom_app_ctx_globals_class(app):167    class CustomRequestGlobals(object):168        def __init__(self):169            self.spam = "eggs"170171    app.app_ctx_globals_class = CustomRequestGlobals172    with app.app_context():173        assert flask.render_template_string("{{ g.spam }}") == "eggs"174175176def test_context_refcounts(app, client):177    called = []178179    @app.teardown_request180    def teardown_req(error=None):181        called.append("request")182183    @app.teardown_appcontext184    def teardown_app(error=None):185        called.append("app")186187    @app.route("/")188    def index():189        with flask._app_ctx_stack.top:190            with flask._request_ctx_stack.top:191                pass192        env = flask._request_ctx_stack.top.request.environ193        assert env["werkzeug.request"] is not None194        return u""195196    res = client.get("/")197    assert res.status_code == 200198    assert res.data == b""199    assert called == ["request", "app"]200201202def test_clean_pop(app):203    app.testing = False204    called = []205206    @app.teardown_request207    def teardown_req(error=None):208        1 / 0209210    @app.teardown_appcontext211    def teardown_app(error=None):212        called.append("TEARDOWN")213214    try:215        with app.test_request_context():216            called.append(flask.current_app.name)217    except ZeroDivisionError:218        pass219220    assert called == ["flask_test", "TEARDOWN"]221    assert not flask.current_app