Skip to content
Myr

test_blueprints.py

This file

Path

tests/test_blueprints.py

1,054 lines · 28.3 KiB · Python

Last changed by

use ruff linter and formatterDavid Lordbefore adoption54e05a2

History of this file

Take it

1import pytest2from jinja2 import TemplateNotFound3from werkzeug.http import parse_cache_control_header45import flask678def test_blueprint_specific_error_handling(app, client):9    frontend = flask.Blueprint("frontend", __name__)10    backend = flask.Blueprint("backend", __name__)11    sideend = flask.Blueprint("sideend", __name__)1213    @frontend.errorhandler(403)14    def frontend_forbidden(e):15        return "frontend says no", 4031617    @frontend.route("/frontend-no")18    def frontend_no():19        flask.abort(403)2021    @backend.errorhandler(403)22    def backend_forbidden(e):23        return "backend says no", 4032425    @backend.route("/backend-no")26    def backend_no():27        flask.abort(403)2829    @sideend.route("/what-is-a-sideend")30    def sideend_no():31        flask.abort(403)3233    app.register_blueprint(frontend)34    app.register_blueprint(backend)35    app.register_blueprint(sideend)3637    @app.errorhandler(403)38    def app_forbidden(e):39        return "application itself says no", 4034041    assert client.get("/frontend-no").data == b"frontend says no"42    assert client.get("/backend-no").data == b"backend says no"43    assert client.get("/what-is-a-sideend").data == b"application itself says no"444546def test_blueprint_specific_user_error_handling(app, client):47    class MyDecoratorException(Exception):48        pass4950    class MyFunctionException(Exception):51        pass5253    blue = flask.Blueprint("blue", __name__)5455    @blue.errorhandler(MyDecoratorException)56    def my_decorator_exception_handler(e):57        assert isinstance(e, MyDecoratorException)58        return "boom"5960    def my_function_exception_handler(e):61        assert isinstance(e, MyFunctionException)62        return "bam"6364    blue.register_error_handler(MyFunctionException, my_function_exception_handler)6566    @blue.route("/decorator")67    def blue_deco_test():68        raise MyDecoratorException()6970    @blue.route("/function")71    def blue_func_test():72        raise MyFunctionException()7374    app.register_blueprint(blue)7576    assert client.get("/decorator").data == b"boom"77    assert client.get("/function").data == b"bam"787980def test_blueprint_app_error_handling(app, client):81    errors = flask.Blueprint("errors", __name__)8283    @errors.app_errorhandler(403)84    def forbidden_handler(e):85        return "you shall not pass", 4038687    @app.route("/forbidden")88    def app_forbidden():89        flask.abort(403)9091    forbidden_bp = flask.Blueprint("forbidden_bp", __name__)9293    @forbidden_bp.route("/nope")94    def bp_forbidden():95        flask.abort(403)9697    app.register_blueprint(errors)98    app.register_blueprint(forbidden_bp)99100    assert client.get("/forbidden").data == b"you shall not pass"101    assert client.get("/nope").data == b"you shall not pass"102103104@pytest.mark.parametrize(105    ("prefix", "rule", "url"),106    (107        ("", "/", "/"),108        ("/", "", "/"),109        ("/", "/", "/"),110        ("/foo", "", "/foo"),111        ("/foo/", "", "/foo/"),112        ("", "/bar", "/bar"),113        ("/foo/", "/bar", "/foo/bar"),114        ("/foo/", "bar", "/foo/bar"),115        ("/foo", "/bar", "/foo/bar"),116        ("/foo/", "//bar", "/foo/bar"),117        ("/foo//", "/bar", "/foo/bar"),118    ),119)120def test_blueprint_prefix_slash(app, client, prefix, rule, url):121    bp = flask.Blueprint("test", __name__, url_prefix=prefix)122123    @bp.route(rule)124    def index():125        return "", 204126127    app.register_blueprint(bp)128    assert client.get(url).status_code == 204129130131def test_blueprint_url_defaults(app, client):132    bp = flask.Blueprint("test", __name__)133134    @bp.route("/foo", defaults={"baz": 42})135    def foo(bar, baz):136        return f"{bar}/{baz:d}"137138    @bp.route("/bar")139    def bar(bar):140        return str(bar)141142    app.register_blueprint(bp, url_prefix="/1", url_defaults={"bar": 23})143    app.register_blueprint(bp, name="test2", url_prefix="/2", url_defaults={"bar": 19})144145    assert client.get("/1/foo").data == b"23/42"146    assert client.get("/2/foo").data == b"19/42"147    assert client.get("/1/bar").data == b"23"148    assert client.get("/2/bar").data == b"19"149150151def test_blueprint_url_processors(app, client):152    bp = flask.Blueprint("frontend", __name__, url_prefix="/<lang_code>")153154    @bp.url_defaults155    def add_language_code(endpoint, values):156        values.setdefault("lang_code", flask.g.lang_code)157158    @bp.url_value_preprocessor159    def pull_lang_code(endpoint, values):160        flask.g.lang_code = values.pop("lang_code")161162    @bp.route("/")163    def index():164        return flask.url_for(".about")165166    @bp.route("/about")167    def about():168        return flask.url_for(".index")169170    app.register_blueprint(bp)171172    assert client.get("/de/").data == b"/de/about"173    assert client.get("/de/about").data == b"/de/"174175176def test_templates_and_static(test_apps):177    from blueprintapp import app178179    client = app.test_client()180181    rv = client.get("/")182    assert rv.data == b"Hello from the Frontend"183    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()193194    # 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()205    finally:206        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default207208    with app.test_request_context():209        assert (210            flask.url_for("admin.static", filename="test.txt")211            == "/admin/static/test.txt"212        )213214    with app.test_request_context():215        with pytest.raises(TemplateNotFound) as e:216            flask.render_template("missing.html")217        assert e.value.name == "missing.html"218219    with flask.Flask(__name__).test_request_context():220        assert flask.render_template("nested/nested.txt") == "I'm nested"221222223def test_default_static_max_age(app):224    class MyBlueprint(flask.Blueprint):225        def get_send_file_max_age(self, filename):226            return 100227228    blueprint = MyBlueprint("blueprint", __name__, static_folder="static")229    app.register_blueprint(blueprint)230231    # try/finally, in case other tests use this app for Blueprint tests.232    max_age_default = app.config["SEND_FILE_MAX_AGE_DEFAULT"]233    try:234        with app.test_request_context():235            unexpected_max_age = 3600236            if app.config["SEND_FILE_MAX_AGE_DEFAULT"] == unexpected_max_age:237                unexpected_max_age = 7200238            app.config["SEND_FILE_MAX_AGE_DEFAULT"] = unexpected_max_age239            rv = blueprint.send_static_file("index.html")240            cc = parse_cache_control_header(rv.headers["Cache-Control"])241            assert cc.max_age == 100242            rv.close()243    finally:244        app.config["SEND_FILE_MAX_AGE_DEFAULT"] = max_age_default245246247def test_templates_list(test_apps):248    from blueprintapp import app249250    templates = sorted(app.jinja_env.list_templates())251    assert templates == ["admin/index.html", "frontend/index.html"]252253254def test_dotted_name_not_allowed(app, client):255    with pytest.raises(ValueError):256        flask.Blueprint("app.ui", __name__)257258259def test_empty_name_not_allowed(app, client):260    with pytest.raises(ValueError):261        flask.Blueprint("", __name__)262263264def test_dotted_names_from_app(app, client):265    test = flask.Blueprint("test", __name__)266267    @app.route("/")268    def app_index():269        return flask.url_for("test.index")270271    @test.route("/test/")272    def index():273        return flask.url_for("app_index")274275    app.register_blueprint(test)276277    rv = client.get("/")278    assert rv.data == b"/test/"279280281def test_empty_url_defaults(app, client):282    bp = flask.Blueprint("bp", __name__)283284    @bp.route("/", defaults={"page": 1})285    @bp.route("/page/<int:page>")286    def something(page):287        return str(page)288289    app.register_blueprint(bp)290291    assert client.get("/").data == b"1"292    assert client.get("/page/2").data == b"2"293294295def test_route_decorator_custom_endpoint(app, client):296    bp = flask.Blueprint("bp", __name__)297298    @bp.route("/foo")299    def foo():300        return flask.request.endpoint301302    @bp.route("/bar", endpoint="bar")303    def foo_bar():304        return flask.request.endpoint305306    @bp.route("/bar/123", endpoint="123")307    def foo_bar_foo():308        return flask.request.endpoint309310    @bp.route("/bar/foo")311    def bar_foo():312        return flask.request.endpoint313314    app.register_blueprint(bp, url_prefix="/py")315316    @app.route("/")317    def index():318        return flask.request.endpoint319320    assert client.get("/").data == b"index"321    assert client.get("/py/foo").data == b"bp.foo"322    assert client.get("/py/bar").data == b"bp.bar"323    assert client.get("/py/bar/123").data == b"bp.123"324    assert client.get("/py/bar/foo").data == b"bp.bar_foo"325326327def test_route_decorator_custom_endpoint_with_dots(app, client):328    bp = flask.Blueprint("bp", __name__)329330    with pytest.raises(ValueError):331        bp.route("/", endpoint="a.b")(lambda: "")332333    with pytest.raises(ValueError):334        bp.add_url_rule("/", endpoint="a.b")335336    def view():337        return ""338339    view.__name__ = "a.b"340341    with pytest.raises(ValueError):342        bp.add_url_rule("/", view_func=view)343344345def test_endpoint_decorator(app, client):346    from werkzeug.routing import Rule347348    app.url_map.add(Rule("/foo", endpoint="bar"))349350    bp = flask.Blueprint("bp", __name__)351352    @bp.endpoint("bar")353    def foobar():354        return flask.request.endpoint355356    app.register_blueprint(bp, url_prefix="/bp_prefix")357358    assert client.get("/foo").data == b"bar"359    assert client.get("/bp_prefix/bar").status_code == 404360361362def test_template_filter(app):363    bp = flask.Blueprint("bp", __name__)364365    @bp.app_template_filter()366    def my_reverse(s):367        return s[::-1]368369    app.register_blueprint(bp, url_prefix="/py")370    assert "my_reverse" in app.jinja_env.filters.keys()371    assert app.jinja_env.filters["my_reverse"] == my_reverse372    assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"373374375def test_add_template_filter(app):376    bp = flask.Blueprint("bp", __name__)377378    def my_reverse(s):379        return s[::-1]380381    bp.add_app_template_filter(my_reverse)382    app.register_blueprint(bp, url_prefix="/py")383    assert "my_reverse" in app.jinja_env.filters.keys()384    assert app.jinja_env.filters["my_reverse"] == my_reverse385    assert app.jinja_env.filters["my_reverse"]("abcd") == "dcba"386387388def test_template_filter_with_name(app):389    bp = flask.Blueprint("bp", __name__)390391    @bp.app_template_filter("strrev")392    def my_reverse(s):393        return s[::-1]394395    app.register_blueprint(bp, url_prefix="/py")396    assert "strrev" in app.jinja_env.filters.keys()397    assert app.jinja_env.filters["strrev"] == my_reverse398    assert app.jinja_env.filters["strrev"]("abcd") == "dcba"399400401def test_add_template_filter_with_name(app):402    bp = flask.Blueprint("bp", __name__)403404    def my_reverse(s):405        return s[::-1]406407    bp.add_app_template_filter(my_reverse, "strrev")408    app.register_blueprint(bp, url_prefix="/py")409    assert "strrev" in app.jinja_env.filters.keys()410    assert app.jinja_env.filters["strrev"] == my_reverse411    assert app.jinja_env.filters["strrev"]("abcd") == "dcba"412413414def test_template_filter_with_template(app, client):415    bp = flask.Blueprint("bp", __name__)416417    @bp.app_template_filter()418    def super_reverse(s):419        return s[::-1]420421    app.register_blueprint(bp, url_prefix="/py")422423    @app.route("/")424    def index():425        return flask.render_template("template_filter.html", value="abcd")426427    rv = client.get("/")428    assert rv.data == b"dcba"429430431def test_template_filter_after_route_with_template(app, client):432    @app.route("/")433    def index():434        return flask.render_template("template_filter.html", value="abcd")435436    bp = flask.Blueprint("bp", __name__)437438    @bp.app_template_filter()439    def super_reverse(s):440        return s[::-1]441442    app.register_blueprint(bp, url_prefix="/py")443    rv = client.get("/")444    assert rv.data == b"dcba"445446447def test_add_template_filter_with_template(app, client):448    bp = flask.Blueprint("bp", __name__)449450    def super_reverse(s):451        return s[::-1]452453    bp.add_app_template_filter(super_reverse)454    app.register_blueprint(bp, url_prefix="/py")455456    @app.route("/")457    def index():458        return flask.render_template("template_filter.html", value="abcd")459460    rv = client.get("/")461    assert rv.data == b"dcba"462463464def test_template_filter_with_name_and_template(app, client):465    bp = flask.Blueprint("bp", __name__)466467    @bp.app_template_filter("super_reverse")468    def my_reverse(s):469        return s[::-1]470471    app.register_blueprint(bp, url_prefix="/py")472473    @app.route("/")474    def index():475        return flask.render_template("template_filter.html", value="abcd")476477    rv = client.get("/")478    assert rv.data == b"dcba"479480481def test_add_template_filter_with_name_and_template(app, client):482    bp = flask.Blueprint("bp", __name__)483484    def my_reverse(s):485        return s[::-1]486487    bp.add_app_template_filter(my_reverse, "super_reverse")488    app.register_blueprint(bp, url_prefix="/py")489490    @app.route("/")491    def index():492        return flask.render_template("template_filter.html", value="abcd")493494    rv = client.get("/")495    assert rv.data == b"dcba"496497498def test_template_test(app):499    bp = flask.Blueprint("bp", __name__)500501    @bp.app_template_test()502    def is_boolean(value):503        return isinstance(value, bool)504505    app.register_blueprint(bp, url_prefix="/py")506    assert "is_boolean" in app.jinja_env.tests.keys()507    assert app.jinja_env.tests["is_boolean"] == is_boolean508    assert app.jinja_env.tests["is_boolean"](False)509510511def test_add_template_test(app):512    bp = flask.Blueprint("bp", __name__)513514    def is_boolean(value):515        return isinstance(value, bool)516517    bp.add_app_template_test(is_boolean)518    app.register_blueprint(bp, url_prefix="/py")519    assert "is_boolean" in app.jinja_env.tests.keys()520    assert app.jinja_env.tests["is_boolean"] == is_boolean521    assert app.jinja_env.tests["is_boolean"](False)522523524def test_template_test_with_name(app):525    bp = flask.Blueprint("bp", __name__)526527    @bp.app_template_test("boolean")528    def is_boolean(value):529        return isinstance(value, bool)530531    app.register_blueprint(bp, url_prefix="/py")532    assert "boolean" in app.jinja_env.tests.keys()533    assert app.jinja_env.tests["boolean"] == is_boolean534    assert app.jinja_env.tests["boolean"](False)535536537def test_add_template_test_with_name(app):538    bp = flask.Blueprint("bp", __name__)539540    def is_boolean(value):541        return isinstance(value, bool)542543    bp.add_app_template_test(is_boolean, "boolean")544    app.register_blueprint(bp, url_prefix="/py")545    assert "boolean" in app.jinja_env.tests.keys()546    assert app.jinja_env.tests["boolean"] == is_boolean547    assert app.jinja_env.tests["boolean"](False)548549550def test_template_test_with_template(app, client):551    bp = flask.Blueprint("bp", __name__)552553    @bp.app_template_test()554    def boolean(value):555        return isinstance(value, bool)556557    app.register_blueprint(bp, url_prefix="/py")558559    @app.route("/")560    def index():561        return flask.render_template("template_test.html", value=False)562563    rv = client.get("/")564    assert b"Success!" in rv.data565566567def test_template_test_after_route_with_template(app, client):568    @app.route("/")569    def index():570        return flask.render_template("template_test.html", value=False)571572    bp = flask.Blueprint("bp", __name__)573574    @bp.app_template_test()575    def boolean(value):576        return isinstance(value, bool)577578    app.register_blueprint(bp, url_prefix="/py")579    rv = client.get("/")580    assert b"Success!" in rv.data581582583def test_add_template_test_with_template(app, client):584    bp = flask.Blueprint("bp", __name__)585586    def boolean(value):587        return isinstance(value, bool)588589    bp.add_app_template_test(boolean)590    app.register_blueprint(bp, url_prefix="/py")591592    @app.route("/")593    def index():594        return flask.render_template("template_test.html", value=False)595596    rv = client.get("/")597    assert b"Success!" in rv.data598599600def test_template_test_with_name_and_template(app, client):601    bp = flask.Blueprint("bp", __name__)602603    @bp.app_template_test("boolean")604    def is_boolean(value):605        return isinstance(value, bool)606607    app.register_blueprint(bp, url_prefix="/py")608609    @app.route("/")610    def index():611        return flask.render_template("template_test.html", value=False)612613    rv = client.get("/")614    assert b"Success!" in rv.data615616617def test_add_template_test_with_name_and_template(app, client):618    bp = flask.Blueprint("bp", __name__)619620    def is_boolean(value):621        return isinstance(value, bool)622623    bp.add_app_template_test(is_boolean, "boolean")624    app.register_blueprint(bp, url_prefix="/py")625626    @app.route("/")627    def index():628        return flask.render_template("template_test.html", value=False)629630    rv = client.get("/")631    assert b"Success!" in rv.data632633634def test_context_processing(app, client):635    answer_bp = flask.Blueprint("answer_bp", __name__)636637    def template_string():638        return flask.render_template_string(639            "{% if notanswer %}{{ notanswer }} is not the answer. {% endif %}"640            "{% if answer %}{{ answer }} is the answer.{% endif %}"641        )642643    # App global context processor644    @answer_bp.app_context_processor645    def not_answer_context_processor():646        return {"notanswer": 43}647648    # Blueprint local context processor649    @answer_bp.context_processor650    def answer_context_processor():651        return {"answer": 42}652653    # Setup endpoints for testing654    @answer_bp.route("/bp")655    def bp_page():656        return template_string()657658    @app.route("/")659    def app_page():660        return template_string()661662    # Register the blueprint663    app.register_blueprint(answer_bp)664665    app_page_bytes = client.get("/").data666    answer_page_bytes = client.get("/bp").data667668    assert b"43" in app_page_bytes669    assert b"42" not in app_page_bytes670671    assert b"42" in answer_page_bytes672    assert b"43" in answer_page_bytes673674675def test_template_global(app):676    bp = flask.Blueprint("bp", __name__)677678    @bp.app_template_global()679    def get_answer():680        return 42681682    # Make sure the function is not in the jinja_env already683    assert "get_answer" not in app.jinja_env.globals.keys()684    app.register_blueprint(bp)685686    # Tests687    assert "get_answer" in app.jinja_env.globals.keys()688    assert app.jinja_env.globals["get_answer"] is get_answer689    assert app.jinja_env.globals["get_answer"]() == 42690691    with app.app_context():692        rv = flask.render_template_string("{{ get_answer() }}")693        assert rv == "42"694695696def test_request_processing(app, client):697    bp = flask.Blueprint("bp", __name__)698    evts = []699700    @bp.before_request701    def before_bp():702        evts.append("before")703704    @bp.after_request705    def after_bp(response):706        response.data += b"|after"707        evts.append("after")708        return response709710    @bp.teardown_request711    def teardown_bp(exc):712        evts.append("teardown")713714    # Setup routes for testing715    @bp.route("/bp")716    def bp_endpoint():717        return "request"718719    app.register_blueprint(bp)720721    assert evts == []722    rv = client.get("/bp")723    assert rv.data == b"request|after"724    assert evts == ["before", "after", "teardown"]725726727def test_app_request_processing(app, client):728    bp = flask.Blueprint("bp", __name__)729    evts = []730731    @bp.before_app_request732    def before_app():733        evts.append("before")734735    @bp.after_app_request736    def after_app(response):737        response.data += b"|after"738        evts.append("after")739        return response740741    @bp.teardown_app_request742    def teardown_app(exc):743        evts.append("teardown")744745    app.register_blueprint(bp)746747    # Setup routes for testing748    @app.route("/")749    def bp_endpoint():750        return "request"751752    # before first request753    assert evts == []754755    # first request756    resp = client.get("/").data757    assert resp == b"request|after"758    assert evts == ["before", "after", "teardown"]759760    # second request761    resp = client.get("/").data762    assert resp == b"request|after"763    assert evts == ["before", "after", "teardown"] * 2764765766def test_app_url_processors(app, client):767    bp = flask.Blueprint("bp", __name__)768769    # Register app-wide url defaults and preprocessor on blueprint770    @bp.app_url_defaults771    def add_language_code(endpoint, values):772        values.setdefault("lang_code", flask.g.lang_code)773774    @bp.app_url_value_preprocessor775    def pull_lang_code(endpoint, values):776        flask.g.lang_code = values.pop("lang_code")777778    # Register route rules at the app level779    @app.route("/<lang_code>/")780    def index():781        return flask.url_for("about")782783    @app.route("/<lang_code>/about")784    def about():785        return flask.url_for("index")786787    app.register_blueprint(bp)788789    assert client.get("/de/").data == b"/de/about"790    assert client.get("/de/about").data == b"/de/"791792793def test_nested_blueprint(app, client):794    parent = flask.Blueprint("parent", __name__)795    child = flask.Blueprint("child", __name__)796    grandchild = flask.Blueprint("grandchild", __name__)797798    @parent.errorhandler(403)799    def forbidden(e):800        return "Parent no", 403801802    @parent.route("/")803    def parent_index():804        return "Parent yes"805806    @parent.route("/no")807    def parent_no():808        flask.abort(403)809810    @child.route("/")811    def child_index():812        return "Child yes"813814    @child.route("/no")815    def child_no():816        flask.abort(403)817818    @grandchild.errorhandler(403)819    def grandchild_forbidden(e):820        return "Grandchild no", 403821822    @grandchild.route("/")823    def grandchild_index():824        return "Grandchild yes"825826    @grandchild.route("/no")827    def grandchild_no():828        flask.abort(403)829830    child.register_blueprint(grandchild, url_prefix="/grandchild")831    parent.register_blueprint(child, url_prefix="/child")832    app.register_blueprint(parent, url_prefix="/parent")833834    assert client.get("/parent/").data == b"Parent yes"835    assert client.get("/parent/child/").data == b"Child yes"836    assert client.get("/parent/child/grandchild/").data == b"Grandchild yes"837    assert client.get("/parent/no").data == b"Parent no"838    assert client.get("/parent/child/no").data == b"Parent no"839    assert client.get("/parent/child/grandchild/no").data == b"Grandchild no"840841842def test_nested_callback_order(app, client):843    parent = flask.Blueprint("parent", __name__)844    child = flask.Blueprint("child", __name__)845846    @app.before_request847    def app_before1():848        flask.g.setdefault("seen", []).append("app_1")849850    @app.teardown_request851    def app_teardown1(e=None):852        assert flask.g.seen.pop() == "app_1"853854    @app.before_request855    def app_before2():856        flask.g.setdefault("seen", []).append("app_2")857858    @app.teardown_request859    def app_teardown2(e=None):860        assert flask.g.seen.pop() == "app_2"861862    @app.context_processor863    def app_ctx():864        return dict(key="app")865866    @parent.before_request867    def parent_before1():868        flask.g.setdefault("seen", []).append("parent_1")869870    @parent.teardown_request871    def parent_teardown1(e=None):872        assert flask.g.seen.pop() == "parent_1"873874    @parent.before_request875    def parent_before2():876        flask.g.setdefault("seen", []).append("parent_2")877878    @parent.teardown_request879    def parent_teardown2(e=None):880        assert flask.g.seen.pop() == "parent_2"881882    @parent.context_processor883    def parent_ctx():884        return dict(key="parent")885886    @child.before_request887    def child_before1():888        flask.g.setdefault("seen", []).append("child_1")889890    @child.teardown_request891    def child_teardown1(e=None):892        assert flask.g.seen.pop() == "child_1"893894    @child.before_request895    def child_before2():896        flask.g.setdefault("seen", []).append("child_2")897898    @child.teardown_request899    def child_teardown2(e=None):900        assert flask.g.seen.pop() == "child_2"901902    @child.context_processor903    def child_ctx():904        return dict(key="child")905906    @child.route("/a")907    def a():908        return ", ".join(flask.g.seen)909910    @child.route("/b")911    def b():912        return flask.render_template_string("{{ key }}")913914    parent.register_blueprint(child)915    app.register_blueprint(parent)916    assert (917        client.get("/a").data == b"app_1, app_2, parent_1, parent_2, child_1, child_2"918    )919    assert client.get("/b").data == b"child"920921922@pytest.mark.parametrize(923    "parent_init, child_init, parent_registration, child_registration",924    [925        ("/parent", "/child", None, None),926        ("/parent", None, None, "/child"),927        (None, None, "/parent", "/child"),928        ("/other", "/something", "/parent", "/child"),929    ],930)931def test_nesting_url_prefixes(932    parent_init,933    child_init,934    parent_registration,935    child_registration,936    app,937    client,938) -> None:939    parent = flask.Blueprint("parent", __name__, url_prefix=parent_init)940    child = flask.Blueprint("child", __name__, url_prefix=child_init)941942    @child.route("/")943    def index():944        return "index"945946    parent.register_blueprint(child, url_prefix=child_registration)947    app.register_blueprint(parent, url_prefix=parent_registration)948949    response = client.get("/parent/child/")950    assert response.status_code == 200951952953def test_nesting_subdomains(app, client) -> None:954    subdomain = "api"955    parent = flask.Blueprint("parent", __name__)956    child = flask.Blueprint("child", __name__)957958    @child.route("/child/")959    def index():960        return "child"961962    parent.register_blueprint(child)963    app.register_blueprint(parent, subdomain=subdomain)964965    client.allow_subdomain_redirects = True966967    domain_name = "domain.tld"968    app.config["SERVER_NAME"] = domain_name969    response = client.get("/child/", base_url="http://api." + domain_name)970971    assert response.status_code == 200972973974def test_child_and_parent_subdomain(app, client) -> None:975    child_subdomain = "api"976    parent_subdomain = "parent"977    parent = flask.Blueprint("parent", __name__)978    child = flask.Blueprint("child", __name__, subdomain=child_subdomain)979980    @child.route("/")981    def index():982        return "child"983984    parent.register_blueprint(child)985    app.register_blueprint(parent, subdomain=parent_subdomain)986987    client.allow_subdomain_redirects = True988989    domain_name = "domain.tld"990    app.config["SERVER_NAME"] = domain_name991    response = client.get(992        "/", base_url=f"http://{child_subdomain}.{parent_subdomain}.{domain_name}"993    )994995    assert response.status_code == 200996997    response = client.get("/", base_url=f"http://{parent_subdomain}.{domain_name}")998999    assert response.status_code == 404100010011002def test_unique_blueprint_names(app, client) -> None:1003    bp = flask.Blueprint("bp", __name__)1004    bp2 = flask.Blueprint("bp", __name__)10051006    app.register_blueprint(bp)10071008    with pytest.raises(ValueError):1009        app.register_blueprint(bp)  # same bp, same name, error10101011    app.register_blueprint(bp, name="again")  # same bp, different name, ok10121013    with pytest.raises(ValueError):1014        app.register_blueprint(bp2)  # different bp, same name, error10151016    app.register_blueprint(bp2, name="alt")  # different bp, different name, ok101710181019def test_self_registration(app, client) -> None:1020    bp = flask.Blueprint("bp", __name__)1021    with pytest.raises(ValueError):1022        bp.register_blueprint(bp)102310241025def test_blueprint_renaming(app, client) -> None:1026    bp = flask.Blueprint("bp", __name__)1027    bp2 = flask.Blueprint("bp2", __name__)10281029    @bp.get("/")1030    def index():1031        return flask.request.endpoint10321033    @bp.get("/error")1034    def error():1035        flask.abort(403)10361037    @bp.errorhandler(403)1038    def forbidden(_: Exception):1039        return "Error", 40310401041    @bp2.get("/")1042    def index2():1043        return flask.request.endpoint10441045    bp.register_blueprint(bp2, url_prefix="/a", name="sub")1046    app.register_blueprint(bp, url_prefix="/a")1047    app.register_blueprint(bp, url_prefix="/b", name="alt")10481049    assert client.get("/a/").data == b"bp.index"1050    assert client.get("/b/").data == b"alt.index"1051    assert client.get("/a/a/").data == b"bp.sub.index2"1052    assert client.get("/b/a/").data == b"alt.sub.index2"1053    assert client.get("/a/error").data == b"Error"1054    assert client.get("/b/error").data == b"Error"